hash
stringlengths
64
64
content
stringlengths
0
1.51M
24706231e2843ad4724f7f99df5c4027cde3794dd655d34129c5f42eb8ac4321
""" Multi-part parsing for file uploads. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ import base64 import binascii import collections import html from django.conf import settings from django.core.exceptions import ( RequestDataTooBig, SuspiciousMultipartForm, TooManyFieldsSent, ) from django.core.files.uploadhandler import SkipFile, StopFutureHandlers, StopUpload from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str from django.utils.http import parse_header_parameters from django.utils.regex_helper import _lazy_re_compile __all__ = ("MultiPartParser", "MultiPartParserError", "InputStreamExhausted") class MultiPartParserError(Exception): pass class InputStreamExhausted(Exception): """ No more reads are allowed from this device. """ pass RAW = "raw" FILE = "file" FIELD = "field" class MultiPartParser: """ A rfc2388 multipart/form-data parser. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``. """ boundary_re = _lazy_re_compile(r"[ -~]{0,200}[!-~]") def __init__(self, META, input_data, upload_handlers, encoding=None): """ Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handlers: A list of UploadHandler instances that perform operations on the uploaded data. :encoding: The encoding with which to treat the incoming data. """ # Content-Type should contain multipart and the boundary information. content_type = META.get("CONTENT_TYPE", "") if not content_type.startswith("multipart/"): raise MultiPartParserError("Invalid Content-Type: %s" % content_type) try: content_type.encode("ascii") except UnicodeEncodeError: raise MultiPartParserError( "Invalid non-ASCII Content-Type in multipart: %s" % force_str(content_type) ) # Parse the header to get the boundary to split the parts. _, opts = parse_header_parameters(content_type) boundary = opts.get("boundary") if not boundary or not self.boundary_re.fullmatch(boundary): raise MultiPartParserError( "Invalid boundary in multipart: %s" % force_str(boundary) ) # Content-Length should contain the length of the body we are about # to receive. try: content_length = int(META.get("CONTENT_LENGTH", 0)) except (ValueError, TypeError): content_length = 0 if content_length < 0: # This means we shouldn't continue...raise an error. raise MultiPartParserError("Invalid content length: %r" % content_length) self._boundary = boundary.encode("ascii") self._input_data = input_data # For compatibility with low-level network APIs (with 32-bit integers), # the chunk size should be < 2^31, but still divisible by 4. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] self._chunk_size = min([2**31 - 4] + possible_sizes) self._meta = META self._encoding = encoding or settings.DEFAULT_CHARSET self._content_length = content_length self._upload_handlers = upload_handlers def parse(self): """ Parse the POST data and break it into a FILES MultiValueDict and a POST MultiValueDict. Return a tuple containing the POST and FILES dictionary, respectively. """ from django.http import QueryDict encoding = self._encoding handlers = self._upload_handlers # HTTP spec says that Content-Length >= 0 is valid # handling content-length == 0 before continuing if self._content_length == 0: return QueryDict(encoding=self._encoding), MultiValueDict() # See if any of the handlers take care of the parsing. # This allows overriding everything if need be. for handler in handlers: result = handler.handle_raw_input( self._input_data, self._meta, self._content_length, self._boundary, encoding, ) # Check to see if it was handled if result is not None: return result[0], result[1] # Create the data structures to be used later. self._post = QueryDict(mutable=True) self._files = MultiValueDict() # Instantiate the parser and stream: stream = LazyStream(ChunkIter(self._input_data, self._chunk_size)) # Whether or not to signal a file-completion at the beginning of the loop. old_field_name = None counters = [0] * len(handlers) # Number of bytes that have been read. num_bytes_read = 0 # To count the number of keys in the request. num_post_keys = 0 # To limit the amount of data read from the request. read_size = None # Whether a file upload is finished. uploaded_file = True try: for item_type, meta_data, field_stream in Parser(stream, self._boundary): if old_field_name: # We run this at the beginning of the next loop # since we cannot be sure a file is complete until # we hit the next boundary/part of the multipart content. self.handle_file_complete(old_field_name, counters) old_field_name = None uploaded_file = True try: disposition = meta_data["content-disposition"][1] field_name = disposition["name"].strip() except (KeyError, IndexError, AttributeError): continue transfer_encoding = meta_data.get("content-transfer-encoding") if transfer_encoding is not None: transfer_encoding = transfer_encoding[0].strip() field_name = force_str(field_name, encoding, errors="replace") if item_type == FIELD: # Avoid storing more than DATA_UPLOAD_MAX_NUMBER_FIELDS. num_post_keys += 1 if ( settings.DATA_UPLOAD_MAX_NUMBER_FIELDS is not None and settings.DATA_UPLOAD_MAX_NUMBER_FIELDS < num_post_keys ): raise TooManyFieldsSent( "The number of GET/POST parameters exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS." ) # Avoid reading more than DATA_UPLOAD_MAX_MEMORY_SIZE. if settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None: read_size = ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE - num_bytes_read ) # This is a post field, we can just set it in the post if transfer_encoding == "base64": raw_data = field_stream.read(size=read_size) num_bytes_read += len(raw_data) try: data = base64.b64decode(raw_data) except binascii.Error: data = raw_data else: data = field_stream.read(size=read_size) num_bytes_read += len(data) # Add two here to make the check consistent with the # x-www-form-urlencoded check that includes '&='. num_bytes_read += len(field_name) + 2 if ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and num_bytes_read > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( "Request body exceeded " "settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) self._post.appendlist( field_name, force_str(data, encoding, errors="replace") ) elif item_type == FILE: # This is a file, use the handler... file_name = disposition.get("filename") if file_name: file_name = force_str(file_name, encoding, errors="replace") file_name = self.sanitize_file_name(file_name) if not file_name: continue content_type, content_type_extra = meta_data.get( "content-type", ("", {}) ) content_type = content_type.strip() charset = content_type_extra.get("charset") try: content_length = int(meta_data.get("content-length")[0]) except (IndexError, TypeError, ValueError): content_length = None counters = [0] * len(handlers) uploaded_file = False try: for handler in handlers: try: handler.new_file( field_name, file_name, content_type, content_length, charset, content_type_extra, ) except StopFutureHandlers: break for chunk in field_stream: if transfer_encoding == "base64": # We only special-case base64 transfer encoding # We should always decode base64 chunks by # multiple of 4, ignoring whitespace. stripped_chunk = b"".join(chunk.split()) remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: break stripped_chunk += b"".join(over_chunk.split()) remaining = len(stripped_chunk) % 4 try: chunk = base64.b64decode(stripped_chunk) except Exception as exc: # Since this is only a chunk, any error is # an unfixable error. raise MultiPartParserError( "Could not decode base64 data." ) from exc for i, handler in enumerate(handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[i]) counters[i] += chunk_length if chunk is None: # Don't continue if the chunk received by # the handler is None. break except SkipFile: self._close_files() # Just use up the rest of this file... exhaust(field_stream) else: # Handle file upload completions on next iteration. old_field_name = field_name else: # If this is neither a FIELD or a FILE, just exhaust the stream. exhaust(stream) except StopUpload as e: self._close_files() if not e.connection_reset: exhaust(self._input_data) else: if not uploaded_file: for handler in handlers: handler.upload_interrupted() # Make sure that the request data is all fed exhaust(self._input_data) # Signal that the upload has completed. # any() shortcircuits if a handler's upload_complete() returns a value. any(handler.upload_complete() for handler in handlers) self._post._mutable = False return self._post, self._files def handle_file_complete(self, old_field_name, counters): """ Handle all the signaling that takes place when a file is complete. """ for i, handler in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: # If it returns a file object, then set the files dict. self._files.appendlist( force_str(old_field_name, self._encoding, errors="replace"), file_obj, ) break def sanitize_file_name(self, file_name): """ Sanitize the filename of an upload. Remove all possible path separators, even though that might remove more than actually required by the target system. Filenames that could potentially cause problems (current/parent dir) are also discarded. It should be noted that this function could still return a "filepath" like "C:some_file.txt" which is handled later on by the storage layer. So while this function does sanitize filenames to some extent, the resulting filename should still be considered as untrusted user input. """ file_name = html.unescape(file_name) file_name = file_name.rsplit("/")[-1] file_name = file_name.rsplit("\\")[-1] # Remove non-printable characters. file_name = "".join([char for char in file_name if char.isprintable()]) if file_name in {"", ".", ".."}: return None return file_name IE_sanitize = sanitize_file_name def _close_files(self): # Free up all file handles. # FIXME: this currently assumes that upload handlers store the file as 'file' # We should document that... # (Maybe add handler.free_file to complement new_file) for handler in self._upload_handlers: if hasattr(handler, "file"): handler.file.close() class LazyStream: """ The LazyStream wrapper allows one to get and "unget" bytes from a stream. Given a producer object (an iterator that yields bytestrings), the LazyStream object will support iteration, reading, and keeping a "look-back" variable in case you need to "unget" some bytes. """ def __init__(self, producer, length=None): """ Every LazyStream must have a producer when instantiated. A producer is an iterable that returns a string each time it is called. """ self._producer = producer self._empty = False self._leftover = b"" self.length = length self.position = 0 self._remaining = length self._unget_history = [] def tell(self): return self.position def read(self, size=None): def parts(): remaining = self._remaining if size is None else size # do the whole thing in one shot if no limit was provided. if remaining is None: yield b"".join(self) return # otherwise do some bookkeeping to return exactly enough # of the stream and stashing any extra content we get from # the producer while remaining != 0: assert remaining > 0, "remaining bytes to read should never go negative" try: chunk = next(self) except StopIteration: return else: emitting = chunk[:remaining] self.unget(chunk[remaining:]) remaining -= len(emitting) yield emitting return b"".join(parts()) def __next__(self): """ Used when the exact number of bytes to read is unimportant. Return whatever chunk is conveniently returned from the iterator. Useful to avoid unnecessary bookkeeping if performance is an issue. """ if self._leftover: output = self._leftover self._leftover = b"" else: output = next(self._producer) self._unget_history = [] self.position += len(output) return output def close(self): """ Used to invalidate/disable this lazy stream. Replace the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next(). """ self._producer = [] def __iter__(self): return self def unget(self, bytes): """ Place bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound. """ if not bytes: return self._update_unget_history(len(bytes)) self.position -= len(bytes) self._leftover = bytes + self._leftover def _update_unget_history(self, num_bytes): """ Update the unget history as a sanity check to see if we've pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we're mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request. """ self._unget_history = [num_bytes] + self._unget_history[:49] number_equal = len( [ current_number for current_number in self._unget_history if current_number == num_bytes ] ) if number_equal > 40: raise SuspiciousMultipartForm( "The multipart parser got stuck, which shouldn't happen with" " normal uploaded files. Check for malicious upload activity;" " if there is none, report this to the Django developers." ) class ChunkIter: """ An iterable that will yield chunks of data. Given a file-like object as the constructor, yield chunks of read operations from that object. """ def __init__(self, flo, chunk_size=64 * 1024): self.flo = flo self.chunk_size = chunk_size def __next__(self): try: data = self.flo.read(self.chunk_size) except InputStreamExhausted: raise StopIteration() if data: return data else: raise StopIteration() def __iter__(self): return self class InterBoundaryIter: """ A Producer that will iterate over boundaries. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary def __iter__(self): return self def __next__(self): try: return LazyStream(BoundaryIter(self._stream, self._boundary)) except InputStreamExhausted: raise StopIteration() class BoundaryIter: """ A Producer that is sensitive to boundaries. Will happily yield bytes until a boundary is found. Will yield the bytes before the boundary, throw away the boundary bytes themselves, and push the post-boundary bytes back on the stream. The future calls to next() after locating the boundary will raise a StopIteration exception. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary self._done = False # rollback an additional six bytes because the format is like # this: CRLF<boundary>[--CRLF] self._rollback = len(boundary) + 6 # Try to use mx fast string search if available. Otherwise # use Python find. Wrap the latter for consistency. unused_char = self._stream.read(1) if not unused_char: raise InputStreamExhausted() self._stream.unget(unused_char) def __iter__(self): return self def __next__(self): if self._done: raise StopIteration() stream = self._stream rollback = self._rollback bytes_read = 0 chunks = [] for bytes in stream: bytes_read += len(bytes) chunks.append(bytes) if bytes_read > rollback: break if not bytes: break else: self._done = True if not chunks: raise StopIteration() chunk = b"".join(chunks) boundary = self._find_boundary(chunk) if boundary: end, next = boundary stream.unget(chunk[next:]) self._done = True return chunk[:end] else: # make sure we don't treat a partial boundary (and # its separators) as data if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6): # There's nothing left, we should just return and mark as done. self._done = True return chunk else: stream.unget(chunk[-rollback:]) return chunk[:-rollback] def _find_boundary(self, data): """ Find a multipart boundary in data. Should no boundary exist in the data, return None. Otherwise, return a tuple containing the indices of the following: * the end of current encapsulation * the start of the next encapsulation """ index = data.find(self._boundary) if index < 0: return None else: end = index next = index + len(self._boundary) # backup over CRLF last = max(0, end - 1) if data[last : last + 1] == b"\n": end -= 1 last = max(0, end - 1) if data[last : last + 1] == b"\r": end -= 1 return end, next def exhaust(stream_or_iterable): """Exhaust an iterator or stream.""" try: iterator = iter(stream_or_iterable) except TypeError: iterator = ChunkIter(stream_or_iterable, 16384) collections.deque(iterator, maxlen=0) # consume iterator quickly. def parse_boundary_stream(stream, max_header_size): """ Parse one and exactly one stream that encapsulates a boundary. """ # Stream at beginning of header, look for end of header # and parse it if found. The header must fit within one # chunk. chunk = stream.read(max_header_size) # 'find' returns the top of these four bytes, so we'll # need to munch them later to prevent them from polluting # the payload. header_end = chunk.find(b"\r\n\r\n") if header_end == -1: # we find no header, so we just mark this fact and pass on # the stream verbatim stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] # here we place any excess chunk back onto the stream, as # well as throwing away the CRLFCRLF bytes from above. stream.unget(chunk[header_end + 4 :]) TYPE = RAW outdict = {} # Eliminate blank lines for line in header.split(b"\r\n"): # This terminology ("main value" and "dictionary of # parameters") is from the Python docs. try: main_value_pair, params = parse_header_parameters(line.decode()) name, value = main_value_pair.split(":", 1) params = {k: v.encode() for k, v in params.items()} except ValueError: # Invalid header. continue if name == "content-disposition": TYPE = FIELD if params.get("filename"): TYPE = FILE outdict[name] = value, params if TYPE == RAW: stream.unget(chunk) return (TYPE, outdict, stream) class Parser: def __init__(self, stream, boundary): self._stream = stream self._separator = b"--" + boundary def __iter__(self): boundarystream = InterBoundaryIter(self._stream, self._separator) for sub_stream in boundarystream: # Iterate over each part yield parse_boundary_stream(sub_stream, 1024)
9556031b867df862859e745ac7e2151dd6d0e8839166e47826324c11f13be779
import datetime import io import json import mimetypes import os import re import sys import time from email.header import Header from http.client import responses from urllib.parse import quote, urlparse from django.conf import settings from django.core import signals, signing from django.core.exceptions import DisallowedRedirect from django.core.serializers.json import DjangoJSONEncoder from django.http.cookie import SimpleCookie from django.utils import timezone from django.utils.datastructures import CaseInsensitiveMapping from django.utils.encoding import iri_to_uri from django.utils.http import http_date from django.utils.regex_helper import _lazy_re_compile _charset_from_content_type_re = _lazy_re_compile( r";\s*charset=(?P<charset>[^\s;]+)", re.I ) class ResponseHeaders(CaseInsensitiveMapping): def __init__(self, data): """ Populate the initial data using __setitem__ to ensure values are correctly encoded. """ self._store = {} if data: for header, value in self._unpack_items(data): self[header] = value def _convert_to_charset(self, value, charset, mime_encode=False): """ Convert headers key/value to ascii/latin-1 native strings. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and `value` can't be represented in the given charset, apply MIME-encoding. """ try: if isinstance(value, str): # Ensure string is valid in given charset value.encode(charset) elif isinstance(value, bytes): # Convert bytestring using given charset value = value.decode(charset) else: value = str(value) # Ensure string is valid in given charset. value.encode(charset) if "\n" in value or "\r" in value: raise BadHeaderError( f"Header values can't contain newlines (got {value!r})" ) except UnicodeError as e: # Encoding to a string of the specified charset failed, but we # don't know what type that value was, or if it contains newlines, # which we may need to check for before sending it to be # encoded for multiple character sets. if (isinstance(value, bytes) and (b"\n" in value or b"\r" in value)) or ( isinstance(value, str) and ("\n" in value or "\r" in value) ): raise BadHeaderError( f"Header values can't contain newlines (got {value!r})" ) from e if mime_encode: value = Header(value, "utf-8", maxlinelen=sys.maxsize).encode() else: e.reason += ", HTTP response headers must be in %s format" % charset raise return value def __delitem__(self, key): self.pop(key) def __setitem__(self, key, value): key = self._convert_to_charset(key, "ascii") value = self._convert_to_charset(value, "latin-1", mime_encode=True) self._store[key.lower()] = (key, value) def pop(self, key, default=None): return self._store.pop(key.lower(), default) def setdefault(self, key, value): if key not in self: self[key] = value class BadHeaderError(ValueError): pass class HttpResponseBase: """ An HTTP response base class with dictionary-accessed headers. This class doesn't handle content. It should not be used directly. Use the HttpResponse and StreamingHttpResponse subclasses instead. """ status_code = 200 def __init__( self, content_type=None, status=None, reason=None, charset=None, headers=None ): self.headers = ResponseHeaders(headers) self._charset = charset if "Content-Type" not in self.headers: if content_type is None: content_type = f"text/html; charset={self.charset}" self.headers["Content-Type"] = content_type elif content_type: raise ValueError( "'headers' must not contain 'Content-Type' when the " "'content_type' parameter is provided." ) self._resource_closers = [] # This parameter is set by the handler. It's necessary to preserve the # historical behavior of request_finished. self._handler_class = None self.cookies = SimpleCookie() self.closed = False if status is not None: try: self.status_code = int(status) except (ValueError, TypeError): raise TypeError("HTTP status code must be an integer.") if not 100 <= self.status_code <= 599: raise ValueError("HTTP status code must be an integer from 100 to 599.") self._reason_phrase = reason @property def reason_phrase(self): if self._reason_phrase is not None: return self._reason_phrase # Leave self._reason_phrase unset in order to use the default # reason phrase for status code. return responses.get(self.status_code, "Unknown Status Code") @reason_phrase.setter def reason_phrase(self, value): self._reason_phrase = value @property def charset(self): if self._charset is not None: return self._charset # The Content-Type header may not yet be set, because the charset is # being inserted *into* it. if content_type := self.headers.get("Content-Type"): if matched := _charset_from_content_type_re.search(content_type): # Extract the charset and strip its double quotes. # Note that having parsed it from the Content-Type, we don't # store it back into the _charset for later intentionally, to # allow for the Content-Type to be switched again later. return matched["charset"].replace('"', "") return settings.DEFAULT_CHARSET @charset.setter def charset(self, value): self._charset = value def serialize_headers(self): """HTTP headers as a bytestring.""" return b"\r\n".join( [ key.encode("ascii") + b": " + value.encode("latin-1") for key, value in self.headers.items() ] ) __bytes__ = serialize_headers @property def _content_type_for_repr(self): return ( ', "%s"' % self.headers["Content-Type"] if "Content-Type" in self.headers else "" ) def __setitem__(self, header, value): self.headers[header] = value def __delitem__(self, header): del self.headers[header] def __getitem__(self, header): return self.headers[header] def has_header(self, header): """Case-insensitive check for a header.""" return header in self.headers __contains__ = has_header def items(self): return self.headers.items() def get(self, header, alternate=None): return self.headers.get(header, alternate) def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): """ Set a cookie. ``expires`` can be: - a string in the correct format, - a naive ``datetime.datetime`` object in UTC, - an aware ``datetime.datetime`` object in any time zone. If it is a ``datetime.datetime`` object then calculate ``max_age``. ``max_age`` can be: - int/float specifying seconds, - ``datetime.timedelta`` object. """ self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_naive(expires): expires = timezone.make_aware(expires, datetime.timezone.utc) delta = expires - datetime.datetime.now(tz=datetime.timezone.utc) # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). delta = delta + datetime.timedelta(seconds=1) # Just set max_age - the max_age logic will set expires. expires = None if max_age is not None: raise ValueError("'expires' and 'max_age' can't be used together.") max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]["expires"] = expires else: self.cookies[key]["expires"] = "" if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() self.cookies[key]["max-age"] = int(max_age) # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]["expires"] = http_date(time.time() + max_age) if path is not None: self.cookies[key]["path"] = path if domain is not None: self.cookies[key]["domain"] = domain if secure: self.cookies[key]["secure"] = True if httponly: self.cookies[key]["httponly"] = True if samesite: if samesite.lower() not in ("lax", "none", "strict"): raise ValueError('samesite must be "lax", "none", or "strict".') self.cookies[key]["samesite"] = samesite def setdefault(self, key, value): """Set a header unless it has already been set.""" self.headers.setdefault(key, value) def set_signed_cookie(self, key, value, salt="", **kwargs): value = signing.get_cookie_signer(salt=key + salt).sign(value) return self.set_cookie(key, value, **kwargs) def delete_cookie(self, key, path="/", domain=None, samesite=None): # Browsers can ignore the Set-Cookie header if the cookie doesn't use # the secure flag and: # - the cookie name starts with "__Host-" or "__Secure-", or # - the samesite is "none". secure = key.startswith(("__Secure-", "__Host-")) or ( samesite and samesite.lower() == "none" ) self.set_cookie( key, max_age=0, path=path, domain=domain, secure=secure, expires="Thu, 01 Jan 1970 00:00:00 GMT", samesite=samesite, ) # Common methods used by subclasses def make_bytes(self, value): """Turn a value into a bytestring encoded in the output charset.""" # Per PEP 3333, this response body must be bytes. To avoid returning # an instance of a subclass, this function returns `bytes(value)`. # This doesn't make a copy when `value` already contains bytes. # Handle string types -- we can't rely on force_bytes here because: # - Python attempts str conversion first # - when self._charset != 'utf-8' it re-encodes the content if isinstance(value, (bytes, memoryview)): return bytes(value) if isinstance(value, str): return bytes(value.encode(self.charset)) # Handle non-string types. return str(value).encode(self.charset) # These methods partially implement the file-like object interface. # See https://docs.python.org/library/io.html#io.IOBase # The WSGI server must call this method upon completion of the request. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html def close(self): for closer in self._resource_closers: try: closer() except Exception: pass # Free resources that were still referenced. self._resource_closers.clear() self.closed = True signals.request_finished.send(sender=self._handler_class) def write(self, content): raise OSError("This %s instance is not writable" % self.__class__.__name__) def flush(self): pass def tell(self): raise OSError( "This %s instance cannot tell its position" % self.__class__.__name__ ) # These methods partially implement a stream-like object interface. # See https://docs.python.org/library/io.html#io.IOBase def readable(self): return False def seekable(self): return False def writable(self): return False def writelines(self, lines): raise OSError("This %s instance is not writable" % self.__class__.__name__) class HttpResponse(HttpResponseBase): """ An HTTP response class with a string as content. This content can be read, appended to, or replaced. """ streaming = False non_picklable_attrs = frozenset( [ "resolver_match", # Non-picklable attributes added by test clients. "asgi_request", "client", "context", "json", "templates", "wsgi_request", ] ) def __init__(self, content=b"", *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content def __getstate__(self): obj_dict = self.__dict__.copy() for attr in self.non_picklable_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def __repr__(self): return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, } def serialize(self): """Full HTTP message, including headers, as a bytestring.""" return self.serialize_headers() + b"\r\n\r\n" + self.content __bytes__ = serialize @property def content(self): return b"".join(self._container) @content.setter def content(self, value): # Consume iterators upon assignment to allow repeated iteration. if hasattr(value, "__iter__") and not isinstance( value, (bytes, memoryview, str) ): content = b"".join(self.make_bytes(chunk) for chunk in value) if hasattr(value, "close"): try: value.close() except Exception: pass else: content = self.make_bytes(value) # Create a list of properly encoded bytestrings to support write(). self._container = [content] def __iter__(self): return iter(self._container) def write(self, content): self._container.append(self.make_bytes(content)) def tell(self): return len(self.content) def getvalue(self): return self.content def writable(self): return True def writelines(self, lines): for line in lines: self.write(line) class StreamingHttpResponse(HttpResponseBase): """ A streaming HTTP response class with an iterator as content. This should only be iterated once, when the response is streamed to the client. However, it can be appended to or replaced with a new iterator that wraps the original content (or yields entirely new content). """ streaming = True def __init__(self, streaming_content=(), *args, **kwargs): super().__init__(*args, **kwargs) # `streaming_content` should be an iterable of bytestrings. # See the `streaming_content` property methods. self.streaming_content = streaming_content def __repr__(self): return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__qualname__, "status_code": self.status_code, "content_type": self._content_type_for_repr, } @property def content(self): raise AttributeError( "This %s instance has no `content` attribute. Use " "`streaming_content` instead." % self.__class__.__name__ ) @property def streaming_content(self): return map(self.make_bytes, self._iterator) @streaming_content.setter def streaming_content(self, value): self._set_streaming_content(value) def _set_streaming_content(self, value): # Ensure we can never iterate on "value" more than once. self._iterator = iter(value) if hasattr(value, "close"): self._resource_closers.append(value.close) def __iter__(self): return self.streaming_content def getvalue(self): return b"".join(self.streaming_content) class FileResponse(StreamingHttpResponse): """ A streaming HTTP response class optimized for files. """ block_size = 4096 def __init__(self, *args, as_attachment=False, filename="", **kwargs): self.as_attachment = as_attachment self.filename = filename self._no_explicit_content_type = ( "content_type" not in kwargs or kwargs["content_type"] is None ) super().__init__(*args, **kwargs) def _set_streaming_content(self, value): if not hasattr(value, "read"): self.file_to_stream = None return super()._set_streaming_content(value) self.file_to_stream = filelike = value if hasattr(filelike, "close"): self._resource_closers.append(filelike.close) value = iter(lambda: filelike.read(self.block_size), b"") self.set_headers(filelike) super()._set_streaming_content(value) def set_headers(self, filelike): """ Set some common response headers (Content-Length, Content-Type, and Content-Disposition) based on the `filelike` response content. """ filename = getattr(filelike, "name", "") filename = filename if isinstance(filename, str) else "" seekable = hasattr(filelike, "seek") and ( not hasattr(filelike, "seekable") or filelike.seekable() ) if hasattr(filelike, "tell"): if seekable: initial_position = filelike.tell() filelike.seek(0, io.SEEK_END) self.headers["Content-Length"] = filelike.tell() - initial_position filelike.seek(initial_position) elif hasattr(filelike, "getbuffer"): self.headers["Content-Length"] = ( filelike.getbuffer().nbytes - filelike.tell() ) elif os.path.exists(filename): self.headers["Content-Length"] = ( os.path.getsize(filename) - filelike.tell() ) elif seekable: self.headers["Content-Length"] = sum( iter(lambda: len(filelike.read(self.block_size)), 0) ) filelike.seek(-int(self.headers["Content-Length"]), io.SEEK_END) filename = os.path.basename(self.filename or filename) if self._no_explicit_content_type: if filename: content_type, encoding = mimetypes.guess_type(filename) # Encoding isn't set to prevent browsers from automatically # uncompressing files. content_type = { "bzip2": "application/x-bzip", "gzip": "application/gzip", "xz": "application/x-xz", }.get(encoding, content_type) self.headers["Content-Type"] = ( content_type or "application/octet-stream" ) else: self.headers["Content-Type"] = "application/octet-stream" if filename: disposition = "attachment" if self.as_attachment else "inline" try: filename.encode("ascii") file_expr = 'filename="{}"'.format(filename) except UnicodeEncodeError: file_expr = "filename*=utf-8''{}".format(quote(filename)) self.headers["Content-Disposition"] = "{}; {}".format( disposition, file_expr ) elif self.as_attachment: self.headers["Content-Disposition"] = "attachment" class HttpResponseRedirectBase(HttpResponse): allowed_schemes = ["http", "https", "ftp"] def __init__(self, redirect_to, *args, **kwargs): super().__init__(*args, **kwargs) self["Location"] = iri_to_uri(redirect_to) parsed = urlparse(str(redirect_to)) if parsed.scheme and parsed.scheme not in self.allowed_schemes: raise DisallowedRedirect( "Unsafe redirect to URL with protocol '%s'" % parsed.scheme ) url = property(lambda self: self["Location"]) def __repr__(self): return ( '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">' % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, "url": self.url, } ) class HttpResponseRedirect(HttpResponseRedirectBase): status_code = 302 class HttpResponsePermanentRedirect(HttpResponseRedirectBase): status_code = 301 class HttpResponseNotModified(HttpResponse): status_code = 304 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self["content-type"] @HttpResponse.content.setter def content(self, value): if value: raise AttributeError( "You cannot set content to a 304 (Not Modified) response" ) self._container = [] class HttpResponseBadRequest(HttpResponse): status_code = 400 class HttpResponseNotFound(HttpResponse): status_code = 404 class HttpResponseForbidden(HttpResponse): status_code = 403 class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, permitted_methods, *args, **kwargs): super().__init__(*args, **kwargs) self["Allow"] = ", ".join(permitted_methods) def __repr__(self): return "<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, "methods": self["Allow"], } class HttpResponseGone(HttpResponse): status_code = 410 class HttpResponseServerError(HttpResponse): status_code = 500 class Http404(Exception): pass class JsonResponse(HttpResponse): """ An HTTP response class that consumes data to be serialized to JSON. :param data: Data to be dumped into json. By default only ``dict`` objects are allowed to be passed due to a security flaw before ECMAScript 5. See the ``safe`` parameter for more information. :param encoder: Should be a json encoder class. Defaults to ``django.core.serializers.json.DjangoJSONEncoder``. :param safe: Controls if only ``dict`` objects may be serialized. Defaults to ``True``. :param json_dumps_params: A dictionary of kwargs passed to json.dumps(). """ def __init__( self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs, ): if safe and not isinstance(data, dict): raise TypeError( "In order to allow non-dict objects to be serialized set the " "safe parameter to False." ) if json_dumps_params is None: json_dumps_params = {} kwargs.setdefault("content_type", "application/json") data = json.dumps(data, cls=encoder, **json_dumps_params) super().__init__(content=data, **kwargs)
868d7489d50cd611c11a7c7ebddd706c79379d0ccf7a5b3d0ff48be223d8a092
import codecs import copy from io import BytesIO from itertools import chain from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit from django.conf import settings from django.core import signing from django.core.exceptions import ( DisallowedHost, ImproperlyConfigured, RequestDataTooBig, TooManyFieldsSent, ) from django.core.files import uploadhandler from django.http.multipartparser import MultiPartParser, MultiPartParserError from django.utils.datastructures import ( CaseInsensitiveMapping, ImmutableList, MultiValueDict, ) from django.utils.encoding import escape_uri_path, iri_to_uri from django.utils.functional import cached_property from django.utils.http import is_same_domain, parse_header_parameters from django.utils.regex_helper import _lazy_re_compile RAISE_ERROR = object() host_validation_re = _lazy_re_compile( r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:[0-9]+)?$" ) class UnreadablePostError(OSError): pass class RawPostDataException(Exception): """ You cannot access raw_post_data from a request that has multipart/* POST data if it has been accessed via POST, FILES, etc.. """ pass class HttpRequest: """A basic HTTP request.""" # The encoding used in GET/POST dicts. None means use default setting. _encoding = None _upload_handlers = [] def __init__(self): # WARNING: The `WSGIRequest` subclass doesn't call `super`. # Any variable assignment made here should also happen in # `WSGIRequest.__init__()`. self.GET = QueryDict(mutable=True) self.POST = QueryDict(mutable=True) self.COOKIES = {} self.META = {} self.FILES = MultiValueDict() self.path = "" self.path_info = "" self.method = None self.resolver_match = None self.content_type = None self.content_params = None def __repr__(self): if self.method is None or not self.get_full_path(): return "<%s>" % self.__class__.__name__ return "<%s: %s %r>" % ( self.__class__.__name__, self.method, self.get_full_path(), ) @cached_property def headers(self): return HttpHeaders(self.META) @cached_property def accepted_types(self): """Return a list of MediaType instances.""" return parse_accept_header(self.headers.get("Accept", "*/*")) def accepts(self, media_type): return any( accepted_type.match(media_type) for accepted_type in self.accepted_types ) def _set_content_type_params(self, meta): """Set content_type, content_params, and encoding.""" self.content_type, self.content_params = parse_header_parameters( meta.get("CONTENT_TYPE", "") ) if "charset" in self.content_params: try: codecs.lookup(self.content_params["charset"]) except LookupError: pass else: self.encoding = self.content_params["charset"] def _get_raw_host(self): """ Return the HTTP host using the environment or request headers. Skip allowed hosts protection, so may return an insecure host. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ("HTTP_X_FORWARDED_HOST" in self.META): host = self.META["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in self.META: host = self.META["HTTP_HOST"] else: # Reconstruct the host using the algorithm from PEP 333. host = self.META["SERVER_NAME"] server_port = self.get_port() if server_port != ("443" if self.is_secure() else "80"): host = "%s:%s" % (host, server_port) return host def get_host(self): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: allowed_hosts = [".localhost", "127.0.0.1", "[::1]"] domain, port = split_domain_port(host) if domain and validate_host(domain, allowed_hosts): return host else: msg = "Invalid HTTP_HOST header: %r." % host if domain: msg += " You may need to add %r to ALLOWED_HOSTS." % domain else: msg += ( " The domain name provided is not valid according to RFC 1034/1035." ) raise DisallowedHost(msg) def get_port(self): """Return the port number for the request as a string.""" if settings.USE_X_FORWARDED_PORT and "HTTP_X_FORWARDED_PORT" in self.META: port = self.META["HTTP_X_FORWARDED_PORT"] else: port = self.META["SERVER_PORT"] return str(port) def get_full_path(self, force_append_slash=False): return self._get_full_path(self.path, force_append_slash) def get_full_path_info(self, force_append_slash=False): return self._get_full_path(self.path_info, force_append_slash) def _get_full_path(self, path, force_append_slash): # RFC 3986 requires query string arguments to be in the ASCII range. # Rather than crash if this doesn't happen, we encode defensively. return "%s%s%s" % ( escape_uri_path(path), "/" if force_append_slash and not path.endswith("/") else "", ("?" + iri_to_uri(self.META.get("QUERY_STRING", ""))) if self.META.get("QUERY_STRING", "") else "", ) def get_signed_cookie(self, key, default=RAISE_ERROR, salt="", max_age=None): """ Attempt to return a signed cookie. If the signature fails or the cookie has expired, raise an exception, unless the `default` argument is provided, in which case return that value. """ try: cookie_value = self.COOKIES[key] except KeyError: if default is not RAISE_ERROR: return default else: raise try: value = signing.get_cookie_signer(salt=key + salt).unsign( cookie_value, max_age=max_age ) except signing.BadSignature: if default is not RAISE_ERROR: return default else: raise return value def build_absolute_uri(self, location=None): """ Build an absolute URI from the location and the variables available in this request. If no ``location`` is specified, build the absolute URI using request.get_full_path(). If the location is absolute, convert it to an RFC 3987 compliant URI and return it. If location is relative or is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base URL constructed from the request variables. """ if location is None: # Make it an absolute url (but schemeless and domainless) for the # edge case that the path starts with '//'. location = "//%s" % self.get_full_path() else: # Coerce lazy locations. location = str(location) bits = urlsplit(location) if not (bits.scheme and bits.netloc): # Handle the simple, most common case. If the location is absolute # and a scheme or host (netloc) isn't provided, skip an expensive # urljoin() as long as no path segments are '.' or '..'. if ( bits.path.startswith("/") and not bits.scheme and not bits.netloc and "/./" not in bits.path and "/../" not in bits.path ): # If location starts with '//' but has no netloc, reuse the # schema and netloc from the current request. Strip the double # slashes and continue as if it wasn't specified. if location.startswith("//"): location = location[2:] location = self._current_scheme_host + location else: # Join the constructed URL with the provided location, which # allows the provided location to apply query strings to the # base path. location = urljoin(self._current_scheme_host + self.path, location) return iri_to_uri(location) @cached_property def _current_scheme_host(self): return "{}://{}".format(self.scheme, self.get_host()) def _get_scheme(self): """ Hook for subclasses like WSGIRequest to implement. Return 'http' by default. """ return "http" @property def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( "The SECURE_PROXY_SSL_HEADER setting must be a tuple containing " "two values." ) header_value = self.META.get(header) if header_value is not None: header_value, *_ = header_value.split(",", 1) return "https" if header_value.strip() == secure_value else "http" return self._get_scheme() def is_secure(self): return self.scheme == "https" @property def encoding(self): return self._encoding @encoding.setter def encoding(self, val): """ Set the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, remove and recreate it on the next access (so that it is decoded correctly). """ self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._post def _initialize_handlers(self): self._upload_handlers = [ uploadhandler.load_handler(handler, self) for handler in settings.FILE_UPLOAD_HANDLERS ] @property def upload_handlers(self): if not self._upload_handlers: # If there are no upload handlers defined, initialize them from settings. self._initialize_handlers() return self._upload_handlers @upload_handlers.setter def upload_handlers(self, upload_handlers): if hasattr(self, "_files"): raise AttributeError( "You cannot set the upload handlers after the upload has been " "processed." ) self._upload_handlers = upload_handlers def parse_file_upload(self, META, post_data): """Return a tuple of (POST QueryDict, FILES MultiValueDict).""" self.upload_handlers = ImmutableList( self.upload_handlers, warning=( "You cannot alter upload handlers after the upload has been " "processed." ), ) parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding) return parser.parse() @property def body(self): if not hasattr(self, "_body"): if self._read_started: raise RawPostDataException( "You cannot access body after reading from request's data stream" ) # Limit the maximum request data size that will be handled in-memory. if ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and int(self.META.get("CONTENT_LENGTH") or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) try: self._body = self.read() except OSError as e: raise UnreadablePostError(*e.args) from e finally: self._stream.close() self._stream = BytesIO(self._body) return self._body def _mark_post_parse_error(self): self._post = QueryDict() self._files = MultiValueDict() def _load_post_and_files(self): """Populate self._post and self._files if the content-type is a form type""" if self.method != "POST": self._post, self._files = ( QueryDict(encoding=self._encoding), MultiValueDict(), ) return if self._read_started and not hasattr(self, "_body"): self._mark_post_parse_error() return if self.content_type == "multipart/form-data": if hasattr(self, "_body"): # Use already read data data = BytesIO(self._body) else: data = self try: self._post, self._files = self.parse_file_upload(self.META, data) except MultiPartParserError: # An error occurred while parsing POST data. Since when # formatting the error the request handler might access # self.POST, set self._post and self._file to prevent # attempts to parse POST data again. self._mark_post_parse_error() raise elif self.content_type == "application/x-www-form-urlencoded": self._post, self._files = ( QueryDict(self.body, encoding=self._encoding), MultiValueDict(), ) else: self._post, self._files = ( QueryDict(encoding=self._encoding), MultiValueDict(), ) def close(self): if hasattr(self, "_files"): for f in chain.from_iterable(list_[1] for list_ in self._files.lists()): f.close() # File-like and iterator interface. # # Expects self._stream to be set to an appropriate source of bytes by # a corresponding request subclass (e.g. WSGIRequest). # Also when request data has already been read by request.POST or # request.body, self._stream points to a BytesIO instance # containing that data. def read(self, *args, **kwargs): self._read_started = True try: return self._stream.read(*args, **kwargs) except OSError as e: raise UnreadablePostError(*e.args) from e def readline(self, *args, **kwargs): self._read_started = True try: return self._stream.readline(*args, **kwargs) except OSError as e: raise UnreadablePostError(*e.args) from e def __iter__(self): return iter(self.readline, b"") def readlines(self): return list(self) class HttpHeaders(CaseInsensitiveMapping): HTTP_PREFIX = "HTTP_" # PEP 333 gives two headers which aren't prepended with HTTP_. UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"} def __init__(self, environ): headers = {} for header, value in environ.items(): name = self.parse_header_name(header) if name: headers[name] = value super().__init__(headers) def __getitem__(self, key): """Allow header lookup using underscores in place of hyphens.""" return super().__getitem__(key.replace("_", "-")) @classmethod def parse_header_name(cls, header): if header.startswith(cls.HTTP_PREFIX): header = header[len(cls.HTTP_PREFIX) :] elif header not in cls.UNPREFIXED_HEADERS: return None return header.replace("_", "-").title() class QueryDict(MultiValueDict): """ A specialized MultiValueDict which represents a query string. A QueryDict can be used to represent GET or POST data. It subclasses MultiValueDict since keys in such data can be repeated, for instance in the data from a form with a <select multiple> field. By default QueryDicts are immutable, though the copy() method will always return a mutable copy. Both keys and values set on this class are converted from the given encoding (DEFAULT_CHARSET by default) to str. """ # These are both reset in __init__, but is specified here at the class # level so that unpickling will have valid values _mutable = True _encoding = None def __init__(self, query_string=None, mutable=False, encoding=None): super().__init__() self.encoding = encoding or settings.DEFAULT_CHARSET query_string = query_string or "" parse_qsl_kwargs = { "keep_blank_values": True, "encoding": self.encoding, "max_num_fields": settings.DATA_UPLOAD_MAX_NUMBER_FIELDS, } if isinstance(query_string, bytes): # query_string normally contains URL-encoded data, a subset of ASCII. try: query_string = query_string.decode(self.encoding) except UnicodeDecodeError: # ... but some user agents are misbehaving :-( query_string = query_string.decode("iso-8859-1") try: for key, value in parse_qsl(query_string, **parse_qsl_kwargs): self.appendlist(key, value) except ValueError as e: # ValueError can also be raised if the strict_parsing argument to # parse_qsl() is True. As that is not used by Django, assume that # the exception was raised by exceeding the value of max_num_fields # instead of fragile checks of exception message strings. raise TooManyFieldsSent( "The number of GET/POST parameters exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS." ) from e self._mutable = mutable @classmethod def fromkeys(cls, iterable, value="", mutable=False, encoding=None): """ Return a new QueryDict with keys (may be repeated) from an iterable and values from value. """ q = cls("", mutable=True, encoding=encoding) for key in iterable: q.appendlist(key, value) if not mutable: q._mutable = False return q @property def encoding(self): if self._encoding is None: self._encoding = settings.DEFAULT_CHARSET return self._encoding @encoding.setter def encoding(self, value): self._encoding = value def _assert_mutable(self): if not self._mutable: raise AttributeError("This QueryDict instance is immutable") def __setitem__(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) super().__setitem__(key, value) def __delitem__(self, key): self._assert_mutable() super().__delitem__(key) def __copy__(self): result = self.__class__("", mutable=True, encoding=self.encoding) for key, value in self.lists(): result.setlist(key, value) return result def __deepcopy__(self, memo): result = self.__class__("", mutable=True, encoding=self.encoding) memo[id(self)] = result for key, value in self.lists(): result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def setlist(self, key, list_): self._assert_mutable() key = bytes_to_text(key, self.encoding) list_ = [bytes_to_text(elt, self.encoding) for elt in list_] super().setlist(key, list_) def setlistdefault(self, key, default_list=None): self._assert_mutable() return super().setlistdefault(key, default_list) def appendlist(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) super().appendlist(key, value) def pop(self, key, *args): self._assert_mutable() return super().pop(key, *args) def popitem(self): self._assert_mutable() return super().popitem() def clear(self): self._assert_mutable() super().clear() def setdefault(self, key, default=None): self._assert_mutable() key = bytes_to_text(key, self.encoding) default = bytes_to_text(default, self.encoding) return super().setdefault(key, default) def copy(self): """Return a mutable copy of this object.""" return self.__deepcopy__({}) def urlencode(self, safe=None): """ Return an encoded string of all query string arguments. `safe` specifies characters which don't require quoting, for example:: >>> q = QueryDict(mutable=True) >>> q['next'] = '/a&b/' >>> q.urlencode() 'next=%2Fa%26b%2F' >>> q.urlencode(safe='/') 'next=/a%26b/' """ output = [] if safe: safe = safe.encode(self.encoding) def encode(k, v): return "%s=%s" % ((quote(k, safe), quote(v, safe))) else: def encode(k, v): return urlencode({k: v}) for k, list_ in self.lists(): output.extend( encode(k.encode(self.encoding), str(v).encode(self.encoding)) for v in list_ ) return "&".join(output) class MediaType: def __init__(self, media_type_raw_line): full_type, self.params = parse_header_parameters( media_type_raw_line if media_type_raw_line else "" ) self.main_type, _, self.sub_type = full_type.partition("/") def __str__(self): params_str = "".join("; %s=%s" % (k, v) for k, v in self.params.items()) return "%s%s%s" % ( self.main_type, ("/%s" % self.sub_type) if self.sub_type else "", params_str, ) def __repr__(self): return "<%s: %s>" % (self.__class__.__qualname__, self) @property def is_all_types(self): return self.main_type == "*" and self.sub_type == "*" def match(self, other): if self.is_all_types: return True other = MediaType(other) if self.main_type == other.main_type and self.sub_type in {"*", other.sub_type}: return True return False # It's neither necessary nor appropriate to use # django.utils.encoding.force_str() for parsing URLs and form inputs. Thus, # this slightly more restricted function, used by QueryDict. def bytes_to_text(s, encoding): """ Convert bytes objects to strings, using the given encoding. Illegally encoded input characters are replaced with Unicode "unknown" codepoint (\ufffd). Return any non-bytes objects without change. """ if isinstance(s, bytes): return str(s, encoding, "replace") else: return s def split_domain_port(host): """ Return a (domain, port) tuple from a given host. Returned domain is lowercased. If the host is invalid, the domain will be empty. """ host = host.lower() if not host_validation_re.match(host): return "", "" if host[-1] == "]": # It's an IPv6 address without a port. return host, "" bits = host.rsplit(":", 1) domain, port = bits if len(bits) == 2 else (bits[0], "") # Remove a trailing dot (if present) from the domain. domain = domain[:-1] if domain.endswith(".") else domain return domain, port def validate_host(host, allowed_hosts): """ Validate the given host for this site. Check that the host looks valid and matches a host or host pattern in the given list of ``allowed_hosts``. Any pattern beginning with a period matches a domain and all its subdomains (e.g. ``.example.com`` matches ``example.com`` and any subdomain), ``*`` matches anything, and anything else must match exactly. Note: This function assumes that the given host is lowercased and has already had the port, if any, stripped off. Return ``True`` for a valid host, ``False`` otherwise. """ return any( pattern == "*" or is_same_domain(host, pattern) for pattern in allowed_hosts ) def parse_accept_header(header): return [MediaType(token) for token in header.split(",") if token.strip()]
44a2fa7b16280ffc65e7b287aeb43530cf6537bc748946524487adb1a2b0c26b
"""Translation helper functions.""" import functools import gettext as gettext_module import os import re import sys import warnings from asgiref.local import Local from django.apps import apps from django.conf import settings from django.conf.locale import LANG_INFO from django.core.exceptions import AppRegistryNotReady from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, mark_safe from . import to_language, to_locale # Translations are cached in a dictionary for every language. # The active translations are stored by threadid to make them thread local. _translations = {} _active = Local() # The default translation is based on the settings file. _default = None # magic gettext number to separate context from message CONTEXT_SEPARATOR = "\x04" # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9 # and RFC 3066, section 2.1 accept_language_re = _lazy_re_compile( r""" # "en", "en-au", "x-y-z", "es-419", "*" ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # Optional "q=1.00", "q=0.8" (?:\s*;\s*q=(0(?:\.[0-9]{,3})?|1(?:\.0{,3})?))? # Multiple accepts per header. (?:\s*,\s*|$) """, re.VERBOSE, ) language_code_re = _lazy_re_compile( r"^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$", re.IGNORECASE ) language_code_prefix_re = _lazy_re_compile(r"^/(\w+([@-]\w+){0,2})(/|$)") @receiver(setting_changed) def reset_cache(*, setting, **kwargs): """ Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted. """ if setting in ("LANGUAGES", "LANGUAGE_CODE"): check_for_language.cache_clear() get_languages.cache_clear() get_supported_language_variant.cache_clear() class TranslationCatalog: """ Simulate a dict for DjangoTranslation._catalog so as multiple catalogs with different plural equations are kept separate. """ def __init__(self, trans=None): self._catalogs = [trans._catalog.copy()] if trans else [{}] self._plurals = [trans.plural] if trans else [lambda n: int(n != 1)] def __getitem__(self, key): for cat in self._catalogs: try: return cat[key] except KeyError: pass raise KeyError(key) def __setitem__(self, key, value): self._catalogs[0][key] = value def __contains__(self, key): return any(key in cat for cat in self._catalogs) def items(self): for cat in self._catalogs: yield from cat.items() def keys(self): for cat in self._catalogs: yield from cat.keys() def update(self, trans): # Merge if plural function is the same, else prepend. for cat, plural in zip(self._catalogs, self._plurals): if trans.plural.__code__ == plural.__code__: cat.update(trans._catalog) break else: self._catalogs.insert(0, trans._catalog.copy()) self._plurals.insert(0, trans.plural) def get(self, key, default=None): missing = object() for cat in self._catalogs: result = cat.get(key, missing) if result is not missing: return result return default def plural(self, msgid, num): for cat, plural in zip(self._catalogs, self._plurals): tmsg = cat.get((msgid, plural(num))) if tmsg is not None: return tmsg raise KeyError class DjangoTranslation(gettext_module.GNUTranslations): """ Set up the GNUTranslations context with regard to output charset. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct an object for the requested language and add a fallback to the default language, if it's different from the requested language. """ domain = "django" def __init__(self, language, domain=None, localedirs=None): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) if domain is not None: self.domain = domain self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self._catalog = None # If a language doesn't have a catalog, use the Germanic default for # pluralization: anything except one is pluralized. self.plural = lambda n: int(n != 1) if self.domain == "django": if localedirs is not None: # A module-level cache is used for caching 'django' translations warnings.warn( "localedirs is ignored when domain is 'django'.", RuntimeWarning ) localedirs = None self._init_translation_catalog() if localedirs: for localedir in localedirs: translation = self._new_gnu_trans(localedir) self.merge(translation) else: self._add_installed_apps_translations() self._add_local_translations() if ( self.__language == settings.LANGUAGE_CODE and self.domain == "django" and self._catalog is None ): # default lang should have at least one translation file available. raise OSError( "No translation files found for default language %s." % settings.LANGUAGE_CODE ) self._add_fallback(localedirs) if self._catalog is None: # No catalogs found for this language, set an empty catalog. self._catalog = TranslationCatalog() def __repr__(self): return "<DjangoTranslation lang:%s>" % self.__language def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ return gettext_module.translation( domain=self.domain, localedir=localedir, languages=[self.__locale], fallback=use_null_fallback, ) def _init_translation_catalog(self): """Create a base catalog using global django translations.""" settingsfile = sys.modules[settings.__module__].__file__ localedir = os.path.join(os.path.dirname(settingsfile), "locale") translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_installed_apps_translations(self): """Merge translations from each installed app.""" try: app_configs = reversed(apps.get_app_configs()) except AppRegistryNotReady: raise AppRegistryNotReady( "The translation infrastructure cannot be initialized before the " "apps registry is ready. Check that you don't make non-lazy " "gettext calls at import time." ) for app_config in app_configs: localedir = os.path.join(app_config.path, "locale") if os.path.exists(localedir): translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_local_translations(self): """Merge translations defined in LOCALE_PATHS.""" for localedir in reversed(settings.LOCALE_PATHS): translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_fallback(self, localedirs=None): """Set the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or any English variant # (as it's empty, so it'll ALWAYS fall back to the default language) if self.__language == settings.LANGUAGE_CODE or self.__language.startswith( "en" ): return if self.domain == "django": # Get from cache default_translation = translation(settings.LANGUAGE_CODE) else: default_translation = DjangoTranslation( settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs ) self.add_fallback(default_translation) def merge(self, other): """Merge another translation into this catalog.""" if not getattr(other, "_catalog", None): return # NullTranslations() has no _catalog if self._catalog is None: # Take plural and _info from first catalog found (generally Django's). self.plural = other.plural self._info = other._info.copy() self._catalog = TranslationCatalog(other) else: self._catalog.update(other) if other._fallback: self.add_fallback(other._fallback) def language(self): """Return the translation language.""" return self.__language def to_language(self): """Return the translation language name.""" return self.__to_language def ngettext(self, msgid1, msgid2, n): try: tmsg = self._catalog.plural(msgid1, n) except KeyError: if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 return tmsg def translation(language): """ Return a translation object in the default 'django' domain. """ global _translations if language not in _translations: _translations[language] = DjangoTranslation(language) return _translations[language] def activate(language): """ Fetch the translation object for a given language and install it as the current translation object for the current thread. """ if not language: return _active.value = translation(language) def deactivate(): """ Uninstall the active translation object so that further _() calls resolve to the default translation object. """ if hasattr(_active, "value"): del _active.value def deactivate_all(): """ Make the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """ _active.value = gettext_module.NullTranslations() _active.value.to_language = lambda *args: None def get_language(): """Return the currently selected language.""" t = getattr(_active, "value", None) if t is not None: try: return t.to_language() except AttributeError: pass # If we don't have a real translation object, assume it's the default language. return settings.LANGUAGE_CODE def get_language_bidi(): """ Return selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout """ lang = get_language() if lang is None: return False else: base_lang = get_language().split("-")[0] return base_lang in settings.LANGUAGES_BIDI def catalog(): """ Return the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default t = getattr(_active, "value", None) if t is not None: return t if _default is None: _default = translation(settings.LANGUAGE_CODE) return _default def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace("\r\n", "\n").replace("\r", "\n") if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") if isinstance(message, SafeData): return mark_safe(result) return result def pgettext(context, message): msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message elif isinstance(message, SafeData): result = mark_safe(result) return result def gettext_noop(message): """ Mark strings for translation but don't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message def do_ntranslate(singular, plural, number, translation_function): global _default t = getattr(_active, "value", None) if t is not None: return getattr(t, translation_function)(singular, plural, number) if _default is None: _default = translation(settings.LANGUAGE_CODE) return getattr(_default, translation_function)(singular, plural, number) def ngettext(singular, plural, number): """ Return a string of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, "ngettext") def npgettext(context, singular, plural, number): msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, singular), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural), number, ) result = ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = ngettext(singular, plural, number) return result def all_locale_paths(): """ Return a list of paths to user-provides languages files. """ globalpath = os.path.join( os.path.dirname(sys.modules[settings.__module__].__file__), "locale" ) app_paths = [] for app_config in apps.get_app_configs(): locale_path = os.path.join(app_config.path, "locale") if os.path.exists(locale_path): app_paths.append(locale_path) return [globalpath, *settings.LOCALE_PATHS, *app_paths] @functools.lru_cache(maxsize=1000) def check_for_language(lang_code): """ Check whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ # First, a quick check to make sure lang_code is well-formed (#21458) if lang_code is None or not language_code_re.search(lang_code): return False return any( gettext_module.find("django", path, [to_locale(lang_code)]) is not None for path in all_locale_paths() ) @functools.lru_cache def get_languages(): """ Cache of settings.LANGUAGES in a dictionary for easy lookups by key. Convert keys to lowercase as they should be treated as case-insensitive. """ return {key.lower(): value for key, value in dict(settings.LANGUAGES).items()} @functools.lru_cache(maxsize=1000) def get_supported_language_variant(lang_code, strict=False): """ Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ if lang_code: # If 'zh-hant-tw' is not supported, try special fallback or subsequent # language codes i.e. 'zh-hant' and 'zh'. possible_lang_codes = [lang_code] try: possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"]) except KeyError: pass i = None while (i := lang_code.rfind("-", 0, i)) > -1: possible_lang_codes.append(lang_code[:i]) generic_lang_code = possible_lang_codes[-1] supported_lang_codes = get_languages() for code in possible_lang_codes: if code.lower() in supported_lang_codes and check_for_language(code): return code if not strict: # if fr-fr is not supported, try fr-ca. for supported_code in supported_lang_codes: if supported_code.startswith(generic_lang_code + "-"): return supported_code raise LookupError(lang_code) def get_language_from_path(path, strict=False): """ Return the language code if there's a valid language code found in `path`. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. """ regex_match = language_code_prefix_re.match(path) if not regex_match: return None lang_code = regex_match[1] try: return get_supported_language_variant(lang_code, strict=strict) except LookupError: return None def get_language_from_request(request, check_path=False): """ Analyze the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility. """ if check_path: lang_code = get_language_from_path(request.path_info) if lang_code is not None: return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if ( lang_code is not None and lang_code in get_languages() and check_for_language(lang_code) ): return lang_code try: return get_supported_language_variant(lang_code) except LookupError: pass accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "") for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == "*": break if not language_code_re.search(accept_lang): continue try: return get_supported_language_variant(accept_lang) except LookupError: continue try: return get_supported_language_variant(settings.LANGUAGE_CODE) except LookupError: return settings.LANGUAGE_CODE @functools.lru_cache(maxsize=1000) def parse_accept_lang_header(lang_string): """ Parse the lang_string, which is the body of an HTTP Accept-Language header, and return a tuple of (lang, q-value), ordered by 'q' values. Return an empty tuple if there are any format errors in lang_string. """ result = [] pieces = accept_language_re.split(lang_string.lower()) if pieces[-1]: return () for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i : i + 3] if first: return () if priority: priority = float(priority) else: priority = 1.0 result.append((lang, priority)) result.sort(key=lambda k: k[1], reverse=True) return tuple(result)
9e2cbf8359f3b52d9b3ec20da8aeff8341dca48ff0ea12fe73cfe1aa90bb53bb
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. from django.conf import settings def gettext(message): return message gettext_noop = gettext_lazy = _ = gettext def ngettext(singular, plural, number): if number == 1: return singular return plural ngettext_lazy = ngettext def pgettext(context, message): return gettext(message) def npgettext(context, singular, plural, number): return ngettext(singular, plural, number) def activate(x): return None def deactivate(): return None deactivate_all = deactivate def get_language(): return settings.LANGUAGE_CODE def get_language_bidi(): return settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI def check_for_language(x): return True def get_language_from_request(request, check_path=False): return settings.LANGUAGE_CODE def get_language_from_path(request): return None def get_supported_language_variant(lang_code, strict=False): if lang_code and lang_code.lower() == settings.LANGUAGE_CODE.lower(): return lang_code else: raise LookupError(lang_code)
06b20cfb0328d01c35a4918ebcdafd6752a0aefff3ac88939900a627f1fed50d
import functools import re from collections import defaultdict from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db.migrations.operations.models import AlterModelOptions from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.utils import ( COMPILED_REGEX_TYPE, RegexObject, resolve_relation, ) from django.utils.topological_sort import stable_topological_sort class MigrationAutodetector: """ Take a pair of ProjectStates and compare them to see what the first would need doing to make it match the second (the second usually being the project's current state). Note that this naturally operates on entire projects at a time, as it's likely that changes interact (for example, you can't add a ForeignKey without having a migration to add the table it depends on first). A user interface may offer single-app usage if it wishes, with the caveat that it may not always be possible. """ def __init__(self, from_state, to_state, questioner=None): self.from_state = from_state self.to_state = to_state self.questioner = questioner or MigrationQuestioner() self.existing_apps = {app for app, model in from_state.models} def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None): """ Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed) """ changes = self._detect_changes(convert_apps, graph) changes = self.arrange_for_graph(changes, graph, migration_name) if trim_to_apps: changes = self._trim_to_apps(changes, trim_to_apps) return changes def deep_deconstruct(self, obj): """ Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly. """ if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) elif isinstance(obj, dict): return {key: self.deep_deconstruct(value) for key, value in obj.items()} elif isinstance(obj, functools.partial): return ( obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords), ) elif isinstance(obj, COMPILED_REGEX_TYPE): return RegexObject(obj) elif isinstance(obj, type): # If this is a type that implements 'deconstruct' as an instance method, # avoid treating this as being deconstructible itself - see #22951 return obj elif hasattr(obj, "deconstruct"): deconstructed = obj.deconstruct() if isinstance(obj, models.Field): # we have a field which also returns a name deconstructed = deconstructed[1:] path, args, kwargs = deconstructed return ( path, [self.deep_deconstruct(value) for value in args], {key: self.deep_deconstruct(value) for key, value in kwargs.items()}, ) else: return obj def only_relation_agnostic_fields(self, fields): """ Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as the related fields change during renames). """ fields_def = [] for name, field in sorted(fields.items()): deconstruction = self.deep_deconstruct(field) if field.remote_field and field.remote_field.model: deconstruction[2].pop("to", None) fields_def.append(deconstruction) return fields_def def _detect_changes(self, convert_apps=None, graph=None): """ Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the names do matter for dependencies inside the set. convert_apps is the list of apps to convert to use migrations (i.e. to make initial migrations for, in the usual case) graph is an optional argument that, if provided, can help improve dependency generation and avoid potential circular dependencies. """ # The first phase is generating all the operations for each app # and gathering them into a big per-app list. # Then go through that list, order it, and split into migrations to # resolve dependencies caused by M2Ms and FKs. self.generated_operations = {} self.altered_indexes = {} self.altered_constraints = {} self.renamed_fields = {} # Prepare some old/new state and model lists, separating # proxy models and ignoring unmigrated apps. self.old_model_keys = set() self.old_proxy_keys = set() self.old_unmanaged_keys = set() self.new_model_keys = set() self.new_proxy_keys = set() self.new_unmanaged_keys = set() for (app_label, model_name), model_state in self.from_state.models.items(): if not model_state.options.get("managed", True): self.old_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps: if model_state.options.get("proxy"): self.old_proxy_keys.add((app_label, model_name)) else: self.old_model_keys.add((app_label, model_name)) for (app_label, model_name), model_state in self.to_state.models.items(): if not model_state.options.get("managed", True): self.new_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps or ( convert_apps and app_label in convert_apps ): if model_state.options.get("proxy"): self.new_proxy_keys.add((app_label, model_name)) else: self.new_model_keys.add((app_label, model_name)) self.from_state.resolve_fields_and_relations() self.to_state.resolve_fields_and_relations() # Renames have to come first self.generate_renamed_models() # Prepare lists of fields and generate through model map self._prepare_field_lists() self._generate_through_model_map() # Generate non-rename model operations self.generate_deleted_models() self.generate_created_models() self.generate_deleted_proxies() self.generate_created_proxies() self.generate_altered_options() self.generate_altered_managers() # Create the renamed fields and store them in self.renamed_fields. # They are used by create_altered_indexes(), generate_altered_fields(), # generate_removed_altered_index/unique_together(), and # generate_altered_index/unique_together(). self.create_renamed_fields() # Create the altered indexes and store them in self.altered_indexes. # This avoids the same computation in generate_removed_indexes() # and generate_added_indexes(). self.create_altered_indexes() self.create_altered_constraints() # Generate index removal operations before field is removed self.generate_removed_constraints() self.generate_removed_indexes() # Generate field renaming operations. self.generate_renamed_fields() self.generate_renamed_indexes() # Generate removal of foo together. self.generate_removed_altered_unique_together() self.generate_removed_altered_index_together() # Generate field operations. self.generate_removed_fields() self.generate_added_fields() self.generate_altered_fields() self.generate_altered_order_with_respect_to() self.generate_altered_unique_together() self.generate_altered_index_together() self.generate_added_indexes() self.generate_added_constraints() self.generate_altered_db_table() self._sort_migrations() self._build_migration_list(graph) self._optimize_migrations() return self.migrations def _prepare_field_lists(self): """ Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it. """ self.kept_model_keys = self.old_model_keys & self.new_model_keys self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys self.through_users = {} self.old_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.from_state.models[ app_label, self.renamed_models.get((app_label, model_name), model_name) ].fields } self.new_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.to_state.models[app_label, model_name].fields } def _generate_through_model_map(self): """Through model map generation.""" for app_label, model_name in sorted(self.old_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] for field_name, field in old_model_state.fields.items(): if hasattr(field, "remote_field") and getattr( field.remote_field, "through", None ): through_key = resolve_relation( field.remote_field.through, app_label, model_name ) self.through_users[through_key] = ( app_label, old_model_name, field_name, ) @staticmethod def _resolve_dependency(dependency): """ Return the resolved dependency and a boolean denoting whether or not it was swappable. """ if dependency[0] != "__setting__": return dependency, False resolved_app_label, resolved_object_name = getattr( settings, dependency[1] ).split(".") return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True def _build_migration_list(self, graph=None): """ Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off the operations before it into a migration and move onto the next app. If the loops completes without doing anything, there's a circular dependency (which _should_ be impossible as the operations are all split at this point so they can't depend and be depended on). """ self.migrations = {} num_ops = sum(len(x) for x in self.generated_operations.values()) chop_mode = False while num_ops: # On every iteration, we step through all the apps and see if there # is a completed set of operations. # If we find that a subset of the operations are complete we can # try to chop it off from the rest and continue, but we only # do this if we've already been through the list once before # without any chopping and nothing has changed. for app_label in sorted(self.generated_operations): chopped = [] dependencies = set() for operation in list(self.generated_operations[app_label]): deps_satisfied = True operation_dependencies = set() for dep in operation._auto_deps: # Temporarily resolve the swappable dependency to # prevent circular references. While keeping the # dependency checks on the resolved model, add the # swappable dependencies. original_dep = dep dep, is_swappable_dep = self._resolve_dependency(dep) if dep[0] != app_label: # External app dependency. See if it's not yet # satisfied. for other_operation in self.generated_operations.get( dep[0], [] ): if self.check_dependency(other_operation, dep): deps_satisfied = False break if not deps_satisfied: break else: if is_swappable_dep: operation_dependencies.add( (original_dep[0], original_dep[1]) ) elif dep[0] in self.migrations: operation_dependencies.add( (dep[0], self.migrations[dep[0]][-1].name) ) else: # If we can't find the other app, we add a # first/last dependency, but only if we've # already been through once and checked # everything. if chop_mode: # If the app already exists, we add a # dependency on the last migration, as # we don't know which migration # contains the target field. If it's # not yet migrated or has no # migrations, we use __first__. if graph and graph.leaf_nodes(dep[0]): operation_dependencies.add( graph.leaf_nodes(dep[0])[0] ) else: operation_dependencies.add( (dep[0], "__first__") ) else: deps_satisfied = False if deps_satisfied: chopped.append(operation) dependencies.update(operation_dependencies) del self.generated_operations[app_label][0] else: break # Make a migration! Well, only if there's stuff to put in it if dependencies or chopped: if not self.generated_operations[app_label] or chop_mode: subclass = type( "Migration", (Migration,), {"operations": [], "dependencies": []}, ) instance = subclass( "auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label, ) instance.dependencies = list(dependencies) instance.operations = chopped instance.initial = app_label not in self.existing_apps self.migrations.setdefault(app_label, []).append(instance) chop_mode = False else: self.generated_operations[app_label] = ( chopped + self.generated_operations[app_label] ) new_num_ops = sum(len(x) for x in self.generated_operations.values()) if new_num_ops == num_ops: if not chop_mode: chop_mode = True else: raise ValueError( "Cannot resolve operation dependencies: %r" % self.generated_operations ) num_ops = new_num_ops def _sort_migrations(self): """ Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app. """ for app_label, ops in sorted(self.generated_operations.items()): # construct a dependency graph for intra-app dependencies dependency_graph = {op: set() for op in ops} for op in ops: for dep in op._auto_deps: # Resolve intra-app dependencies to handle circular # references involving a swappable model. dep = self._resolve_dependency(dep)[0] if dep[0] == app_label: for op2 in ops: if self.check_dependency(op2, dep): dependency_graph[op].add(op2) # we use a stable sort for deterministic tests & general behavior self.generated_operations[app_label] = stable_topological_sort( ops, dependency_graph ) def _optimize_migrations(self): # Add in internal dependencies among the migrations for app_label, migrations in self.migrations.items(): for m1, m2 in zip(migrations, migrations[1:]): m2.dependencies.append((app_label, m1.name)) # De-dupe dependencies for migrations in self.migrations.values(): for migration in migrations: migration.dependencies = list(set(migration.dependencies)) # Optimize migrations for app_label, migrations in self.migrations.items(): for migration in migrations: migration.operations = MigrationOptimizer().optimize( migration.operations, app_label ) def check_dependency(self, operation, dependency): """ Return True if the given operation depends on the given dependency, False otherwise. """ # Created model if dependency[2] is None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() ) # Created field elif dependency[2] is not None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() and any(dependency[2] == x for x, y in operation.fields) ) or ( isinstance(operation, operations.AddField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed field elif dependency[2] is not None and dependency[3] is False: return ( isinstance(operation, operations.RemoveField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed model elif dependency[2] is None and dependency[3] is False: return ( isinstance(operation, operations.DeleteModel) and operation.name_lower == dependency[1].lower() ) # Field being altered elif dependency[2] is not None and dependency[3] == "alter": return ( isinstance(operation, operations.AlterField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # order_with_respect_to being unset for a field elif dependency[2] is not None and dependency[3] == "order_wrt_unset": return ( isinstance(operation, operations.AlterOrderWithRespectTo) and operation.name_lower == dependency[1].lower() and (operation.order_with_respect_to or "").lower() != dependency[2].lower() ) # Field is removed and part of an index/unique_together elif dependency[2] is not None and dependency[3] == "foo_together_change": return ( isinstance( operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether), ) and operation.name_lower == dependency[1].lower() ) # Unknown dependency. Raise an error. else: raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): # Dependencies are # (app_label, model_name, field_name, create/delete as True/False) operation._auto_deps = dependencies or [] if beginning: self.generated_operations.setdefault(app_label, []).insert(0, operation) else: self.generated_operations.setdefault(app_label, []).append(operation) def swappable_first_key(self, item): """ Place potential swappable models first in lists of created models (only real way to solve #22783). """ try: model_state = self.to_state.models[item] base_names = { base if isinstance(base, str) else base.__name__ for base in model_state.bases } string_version = "%s.%s" % (item[0], item[1]) if ( model_state.options.get("swappable") or "AbstractUser" in base_names or "AbstractBaseUser" in base_names or settings.AUTH_USER_MODEL.lower() == string_version.lower() ): return ("___" + item[0], "___" + item[1]) except LookupError: pass return item def generate_renamed_models(self): """ Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation. """ self.renamed_models = {} self.renamed_models_rel = {} added_models = self.new_model_keys - self.old_model_keys for app_label, model_name in sorted(added_models): model_state = self.to_state.models[app_label, model_name] model_fields_def = self.only_relation_agnostic_fields(model_state.fields) removed_models = self.old_model_keys - self.new_model_keys for rem_app_label, rem_model_name in removed_models: if rem_app_label == app_label: rem_model_state = self.from_state.models[ rem_app_label, rem_model_name ] rem_model_fields_def = self.only_relation_agnostic_fields( rem_model_state.fields ) if model_fields_def == rem_model_fields_def: if self.questioner.ask_rename_model( rem_model_state, model_state ): dependencies = [] fields = list(model_state.fields.values()) + [ field.remote_field for relations in self.to_state.relations[ app_label, model_name ].values() for field in relations.values() ] for field in fields: if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) self.add_operation( app_label, operations.RenameModel( old_name=rem_model_state.name, new_name=model_state.name, ), dependencies=dependencies, ) self.renamed_models[app_label, model_name] = rem_model_name renamed_models_rel_key = "%s.%s" % ( rem_model_state.app_label, rem_model_state.name_lower, ) self.renamed_models_rel[ renamed_models_rel_key ] = "%s.%s" % ( model_state.app_label, model_state.name_lower, ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.add((app_label, model_name)) break def generate_created_models(self): """ Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options that refer to collections of fields that might be deferred (e.g. unique_together, index_together). """ old_keys = self.old_model_keys | self.old_unmanaged_keys added_models = self.new_model_keys - old_keys added_unmanaged_models = self.new_unmanaged_keys - old_keys all_added_models = chain( sorted(added_models, key=self.swappable_first_key, reverse=True), sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True), ) for app_label, model_name in all_added_models: model_state = self.to_state.models[app_label, model_name] # Gather related fields related_fields = {} primary_key_rel = None for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: if field.primary_key: primary_key_rel = field.remote_field.model elif not field.remote_field.parent_link: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Are there indexes/unique|index_together to defer? indexes = model_state.options.pop("indexes") constraints = model_state.options.pop("constraints") unique_together = model_state.options.pop("unique_together", None) index_together = model_state.options.pop("index_together", None) order_with_respect_to = model_state.options.pop( "order_with_respect_to", None ) # Depend on the deletion of any possible proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Depend on the removal of base fields if the new model has # a field with the same name. old_base_model_state = self.from_state.models.get( (base_app_label, base_name) ) new_base_model_state = self.to_state.models.get( (base_app_label, base_name) ) if old_base_model_state and new_base_model_state: removed_base_fields = ( set(old_base_model_state.fields) .difference( new_base_model_state.fields, ) .intersection(model_state.fields) ) for removed_base_field in removed_base_fields: dependencies.append( (base_app_label, base_name, removed_base_field, False) ) # Depend on the other end of the primary key if it's a relation if primary_key_rel: dependencies.append( resolve_relation( primary_key_rel, app_label, model_name, ) + (None, True) ) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[ d for d in model_state.fields.items() if d[0] not in related_fields ], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), dependencies=dependencies, beginning=True, ) # Don't add operations which modify the database for unmanaged models if not model_state.options.get("managed", True): continue # Generate operations for each related field for name, field in sorted(related_fields.items()): dependencies = self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) # Depend on our own model being created dependencies.append((app_label, model_name, None, True)) # Make operation self.add_operation( app_label, operations.AddField( model_name=model_name, name=name, field=field, ), dependencies=list(set(dependencies)), ) # Generate other opns if order_with_respect_to: self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=order_with_respect_to, ), dependencies=[ (app_label, model_name, order_with_respect_to, True), (app_label, model_name, None, True), ], ) related_dependencies = [ (app_label, model_name, name, True) for name in sorted(related_fields) ] related_dependencies.append((app_label, model_name, None, True)) for index in indexes: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=related_dependencies, ) for constraint in constraints: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=related_dependencies, ) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=unique_together, ), dependencies=related_dependencies, ) if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=index_together, ), dependencies=related_dependencies, ) # Fix relationships if the model changed from a proxy model to a # concrete model. relations = self.to_state.relations if (app_label, model_name) in self.old_proxy_keys: for related_model_key, related_fields in relations[ app_label, model_name ].items(): related_model_state = self.to_state.models[related_model_key] for related_field_name, related_field in related_fields.items(): self.add_operation( related_model_state.app_label, operations.AlterField( model_name=related_model_state.name, name=related_field_name, field=related_field, ), dependencies=[(app_label, model_name, None, True)], ) def generate_created_proxies(self): """ Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but for proxy models it's safe to skip all the pointless field stuff and chuck out an operation. """ added = self.new_proxy_keys - self.old_proxy_keys for app_label, model_name in sorted(added): model_state = self.to_state.models[app_label, model_name] assert model_state.options.get("proxy") # Depend on the deletion of any possible non-proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), # Depend on the deletion of any possible non-proxy version of us dependencies=dependencies, ) def generate_deleted_models(self): """ Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal of any model options that refer to collections of fields - the inverse of generate_created_models(). """ new_keys = self.new_model_keys | self.new_unmanaged_keys deleted_models = self.old_model_keys - new_keys deleted_unmanaged_models = self.old_unmanaged_keys - new_keys all_deleted_models = chain( sorted(deleted_models), sorted(deleted_unmanaged_models) ) for app_label, model_name in all_deleted_models: model_state = self.from_state.models[app_label, model_name] # Gather related fields related_fields = {} for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Generate option removal first unique_together = model_state.options.pop("unique_together", None) index_together = model_state.options.pop("index_together", None) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=None, ), ) if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=None, ), ) # Then remove each related field for name in sorted(related_fields): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=name, ), ) # Finally, remove the model. # This depends on both the removal/alteration of all incoming fields # and the removal of all its own related fields, and if it's # a through model the field that references it. dependencies = [] relations = self.from_state.relations for ( related_object_app_label, object_name, ), relation_related_fields in relations[app_label, model_name].items(): for field_name, field in relation_related_fields.items(): dependencies.append( (related_object_app_label, object_name, field_name, False), ) if not field.many_to_many: dependencies.append( ( related_object_app_label, object_name, field_name, "alter", ), ) for name in sorted(related_fields): dependencies.append((app_label, model_name, name, False)) # We're referenced in another field's through= through_user = self.through_users.get((app_label, model_state.name_lower)) if through_user: dependencies.append( (through_user[0], through_user[1], through_user[2], False) ) # Finally, make the operation, deduping any dependencies self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), dependencies=list(set(dependencies)), ) def generate_deleted_proxies(self): """Make DeleteModel options for proxy models.""" deleted = self.old_proxy_keys - self.new_proxy_keys for app_label, model_name in sorted(deleted): model_state = self.from_state.models[app_label, model_name] assert model_state.options.get("proxy") self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), ) def create_renamed_fields(self): """Work out renamed fields.""" self.renamed_operations = [] old_field_keys = self.old_field_keys.copy() for app_label, model_name, field_name in sorted( self.new_field_keys - old_field_keys ): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] field = new_model_state.get_field(field_name) # Scan to see if this is actually a rename! field_dec = self.deep_deconstruct(field) for rem_app_label, rem_model_name, rem_field_name in sorted( old_field_keys - self.new_field_keys ): if rem_app_label == app_label and rem_model_name == model_name: old_field = old_model_state.get_field(rem_field_name) old_field_dec = self.deep_deconstruct(old_field) if ( field.remote_field and field.remote_field.model and "to" in old_field_dec[2] ): old_rel_to = old_field_dec[2]["to"] if old_rel_to in self.renamed_models_rel: old_field_dec[2]["to"] = self.renamed_models_rel[old_rel_to] old_field.set_attributes_from_name(rem_field_name) old_db_column = old_field.get_attname_column()[1] if old_field_dec == field_dec or ( # Was the field renamed and db_column equal to the # old field's column added? old_field_dec[0:2] == field_dec[0:2] and dict(old_field_dec[2], db_column=old_db_column) == field_dec[2] ): if self.questioner.ask_rename( model_name, rem_field_name, field_name, field ): self.renamed_operations.append( ( rem_app_label, rem_model_name, old_field.db_column, rem_field_name, app_label, model_name, field, field_name, ) ) old_field_keys.remove( (rem_app_label, rem_model_name, rem_field_name) ) old_field_keys.add((app_label, model_name, field_name)) self.renamed_fields[ app_label, model_name, field_name ] = rem_field_name break def generate_renamed_fields(self): """Generate RenameField operations.""" for ( rem_app_label, rem_model_name, rem_db_column, rem_field_name, app_label, model_name, field, field_name, ) in self.renamed_operations: # A db_column mismatch requires a prior noop AlterField for the # subsequent RenameField to be a noop on attempts at preserving the # old name. if rem_db_column != field.db_column: altered_field = field.clone() altered_field.name = rem_field_name self.add_operation( app_label, operations.AlterField( model_name=model_name, name=rem_field_name, field=altered_field, ), ) self.add_operation( app_label, operations.RenameField( model_name=model_name, old_name=rem_field_name, new_name=field_name, ), ) self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name)) self.old_field_keys.add((app_label, model_name, field_name)) def generate_added_fields(self): """Make AddField operations.""" for app_label, model_name, field_name in sorted( self.new_field_keys - self.old_field_keys ): self._generate_added_field(app_label, model_name, field_name) def _generate_added_field(self, app_label, model_name, field_name): field = self.to_state.models[app_label, model_name].get_field(field_name) # Adding a field always depends at least on its removal. dependencies = [(app_label, model_name, field_name, False)] # Fields that are foreignkeys/m2ms depend on stuff. if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) # You can't just add NOT NULL fields with no default or fields # which don't allow empty strings as default. time_fields = (models.DateField, models.DateTimeField, models.TimeField) preserve_default = ( field.null or field.has_default() or field.many_to_many or (field.blank and field.empty_strings_allowed) or (isinstance(field, time_fields) and field.auto_now) ) if not preserve_default: field = field.clone() if isinstance(field, time_fields) and field.auto_now_add: field.default = self.questioner.ask_auto_now_add_addition( field_name, model_name ) else: field.default = self.questioner.ask_not_null_addition( field_name, model_name ) if ( field.unique and field.default is not models.NOT_PROVIDED and callable(field.default) ): self.questioner.ask_unique_callable_default_addition(field_name, model_name) self.add_operation( app_label, operations.AddField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) def generate_removed_fields(self): """Make RemoveField operations.""" for app_label, model_name, field_name in sorted( self.old_field_keys - self.new_field_keys ): self._generate_removed_field(app_label, model_name, field_name) def _generate_removed_field(self, app_label, model_name, field_name): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=field_name, ), # We might need to depend on the removal of an # order_with_respect_to or index/unique_together operation; # this is safely ignored if there isn't one dependencies=[ (app_label, model_name, field_name, "order_wrt_unset"), (app_label, model_name, field_name, "foo_together_change"), ], ) def generate_altered_fields(self): """ Make AlterField operations, or possibly RemovedField/AddField if alter isn't possible. """ for app_label, model_name, field_name in sorted( self.old_field_keys & self.new_field_keys ): # Did the field change? old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_field_name = self.renamed_fields.get( (app_label, model_name, field_name), field_name ) old_field = self.from_state.models[app_label, old_model_name].get_field( old_field_name ) new_field = self.to_state.models[app_label, model_name].get_field( field_name ) dependencies = [] # Implement any model renames on relations; these are handled by RenameModel # so we need to exclude them from the comparison if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "model", None ): rename_key = resolve_relation( new_field.remote_field.model, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.model = old_field.remote_field.model # Handle ForeignKey which can only have a single to_field. remote_field_name = getattr(new_field.remote_field, "field_name", None) if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: # Repoint both model and field name because to_field # inclusion in ForeignKey.deconstruct() is based on # both. new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = ( old_field.remote_field.field_name ) # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, "from_fields", None) if from_fields: from_rename_key = (app_label, model_name) new_field.from_fields = tuple( [ self.renamed_fields.get( from_rename_key + (from_field,), from_field ) for from_field in from_fields ] ) new_field.to_fields = tuple( [ self.renamed_fields.get(rename_key + (to_field,), to_field) for to_field in new_field.to_fields ] ) dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, new_field, self.to_state, ) ) if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "through", None ): rename_key = resolve_relation( new_field.remote_field.through, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.through = old_field.remote_field.through old_field_dec = self.deep_deconstruct(old_field) new_field_dec = self.deep_deconstruct(new_field) # If the field was confirmed to be renamed it means that only # db_column was allowed to change which generate_renamed_fields() # already accounts for by adding an AlterField operation. if old_field_dec != new_field_dec and old_field_name == field_name: both_m2m = old_field.many_to_many and new_field.many_to_many neither_m2m = not old_field.many_to_many and not new_field.many_to_many if both_m2m or neither_m2m: # Either both fields are m2m or neither is preserve_default = True if ( old_field.null and not new_field.null and not new_field.has_default() and not new_field.many_to_many ): field = new_field.clone() new_default = self.questioner.ask_not_null_alteration( field_name, model_name ) if new_default is not models.NOT_PROVIDED: field.default = new_default preserve_default = False else: field = new_field self.add_operation( app_label, operations.AlterField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) else: # We cannot alter between m2m and concrete fields self._generate_removed_field(app_label, model_name, field_name) self._generate_added_field(app_label, model_name, field_name) def create_altered_indexes(self): option_name = operations.AddIndex.option_name self.renamed_index_together_values = defaultdict(list) for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_indexes = old_model_state.options[option_name] new_indexes = new_model_state.options[option_name] added_indexes = [idx for idx in new_indexes if idx not in old_indexes] removed_indexes = [idx for idx in old_indexes if idx not in new_indexes] renamed_indexes = [] # Find renamed indexes. remove_from_added = [] remove_from_removed = [] for new_index in added_indexes: new_index_dec = new_index.deconstruct() new_index_name = new_index_dec[2].pop("name") for old_index in removed_indexes: old_index_dec = old_index.deconstruct() old_index_name = old_index_dec[2].pop("name") # Indexes are the same except for the names. if ( new_index_dec == old_index_dec and new_index_name != old_index_name ): renamed_indexes.append((old_index_name, new_index_name, None)) remove_from_added.append(new_index) remove_from_removed.append(old_index) # Find index_together changed to indexes. for ( old_value, new_value, index_together_app_label, index_together_model_name, dependencies, ) in self._get_altered_foo_together_operations( operations.AlterIndexTogether.option_name ): if ( app_label != index_together_app_label or model_name != index_together_model_name ): continue removed_values = old_value.difference(new_value) for removed_index_together in removed_values: renamed_index_together_indexes = [] for new_index in added_indexes: _, args, kwargs = new_index.deconstruct() # Ensure only 'fields' are defined in the Index. if ( not args and new_index.fields == list(removed_index_together) and set(kwargs) == {"name", "fields"} ): renamed_index_together_indexes.append(new_index) if len(renamed_index_together_indexes) == 1: renamed_index = renamed_index_together_indexes[0] remove_from_added.append(renamed_index) renamed_indexes.append( (None, renamed_index.name, removed_index_together) ) self.renamed_index_together_values[ index_together_app_label, index_together_model_name ].append(removed_index_together) # Remove renamed indexes from the lists of added and removed # indexes. added_indexes = [ idx for idx in added_indexes if idx not in remove_from_added ] removed_indexes = [ idx for idx in removed_indexes if idx not in remove_from_removed ] self.altered_indexes.update( { (app_label, model_name): { "added_indexes": added_indexes, "removed_indexes": removed_indexes, "renamed_indexes": renamed_indexes, } } ) def generate_added_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes["added_indexes"]: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), ) def generate_removed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes["removed_indexes"]: self.add_operation( app_label, operations.RemoveIndex( model_name=model_name, name=index.name, ), ) def generate_renamed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for old_index_name, new_index_name, old_fields in alt_indexes[ "renamed_indexes" ]: self.add_operation( app_label, operations.RenameIndex( model_name=model_name, new_name=new_index_name, old_name=old_index_name, old_fields=old_fields, ), ) def create_altered_constraints(self): option_name = operations.AddConstraint.option_name for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_constraints = old_model_state.options[option_name] new_constraints = new_model_state.options[option_name] add_constraints = [c for c in new_constraints if c not in old_constraints] rem_constraints = [c for c in old_constraints if c not in new_constraints] self.altered_constraints.update( { (app_label, model_name): { "added_constraints": add_constraints, "removed_constraints": rem_constraints, } } ) def generate_added_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints["added_constraints"]: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), ) def generate_removed_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints["removed_constraints"]: self.add_operation( app_label, operations.RemoveConstraint( model_name=model_name, name=constraint.name, ), ) @staticmethod def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state): remote_field_model = None if hasattr(field.remote_field, "model"): remote_field_model = field.remote_field.model else: relations = project_state.relations[app_label, model_name] for (remote_app_label, remote_model_name), fields in relations.items(): if any( field == related_field.remote_field for related_field in fields.values() ): remote_field_model = f"{remote_app_label}.{remote_model_name}" break # Account for FKs to swappable models swappable_setting = getattr(field, "swappable_setting", None) if swappable_setting is not None: dep_app_label = "__setting__" dep_object_name = swappable_setting else: dep_app_label, dep_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies = [(dep_app_label, dep_object_name, None, True)] if getattr(field.remote_field, "through", None): through_app_label, through_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies.append((through_app_label, through_object_name, None, True)) return dependencies def _get_altered_foo_together_operations(self, option_name): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] # We run the old version through the field renames to account for those old_value = old_model_state.options.get(option_name) old_value = ( { tuple( self.renamed_fields.get((app_label, model_name, n), n) for n in unique ) for unique in old_value } if old_value else set() ) new_value = new_model_state.options.get(option_name) new_value = set(new_value) if new_value else set() if old_value != new_value: dependencies = [] for foo_togethers in new_value: for field_name in foo_togethers: field = new_model_state.get_field(field_name) if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) yield ( old_value, new_value, app_label, model_name, dependencies, ) def _generate_removed_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): if operation == operations.AlterIndexTogether: old_value = { value for value in old_value if value not in self.renamed_index_together_values[app_label, model_name] } removal_value = new_value.intersection(old_value) if removal_value or old_value: self.add_operation( app_label, operation( name=model_name, **{operation.option_name: removal_value} ), dependencies=dependencies, ) def generate_removed_altered_unique_together(self): self._generate_removed_altered_foo_together(operations.AlterUniqueTogether) def generate_removed_altered_index_together(self): self._generate_removed_altered_foo_together(operations.AlterIndexTogether) def _generate_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): removal_value = new_value.intersection(old_value) if new_value != removal_value: self.add_operation( app_label, operation(name=model_name, **{operation.option_name: new_value}), dependencies=dependencies, ) def generate_altered_unique_together(self): self._generate_altered_foo_together(operations.AlterUniqueTogether) def generate_altered_index_together(self): self._generate_altered_foo_together(operations.AlterIndexTogether) def generate_altered_db_table(self): models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_name = old_model_state.options.get("db_table") new_db_table_name = new_model_state.options.get("db_table") if old_db_table_name != new_db_table_name: self.add_operation( app_label, operations.AlterModelTable( name=model_name, table=new_db_table_name, ), ) def generate_altered_options(self): """ Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them). """ models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys, # unmanaged converted to managed self.old_unmanaged_keys & self.new_model_keys, # managed converted to unmanaged self.old_model_keys & self.new_unmanaged_keys, ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_options = { key: value for key, value in old_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } new_options = { key: value for key, value in new_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } if old_options != new_options: self.add_operation( app_label, operations.AlterModelOptions( name=model_name, options=new_options, ), ) def generate_altered_order_with_respect_to(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.options.get( "order_with_respect_to" ) != new_model_state.options.get("order_with_respect_to"): # Make sure it comes second if we're adding # (removal dependency is part of RemoveField) dependencies = [] if new_model_state.options.get("order_with_respect_to"): dependencies.append( ( app_label, model_name, new_model_state.options["order_with_respect_to"], True, ) ) # Actually generate the operation self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=new_model_state.options.get( "order_with_respect_to" ), ), dependencies=dependencies, ) def generate_altered_managers(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.managers != new_model_state.managers: self.add_operation( app_label, operations.AlterModelManagers( name=model_name, managers=new_model_state.managers, ), ) def arrange_for_graph(self, changes, graph, migration_name=None): """ Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app. """ leaves = graph.leaf_nodes() name_map = {} for app_label, migrations in list(changes.items()): if not migrations: continue # Find the app label's current leaf node app_leaf = None for leaf in leaves: if leaf[0] == app_label: app_leaf = leaf break # Do they want an initial migration for this app? if app_leaf is None and not self.questioner.ask_initial(app_label): # They don't. for migration in migrations: name_map[(app_label, migration.name)] = (app_label, "__first__") del changes[app_label] continue # Work out the next number in the sequence if app_leaf is None: next_number = 1 else: next_number = (self.parse_number(app_leaf[1]) or 0) + 1 # Name each migration for i, migration in enumerate(migrations): if i == 0 and app_leaf: migration.dependencies.append(app_leaf) new_name_parts = ["%04i" % next_number] if migration_name: new_name_parts.append(migration_name) elif i == 0 and not app_leaf: new_name_parts.append("initial") else: new_name_parts.append(migration.suggest_name()[:100]) new_name = "_".join(new_name_parts) name_map[(app_label, migration.name)] = (app_label, new_name) next_number += 1 migration.name = new_name # Now fix dependencies for migrations in changes.values(): for migration in migrations: migration.dependencies = [ name_map.get(d, d) for d in migration.dependencies ] return changes def _trim_to_apps(self, changes, app_labels): """ Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies. """ # Gather other app dependencies in a first pass app_dependencies = {} for app_label, migrations in changes.items(): for migration in migrations: for dep_app_label, name in migration.dependencies: app_dependencies.setdefault(app_label, set()).add(dep_app_label) required_apps = set(app_labels) # Keep resolving till there's no change old_required_apps = None while old_required_apps != required_apps: old_required_apps = set(required_apps) required_apps.update( *[app_dependencies.get(app_label, ()) for app_label in required_apps] ) # Remove all migrations that aren't needed for app_label in list(changes): if app_label not in required_apps: del changes[app_label] return changes @classmethod def parse_number(cls, name): """ Given a migration name, try to extract a number from the beginning of it. For a squashed migration such as '0001_squashed_0004…', return the second number. If no number is found, return None. """ if squashed_match := re.search(r".*_squashed_(\d+)", name): return int(squashed_match[1]) match = re.match(r"^\d+", name) if match: return int(match[0]) return None
9abf291c065a0186b08541a4568d7a2968bf1bdfa0c009dc412e21933828ef21
""" The main QuerySet implementation. This provides the public API for the ORM. """ import copy import operator import warnings from itertools import chain, islice from asgiref.sync import sync_to_async import django from django.conf import settings from django.core import exceptions from django.db import ( DJANGO_VERSION_PICKLE_KEY, IntegrityError, NotSupportedError, connections, router, transaction, ) from django.db.models import AutoField, DateField, DateTimeField, sql from django.db.models.constants import LOOKUP_SEP, OnConflict from django.db.models.deletion import Collector from django.db.models.expressions import Case, F, Ref, Value, When from django.db.models.functions import Cast, Trunc from django.db.models.query_utils import FilteredRelation, Q from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE from django.db.models.utils import create_namedtuple_class, resolve_callables from django.utils import timezone from django.utils.deprecation import RemovedInDjango50Warning from django.utils.functional import cached_property, partition # The maximum number of results to fetch in a get() query. MAX_GET_RESULTS = 21 # The maximum number of items to display in a QuerySet.__repr__ REPR_OUTPUT_SIZE = 20 class BaseIterable: def __init__( self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): self.queryset = queryset self.chunked_fetch = chunked_fetch self.chunk_size = chunk_size async def _async_generator(self): # Generators don't actually start running until the first time you call # next() on them, so make the generator object in the async thread and # then repeatedly dispatch to it in a sync thread. sync_generator = self.__iter__() def next_slice(gen): return list(islice(gen, self.chunk_size)) while True: chunk = await sync_to_async(next_slice)(sync_generator) for item in chunk: yield item if len(chunk) < self.chunk_size: break # __aiter__() is a *synchronous* method that has to then return an # *asynchronous* iterator/generator. Thus, nest an async generator inside # it. # This is a generic iterable converter for now, and is going to suffer a # performance penalty on large sets of items due to the cost of crossing # over the sync barrier for each chunk. Custom __aiter__() methods should # be added to each Iterable subclass, but that needs some work in the # Compiler first. def __aiter__(self): return self._async_generator() class ModelIterable(BaseIterable): """Iterable that yields a model instance for each row.""" def __iter__(self): queryset = self.queryset db = queryset.db compiler = queryset.query.get_compiler(using=db) # Execute the query. This will also fill compiler.select, klass_info, # and annotations. results = compiler.execute_sql( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ) select, klass_info, annotation_col_map = ( compiler.select, compiler.klass_info, compiler.annotation_col_map, ) model_cls = klass_info["model"] select_fields = klass_info["select_fields"] model_fields_start, model_fields_end = select_fields[0], select_fields[-1] + 1 init_list = [ f[0].target.attname for f in select[model_fields_start:model_fields_end] ] related_populators = get_related_populators(klass_info, select, db) known_related_objects = [ ( field, related_objs, operator.attrgetter( *[ field.attname if from_field == "self" else queryset.model._meta.get_field(from_field).attname for from_field in field.from_fields ] ), ) for field, related_objs in queryset._known_related_objects.items() ] for row in compiler.results_iter(results): obj = model_cls.from_db( db, init_list, row[model_fields_start:model_fields_end] ) for rel_populator in related_populators: rel_populator.populate(row, obj) if annotation_col_map: for attr_name, col_pos in annotation_col_map.items(): setattr(obj, attr_name, row[col_pos]) # Add the known related objects to the model. for field, rel_objs, rel_getter in known_related_objects: # Avoid overwriting objects loaded by, e.g., select_related(). if field.is_cached(obj): continue rel_obj_id = rel_getter(obj) try: rel_obj = rel_objs[rel_obj_id] except KeyError: pass # May happen in qs1 | qs2 scenarios. else: setattr(obj, field.name, rel_obj) yield obj class RawModelIterable(BaseIterable): """ Iterable that yields a model instance for each row from a raw queryset. """ def __iter__(self): # Cache some things for performance reasons outside the loop. db = self.queryset.db query = self.queryset.query connection = connections[db] compiler = connection.ops.compiler("SQLCompiler")(query, connection, db) query_iterator = iter(query) try: ( model_init_names, model_init_pos, annotation_fields, ) = self.queryset.resolve_model_init_order() model_cls = self.queryset.model if model_cls._meta.pk.attname not in model_init_names: raise exceptions.FieldDoesNotExist( "Raw query must include the primary key" ) fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns] converters = compiler.get_converters( [f.get_col(f.model._meta.db_table) if f else None for f in fields] ) if converters: query_iterator = compiler.apply_converters(query_iterator, converters) for values in query_iterator: # Associate fields to values model_init_values = [values[pos] for pos in model_init_pos] instance = model_cls.from_db(db, model_init_names, model_init_values) if annotation_fields: for column, pos in annotation_fields: setattr(instance, column, values[pos]) yield instance finally: # Done iterating the Query. If it has its own cursor, close it. if hasattr(query, "cursor") and query.cursor: query.cursor.close() class ValuesIterable(BaseIterable): """ Iterable returned by QuerySet.values() that yields a dict for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] indexes = range(len(names)) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield {names[i]: row[i] for i in indexes} class ValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=False) that yields a tuple for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) if queryset._fields: # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] fields = [ *queryset._fields, *(f for f in query.annotation_select if f not in queryset._fields), ] if fields != names: # Reorder according to fields. index_map = {name: idx for idx, name in enumerate(names)} rowfactory = operator.itemgetter(*[index_map[f] for f in fields]) return map( rowfactory, compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ), ) return compiler.results_iter( tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size, ) class NamedValuesListIterable(ValuesListIterable): """ Iterable returned by QuerySet.values_list(named=True) that yields a namedtuple for each row. """ def __iter__(self): queryset = self.queryset if queryset._fields: names = queryset._fields else: query = queryset.query names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] tuple_class = create_namedtuple_class(*names) new = tuple.__new__ for row in super().__iter__(): yield new(tuple_class, row) class FlatValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=True) that yields single values. """ def __iter__(self): queryset = self.queryset compiler = queryset.query.get_compiler(queryset.db) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield row[0] class QuerySet: """Represent a lazy database lookup for a set of objects.""" def __init__(self, model=None, query=None, using=None, hints=None): self.model = model self._db = using self._hints = hints or {} self._query = query or sql.Query(self.model) self._result_cache = None self._sticky_filter = False self._for_write = False self._prefetch_related_lookups = () self._prefetch_done = False self._known_related_objects = {} # {rel_field: {pk: rel_obj}} self._iterable_class = ModelIterable self._fields = None self._defer_next_filter = False self._deferred_filter = None @property def query(self): if self._deferred_filter: negate, args, kwargs = self._deferred_filter self._filter_or_exclude_inplace(negate, args, kwargs) self._deferred_filter = None return self._query @query.setter def query(self, value): if value.values_select: self._iterable_class = ValuesIterable self._query = value def as_manager(cls): # Address the circular dependency between `Queryset` and `Manager`. from django.db.models.manager import Manager manager = Manager.from_queryset(cls)() manager._built_with_as_manager = True return manager as_manager.queryset_only = True as_manager = classmethod(as_manager) ######################## # PYTHON MAGIC METHODS # ######################## def __deepcopy__(self, memo): """Don't populate the QuerySet's cache.""" obj = self.__class__() for k, v in self.__dict__.items(): if k == "_result_cache": obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return obj def __getstate__(self): # Force the cache to be fully populated. self._fetch_all() return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__} def __setstate__(self, state): pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: if pickled_version != django.__version__: warnings.warn( "Pickled queryset instance's Django version %s does not " "match the current version %s." % (pickled_version, django.__version__), RuntimeWarning, stacklevel=2, ) else: warnings.warn( "Pickled queryset instance's Django version is not specified.", RuntimeWarning, stacklevel=2, ) self.__dict__.update(state) def __repr__(self): data = list(self[: REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." return "<%s %r>" % (self.__class__.__name__, data) def __len__(self): self._fetch_all() return len(self._result_cache) def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql.compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects. """ self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def __bool__(self): self._fetch_all() return bool(self._result_cache) def __getitem__(self, k): """Retrieve an item or slice from the set of results.""" if not isinstance(k, (int, slice)): raise TypeError( "QuerySet indices must be integers or slices, not %s." % type(k).__name__ ) if (isinstance(k, int) and k < 0) or ( isinstance(k, slice) and ( (k.start is not None and k.start < 0) or (k.stop is not None and k.stop < 0) ) ): raise ValueError("Negative indexing is not supported.") if self._result_cache is not None: return self._result_cache[k] if isinstance(k, slice): qs = self._chain() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return list(qs)[:: k.step] if k.step else qs qs = self._chain() qs.query.set_limits(k, k + 1) qs._fetch_all() return qs._result_cache[0] def __class_getitem__(cls, *args, **kwargs): return cls def __and__(self, other): self._check_operator_queryset(other, "&") self._merge_sanity_check(other) if isinstance(other, EmptyQuerySet): return other if isinstance(self, EmptyQuerySet): return self combined = self._chain() combined._merge_known_related_objects(other) combined.query.combine(other.query, sql.AND) return combined def __or__(self, other): self._check_operator_queryset(other, "|") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.OR) return combined def __xor__(self, other): self._check_operator_queryset(other, "^") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.XOR) return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def _iterator(self, use_chunked_fetch, chunk_size): iterable = self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size or 2000, ) if not self._prefetch_related_lookups or chunk_size is None: yield from iterable return iterator = iter(iterable) while results := list(islice(iterator, chunk_size)): prefetch_related_objects(results, *self._prefetch_related_lookups) yield from results def iterator(self, chunk_size=None): """ An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied. """ if chunk_size is None: if self._prefetch_related_lookups: # When the deprecation ends, replace with: # raise ValueError( # 'chunk_size must be provided when using ' # 'QuerySet.iterator() after prefetch_related().' # ) warnings.warn( "Using QuerySet.iterator() after prefetch_related() " "without specifying chunk_size is deprecated.", category=RemovedInDjango50Warning, stacklevel=2, ) elif chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) return self._iterator(use_chunked_fetch, chunk_size) async def aiterator(self, chunk_size=2000): """ An asynchronous iterator over the results from applying this QuerySet to the database. """ if self._prefetch_related_lookups: raise NotSupportedError( "Using QuerySet.aiterator() after prefetch_related() is not supported." ) if chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) async for item in self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size ): yield item def aggregate(self, *args, **kwargs): """ Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") self._validate_values_are_expressions( (*args, *kwargs.values()), method_name="aggregate" ) for arg in args: # The default_alias property raises TypeError if default_alias # can't be set automatically or AttributeError if it isn't an # attribute. try: arg.default_alias except (AttributeError, TypeError): raise TypeError("Complex aggregates require an alias") kwargs[arg.default_alias] = arg query = self.query.chain() for (alias, aggregate_expr) in kwargs.items(): query.add_annotation(aggregate_expr, alias, is_summary=True) annotation = query.annotations[alias] if not annotation.contains_aggregate: raise TypeError("%s is not an aggregate expression" % alias) for expr in annotation.get_source_expressions(): if ( expr.contains_aggregate and isinstance(expr, Ref) and expr.refs in kwargs ): name = expr.refs raise exceptions.FieldError( "Cannot compute %s('%s'): '%s' is an aggregate" % (annotation.name, name, name) ) return query.get_aggregation(self.db, kwargs) async def aaggregate(self, *args, **kwargs): return await sync_to_async(self.aggregate)(*args, **kwargs) def count(self): """ Perform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None: return len(self._result_cache) return self.query.get_count(using=self.db) async def acount(self): return await sync_to_async(self.count)() def get(self, *args, **kwargs): """ Perform the query and return a single object matching the given keyword arguments. """ if self.query.combinator and (args or kwargs): raise NotSupportedError( "Calling QuerySet.get(...) with filters after %s() is not " "supported." % self.query.combinator ) clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() limit = None if ( not clone.query.select_for_update or connections[clone.db].features.supports_select_for_update_with_limit ): limit = MAX_GET_RESULTS clone.query.set_limits(high=limit) num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist( "%s matching query does not exist." % self.model._meta.object_name ) raise self.model.MultipleObjectsReturned( "get() returned more than one %s -- it returned %s!" % ( self.model._meta.object_name, num if not limit or num < limit else "more than %s" % (limit - 1), ) ) async def aget(self, *args, **kwargs): return await sync_to_async(self.get)(*args, **kwargs) def create(self, **kwargs): """ Create a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj async def acreate(self, **kwargs): return await sync_to_async(self.create)(**kwargs) def _prepare_for_bulk_create(self, objs): for obj in objs: if obj.pk is None: # Populate new PK values. obj.pk = obj._meta.pk.get_pk_value_on_save(obj) obj._prepare_related_fields_for_save(operation_name="bulk_create") def _check_bulk_create_options( self, ignore_conflicts, update_conflicts, update_fields, unique_fields ): if ignore_conflicts and update_conflicts: raise ValueError( "ignore_conflicts and update_conflicts are mutually exclusive." ) db_features = connections[self.db].features if ignore_conflicts: if not db_features.supports_ignore_conflicts: raise NotSupportedError( "This database backend does not support ignoring conflicts." ) return OnConflict.IGNORE elif update_conflicts: if not db_features.supports_update_conflicts: raise NotSupportedError( "This database backend does not support updating conflicts." ) if not update_fields: raise ValueError( "Fields that will be updated when a row insertion fails " "on conflicts must be provided." ) if unique_fields and not db_features.supports_update_conflicts_with_target: raise NotSupportedError( "This database backend does not support updating " "conflicts with specifying unique fields that can trigger " "the upsert." ) if not unique_fields and db_features.supports_update_conflicts_with_target: raise ValueError( "Unique fields that can trigger the upsert must be provided." ) # Updating primary keys and non-concrete fields is forbidden. update_fields = [self.model._meta.get_field(name) for name in update_fields] if any(not f.concrete or f.many_to_many for f in update_fields): raise ValueError( "bulk_create() can only be used with concrete fields in " "update_fields." ) if any(f.primary_key for f in update_fields): raise ValueError( "bulk_create() cannot be used with primary keys in " "update_fields." ) if unique_fields: # Primary key is allowed in unique_fields. unique_fields = [ self.model._meta.get_field(name) for name in unique_fields if name != "pk" ] if any(not f.concrete or f.many_to_many for f in unique_fields): raise ValueError( "bulk_create() can only be used with concrete fields " "in unique_fields." ) return OnConflict.UPDATE return None def bulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): """ Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported. """ # When you bulk insert you don't get the primary keys back (if it's an # autoincrement, except if can_return_rows_from_bulk_insert=True), so # you can't insert into the child tables which references this. There # are two workarounds: # 1) This could be implemented if you didn't have an autoincrement pk # 2) You could do it by doing O(n) normal inserts into the parent # tables to get the primary keys back and then doing a single bulk # insert into the childmost table. # We currently set the primary keys on the objects when using # PostgreSQL via the RETURNING ID clause. It should be possible for # Oracle as well, but the semantics for extracting the primary keys is # trickier so it's not done yet. if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") # Check that the parents share the same concrete model with the our # model to detect the inheritance pattern ConcreteGrandParent -> # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy # would not identify that case as involving multiple tables. for parent in self.model._meta.get_parent_list(): if parent._meta.concrete_model is not self.model._meta.concrete_model: raise ValueError("Can't bulk create a multi-table inherited model") if not objs: return objs on_conflict = self._check_bulk_create_options( ignore_conflicts, update_conflicts, update_fields, unique_fields, ) self._for_write = True opts = self.model._meta fields = opts.concrete_fields objs = list(objs) self._prepare_for_bulk_create(objs) with transaction.atomic(using=self.db, savepoint=False): objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs) if objs_with_pk: returned_columns = self._batched_insert( objs_with_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) for obj_with_pk, results in zip(objs_with_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): if field != opts.pk: setattr(obj_with_pk, field.attname, result) for obj_with_pk in objs_with_pk: obj_with_pk._state.adding = False obj_with_pk._state.db = self.db if objs_without_pk: fields = [f for f in fields if not isinstance(f, AutoField)] returned_columns = self._batched_insert( objs_without_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) connection = connections[self.db] if ( connection.features.can_return_rows_from_bulk_insert and on_conflict is None ): assert len(returned_columns) == len(objs_without_pk) for obj_without_pk, results in zip(objs_without_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): setattr(obj_without_pk, field.attname, result) obj_without_pk._state.adding = False obj_without_pk._state.db = self.db return objs async def abulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): return await sync_to_async(self.bulk_create)( objs=objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts, update_conflicts=update_conflicts, update_fields=update_fields, unique_fields=unique_fields, ) def bulk_update(self, objs, fields, batch_size=None): """ Update the given fields in each of the given objects in the database. """ if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") if not fields: raise ValueError("Field names must be given to bulk_update().") objs = tuple(objs) if any(obj.pk is None for obj in objs): raise ValueError("All bulk_update() objects must have a primary key set.") fields = [self.model._meta.get_field(name) for name in fields] if any(not f.concrete or f.many_to_many for f in fields): raise ValueError("bulk_update() can only be used with concrete fields.") if any(f.primary_key for f in fields): raise ValueError("bulk_update() cannot be used with primary key fields.") if not objs: return 0 for obj in objs: obj._prepare_related_fields_for_save( operation_name="bulk_update", fields=fields ) # PK is used twice in the resulting update query, once in the filter # and once in the WHEN. Each field will also have one CAST. self._for_write = True connection = connections[self.db] max_batch_size = connection.ops.bulk_batch_size(["pk", "pk"] + fields, objs) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size requires_casting = connection.features.requires_casted_case_in_updates batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size)) updates = [] for batch_objs in batches: update_kwargs = {} for field in fields: when_statements = [] for obj in batch_objs: attr = getattr(obj, field.attname) if not hasattr(attr, "resolve_expression"): attr = Value(attr, output_field=field) when_statements.append(When(pk=obj.pk, then=attr)) case_statement = Case(*when_statements, output_field=field) if requires_casting: case_statement = Cast(case_statement, output_field=field) update_kwargs[field.attname] = case_statement updates.append(([obj.pk for obj in batch_objs], update_kwargs)) rows_updated = 0 queryset = self.using(self.db) with transaction.atomic(using=self.db, savepoint=False): for pks, update_kwargs in updates: rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs) return rows_updated bulk_update.alters_data = True async def abulk_update(self, objs, fields, batch_size=None): return await sync_to_async(self.bulk_update)( objs=objs, fields=fields, batch_size=batch_size, ) abulk_update.alters_data = True def get_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. """ # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: return self.get(**kwargs), False except self.model.DoesNotExist: params = self._extract_model_params(defaults, **kwargs) # Try to create an object using passed params. try: with transaction.atomic(using=self.db): params = dict(resolve_callables(params)) return self.create(**params), True except IntegrityError: try: return self.get(**kwargs), False except self.model.DoesNotExist: pass raise async def aget_or_create(self, defaults=None, **kwargs): return await sync_to_async(self.get_or_create)( defaults=defaults, **kwargs, ) def update_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Return a tuple (object, created), where created is a boolean specifying whether an object was created. """ defaults = defaults or {} self._for_write = True with transaction.atomic(using=self.db): # Lock the row so that a concurrent update is blocked until # update_or_create() has performed its save. obj, created = self.select_for_update().get_or_create(defaults, **kwargs) if created: return obj, created for k, v in resolve_callables(defaults): setattr(obj, k, v) obj.save(using=self.db) return obj, False async def aupdate_or_create(self, defaults=None, **kwargs): return await sync_to_async(self.update_or_create)( defaults=defaults, **kwargs, ) def _extract_model_params(self, defaults, **kwargs): """ Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create(). """ defaults = defaults or {} params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k} params.update(defaults) property_names = self.model._meta._property_names invalid_params = [] for param in params: try: self.model._meta.get_field(param) except exceptions.FieldDoesNotExist: # It's okay to use a model's property if it has a setter. if not (param in property_names and getattr(self.model, param).fset): invalid_params.append(param) if invalid_params: raise exceptions.FieldError( "Invalid field name(s) for model %s: '%s'." % ( self.model._meta.object_name, "', '".join(sorted(invalid_params)), ) ) return params def _earliest(self, *fields): """ Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by. """ if fields: order_by = fields else: order_by = getattr(self.model._meta, "get_latest_by") if order_by and not isinstance(order_by, (tuple, list)): order_by = (order_by,) if order_by is None: raise ValueError( "earliest() and latest() require either fields as positional " "arguments or 'get_latest_by' in the model's Meta." ) obj = self._chain() obj.query.set_limits(high=1) obj.query.clear_ordering(force=True) obj.query.add_ordering(*order_by) return obj.get() def earliest(self, *fields): if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self._earliest(*fields) async def aearliest(self, *fields): return await sync_to_async(self.earliest)(*fields) def latest(self, *fields): """ Return the latest object according to fields (if given) or by the model's Meta.get_latest_by. """ if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self.reverse()._earliest(*fields) async def alatest(self, *fields): return await sync_to_async(self.latest)(*fields) def first(self): """Return the first object of a query or None if no match is found.""" if self.ordered: queryset = self else: self._check_ordering_first_last_queryset_aggregation(method="first") queryset = self.order_by("pk") for obj in queryset[:1]: return obj async def afirst(self): return await sync_to_async(self.first)() def last(self): """Return the last object of a query or None if no match is found.""" if self.ordered: queryset = self.reverse() else: self._check_ordering_first_last_queryset_aggregation(method="last") queryset = self.order_by("-pk") for obj in queryset[:1]: return obj async def alast(self): return await sync_to_async(self.last)() def in_bulk(self, id_list=None, *, field_name="pk"): """ Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet. """ if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with in_bulk().") opts = self.model._meta unique_fields = [ constraint.fields[0] for constraint in opts.total_unique_constraints if len(constraint.fields) == 1 ] if ( field_name != "pk" and not opts.get_field(field_name).unique and field_name not in unique_fields and self.query.distinct_fields != (field_name,) ): raise ValueError( "in_bulk()'s field_name must be a unique field but %r isn't." % field_name ) if id_list is not None: if not id_list: return {} filter_key = "{}__in".format(field_name) batch_size = connections[self.db].features.max_query_params id_list = tuple(id_list) # If the database has a limit on the number of query parameters # (e.g. SQLite), retrieve objects in batches if necessary. if batch_size and batch_size < len(id_list): qs = () for offset in range(0, len(id_list), batch_size): batch = id_list[offset : offset + batch_size] qs += tuple(self.filter(**{filter_key: batch}).order_by()) else: qs = self.filter(**{filter_key: id_list}).order_by() else: qs = self._chain() return {getattr(obj, field_name): obj for obj in qs} async def ain_bulk(self, id_list=None, *, field_name="pk"): return await sync_to_async(self.in_bulk)( id_list=id_list, field_name=field_name, ) def delete(self): """Delete the records in the current QuerySet.""" self._not_support_combined_queries("delete") if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with delete().") if self.query.distinct or self.query.distinct_fields: raise TypeError("Cannot call delete() after .distinct().") if self._fields is not None: raise TypeError("Cannot call delete() after .values() or .values_list()") del_query = self._chain() # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force=True) collector = Collector(using=del_query.db, origin=self) collector.collect(del_query) deleted, _rows_count = collector.delete() # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None return deleted, _rows_count delete.alters_data = True delete.queryset_only = True async def adelete(self): return await sync_to_async(self.delete)() adelete.alters_data = True adelete.queryset_only = True def _raw_delete(self, using): """ Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades. """ query = self.query.clone() query.__class__ = sql.DeleteQuery cursor = query.get_compiler(using).execute_sql(CURSOR) if cursor: with cursor: return cursor.rowcount return 0 _raw_delete.alters_data = True def update(self, **kwargs): """ Update all elements in the current QuerySet, setting all the given fields to the appropriate values. """ self._not_support_combined_queries("update") if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") self._for_write = True query = self.query.chain(sql.UpdateQuery) query.add_update_values(kwargs) # Inline annotations in order_by(), if possible. new_order_by = [] for col in query.order_by: if annotation := query.annotations.get(col): if getattr(annotation, "contains_aggregate", False): raise exceptions.FieldError( f"Cannot update when ordering by an aggregate: {annotation}" ) new_order_by.append(annotation) else: new_order_by.append(col) query.order_by = tuple(new_order_by) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} with transaction.mark_for_rollback_on_error(using=self.db): rows = query.get_compiler(self.db).execute_sql(CURSOR) self._result_cache = None return rows update.alters_data = True async def aupdate(self, **kwargs): return await sync_to_async(self.update)(**kwargs) aupdate.alters_data = True def _update(self, values): """ A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") query = self.query.chain(sql.UpdateQuery) query.add_update_fields(values) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} self._result_cache = None return query.get_compiler(self.db).execute_sql(CURSOR) _update.alters_data = True _update.queryset_only = False def exists(self): """ Return True if the QuerySet would have any results, False otherwise. """ if self._result_cache is None: return self.query.has_results(using=self.db) return bool(self._result_cache) async def aexists(self): return await sync_to_async(self.exists)() def contains(self, obj): """ Return True if the QuerySet contains the provided obj, False otherwise. """ self._not_support_combined_queries("contains") if self._fields is not None: raise TypeError( "Cannot call QuerySet.contains() after .values() or .values_list()." ) try: if obj._meta.concrete_model != self.model._meta.concrete_model: return False except AttributeError: raise TypeError("'obj' must be a model instance.") if obj.pk is None: raise ValueError("QuerySet.contains() cannot be used on unsaved objects.") if self._result_cache is not None: return obj in self._result_cache return self.filter(pk=obj.pk).exists() async def acontains(self, obj): return await sync_to_async(self.contains)(obj=obj) def _prefetch_related_objects(self): # This method can only be called once the result cache has been filled. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def explain(self, *, format=None, **options): """ Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results. """ return self.query.explain(using=self.db, format=format, **options) async def aexplain(self, *, format=None, **options): return await sync_to_async(self.explain)(format=format, **options) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=(), translations=None, using=None): if using is None: using = self.db qs = RawQuerySet( raw_query, model=self.model, params=params, translations=translations, using=using, ) qs._prefetch_related_lookups = self._prefetch_related_lookups[:] return qs def _values(self, *fields, **expressions): clone = self._chain() if expressions: clone = clone.annotate(**expressions) clone._fields = fields clone.query.set_values(fields) return clone def values(self, *fields, **expressions): fields += tuple(expressions) clone = self._values(*fields, **expressions) clone._iterable_class = ValuesIterable return clone def values_list(self, *fields, flat=False, named=False): if flat and named: raise TypeError("'flat' and 'named' can't be used together.") if flat and len(fields) > 1: raise TypeError( "'flat' is not valid when values_list is called with more than one " "field." ) field_names = {f for f in fields if not hasattr(f, "resolve_expression")} _fields = [] expressions = {} counter = 1 for field in fields: if hasattr(field, "resolve_expression"): field_id_prefix = getattr( field, "default_alias", field.__class__.__name__.lower() ) while True: field_id = field_id_prefix + str(counter) counter += 1 if field_id not in field_names: break expressions[field_id] = field _fields.append(field_id) else: _fields.append(field) clone = self._values(*_fields, **expressions) clone._iterable_class = ( NamedValuesListIterable if named else FlatValuesListIterable if flat else ValuesListIterable ) return clone def dates(self, field_name, kind, order="ASC"): """ Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day"): raise ValueError("'kind' must be one of 'year', 'month', 'week', or 'day'.") if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") return ( self.annotate( datefield=Trunc(field_name, kind, output_field=DateField()), plain_field=F(field_name), ) .values_list("datefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datefield") ) # RemovedInDjango50Warning: when the deprecation ends, remove is_dst # argument. def datetimes( self, field_name, kind, order="ASC", tzinfo=None, is_dst=timezone.NOT_PASSED ): """ Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day", "hour", "minute", "second"): raise ValueError( "'kind' must be one of 'year', 'month', 'week', 'day', " "'hour', 'minute', or 'second'." ) if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return ( self.annotate( datetimefield=Trunc( field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo, is_dst=is_dst, ), plain_field=F(field_name), ) .values_list("datetimefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datetimefield") ) def none(self): """Return an empty QuerySet.""" clone = self._chain() clone.query.set_empty() return clone ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self): """ Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._chain() def filter(self, *args, **kwargs): """ Return a new QuerySet instance with the args ANDed to the existing set. """ self._not_support_combined_queries("filter") return self._filter_or_exclude(False, args, kwargs) def exclude(self, *args, **kwargs): """ Return a new QuerySet instance with NOT (args) ANDed to the existing set. """ self._not_support_combined_queries("exclude") return self._filter_or_exclude(True, args, kwargs) def _filter_or_exclude(self, negate, args, kwargs): if (args or kwargs) and self.query.is_sliced: raise TypeError("Cannot filter a query once a slice has been taken.") clone = self._chain() if self._defer_next_filter: self._defer_next_filter = False clone._deferred_filter = negate, args, kwargs else: clone._filter_or_exclude_inplace(negate, args, kwargs) return clone def _filter_or_exclude_inplace(self, negate, args, kwargs): if negate: self._query.add_q(~Q(*args, **kwargs)) else: self._query.add_q(Q(*args, **kwargs)) def complex_filter(self, filter_obj): """ Return a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. """ if isinstance(filter_obj, Q): clone = self._chain() clone.query.add_q(filter_obj) return clone else: return self._filter_or_exclude(False, args=(), kwargs=filter_obj) def _combinator_query(self, combinator, *other_qs, all=False): # Clone the query to inherit the select list and everything clone = self._chain() # Clear limits and ordering so they can be reapplied clone.query.clear_ordering(force=True) clone.query.clear_limits() clone.query.combined_queries = (self.query,) + tuple( qs.query for qs in other_qs ) clone.query.combinator = combinator clone.query.combinator_all = all return clone def union(self, *other_qs, all=False): # If the query is an EmptyQuerySet, combine all nonempty querysets. if isinstance(self, EmptyQuerySet): qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)] if not qs: return self if len(qs) == 1: return qs[0] return qs[0]._combinator_query("union", *qs[1:], all=all) return self._combinator_query("union", *other_qs, all=all) def intersection(self, *other_qs): # If any query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self for other in other_qs: if isinstance(other, EmptyQuerySet): return other return self._combinator_query("intersection", *other_qs) def difference(self, *other_qs): # If the query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self return self._combinator_query("difference", *other_qs) def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False): """ Return a new QuerySet instance that will select objects with a FOR UPDATE lock. """ if nowait and skip_locked: raise ValueError("The nowait option cannot be used with skip_locked.") obj = self._chain() obj._for_write = True obj.query.select_for_update = True obj.query.select_for_update_nowait = nowait obj.query.select_for_update_skip_locked = skip_locked obj.query.select_for_update_of = of obj.query.select_for_no_key_update = no_key return obj def select_related(self, *fields): """ Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list. """ self._not_support_combined_queries("select_related") if self._fields is not None: raise TypeError( "Cannot call select_related() after .values() or .values_list()" ) obj = self._chain() if fields == (None,): obj.query.select_related = False elif fields: obj.query.add_select_related(fields) else: obj.query.select_related = True return obj def prefetch_related(self, *lookups): """ Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list. """ self._not_support_combined_queries("prefetch_related") clone = self._chain() if lookups == (None,): clone._prefetch_related_lookups = () else: for lookup in lookups: if isinstance(lookup, Prefetch): lookup = lookup.prefetch_to lookup = lookup.split(LOOKUP_SEP, 1)[0] if lookup in self.query._filtered_relations: raise ValueError( "prefetch_related() is not supported with FilteredRelation." ) clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with extra data or aggregations. """ self._not_support_combined_queries("annotate") return self._annotate(args, kwargs, select=True) def alias(self, *args, **kwargs): """ Return a query set with added aliases for extra data or aggregations. """ self._not_support_combined_queries("alias") return self._annotate(args, kwargs, select=False) def _annotate(self, args, kwargs, select=True): self._validate_values_are_expressions( args + tuple(kwargs.values()), method_name="annotate" ) annotations = {} for arg in args: # The default_alias property may raise a TypeError. try: if arg.default_alias in kwargs: raise ValueError( "The named annotation '%s' conflicts with the " "default name for another annotation." % arg.default_alias ) except TypeError: raise TypeError("Complex annotations require an alias") annotations[arg.default_alias] = arg annotations.update(kwargs) clone = self._chain() names = self._fields if names is None: names = set( chain.from_iterable( (field.name, field.attname) if hasattr(field, "attname") else (field.name,) for field in self.model._meta.get_fields() ) ) for alias, annotation in annotations.items(): if alias in names: raise ValueError( "The annotation '%s' conflicts with a field on " "the model." % alias ) if isinstance(annotation, FilteredRelation): clone.query.add_filtered_relation(annotation, alias) else: clone.query.add_annotation( annotation, alias, is_summary=False, select=select, ) for alias, annotation in clone.query.annotations.items(): if alias in annotations and annotation.contains_aggregate: if clone._fields is None: clone.query.group_by = True else: clone.query.set_group_by() break return clone def order_by(self, *field_names): """Return a new QuerySet instance with the ordering changed.""" if self.query.is_sliced: raise TypeError("Cannot reorder a query once a slice has been taken.") obj = self._chain() obj.query.clear_ordering(force=True, clear_default=False) obj.query.add_ordering(*field_names) return obj def distinct(self, *field_names): """ Return a new QuerySet instance that will select only distinct results. """ self._not_support_combined_queries("distinct") if self.query.is_sliced: raise TypeError( "Cannot create distinct fields once a slice has been taken." ) obj = self._chain() obj.query.add_distinct_fields(*field_names) return obj def extra( self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None, ): """Add extra SQL fragments to the query.""" self._not_support_combined_queries("extra") if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") clone = self._chain() clone.query.add_extra(select, select_params, where, params, tables, order_by) return clone def reverse(self): """Reverse the ordering of the QuerySet.""" if self.query.is_sliced: raise TypeError("Cannot reverse a query once a slice has been taken.") clone = self._chain() clone.query.standard_ordering = not clone.query.standard_ordering return clone def defer(self, *fields): """ Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals. """ self._not_support_combined_queries("defer") if self._fields is not None: raise TypeError("Cannot call defer() after .values() or .values_list()") clone = self._chain() if fields == (None,): clone.query.clear_deferred_loading() else: clone.query.add_deferred_loading(fields) return clone def only(self, *fields): """ Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ self._not_support_combined_queries("only") if self._fields is not None: raise TypeError("Cannot call only() after .values() or .values_list()") if fields == (None,): # Can only pass None to defer(), not only(), as the rest option. # That won't stop people trying to do this, so let's be explicit. raise TypeError("Cannot pass None as an argument to only().") for field in fields: field = field.split(LOOKUP_SEP, 1)[0] if field in self.query._filtered_relations: raise ValueError("only() is not supported with FilteredRelation.") clone = self._chain() clone.query.add_immediate_loading(fields) return clone def using(self, alias): """Select which database this QuerySet should execute against.""" clone = self._chain() clone._db = alias return clone ################################### # PUBLIC INTROSPECTION ATTRIBUTES # ################################### @property def ordered(self): """ Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty). """ if isinstance(self, EmptyQuerySet): return True if self.query.extra_order_by or self.query.order_by: return True elif ( self.query.default_ordering and self.query.get_meta().ordering and # A default ordering doesn't affect GROUP BY queries. not self.query.group_by ): return True else: return False @property def db(self): """Return the database used if this query is executed now.""" if self._for_write: return self._db or router.db_for_write(self.model, **self._hints) return self._db or router.db_for_read(self.model, **self._hints) ################### # PRIVATE METHODS # ################### def _insert( self, objs, fields, returning_fields=None, raw=False, using=None, on_conflict=None, update_fields=None, unique_fields=None, ): """ Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. """ self._for_write = True if using is None: using = self.db query = sql.InsertQuery( self.model, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) query.insert_values(fields, objs, raw=raw) return query.get_compiler(using=using).execute_sql(returning_fields) _insert.alters_data = True _insert.queryset_only = False def _batched_insert( self, objs, fields, batch_size, on_conflict=None, update_fields=None, unique_fields=None, ): """ Helper method for bulk_create() to insert objs one batch at a time. """ connection = connections[self.db] ops = connection.ops max_batch_size = max(ops.bulk_batch_size(fields, objs), 1) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size inserted_rows = [] bulk_return = connection.features.can_return_rows_from_bulk_insert for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: if bulk_return and on_conflict is None: inserted_rows.extend( self._insert( item, fields=fields, using=self.db, returning_fields=self.model._meta.db_returning_fields, ) ) else: self._insert( item, fields=fields, using=self.db, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) return inserted_rows def _chain(self): """ Return a copy of the current QuerySet that's ready for another operation. """ obj = self._clone() if obj._sticky_filter: obj.query.filter_is_sticky = True obj._sticky_filter = False return obj def _clone(self): """ Return a copy of the current QuerySet. A lightweight alternative to deepcopy(). """ c = self.__class__( model=self.model, query=self.query.chain(), using=self._db, hints=self._hints, ) c._sticky_filter = self._sticky_filter c._for_write = self._for_write c._prefetch_related_lookups = self._prefetch_related_lookups[:] c._known_related_objects = self._known_related_objects c._iterable_class = self._iterable_class c._fields = self._fields return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self._iterable_class(self)) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def _next_is_sticky(self): """ Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. """ self._sticky_filter = True return self def _merge_sanity_check(self, other): """Check that two QuerySet classes may be merged.""" if self._fields is not None and ( set(self.query.values_select) != set(other.query.values_select) or set(self.query.extra_select) != set(other.query.extra_select) or set(self.query.annotation_select) != set(other.query.annotation_select) ): raise TypeError( "Merging '%s' classes must involve the same values in each case." % self.__class__.__name__ ) def _merge_known_related_objects(self, other): """ Keep track of all known related objects from either QuerySet instance. """ for field, objects in other._known_related_objects.items(): self._known_related_objects.setdefault(field, {}).update(objects) def resolve_expression(self, *args, **kwargs): if self._fields and len(self._fields) > 1: # values() queryset can only be used as nested queries # if they are set up to select only a single field. raise TypeError("Cannot use multi-field values as a filter value.") query = self.query.resolve_expression(*args, **kwargs) query._db = self._db return query resolve_expression.queryset_only = True def _add_hints(self, **hints): """ Update hinting information for use by routers. Add new key/values or overwrite existing key/values. """ self._hints.update(hints) def _has_filters(self): """ Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False. """ return self.query.has_filters() @staticmethod def _validate_values_are_expressions(values, method_name): invalid_args = sorted( str(arg) for arg in values if not hasattr(arg, "resolve_expression") ) if invalid_args: raise TypeError( "QuerySet.%s() received non-expression(s): %s." % ( method_name, ", ".join(invalid_args), ) ) def _not_support_combined_queries(self, operation_name): if self.query.combinator: raise NotSupportedError( "Calling QuerySet.%s() after %s() is not supported." % (operation_name, self.query.combinator) ) def _check_operator_queryset(self, other, operator_): if self.query.combinator or other.query.combinator: raise TypeError(f"Cannot use {operator_} operator with combined queryset.") def _check_ordering_first_last_queryset_aggregation(self, method): if isinstance(self.query.group_by, tuple) and not any( col.output_field is self.model._meta.pk for col in self.query.group_by ): raise TypeError( f"Cannot use QuerySet.{method}() on an unordered queryset performing " f"aggregation. Add an ordering with order_by()." ) class InstanceCheckMeta(type): def __instancecheck__(self, instance): return isinstance(instance, QuerySet) and instance.query.is_empty() class EmptyQuerySet(metaclass=InstanceCheckMeta): """ Marker class to checking if a queryset is empty by .none(): isinstance(qs.none(), EmptyQuerySet) -> True """ def __init__(self, *args, **kwargs): raise TypeError("EmptyQuerySet can't be instantiated") class RawQuerySet: """ Provide an iterator which converts the results of raw SQL queries into annotated model instances. """ def __init__( self, raw_query, model=None, query=None, params=(), translations=None, using=None, hints=None, ): self.raw_query = raw_query self.model = model self._db = using self._hints = hints or {} self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params) self.params = params self.translations = translations or {} self._result_cache = None self._prefetch_related_lookups = () self._prefetch_done = False def resolve_model_init_order(self): """Resolve the init field names and value positions.""" converter = connections[self.db].introspection.identifier_converter model_init_fields = [ f for f in self.model._meta.fields if converter(f.column) in self.columns ] annotation_fields = [ (column, pos) for pos, column in enumerate(self.columns) if column not in self.model_fields ] model_init_order = [ self.columns.index(converter(f.column)) for f in model_init_fields ] model_init_names = [f.attname for f in model_init_fields] return model_init_names, model_init_order, annotation_fields def prefetch_related(self, *lookups): """Same as QuerySet.prefetch_related()""" clone = self._clone() if lookups == (None,): clone._prefetch_related_lookups = () else: clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def _prefetch_related_objects(self): prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def _clone(self): """Same as QuerySet._clone()""" c = self.__class__( self.raw_query, model=self.model, query=self.query, params=self.params, translations=self.translations, using=self._db, hints=self._hints, ) c._prefetch_related_lookups = self._prefetch_related_lookups[:] return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def __len__(self): self._fetch_all() return len(self._result_cache) def __bool__(self): self._fetch_all() return bool(self._result_cache) def __iter__(self): self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def iterator(self): yield from RawModelIterable(self) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.query) def __getitem__(self, k): return list(self)[k] @property def db(self): """Return the database used if this query is executed now.""" return self._db or router.db_for_read(self.model, **self._hints) def using(self, alias): """Select the database this RawQuerySet should execute against.""" return RawQuerySet( self.raw_query, model=self.model, query=self.query.chain(using=alias), params=self.params, translations=self.translations, using=alias, ) @cached_property def columns(self): """ A list of model field names in the order they'll appear in the query results. """ columns = self.query.get_columns() # Adjust any column names which don't match field names for (query_name, model_name) in self.translations.items(): # Ignore translations for nonexistent column names try: index = columns.index(query_name) except ValueError: pass else: columns[index] = model_name return columns @cached_property def model_fields(self): """A dict mapping column names to model field names.""" converter = connections[self.db].introspection.identifier_converter model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() model_fields[converter(column)] = field return model_fields class Prefetch: def __init__(self, lookup, queryset=None, to_attr=None): # `prefetch_through` is the path we traverse to perform the prefetch. self.prefetch_through = lookup # `prefetch_to` is the path to the attribute that stores the result. self.prefetch_to = lookup if queryset is not None and ( isinstance(queryset, RawQuerySet) or ( hasattr(queryset, "_iterable_class") and not issubclass(queryset._iterable_class, ModelIterable) ) ): raise ValueError( "Prefetch querysets cannot use raw(), values(), and values_list()." ) if to_attr: self.prefetch_to = LOOKUP_SEP.join( lookup.split(LOOKUP_SEP)[:-1] + [to_attr] ) self.queryset = queryset self.to_attr = to_attr def __getstate__(self): obj_dict = self.__dict__.copy() if self.queryset is not None: queryset = self.queryset._chain() # Prevent the QuerySet from being evaluated queryset._result_cache = [] queryset._prefetch_done = True obj_dict["queryset"] = queryset return obj_dict def add_prefix(self, prefix): self.prefetch_through = prefix + LOOKUP_SEP + self.prefetch_through self.prefetch_to = prefix + LOOKUP_SEP + self.prefetch_to def get_current_prefetch_to(self, level): return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[: level + 1]) def get_current_to_attr(self, level): parts = self.prefetch_to.split(LOOKUP_SEP) to_attr = parts[level] as_attr = self.to_attr and level == len(parts) - 1 return to_attr, as_attr def get_current_queryset(self, level): if self.get_current_prefetch_to(level) == self.prefetch_to: return self.queryset return None def __eq__(self, other): if not isinstance(other, Prefetch): return NotImplemented return self.prefetch_to == other.prefetch_to def __hash__(self): return hash((self.__class__, self.prefetch_to)) def normalize_prefetch_lookups(lookups, prefix=None): """Normalize lookups into Prefetch objects.""" ret = [] for lookup in lookups: if not isinstance(lookup, Prefetch): lookup = Prefetch(lookup) if prefix: lookup.add_prefix(prefix) ret.append(lookup) return ret def prefetch_related_objects(model_instances, *related_lookups): """ Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given. """ if not model_instances: return # nothing to do # We need to be able to dynamically add to the list of prefetch_related # lookups that we look up (see below). So we need some book keeping to # ensure we don't do duplicate work. done_queries = {} # dictionary of things like 'foo__bar': [results] auto_lookups = set() # we add to this as we go through. followed_descriptors = set() # recursion protection all_lookups = normalize_prefetch_lookups(reversed(related_lookups)) while all_lookups: lookup = all_lookups.pop() if lookup.prefetch_to in done_queries: if lookup.queryset is not None: raise ValueError( "'%s' lookup was already seen with a different queryset. " "You may need to adjust the ordering of your lookups." % lookup.prefetch_to ) continue # Top level, the list of objects to decorate is the result cache # from the primary QuerySet. It won't be for deeper levels. obj_list = model_instances through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) for level, through_attr in enumerate(through_attrs): # Prepare main instances if not obj_list: break prefetch_to = lookup.get_current_prefetch_to(level) if prefetch_to in done_queries: # Skip any prefetching, and any object preparation obj_list = done_queries[prefetch_to] continue # Prepare objects: good_objects = True for obj in obj_list: # Since prefetching can re-use instances, it is possible to have # the same instance multiple times in obj_list, so obj might # already be prepared. if not hasattr(obj, "_prefetched_objects_cache"): try: obj._prefetched_objects_cache = {} except (AttributeError, TypeError): # Must be an immutable object from # values_list(flat=True), for example (TypeError) or # a QuerySet subclass that isn't returning Model # instances (AttributeError), either in Django or a 3rd # party. prefetch_related() doesn't make sense, so quit. good_objects = False break if not good_objects: break # Descend down tree # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] to_attr = lookup.get_current_to_attr(level)[0] prefetcher, descriptor, attr_found, is_fetched = get_prefetcher( first_obj, through_attr, to_attr ) if not attr_found: raise AttributeError( "Cannot find '%s' on %s object, '%s' is an invalid " "parameter to prefetch_related()" % ( through_attr, first_obj.__class__.__name__, lookup.prefetch_through, ) ) if level == len(through_attrs) - 1 and prefetcher is None: # Last one, this *must* resolve to something that supports # prefetching, otherwise there is no point adding it and the # developer asking for it has made a mistake. raise ValueError( "'%s' does not resolve to an item that supports " "prefetching - this is an invalid parameter to " "prefetch_related()." % lookup.prefetch_through ) obj_to_fetch = None if prefetcher is not None: obj_to_fetch = [obj for obj in obj_list if not is_fetched(obj)] if obj_to_fetch: obj_list, additional_lookups = prefetch_one_level( obj_to_fetch, prefetcher, lookup, level, ) # We need to ensure we don't keep adding lookups from the # same relationships to stop infinite recursion. So, if we # are already on an automatically added lookup, don't add # the new lookups from relationships we've seen already. if not ( prefetch_to in done_queries and lookup in auto_lookups and descriptor in followed_descriptors ): done_queries[prefetch_to] = obj_list new_lookups = normalize_prefetch_lookups( reversed(additional_lookups), prefetch_to ) auto_lookups.update(new_lookups) all_lookups.extend(new_lookups) followed_descriptors.add(descriptor) else: # Either a singly related object that has already been fetched # (e.g. via select_related), or hopefully some other property # that doesn't support prefetching but needs to be traversed. # We replace the current list of parent objects with the list # of related objects, filtering out empty or missing values so # that we can continue with nullable or reverse relations. new_obj_list = [] for obj in obj_list: if through_attr in getattr(obj, "_prefetched_objects_cache", ()): # If related objects have been prefetched, use the # cache rather than the object's through_attr. new_obj = list(obj._prefetched_objects_cache.get(through_attr)) else: try: new_obj = getattr(obj, through_attr) except exceptions.ObjectDoesNotExist: continue if new_obj is None: continue # We special-case `list` rather than something more generic # like `Iterable` because we don't want to accidentally match # user models that define __iter__. if isinstance(new_obj, list): new_obj_list.extend(new_obj) else: new_obj_list.append(new_obj) obj_list = new_obj_list def get_prefetcher(instance, through_attr, to_attr): """ For the attribute 'through_attr' on the given instance, find an object that has a get_prefetch_queryset(). Return a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute was not found at all, a function that takes an instance and returns a boolean that is True if the attribute has already been fetched for that instance) """ def has_to_attr_attribute(instance): return hasattr(instance, to_attr) prefetcher = None is_fetched = has_to_attr_attribute # For singly related objects, we have to avoid getting the attribute # from the object, as this will trigger the query. So we first try # on the class, in order to get the descriptor object. rel_obj_descriptor = getattr(instance.__class__, through_attr, None) if rel_obj_descriptor is None: attr_found = hasattr(instance, through_attr) else: attr_found = True if rel_obj_descriptor: # singly related object, descriptor object has the # get_prefetch_queryset() method. if hasattr(rel_obj_descriptor, "get_prefetch_queryset"): prefetcher = rel_obj_descriptor is_fetched = rel_obj_descriptor.is_cached else: # descriptor doesn't support prefetching, so we go ahead and get # the attribute on the instance rather than the class to # support many related managers rel_obj = getattr(instance, through_attr) if hasattr(rel_obj, "get_prefetch_queryset"): prefetcher = rel_obj if through_attr != to_attr: # Special case cached_property instances because hasattr # triggers attribute computation and assignment. if isinstance( getattr(instance.__class__, to_attr, None), cached_property ): def has_cached_property(instance): return to_attr in instance.__dict__ is_fetched = has_cached_property else: def in_prefetched_cache(instance): return through_attr in instance._prefetched_objects_cache is_fetched = in_prefetched_cache return prefetcher, rel_obj_descriptor, attr_found, is_fetched def prefetch_one_level(instances, prefetcher, lookup, level): """ Helper function for prefetch_related_objects(). Run prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. Return the prefetched objects along with any additional prefetches that must be done due to prefetch_related lookups found from default managers. """ # prefetcher must have a method get_prefetch_queryset() which takes a list # of instances, and returns a tuple: # (queryset of instances of self.model that are related to passed in instances, # callable that gets value to be matched for returned instances, # callable that gets value to be matched for passed in instances, # boolean that is True for singly related objects, # cache or field name to assign to, # boolean that is True when the previous argument is a cache name vs a field name). # The 'values to be matched' must be hashable as they will be used # in a dictionary. ( rel_qs, rel_obj_attr, instance_attr, single, cache_name, is_descriptor, ) = prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level)) # We have to handle the possibility that the QuerySet we just got back # contains some prefetch_related lookups. We don't want to trigger the # prefetch_related functionality by evaluating the query. Rather, we need # to merge in the prefetch_related lookups. # Copy the lookups in case it is a Prefetch object which could be reused # later (happens in nested prefetch_related). additional_lookups = [ copy.copy(additional_lookup) for additional_lookup in getattr(rel_qs, "_prefetch_related_lookups", ()) ] if additional_lookups: # Don't need to clone because the manager should have given us a fresh # instance, so we access an internal instead of using public interface # for performance reasons. rel_qs._prefetch_related_lookups = () all_related_objects = list(rel_qs) rel_obj_cache = {} for rel_obj in all_related_objects: rel_attr_val = rel_obj_attr(rel_obj) rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj) to_attr, as_attr = lookup.get_current_to_attr(level) # Make sure `to_attr` does not conflict with a field. if as_attr and instances: # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. model = instances[0].__class__ try: model._meta.get_field(to_attr) except exceptions.FieldDoesNotExist: pass else: msg = "to_attr={} conflicts with a field on the {} model." raise ValueError(msg.format(to_attr, model.__name__)) # Whether or not we're prefetching the last part of the lookup. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level for obj in instances: instance_attr_val = instance_attr(obj) vals = rel_obj_cache.get(instance_attr_val, []) if single: val = vals[0] if vals else None if as_attr: # A to_attr has been given for the prefetch. setattr(obj, to_attr, val) elif is_descriptor: # cache_name points to a field name in obj. # This field is a descriptor for a related object. setattr(obj, cache_name, val) else: # No to_attr has been given for this prefetch operation and the # cache_name does not point to a descriptor. Store the value of # the field in the object's field cache. obj._state.fields_cache[cache_name] = val else: if as_attr: setattr(obj, to_attr, vals) else: manager = getattr(obj, to_attr) if leaf and lookup.queryset is not None: qs = manager._apply_rel_filters(lookup.queryset) else: qs = manager.get_queryset() qs._result_cache = vals # We don't want the individual qs doing prefetch_related now, # since we have merged this into the current work. qs._prefetch_done = True obj._prefetched_objects_cache[cache_name] = qs return all_related_objects, additional_lookups class RelatedPopulator: """ RelatedPopulator is used for select_related() object instantiation. The idea is that each select_related() model will be populated by a different RelatedPopulator instance. The RelatedPopulator instances get klass_info and select (computed in SQLCompiler) plus the used db as input for initialization. That data is used to compute which columns to use, how to instantiate the model, and how to populate the links between the objects. The actual creation of the objects is done in populate() method. This method gets row and from_obj as input and populates the select_related() model instance. """ def __init__(self, klass_info, select, db): self.db = db # Pre-compute needed attributes. The attributes are: # - model_cls: the possibly deferred model class to instantiate # - either: # - cols_start, cols_end: usually the columns in the row are # in the same order model_cls.__init__ expects them, so we # can instantiate by model_cls(*row[cols_start:cols_end]) # - reorder_for_init: When select_related descends to a child # class, then we want to reuse the already selected parent # data. However, in this case the parent data isn't necessarily # in the same order that Model.__init__ expects it to be, so # we have to reorder the parent data. The reorder_for_init # attribute contains a function used to reorder the field data # in the order __init__ expects it. # - pk_idx: the index of the primary key field in the reordered # model data. Used to check if a related object exists at all. # - init_list: the field attnames fetched from the database. For # deferred models this isn't the same as all attnames of the # model's fields. # - related_populators: a list of RelatedPopulator instances if # select_related() descends to related models from this model. # - local_setter, remote_setter: Methods to set cached values on # the object being populated and on the remote object. Usually # these are Field.set_cached_value() methods. select_fields = klass_info["select_fields"] from_parent = klass_info["from_parent"] if not from_parent: self.cols_start = select_fields[0] self.cols_end = select_fields[-1] + 1 self.init_list = [ f[0].target.attname for f in select[self.cols_start : self.cols_end] ] self.reorder_for_init = None else: attname_indexes = { select[idx][0].target.attname: idx for idx in select_fields } model_init_attnames = ( f.attname for f in klass_info["model"]._meta.concrete_fields ) self.init_list = [ attname for attname in model_init_attnames if attname in attname_indexes ] self.reorder_for_init = operator.itemgetter( *[attname_indexes[attname] for attname in self.init_list] ) self.model_cls = klass_info["model"] self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname) self.related_populators = get_related_populators(klass_info, select, self.db) self.local_setter = klass_info["local_setter"] self.remote_setter = klass_info["remote_setter"] def populate(self, row, from_obj): if self.reorder_for_init: obj_data = self.reorder_for_init(row) else: obj_data = row[self.cols_start : self.cols_end] if obj_data[self.pk_idx] is None: obj = None else: obj = self.model_cls.from_db(self.db, self.init_list, obj_data) for rel_iter in self.related_populators: rel_iter.populate(row, obj) self.local_setter(from_obj, obj) if obj is not None: self.remote_setter(obj, from_obj) def get_related_populators(klass_info, select, db): iterators = [] related_klass_infos = klass_info.get("related_klass_infos", []) for rel_klass_info in related_klass_infos: rel_cls = RelatedPopulator(rel_klass_info, select, db) iterators.append(rel_cls) return iterators
9fdee9e2ad2db70988d57705f5d025f0f7e0e59b3c8ae76e7e159e6d0ed76aed
import copy import inspect from functools import wraps from importlib import import_module from django.db import router from django.db.models.query import QuerySet class BaseManager: # To retain order, track each time a Manager instance is created. creation_counter = 0 # Set to True for the 'objects' managers that are automatically created. auto_created = False #: If set to True the manager will be serialized into migrations and will #: thus be available in e.g. RunPython operations. use_in_migrations = False def __new__(cls, *args, **kwargs): # Capture the arguments to make returning them trivial. obj = super().__new__(cls) obj._constructor_args = (args, kwargs) return obj def __init__(self): super().__init__() self._set_creation_counter() self.model = None self.name = None self._db = None self._hints = {} def __str__(self): """Return "app_label.model_label.manager_name".""" return "%s.%s" % (self.model._meta.label, self.name) def __class_getitem__(cls, *args, **kwargs): return cls def deconstruct(self): """ Return a 5-tuple of the form (as_manager (True), manager_class, queryset_class, args, kwargs). Raise a ValueError if the manager is dynamically generated. """ qs_class = self._queryset_class if getattr(self, "_built_with_as_manager", False): # using MyQuerySet.as_manager() return ( True, # as_manager None, # manager_class "%s.%s" % (qs_class.__module__, qs_class.__name__), # qs_class None, # args None, # kwargs ) else: module_name = self.__module__ name = self.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find manager %s in %s.\n" "Please note that you need to inherit from managers you " "dynamically generated with 'from_queryset()'." % (name, module_name) ) return ( False, # as_manager "%s.%s" % (module_name, name), # manager_class None, # qs_class self._constructor_args[0], # args self._constructor_args[1], # kwargs ) def check(self, **kwargs): return [] @classmethod def _get_queryset_methods(cls, queryset_class): def create_method(name, method): @wraps(method) def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) return manager_method new_methods = {} for name, method in inspect.getmembers( queryset_class, predicate=inspect.isfunction ): # Only copy missing methods. if hasattr(cls, name): continue # Only copy public methods or methods with the attribute # queryset_only=False. queryset_only = getattr(method, "queryset_only", None) if queryset_only or (queryset_only is None and name.startswith("_")): continue # Copy the method onto the manager. new_methods[name] = create_method(name, method) return new_methods @classmethod def from_queryset(cls, queryset_class, class_name=None): if class_name is None: class_name = "%sFrom%s" % (cls.__name__, queryset_class.__name__) return type( class_name, (cls,), { "_queryset_class": queryset_class, **cls._get_queryset_methods(queryset_class), }, ) def contribute_to_class(self, cls, name): self.name = self.name or name self.model = cls setattr(cls, name, ManagerDescriptor(self)) cls._meta.add_manager(self) def _set_creation_counter(self): """ Set the creation counter value for this instance and increment the class-level copy. """ self.creation_counter = BaseManager.creation_counter BaseManager.creation_counter += 1 def db_manager(self, using=None, hints=None): obj = copy.copy(self) obj._db = using or self._db obj._hints = hints or self._hints return obj @property def db(self): return self._db or router.db_for_read(self.model, **self._hints) ####################### # PROXIES TO QUERYSET # ####################### def get_queryset(self): """ Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager. """ return self._queryset_class(model=self.model, using=self._db, hints=self._hints) def all(self): # We can't proxy this method through the `QuerySet` like we do for the # rest of the `QuerySet` methods. This is because `QuerySet.all()` # works by creating a "copy" of the current queryset and in making said # copy, all the cached `prefetch_related` lookups are lost. See the # implementation of `RelatedManager.get_queryset()` for a better # understanding of how this comes into play. return self.get_queryset() def __eq__(self, other): return ( isinstance(other, self.__class__) and self._constructor_args == other._constructor_args ) def __hash__(self): return id(self) class Manager(BaseManager.from_queryset(QuerySet)): pass class ManagerDescriptor: def __init__(self, manager): self.manager = manager def __get__(self, instance, cls=None): if instance is not None: raise AttributeError( "Manager isn't accessible via %s instances" % cls.__name__ ) if cls._meta.abstract: raise AttributeError( "Manager isn't available; %s is abstract" % (cls._meta.object_name,) ) if cls._meta.swapped: raise AttributeError( "Manager isn't available; '%s' has been swapped for '%s'" % ( cls._meta.label, cls._meta.swapped, ) ) return cls._meta.managers_map[self.manager.name] class EmptyManager(Manager): def __init__(self, model): super().__init__() self.model = model def get_queryset(self): return super().get_queryset().none()
ffabf80660e234bf4e1bc2ca3e308974bf669cd06882153abac0a9a0c8cfabc2
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ import copy import difflib import functools import sys from collections import Counter, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product from string import ascii_uppercase from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections from django.db.models.aggregates import Count from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import ( BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef, Value, ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ["Query", "RawQuery"] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def get_field_names_from_opts(opts): if opts is None: return set() return set( chain.from_iterable( (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields() ) ) def get_children_from_q(q): for child in q.children: if isinstance(child, Node): yield from get_children_from_q(child) else: yield child JoinInfo = namedtuple( "JoinInfo", ("final_field", "targets", "opts", "joins", "path", "transform_function"), ) class RawQuery: """A single raw SQL query.""" def __init__(self, sql, using, params=()): self.params = params self.sql = sql self.using = using self.cursor = None # Mirror some properties of a normal query so that # the compiler can be used to process results. self.low_mark, self.high_mark = 0, None # Used for offset/limit self.extra_select = {} self.annotation_select = {} def chain(self, using): return self.clone(using) def clone(self, using): return RawQuery(self.sql, using, params=self.params) def get_columns(self): if self.cursor is None: self._execute_query() converter = connections[self.using].introspection.identifier_converter return [converter(column_meta[0]) for column_meta in self.cursor.description] def __iter__(self): # Always execute a new query for a new iterator. # This could be optimized with a cache at the expense of RAM. self._execute_query() if not connections[self.using].features.can_use_chunked_reads: # If the database can't use chunked reads we need to make sure we # evaluate the entire query up front. result = list(self.cursor) else: result = self.cursor return iter(result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) @property def params_type(self): if self.params is None: return None return dict if isinstance(self.params, Mapping) else tuple def __str__(self): if self.params_type is None: return self.sql return self.sql % self.params_type(self.params) def _execute_query(self): connection = connections[self.using] # Adapt parameters to the database, as much as possible considering # that the target type isn't known. See #17755. params_type = self.params_type adapter = connection.ops.adapt_unknown_value if params_type is tuple: params = tuple(adapter(val) for val in self.params) elif params_type is dict: params = {key: adapter(val) for key, val in self.params.items()} elif params_type is None: params = None else: raise RuntimeError("Unexpected params type: %s" % params_type) self.cursor = connection.cursor() self.cursor.execute(self.sql, params) ExplainInfo = namedtuple("ExplainInfo", ("format", "options")) class Query(BaseExpression): """A single SQL query.""" alias_prefix = "T" empty_result_set_value = None subq_aliases = frozenset([alias_prefix]) compiler = "SQLCompiler" base_table_class = BaseTable join_class = Join default_cols = True default_ordering = True standard_ordering = True filter_is_sticky = False subquery = False # SQL-related attributes. # Select and related select clauses are expressions to use in the SELECT # clause of the query. The select is used for cases where we want to set up # the select clause to contain other than default fields (values(), # subqueries...). Note that annotations go to annotations dictionary. select = () # The group_by attribute can have one of the following forms: # - None: no group by at all in the query # - A tuple of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. group_by = None order_by = () low_mark = 0 # Used for offset/limit. high_mark = None # Used for offset/limit. distinct = False distinct_fields = () select_for_update = False select_for_update_nowait = False select_for_update_skip_locked = False select_for_update_of = () select_for_no_key_update = False select_related = False # Arbitrary limit for select_related to prevents infinite recursion. max_depth = 5 # Holds the selects defined by a call to values() or values_list() # excluding annotation_select and extra_select. values_select = () # SQL annotation-related attributes. annotation_select_mask = None _annotation_select_cache = None # Set combination attributes. combinator = None combinator_all = False combined_queries = () # These are for extensions. The contents are more or less appended verbatim # to the appropriate clause. extra_select_mask = None _extra_select_cache = None extra_tables = () extra_order_by = () # A tuple that is a set of model field names and either True, if these are # the fields to defer, or False if these are the only fields to load. deferred_loading = (frozenset(), True) explain_info = None def __init__(self, model, alias_cols=True): self.model = model self.alias_refcount = {} # alias_map is the most important data structure regarding joins. # It's used for recording which joins exist in the query and what # types they are. The key is the alias of the joined table (possibly # the table name) and the value is a Join-like object (see # sql.datastructures.Join for more information). self.alias_map = {} # Whether to provide alias to columns during reference resolving. self.alias_cols = alias_cols # Sometimes the query contains references to aliases in outer queries (as # a result of split_exclude). Correct alias quoting needs to know these # aliases too. # Map external tables to whether they are aliased. self.external_aliases = {} self.table_map = {} # Maps table names to list of aliases. self.used_aliases = set() self.where = WhereNode() # Maps alias -> Annotation Expression. self.annotations = {} # These are for extensions. The contents are more or less appended # verbatim to the appropriate clause. self.extra = {} # Maps col_alias -> (col_sql, params). self._filtered_relations = {} @property def output_field(self): if len(self.select) == 1: select = self.select[0] return getattr(select, "target", None) or select.field elif len(self.annotation_select) == 1: return next(iter(self.annotation_select.values())).output_field @property def has_select_fields(self): return bool( self.select or self.annotation_select_mask or self.extra_select_mask ) @cached_property def base_table(self): for alias in self.alias_map: return alias def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params def sql_with_params(self): """ Return the query as an SQL string and the parameters that will be substituted into the query. """ return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() def __deepcopy__(self, memo): """Limit the amount of work when a Query is deepcopied.""" result = self.clone() memo[id(self)] = result return result def get_compiler(self, using=None, connection=None, elide_empty=True): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return connection.ops.compiler(self.compiler)( self, connection, using, elide_empty ) def get_meta(self): """ Return the Options instance (the model._meta) from which to start processing. Normally, this is self.model._meta, but it can be changed by subclasses. """ if self.model: return self.model._meta def clone(self): """ Return a copy of the current Query. A lightweight alternative to deepcopy(). """ obj = Empty() obj.__class__ = self.__class__ # Copy references to everything. obj.__dict__ = self.__dict__.copy() # Clone attributes that can't use shallow copy. obj.alias_refcount = self.alias_refcount.copy() obj.alias_map = self.alias_map.copy() obj.external_aliases = self.external_aliases.copy() obj.table_map = self.table_map.copy() obj.where = self.where.clone() obj.annotations = self.annotations.copy() if self.annotation_select_mask is not None: obj.annotation_select_mask = self.annotation_select_mask.copy() if self.combined_queries: obj.combined_queries = tuple( [query.clone() for query in self.combined_queries] ) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. # It will get re-populated in the cloned queryset the next time it's # used. obj._annotation_select_cache = None obj.extra = self.extra.copy() if self.extra_select_mask is not None: obj.extra_select_mask = self.extra_select_mask.copy() if self._extra_select_cache is not None: obj._extra_select_cache = self._extra_select_cache.copy() if self.select_related is not False: # Use deepcopy because select_related stores fields in nested # dicts. obj.select_related = copy.deepcopy(obj.select_related) if "subq_aliases" in self.__dict__: obj.subq_aliases = self.subq_aliases.copy() obj.used_aliases = self.used_aliases.copy() obj._filtered_relations = self._filtered_relations.copy() # Clear the cached_property, if it exists. obj.__dict__.pop("base_table", None) return obj def chain(self, klass=None): """ Return a copy of the current Query that's ready for another operation. The klass argument changes the type of the Query, e.g. UpdateQuery. """ obj = self.clone() if klass and obj.__class__ != klass: obj.__class__ = klass if not obj.filter_is_sticky: obj.used_aliases = set() obj.filter_is_sticky = False if hasattr(obj, "_setup_query"): obj._setup_query() return obj def relabeled_clone(self, change_map): clone = self.clone() clone.change_aliases(change_map) return clone def _get_col(self, target, field, alias): if not self.alias_cols: alias = None return target.get_col(alias, field) def rewrite_cols(self, annotation, col_cnt): # We must make sure the inner query has the referred columns in it. # If we are aggregating over an annotation, then Django uses Ref() # instances to note this. However, if we are annotating over a column # of a related model, then it might be that column isn't part of the # SELECT clause of the inner query, and we must manually make sure # the column is selected. An example case is: # .aggregate(Sum('author__awards')) # Resolving this expression results in a join to author, but there # is no guarantee the awards column of author is in the select clause # of the query. Thus we must manually add the column to the inner # query. orig_exprs = annotation.get_source_expressions() new_exprs = [] for expr in orig_exprs: # FIXME: These conditions are fairly arbitrary. Identify a better # method of having expressions decide which code path they should # take. if isinstance(expr, Ref): # Its already a Ref to subquery (see resolve_ref() for # details) new_exprs.append(expr) elif isinstance(expr, (WhereNode, Lookup)): # Decompose the subexpressions further. The code here is # copied from the else clause, but this condition must appear # before the contains_aggregate/is_summary condition below. new_expr, col_cnt = self.rewrite_cols(expr, col_cnt) new_exprs.append(new_expr) else: # Reuse aliases of expressions already selected in subquery. for col_alias, selected_annotation in self.annotation_select.items(): if selected_annotation is expr: new_expr = Ref(col_alias, expr) break else: # An expression that is not selected the subquery. if isinstance(expr, Col) or ( expr.contains_aggregate and not expr.is_summary ): # Reference column or another aggregate. Select it # under a non-conflicting alias. col_cnt += 1 col_alias = "__col%d" % col_cnt self.annotations[col_alias] = expr self.append_annotation_mask([col_alias]) new_expr = Ref(col_alias, expr) else: # Some other expression not referencing database values # directly. Its subexpression might contain Cols. new_expr, col_cnt = self.rewrite_cols(expr, col_cnt) new_exprs.append(new_expr) annotation.set_source_expressions(new_exprs) return annotation, col_cnt def get_aggregation(self, using, added_aggregate_names): """ Return the dictionary with the values of the existing aggregations. """ if not self.annotation_select: return {} existing_annotations = [ annotation for alias, annotation in self.annotations.items() if alias not in added_aggregate_names ] # Decide if we need to use a subquery. # # Existing annotations would cause incorrect results as get_aggregation() # must produce just one result and thus must not use GROUP BY. But we # aren't smart enough to remove the existing annotations from the # query, so those would force us to use GROUP BY. # # If the query has limit or distinct, or uses set operations, then # those operations must be done in a subquery so that the query # aggregates on the limit and/or distinct results instead of applying # the distinct and limit after the aggregation. if ( isinstance(self.group_by, tuple) or self.is_sliced or existing_annotations or self.distinct or self.combinator ): from django.db.models.sql.subqueries import AggregateQuery inner_query = self.clone() inner_query.subquery = True outer_query = AggregateQuery(self.model, inner_query) inner_query.select_for_update = False inner_query.select_related = False inner_query.set_annotation_mask(self.annotation_select) # Queries with distinct_fields need ordering and when a limit is # applied we must take the slice from the ordered query. Otherwise # no need for ordering. inner_query.clear_ordering(force=False) if not inner_query.distinct: # If the inner query uses default select and it has some # aggregate annotations, then we must make sure the inner # query is grouped by the main model's primary key. However, # clearing the select clause can alter results if distinct is # used. has_existing_aggregate_annotations = any( annotation for annotation in existing_annotations if getattr(annotation, "contains_aggregate", True) ) if inner_query.default_cols and has_existing_aggregate_annotations: inner_query.group_by = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) inner_query.default_cols = False relabels = {t: "subquery" for t in inner_query.alias_map} relabels[None] = "subquery" # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. col_cnt = 0 for alias, expression in list(inner_query.annotation_select.items()): annotation_select_mask = inner_query.annotation_select_mask if expression.is_summary: expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt) outer_query.annotations[alias] = expression.relabeled_clone( relabels ) del inner_query.annotations[alias] annotation_select_mask.remove(alias) # Make sure the annotation_select wont use cached results. inner_query.set_annotation_mask(inner_query.annotation_select_mask) if ( inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask ): # In case of Model.objects[0:3].count(), there would be no # field selected in the inner query, yet we must use a subquery. # So, make sure at least one field is selected. inner_query.select = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) else: outer_query = self self.select = () self.default_cols = False self.extra = {} empty_set_result = [ expression.empty_result_set_value for expression in outer_query.annotation_select.values() ] elide_empty = not any(result is NotImplemented for result in empty_set_result) outer_query.clear_ordering(force=True) outer_query.clear_limits() outer_query.select_for_update = False outer_query.select_related = False compiler = outer_query.get_compiler(using, elide_empty=elide_empty) result = compiler.execute_sql(SINGLE) if result is None: result = empty_set_result converters = compiler.get_converters(outer_query.annotation_select.values()) result = next(compiler.apply_converters((result,), converters)) return dict(zip(outer_query.annotation_select, result)) def get_count(self, using): """ Perform a COUNT() query using the current filter constraints. """ obj = self.clone() obj.add_annotation(Count("*"), alias="__count", is_summary=True) return obj.get_aggregation(using, ["__count"])["__count"] def has_filters(self): return self.where def exists(self, using, limit=True): q = self.clone() if not (q.distinct and q.is_sliced): if q.group_by is True: q.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. q.set_group_by(allow_aliases=False) q.clear_select_clause() if q.combined_queries and q.combinator == "union": limit_combined = connections[ using ].features.supports_slicing_ordering_in_compound q.combined_queries = tuple( combined_query.exists(using, limit=limit_combined) for combined_query in q.combined_queries ) q.clear_ordering(force=True) if limit: q.set_limits(high=1) q.add_annotation(Value(1), "a") return q def has_results(self, using): q = self.exists(using) compiler = q.get_compiler(using=using) return compiler.has_results() def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"Invalid option name: {option_name!r}.") q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query()) def combine(self, rhs, connector): """ Merge the 'rhs' query into the current one (with any 'rhs' effects being applied *after* (that is, "to the right of") anything in the current query. 'rhs' is not modified during a call to this function. The 'connector' parameter describes how to connect filters from the 'rhs' query. """ if self.model != rhs.model: raise TypeError("Cannot combine queries on two different base models.") if self.is_sliced: raise TypeError("Cannot combine queries once a slice has been taken.") if self.distinct != rhs.distinct: raise TypeError("Cannot combine a unique query with a non-unique query.") if self.distinct_fields != rhs.distinct_fields: raise TypeError("Cannot combine queries with different distinct fields.") # If lhs and rhs shares the same alias prefix, it is possible to have # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up # as T4 -> T6 while combining two querysets. To prevent this, change an # alias prefix of the rhs and update current aliases accordingly, # except if the alias is the base table since it must be present in the # query on both sides. initial_alias = self.get_initial_alias() rhs.bump_prefix(self, exclude={initial_alias}) # Work out how to relabel the rhs aliases, if necessary. change_map = {} conjunction = connector == AND # Determine which existing joins can be reused. When combining the # query with AND we must recreate all joins for m2m filters. When # combining with OR we can reuse joins. The reason is that in AND # case a single row can't fulfill a condition like: # revrel__col=1 & revrel__col=2 # But, there might be two different related rows matching this # condition. In OR case a single True is enough, so single row is # enough, too. # # Note that we will be creating duplicate joins for non-m2m joins in # the AND case. The results will be correct but this creates too many # joins. This is something that could be fixed later on. reuse = set() if conjunction else set(self.alias_map) joinpromoter = JoinPromoter(connector, 2, False) joinpromoter.add_votes( j for j in self.alias_map if self.alias_map[j].join_type == INNER ) rhs_votes = set() # Now, add the joins from rhs query into the new query (skipping base # table). rhs_tables = list(rhs.alias_map)[1:] for alias in rhs_tables: join = rhs.alias_map[alias] # If the left side of the join was already relabeled, use the # updated alias. join = join.relabeled_clone(change_map) new_alias = self.join(join, reuse=reuse) if join.join_type == INNER: rhs_votes.add(new_alias) # We can't reuse the same join again in the query. If we have two # distinct joins for the same connection in rhs query, then the # combined query must have two joins, too. reuse.discard(new_alias) if alias != new_alias: change_map[alias] = new_alias if not rhs.alias_refcount[alias]: # The alias was unused in the rhs query. Unref it so that it # will be unused in the new query, too. We have to add and # unref the alias so that join promotion has information of # the join type for the unused alias. self.unref_alias(new_alias) joinpromoter.add_votes(rhs_votes) joinpromoter.update_join_types(self) # Combine subqueries aliases to ensure aliases relabelling properly # handle subqueries when combining where and select clauses. self.subq_aliases |= rhs.subq_aliases # Now relabel a copy of the rhs where-clause and add it to the current # one. w = rhs.where.clone() w.relabel_aliases(change_map) self.where.add(w, connector) # Selection columns and extra extensions are those provided by 'rhs'. if rhs.select: self.set_select([col.relabeled_clone(change_map) for col in rhs.select]) else: self.select = () if connector == OR: # It would be nice to be able to handle this, but the queries don't # really make sense (or return consistent value sets). Not worth # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( "When merging querysets using 'or', you cannot have " "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() if self.extra_select_mask is not None: extra_select_mask.update(self.extra_select_mask) if rhs.extra_select_mask is not None: extra_select_mask.update(rhs.extra_select_mask) if extra_select_mask: self.set_extra_mask(extra_select_mask) self.extra_tables += rhs.extra_tables # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. self.order_by = rhs.order_by or self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def deferred_to_data(self, target): """ Convert the self.deferred_loading data structure to an alternate data structure, describing the field that *will* be loaded. This is used to compute the columns to select from the database and also by the QuerySet class to work out which fields are being initialized on each model. Models that have all their fields included aren't mentioned in the result, only those that have field restrictions in place. The "target" parameter is the instance that is populated (in place). """ field_names, defer = self.deferred_loading if not field_names: return orig_opts = self.get_meta() seen = {} must_include = {orig_opts.concrete_model: {orig_opts.pk}} for field_name in field_names: parts = field_name.split(LOOKUP_SEP) cur_model = self.model._meta.concrete_model opts = orig_opts for name in parts[:-1]: old_model = cur_model if name in self._filtered_relations: name = self._filtered_relations[name].relation_name source = opts.get_field(name) if is_reverse_o2o(source): cur_model = source.related_model else: cur_model = source.remote_field.model opts = cur_model._meta # Even if we're "just passing through" this model, we must add # both the current model's pk and the related reference field # (if it's not a reverse relation) to the things we select. if not is_reverse_o2o(source): must_include[old_model].add(source) add_to_dict(must_include, cur_model, opts.pk) field = opts.get_field(parts[-1]) is_reverse_object = field.auto_created and not field.concrete model = field.related_model if is_reverse_object else field.model model = model._meta.concrete_model if model == opts.model: model = cur_model if not is_reverse_o2o(field): add_to_dict(seen, model, field) if defer: # We need to load all fields for each model, except those that # appear in "seen" (for all models that appear in "seen"). The only # slight complexity here is handling fields that exist on parent # models. workset = {} for model, values in seen.items(): for field in model._meta.local_fields: if field not in values: m = field.model._meta.concrete_model add_to_dict(workset, m, field) for model, values in must_include.items(): # If we haven't included a model in workset, we don't add the # corresponding must_include fields for that model, since an # empty set means "include all fields". That's why there's no # "else" branch here. if model in workset: workset[model].update(values) for model, fields in workset.items(): target[model] = {f.attname for f in fields} else: for model, values in must_include.items(): if model in seen: seen[model].update(values) else: # As we've passed through this model, but not explicitly # included any fields, we have to make sure it's mentioned # so that only the "must include" fields are pulled in. seen[model] = values # Now ensure that every model in the inheritance chain is mentioned # in the parent list. Again, it must be mentioned to ensure that # only "must include" fields are pulled in. for model in orig_opts.get_parent_list(): seen.setdefault(model, set()) for model, fields in seen.items(): target[model] = {f.attname for f in fields} def table_alias(self, table_name, create=False, filtered_relation=None): """ Return a table alias for the given table_name and whether this is a new alias or not. If 'create' is true, a new alias is always created. Otherwise, the most recently created alias for the table (if one exists) is reused. """ alias_list = self.table_map.get(table_name) if not create and alias_list: alias = alias_list[0] self.alias_refcount[alias] += 1 return alias, False # Create a new alias for this table. if alias_list: alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1) alias_list.append(alias) else: # The first occurrence of a table uses the table name directly. alias = ( filtered_relation.alias if filtered_relation is not None else table_name ) self.table_map[table_name] = [alias] self.alias_refcount[alias] = 1 return alias, True def ref_alias(self, alias): """Increases the reference count for this alias.""" self.alias_refcount[alias] += 1 def unref_alias(self, alias, amount=1): """Decreases the reference count for this alias.""" self.alias_refcount[alias] -= amount def promote_joins(self, aliases): """ Promote recursively the join type of given aliases and its children to an outer join. If 'unconditional' is False, only promote the join if it is nullable or the parent join is an outer join. The children promotion is done to avoid join chains that contain a LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted, then we must also promote b->c automatically, or otherwise the promotion of a->b doesn't actually change anything in the query results. """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type is None: # This is the base table (first FROM entry) - this table # isn't really joined at all in the query, so we should not # alter its join type. continue # Only the first alias (skipped above) should have None join_type assert self.alias_map[alias].join_type is not None parent_alias = self.alias_map[alias].parent_alias parent_louter = ( parent_alias and self.alias_map[parent_alias].join_type == LOUTER ) already_louter = self.alias_map[alias].join_type == LOUTER if (self.alias_map[alias].nullable or parent_louter) and not already_louter: self.alias_map[alias] = self.alias_map[alias].promote() # Join type of 'alias' changed, so re-examine all aliases that # refer to this one. aliases.extend( join for join in self.alias_map if self.alias_map[join].parent_alias == alias and join not in aliases ) def demote_joins(self, aliases): """ Change join type from LOUTER to INNER for all joins in aliases. Similarly to promote_joins(), this method must ensure no join chains containing first an outer, then an inner join are generated. If we are demoting b->c join in chain a LOUTER b LOUTER c then we must demote a->b automatically, or otherwise the demotion of b->c doesn't actually change anything in the query results. . """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type == LOUTER: self.alias_map[alias] = self.alias_map[alias].demote() parent_alias = self.alias_map[alias].parent_alias if self.alias_map[parent_alias].join_type == INNER: aliases.append(parent_alias) def reset_refcounts(self, to_counts): """ Reset reference counts for aliases so that they match the value passed in `to_counts`. """ for alias, cur_refcount in self.alias_refcount.copy().items(): unref_amount = cur_refcount - to_counts.get(alias, 0) self.unref_alias(alias, unref_amount) def change_aliases(self, change_map): """ Change the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause. """ # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. assert set(change_map).isdisjoint(change_map.values()) # 1. Update references in "select" (normal columns plus aliases), # "group by" and "where". self.where.relabel_aliases(change_map) if isinstance(self.group_by, tuple): self.group_by = tuple( [col.relabeled_clone(change_map) for col in self.group_by] ) self.select = tuple([col.relabeled_clone(change_map) for col in self.select]) self.annotations = self.annotations and { key: col.relabeled_clone(change_map) for key, col in self.annotations.items() } # 2. Rename the alias in the internal table/alias datastructures. for old_alias, new_alias in change_map.items(): if old_alias not in self.alias_map: continue alias_data = self.alias_map[old_alias].relabeled_clone(change_map) self.alias_map[new_alias] = alias_data self.alias_refcount[new_alias] = self.alias_refcount[old_alias] del self.alias_refcount[old_alias] del self.alias_map[old_alias] table_aliases = self.table_map[alias_data.table_name] for pos, alias in enumerate(table_aliases): if alias == old_alias: table_aliases[pos] = new_alias break self.external_aliases = { # Table is aliased or it's being changed and thus is aliased. change_map.get(alias, alias): (aliased or alias in change_map) for alias, aliased in self.external_aliases.items() } def bump_prefix(self, other_query, exclude=None): """ Change the alias prefix to the next letter in the alphabet in a way that the other query's aliases and this query's aliases will not conflict. Even tables that previously had no alias will get an alias after this call. To prevent changing aliases use the exclude parameter. """ def prefix_gen(): """ Generate a sequence of characters in alphabetical order: -> 'A', 'B', 'C', ... When the alphabet is finished, the sequence will continue with the Cartesian product: -> 'AA', 'AB', 'AC', ... """ alphabet = ascii_uppercase prefix = chr(ord(self.alias_prefix) + 1) yield prefix for n in count(1): seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet for s in product(seq, repeat=n): yield "".join(s) prefix = None if self.alias_prefix != other_query.alias_prefix: # No clashes between self and outer query should be possible. return # Explicitly avoid infinite loop. The constant divider is based on how # much depth recursive subquery references add to the stack. This value # might need to be adjusted when adding or removing function calls from # the code path in charge of performing these operations. local_recursion_limit = sys.getrecursionlimit() // 16 for pos, prefix in enumerate(prefix_gen()): if prefix not in self.subq_aliases: self.alias_prefix = prefix break if pos > local_recursion_limit: raise RecursionError( "Maximum recursion depth exceeded: too many subqueries." ) self.subq_aliases = self.subq_aliases.union([self.alias_prefix]) other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases) if exclude is None: exclude = {} self.change_aliases( { alias: "%s%d" % (self.alias_prefix, pos) for pos, alias in enumerate(self.alias_map) if alias not in exclude } ) def get_initial_alias(self): """ Return the first alias for this query, after increasing its reference count. """ if self.alias_map: alias = self.base_table self.ref_alias(alias) elif self.model: alias = self.join(self.base_table_class(self.get_meta().db_table, None)) else: alias = None return alias def count_active_tables(self): """ Return the number of tables in this query with a non-zero reference count. After execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method. """ return len([1 for count in self.alias_refcount.values() if count]) def join(self, join, reuse=None, reuse_with_filtered_relation=False): """ Return an alias for the 'join', either reusing an existing alias for that join or creating a new one. 'join' is either a base_table_class or join_class. The 'reuse' parameter can be either None which means all joins are reusable, or it can be a set containing the aliases that can be reused. The 'reuse_with_filtered_relation' parameter is used when computing FilteredRelation instances. A join is always created as LOUTER if the lhs alias is LOUTER to make sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new joins are created as LOUTER if the join is nullable. """ if reuse_with_filtered_relation and reuse: reuse_aliases = [ a for a, j in self.alias_map.items() if a in reuse and j.equals(join) ] else: reuse_aliases = [ a for a, j in self.alias_map.items() if (reuse is None or a in reuse) and j == join ] if reuse_aliases: if join.table_alias in reuse_aliases: reuse_alias = join.table_alias else: # Reuse the most recent alias of the joined table # (a many-to-many relation may be joined multiple times). reuse_alias = reuse_aliases[-1] self.ref_alias(reuse_alias) return reuse_alias # No reuse is possible, so we need a new alias. alias, _ = self.table_alias( join.table_name, create=True, filtered_relation=join.filtered_relation ) if join.join_type: if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable: join_type = LOUTER else: join_type = INNER join.join_type = join_type join.table_alias = alias self.alias_map[alias] = join return alias def join_parent_model(self, opts, model, alias, seen): """ Make sure the given 'model' is joined in the query. If 'model' isn't a parent of 'opts' or if it is None this method is a no-op. The 'alias' is the root alias for starting the join, 'seen' is a dict of model -> alias of existing joins. It must also contain a mapping of None -> some alias. This will be returned in the no-op case. """ if model in seen: return seen[model] chain = opts.get_base_chain(model) if not chain: return alias curr_opts = opts for int_model in chain: if int_model in seen: curr_opts = int_model._meta alias = seen[int_model] continue # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not curr_opts.parents[int_model]: curr_opts = int_model._meta continue link_field = curr_opts.get_ancestor_link(int_model) join_info = self.setup_joins([link_field.name], curr_opts, alias) curr_opts = int_model._meta alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) def add_annotation(self, annotation, alias, is_summary=False, select=True): """Add a single annotation expression to the Query.""" self.check_alias(alias) annotation = annotation.resolve_expression( self, allow_joins=True, reuse=None, summarize=is_summary ) if select: self.append_annotation_mask([alias]) else: self.set_annotation_mask(set(self.annotation_select).difference({alias})) self.annotations[alias] = annotation def resolve_expression(self, query, *args, **kwargs): clone = self.clone() # Subqueries need to use a different set of aliases than the outer query. clone.bump_prefix(query) clone.subquery = True clone.where.resolve_expression(query, *args, **kwargs) # Resolve combined queries. if clone.combinator: clone.combined_queries = tuple( [ combined_query.resolve_expression(query, *args, **kwargs) for combined_query in clone.combined_queries ] ) for key, value in clone.annotations.items(): resolved = value.resolve_expression(query, *args, **kwargs) if hasattr(resolved, "external_aliases"): resolved.external_aliases.update(clone.external_aliases) clone.annotations[key] = resolved # Outer query's aliases are considered external. for alias, table in query.alias_map.items(): clone.external_aliases[alias] = ( isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias ) or ( isinstance(table, BaseTable) and table.table_name != table.table_alias ) return clone def get_external_cols(self): exprs = chain(self.annotations.values(), self.where.children) return [ col for col in self._gen_cols(exprs, include_external=True) if col.alias in self.external_aliases ] def get_group_by_cols(self, alias=None): if alias: return [Ref(alias, self)] external_cols = self.get_external_cols() if any(col.possibly_multivalued for col in external_cols): return [self] return external_cols def as_sql(self, compiler, connection): # Some backends (e.g. Oracle) raise an error when a subquery contains # unnecessary ORDER BY clause. if ( self.subquery and not connection.features.ignores_unnecessary_order_by_in_subqueries ): self.clear_ordering(force=False) for query in self.combined_queries: query.clear_ordering(force=False) sql, params = self.get_compiler(connection=connection).as_sql() if self.subquery: sql = "(%s)" % sql return sql, params def resolve_lookup_value(self, value, can_reuse, allow_joins): if hasattr(value, "resolve_expression"): value = value.resolve_expression( self, reuse=can_reuse, allow_joins=allow_joins, ) elif isinstance(value, (list, tuple)): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( self.resolve_lookup_value(sub_value, can_reuse, allow_joins) for sub_value in value ) type_ = type(value) if hasattr(type_, "_make"): # namedtuple return type_(*values) return type_(values) return value def solve_lookup_type(self, lookup): """ Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains'). """ lookup_splitted = lookup.split(LOOKUP_SEP) if self.annotations: expression, expression_lookups = refs_expression( lookup_splitted, self.annotations ) if expression: return expression_lookups, (), expression _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)] if len(lookup_parts) > 1 and not field_parts: raise FieldError( 'Invalid lookup "%s" for model %s".' % (lookup, self.get_meta().model.__name__) ) return lookup_parts, field_parts, False def check_query_object_type(self, value, opts, field): """ Check whether the object passed while querying is of the correct type. If not, raise a ValueError specifying the wrong object. """ if hasattr(value, "_meta"): if not check_rel_lookup_compatibility(value._meta.model, opts, field): raise ValueError( 'Cannot query "%s": Must be "%s" instance.' % (value, opts.object_name) ) def check_related_objects(self, field, value, opts): """Check the type of object passed to query relations.""" if field.is_relation: # Check that the field and the queryset use the same model in a # query like .filter(author=Author.objects.all()). For example, the # opts would be Author's (from the author field) and value.model # would be Author.objects.all() queryset's .model (Author also). # The field is the related field on the lhs side. if ( isinstance(value, Query) and not value.has_select_fields and not check_rel_lookup_compatibility(value.model, opts, field) ): raise ValueError( 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' % (value.model._meta.object_name, opts.object_name) ) elif hasattr(value, "_meta"): self.check_query_object_type(value, opts, field) elif hasattr(value, "__iter__"): for v in value: self.check_query_object_type(v, opts, field) def check_filterable(self, expression): """Raise an error if expression cannot be used in a WHERE clause.""" if hasattr(expression, "resolve_expression") and not getattr( expression, "filterable", True ): raise NotSupportedError( expression.__class__.__name__ + " is disallowed in the filter " "clause." ) if hasattr(expression, "get_source_expressions"): for expr in expression.get_source_expressions(): self.check_filterable(expr) def build_lookup(self, lookups, lhs, rhs): """ Try to extract transforms and lookup from given lhs. The lhs value is something that works like SQLExpression. The rhs value is what the lookup is going to compare against. The lookups is a list of names to extract using get_lookup() and get_transform(). """ # __exact is the default lookup if one isn't given. *transforms, lookup_name = lookups or ["exact"] for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: if lhs.field.is_relation: raise FieldError( "Related Field got invalid lookup: {}".format(lookup_name) ) # A lookup wasn't found. Try to interpret the name as a transform # and do an Exact lookup against it. lhs = self.try_transform(lhs, lookup_name) lookup_name = "exact" lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: return lookup = lookup_class(lhs, rhs) # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value unless the lookup supports it. if lookup.rhs is None and not lookup.can_use_none_as_rhs: if lookup_name not in ("exact", "iexact"): raise ValueError("Cannot use None as a query value") return lhs.get_lookup("isnull")(lhs, True) # For Oracle '' is equivalent to null. The check must be done at this # stage because join promotion can't be done in the compiler. Using # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here. # A similar thing is done in is_nullable(), too. if ( lookup_name == "exact" and lookup.rhs == "" and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ): return lhs.get_lookup("isnull")(lhs, True) return lookup def try_transform(self, lhs, name): """ Helper method for build_lookup(). Try to fetch and initialize a transform for name parameter from lhs. """ transform_class = lhs.get_transform(name) if transform_class: return transform_class(lhs) else: output_field = lhs.output_field.__class__ suggested_lookups = difflib.get_close_matches( name, output_field.get_lookups() ) if suggested_lookups: suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups) else: suggestion = "." raise FieldError( "Unsupported lookup '%s' for %s or join on the field not " "permitted%s" % (name, output_field.__name__, suggestion) ) def build_filter( self, filter_expr, branch_negated=False, current_negated=False, can_reuse=None, allow_joins=True, split_subq=True, reuse_with_filtered_relation=False, check_filterable=True, ): """ Build a WhereNode for a single filter clause but don't add it to this Query. Query.add_q() will then add this filter to the where Node. The 'branch_negated' tells us if the current branch contains any negations. This will be used to determine if subqueries are needed. The 'current_negated' is used to determine if the current filter is negated or not and this will be used to determine if IS NULL filtering is needed. The difference between current_negated and branch_negated is that branch_negated is set on first negation, but current_negated is flipped for each negation. Note that add_filter will not do any negating itself, that is done upper in the code by add_q(). The 'can_reuse' is a set of reusable joins for multijoins. If 'reuse_with_filtered_relation' is True, then only joins in can_reuse will be reused. The method will create a filter clause that can be added to the current query. However, if the filter isn't added to the query then the caller is responsible for unreffing the joins used. """ if isinstance(filter_expr, dict): raise FieldError("Cannot parse keyword query as dict") if isinstance(filter_expr, Q): return self._add_q( filter_expr, branch_negated=branch_negated, current_negated=current_negated, used_aliases=can_reuse, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, ) if hasattr(filter_expr, "resolve_expression"): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression(self, allow_joins=allow_joins) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) return WhereNode([condition], connector=AND), [] arg, value = filter_expr if not arg: raise FieldError("Cannot parse keyword query %r" % arg) lookups, parts, reffed_expression = self.solve_lookup_type(arg) if check_filterable: self.check_filterable(reffed_expression) if not allow_joins and len(parts) > 1: raise FieldError("Joined field references are not permitted in this query") pre_joins = self.alias_refcount.copy() value = self.resolve_lookup_value(value, can_reuse, allow_joins) used_joins = { k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0) } if check_filterable: self.check_filterable(value) if reffed_expression: condition = self.build_lookup(lookups, reffed_expression, value) return WhereNode([condition], connector=AND), [] opts = self.get_meta() alias = self.get_initial_alias() allow_many = not branch_negated or not split_subq try: join_info = self.setup_joins( parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many, reuse_with_filtered_relation=reuse_with_filtered_relation, ) # Prevent iterator from being consumed by check_related_objects() if isinstance(value, Iterator): value = list(value) self.check_related_objects(join_info.final_field, value, join_info.opts) # split_exclude() needs to know which joins were generated for the # lookup parts self._lookup_joins = join_info.joins except MultiJoin as e: return self.split_exclude(filter_expr, can_reuse, e.names_with_path) # Update used_joins before trimming since they are reused to determine # which joins could be later promoted to INNER. used_joins.update(join_info.joins) targets, alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if can_reuse is not None: can_reuse.update(join_list) if join_info.final_field.is_relation: # No support for transforms for relational fields num_lookups = len(lookups) if num_lookups > 1: raise FieldError( "Related Field got invalid lookup: {}".format(lookups[0]) ) if len(targets) == 1: col = self._get_col(targets[0], join_info.final_field, alias) else: col = MultiColSource( alias, targets, join_info.targets, join_info.final_field ) else: col = self._get_col(targets[0], join_info.final_field, alias) condition = self.build_lookup(lookups, col, value) lookup_type = condition.lookup_name clause = WhereNode([condition], connector=AND) require_outer = ( lookup_type == "isnull" and condition.rhs is True and not current_negated ) if ( current_negated and (lookup_type != "isnull" or condition.rhs is False) and condition.rhs is not None ): require_outer = True if lookup_type != "isnull": # The condition added here will be SQL like this: # NOT (col IS NOT NULL), where the first NOT is added in # upper layers of code. The reason for addition is that if col # is null, then col != someval will result in SQL "unknown" # which isn't the same as in Python. The Python None handling # is wanted, and it can be gotten by # (col IS NULL OR col != someval) # <=> # NOT (col IS NOT NULL AND col = someval). if ( self.is_nullable(targets[0]) or self.alias_map[join_list[-1]].join_type == LOUTER ): lookup_class = targets[0].get_lookup("isnull") col = self._get_col(targets[0], join_info.targets[0], alias) clause.add(lookup_class(col, False), AND) # If someval is a nullable column, someval IS NOT NULL is # added. if isinstance(value, Col) and self.is_nullable(value.target): lookup_class = value.target.get_lookup("isnull") clause.add(lookup_class(value, False), AND) return clause, used_joins if not require_outer else () def add_filter(self, filter_lhs, filter_rhs): self.add_q(Q((filter_lhs, filter_rhs))) def add_q(self, q_object): """ A preprocessor for the internal _add_q(). Responsible for doing final join promotion. """ # For join promotion this case is doing an AND for the added q_object # and existing conditions. So, any existing inner join forces the join # type to remain inner. Existing outer joins can however be demoted. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if # rel_a doesn't produce any rows, then the whole condition must fail. # So, demotion is OK. existing_inner = { a for a in self.alias_map if self.alias_map[a].join_type == INNER } clause, _ = self._add_q(q_object, self.used_aliases) if clause: self.where.add(clause, AND) self.demote_joins(existing_inner) def build_where(self, filter_expr): return self.build_filter(filter_expr, allow_joins=False)[0] def clear_where(self): self.where = WhereNode() def _add_q( self, q_object, used_aliases, branch_negated=False, current_negated=False, allow_joins=True, split_subq=True, check_filterable=True, ): """Add a Q-object to the current filter.""" connector = q_object.connector current_negated = current_negated ^ q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) joinpromoter = JoinPromoter( q_object.connector, len(q_object.children), current_negated ) for child in q_object.children: child_clause, needed_inner = self.build_filter( child, can_reuse=used_aliases, branch_negated=branch_negated, current_negated=current_negated, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, ) joinpromoter.add_votes(needed_inner) if child_clause: target_clause.add(child_clause, connector) needed_inner = joinpromoter.update_join_types(self) return target_clause, needed_inner def build_filtered_relation_q( self, q_object, reuse, branch_negated=False, current_negated=False ): """Add a FilteredRelation object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) for child in q_object.children: if isinstance(child, Node): child_clause = self.build_filtered_relation_q( child, reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, ) else: child_clause, _ = self.build_filter( child, can_reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, allow_joins=True, split_subq=False, reuse_with_filtered_relation=True, ) target_clause.add(child_clause, connector) return target_clause def add_filtered_relation(self, filtered_relation, alias): filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( filtered_relation.relation_name ) if relation_lookup_parts: raise ValueError( "FilteredRelation's relation_name cannot contain lookups " "(got %r)." % filtered_relation.relation_name ) for lookup in chain(lookups): lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup) shift = 2 if not lookup_parts else 1 lookup_field_path = lookup_field_parts[:-shift] for idx, lookup_field_part in enumerate(lookup_field_path): if len(relation_field_parts) > idx: if relation_field_parts[idx] != lookup_field_part: raise ValueError( "FilteredRelation's condition doesn't support " "relations outside the %r (got %r)." % (filtered_relation.relation_name, lookup) ) else: raise ValueError( "FilteredRelation's condition doesn't support nested " "relations deeper than the relation_name (got %r for " "%r)." % (lookup, filtered_relation.relation_name) ) self._filtered_relations[filtered_relation.alias] = filtered_relation def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): """ Walk the list of names and turns them into PathInfo tuples. A single name in 'names' can generate multiple PathInfos (m2m, for example). 'names' is the path of names to travel, 'opts' is the model Options we start the name resolving from, 'allow_many' is as for setup_joins(). If fail_on_missing is set to True, then a name that can't be resolved will generate a FieldError. Return a list of PathInfo tuples. In addition return the final field (the last used join field) and target (which is a field guaranteed to contain the same value as the final field). Finally, return those names that weren't found (which are likely transforms and the final lookup). """ path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == "pk": name = opts.pk.name field = None filtered_relation = None try: if opts is None: raise FieldDoesNotExist field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field elif name in self._filtered_relations and pos == 0: filtered_relation = self._filtered_relations[name] if LOOKUP_SEP in filtered_relation.relation_name: parts = filtered_relation.relation_name.split(LOOKUP_SEP) filtered_relation_path, field, _, _ = self.names_to_path( parts, opts, allow_many, fail_on_missing, ) path.extend(filtered_relation_path[:-1]) else: field = opts.get_field(filtered_relation.relation_name) if field is not None: # Fields that contain one-to-many relations with a generic # model (like a GenericForeignKey) cannot generate reverse # relations and therefore cannot be used for reverse querying. if field.is_relation and not field.related_model: raise FieldError( "Field %r does not generate an automatic reverse " "relation and therefore cannot be used for reverse " "querying. If it is a GenericForeignKey, consider " "adding a GenericRelation." % name ) try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break # Check if we need any joins for concrete inheritance cases (the # field lives in parent, but we are currently in one of its # children) if opts is not None and model is not opts.model: path_to_parent = opts.get_path_to_parent(model) if path_to_parent: path.extend(path_to_parent) cur_names_with_path[1].extend(path_to_parent) opts = path_to_parent[-1].to_opts if hasattr(field, "path_infos"): if filtered_relation: pathinfos = field.get_path_info(filtered_relation) else: pathinfos = field.path_infos if not allow_many: for inner_pos, p in enumerate(pathinfos): if p.m2m: cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1]) names_with_path.append(cur_names_with_path) raise MultiJoin(pos + 1, names_with_path) last = pathinfos[-1] path.extend(pathinfos) final_field = last.join_field opts = last.to_opts targets = last.target_fields cur_names_with_path[1].extend(pathinfos) names_with_path.append(cur_names_with_path) else: # Local non-relational field. final_field = field targets = (field,) if fail_on_missing and pos + 1 != len(names): raise FieldError( "Cannot resolve keyword %r into field. Join on '%s'" " not permitted." % (names[pos + 1], name) ) break return path, final_field, targets, names[pos + 1 :] def setup_joins( self, names, opts, alias, can_reuse=None, allow_many=True, reuse_with_filtered_relation=False, ): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are starting from), 'alias' is the alias for the table to start the joining from. The 'can_reuse' defines the reverse foreign key joins we can reuse. It can be None in which case all joins are reusable or a set of aliases that can be reused. Note that non-reverse foreign keys are always reusable when using setup_joins(). The 'reuse_with_filtered_relation' can be used to force 'can_reuse' parameter and force the relation on the given connections. If 'allow_many' is False, then any reverse foreign key seen will generate a MultiJoin exception. Return the final field involved in the joins, the target field (used for any 'where' constraint), the final 'opts' value, the joins, the field path traveled to generate the joins, and a transform function that takes a field and alias and is equivalent to `field.get_col(alias)` in the simple case but wraps field transforms if they were included in names. The target field is the field containing the concrete value. Final field can be something different, for example foreign key pointing to that value. Final field is needed for example in some value conversions (convert 'obj' in fk__id=obj to pk val using the foreign key field for example). """ joins = [alias] # The transform can't be applied yet, as joins must be trimmed later. # To avoid making every caller of this method look up transforms # directly, compute transforms here and create a partial that converts # fields to the appropriate wrapped version. def final_transformer(field, alias): if not self.alias_cols: alias = None return field.get_col(alias) # Try resolving all the names as fields first. If there's an error, # treat trailing names as lookups until a field can be resolved. last_field_exception = None for pivot in range(len(names), 0, -1): try: path, final_field, targets, rest = self.names_to_path( names[:pivot], opts, allow_many, fail_on_missing=True, ) except FieldError as exc: if pivot == 1: # The first item cannot be a lookup, so it's safe # to raise the field error here. raise else: last_field_exception = exc else: # The transforms are the remaining items that couldn't be # resolved into fields. transforms = names[pivot:] break for name in transforms: def transform(field, alias, *, name, previous): try: wrapped = previous(field, alias) return self.try_transform(wrapped, name) except FieldError: # FieldError is raised if the transform doesn't exist. if isinstance(final_field, Field) and last_field_exception: raise last_field_exception else: raise final_transformer = functools.partial( transform, name=name, previous=final_transformer ) # Then, add the path to the query's joins. Note that we can't trim # joins at this stage - we will need the information about join type # of the trimmed joins. for join in path: if join.filtered_relation: filtered_relation = join.filtered_relation.clone() table_alias = filtered_relation.alias else: filtered_relation = None table_alias = None opts = join.to_opts if join.direct: nullable = self.is_nullable(join.join_field) else: nullable = True connection = self.join_class( opts.db_table, alias, table_alias, INNER, join.join_field, nullable, filtered_relation=filtered_relation, ) reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None alias = self.join( connection, reuse=reuse, reuse_with_filtered_relation=reuse_with_filtered_relation, ) joins.append(alias) if filtered_relation: filtered_relation.path = joins[:] return JoinInfo(final_field, targets, opts, joins, path, final_transformer) def trim_joins(self, targets, joins, path): """ The 'target' parameter is the final field being joined to, 'joins' is the full list of join aliases. The 'path' contain the PathInfos used to create the joins. Return the final target field and table alias and the new active joins. Always trim any direct join if the target column is already in the previous table. Can't trim reverse joins as it's unknown if there's anything on the other side of the join. """ joins = joins[:] for pos, info in enumerate(reversed(path)): if len(joins) == 1 or not info.direct: break if info.filtered_relation: break join_targets = {t.column for t in info.join_field.foreign_related_fields} cur_targets = {t.column for t in targets} if not cur_targets.issubset(join_targets): break targets_dict = { r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets } targets = tuple(targets_dict[t.column] for t in targets) self.unref_alias(joins.pop()) return targets, joins[-1], joins @classmethod def _gen_cols(cls, exprs, include_external=False): for expr in exprs: if isinstance(expr, Col): yield expr elif include_external and callable( getattr(expr, "get_external_cols", None) ): yield from expr.get_external_cols() elif hasattr(expr, "get_source_expressions"): yield from cls._gen_cols( expr.get_source_expressions(), include_external=include_external, ) @classmethod def _gen_col_aliases(cls, exprs): yield from (expr.alias for expr in cls._gen_cols(exprs)) def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False): annotation = self.annotations.get(name) if annotation is not None: if not allow_joins: for alias in self._gen_col_aliases([annotation]): if isinstance(self.alias_map[alias], Join): raise FieldError( "Joined field references are not permitted in this query" ) if summarize: # Summarize currently means we are doing an aggregate() query # which is executed as a wrapped subquery if any of the # aggregate() elements reference an existing annotation. In # that case we need to return a Ref to the subquery's annotation. if name not in self.annotation_select: raise FieldError( "Cannot aggregate over the '%s' alias. Use annotate() " "to promote it." % name ) return Ref(name, self.annotation_select[name]) else: return annotation else: field_list = name.split(LOOKUP_SEP) annotation = self.annotations.get(field_list[0]) if annotation is not None: for transform in field_list[1:]: annotation = self.try_transform(annotation, transform) return annotation join_info = self.setup_joins( field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse ) targets, final_alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if not allow_joins and len(join_list) > 1: raise FieldError( "Joined field references are not permitted in this query" ) if len(targets) > 1: raise FieldError( "Referencing multicolumn fields with F() objects isn't supported" ) # Verify that the last lookup in name is a field or a transform: # transform_function() raises FieldError if not. transform = join_info.transform_function(targets[0], final_alias) if reuse is not None: reuse.update(join_list) return transform def split_exclude(self, filter_expr, can_reuse, names_with_path): """ When doing an exclude against any kind of N-to-many relation, we need to use a subquery. This method constructs the nested query, given the original exclude filter (filter_expr) and the portion up to the first N-to-many relation field. For example, if the origin filter is ~Q(child__name='foo'), filter_expr is ('child__name', 'foo') and can_reuse is a set of joins usable for filters in the original query. We will turn this into equivalent of: WHERE NOT EXISTS( SELECT 1 FROM child WHERE name = 'foo' AND child.parent_id = parent.id LIMIT 1 ) """ # Generate the inner query. query = self.__class__(self.model) query._filtered_relations = self._filtered_relations filter_lhs, filter_rhs = filter_expr if isinstance(filter_rhs, OuterRef): filter_rhs = OuterRef(filter_rhs) elif isinstance(filter_rhs, F): filter_rhs = OuterRef(filter_rhs.name) query.add_filter(filter_lhs, filter_rhs) query.clear_ordering(force=True) # Try to have as simple as possible subquery -> trim leading joins from # the subquery. trimmed_prefix, contains_louter = query.trim_start(names_with_path) col = query.select[0] select_field = col.target alias = col.alias if alias in can_reuse: pk = select_field.model._meta.pk # Need to add a restriction so that outer query's filters are in effect for # the subquery, too. query.bump_prefix(self) lookup_class = select_field.get_lookup("exact") # Note that the query.select[0].alias is different from alias # due to bump_prefix above. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias)) query.where.add(lookup, AND) query.external_aliases[alias] = True lookup_class = select_field.get_lookup("exact") lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix)) query.where.add(lookup, AND) condition, needed_inner = self.build_filter(Exists(query)) if contains_louter: or_null_condition, _ = self.build_filter( ("%s__isnull" % trimmed_prefix, True), current_negated=True, branch_negated=True, can_reuse=can_reuse, ) condition.add(or_null_condition, OR) # Note that the end result will be: # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL. # This might look crazy but due to how IN works, this seems to be # correct. If the IS NOT NULL check is removed then outercol NOT # IN will return UNKNOWN. If the IS NULL check is removed, then if # outercol IS NULL we will not match the row. return condition, needed_inner def set_empty(self): self.where.add(NothingNode(), AND) for query in self.combined_queries: query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children) def set_limits(self, low=None, high=None): """ Adjust the limits on the rows retrieved. Use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, convert them to the appropriate offset and limit values. Apply any limits passed in here to the existing constraints. Add low to the current low value and clamp both to any existing high value. """ if high is not None: if self.high_mark is not None: self.high_mark = min(self.high_mark, self.low_mark + high) else: self.high_mark = self.low_mark + high if low is not None: if self.high_mark is not None: self.low_mark = min(self.high_mark, self.low_mark + low) else: self.low_mark = self.low_mark + low if self.low_mark == self.high_mark: self.set_empty() def clear_limits(self): """Clear any existing limits.""" self.low_mark, self.high_mark = 0, None @property def is_sliced(self): return self.low_mark != 0 or self.high_mark is not None def has_limit_one(self): return self.high_mark is not None and (self.high_mark - self.low_mark) == 1 def can_filter(self): """ Return True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results. """ return not self.is_sliced def clear_select_clause(self): """Remove all fields from SELECT clause.""" self.select = () self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_annotation_mask(()) def clear_select_fields(self): """ Clear the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns. """ self.select = () self.values_select = () def add_select_col(self, col, name): self.select += (col,) self.values_select += (name,) def set_select(self, cols): self.default_cols = False self.select = tuple(cols) def add_distinct_fields(self, *field_names): """ Add and resolve the given fields to the query's "distinct on" clause. """ self.distinct_fields = field_names self.distinct = True def add_fields(self, field_names, allow_m2m=True): """ Add the given (model) fields to the select set. Add the field names in the order specified. """ alias = self.get_initial_alias() opts = self.get_meta() try: cols = [] for name in field_names: # Join promotion note - we must not remove any rows here, so # if there is no existing joins, use outer join. join_info = self.setup_joins( name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m ) targets, final_alias, joins = self.trim_joins( join_info.targets, join_info.joins, join_info.path, ) for target in targets: cols.append(join_info.transform_function(target, final_alias)) if cols: self.set_select(cols) except MultiJoin: raise FieldError("Invalid field name: '%s'" % name) except FieldError: if LOOKUP_SEP in name: # For lookups spanning over relationships, show the error # from the model on which the lookup failed. raise elif name in self.annotations: raise FieldError( "Cannot select the '%s' alias. Use annotate() to promote " "it." % name ) else: names = sorted( [ *get_field_names_from_opts(opts), *self.extra, *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names)) ) def add_ordering(self, *ordering): """ Add items from the 'ordering' sequence to the query's "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix ('-' or '?') -- or OrderBy expressions. If 'ordering' is empty, clear all ordering from the query. """ errors = [] for item in ordering: if isinstance(item, str): if item == "?": continue if item.startswith("-"): item = item[1:] if item in self.annotations: continue if self.extra and item in self.extra: continue # names_to_path() validates the lookup. A descriptive # FieldError will be raise if it's not. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) elif not hasattr(item, "resolve_expression"): errors.append(item) if getattr(item, "contains_aggregate", False): raise FieldError( "Using an aggregate in order_by() without also including " "it in annotate() is not allowed: %s" % item ) if errors: raise FieldError("Invalid order_by arguments: %s" % errors) if ordering: self.order_by += ordering else: self.default_ordering = False def clear_ordering(self, force=False, clear_default=True): """ Remove any ordering settings if the current query allows it without side effects, set 'force' to True to clear the ordering regardless. If 'clear_default' is True, there will be no ordering in the resulting query (not even the model's default). """ if not force and ( self.is_sliced or self.distinct_fields or self.select_for_update ): return self.order_by = () self.extra_order_by = () if clear_default: self.default_ordering = False def set_group_by(self, allow_aliases=True): """ Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made automatically. """ # Column names from JOINs to check collisions with aliases. if allow_aliases: column_names = set() seen_models = set() for join in list(self.alias_map.values())[1:]: # Skip base table. model = join.join_field.related_model if model not in seen_models: column_names.update( {field.column for field in model._meta.local_concrete_fields} ) seen_models.add(model) group_by = list(self.select) if self.annotation_select: for alias, annotation in self.annotation_select.items(): if not allow_aliases or alias in column_names: alias = None group_by_cols = annotation.get_group_by_cols(alias=alias) group_by.extend(group_by_cols) self.group_by = tuple(group_by) def add_select_related(self, fields): """ Set up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True). """ if isinstance(self.select_related, bool): field_dict = {} else: field_dict = self.select_related for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict def add_extra(self, select, select_params, where, params, tables, order_by): """ Add data to the various extra_* attributes for user-created additions to the query. """ if select: # We need to pair any placeholder markers in the 'select' # dictionary with their parameters in 'select_params' so that # subsequent updates to the select dictionary also adjust the # parameters appropriately. select_pairs = {} if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s") while pos != -1: if pos == 0 or entry[pos - 1] != "%": entry_params.append(next(param_iter)) pos = entry.find("%s", pos + 2) select_pairs[name] = (entry, entry_params) self.extra.update(select_pairs) if where or params: self.where.add(ExtraWhere(where, params), AND) if tables: self.extra_tables += tuple(tables) if order_by: self.extra_order_by = order_by def clear_deferred_loading(self): """Remove any fields from the deferred loading set.""" self.deferred_loading = (frozenset(), True) def add_deferred_loading(self, field_names): """ Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. Add the new field names to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading). """ # Fields on related models are stored in the literal double-underscore # format, so that we can use a set datastructure. We do the foo__bar # splitting and handling when computing the SQL column names (as part of # get_columns()). existing, defer = self.deferred_loading if defer: # Add to existing deferred names. self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. if new_existing := existing.difference(field_names): self.deferred_loading = new_existing, False else: self.clear_deferred_loading() if new_only := set(field_names).difference(existing): self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """ Add the given list of model field names to the set of fields to retrieve when the SQL is executed ("immediate loading" fields). The field names replace any existing immediate loading field names. If there are field names already specified for deferred loading, remove those names from the new field_names before storing the new names for immediate loading. (That is, immediate loading overrides any existing immediate values, but respects existing deferrals.) """ existing, defer = self.deferred_loading field_names = set(field_names) if "pk" in field_names: field_names.remove("pk") field_names.add(self.get_meta().pk.name) if defer: # Remove any existing deferred names from the current set before # setting the new names. self.deferred_loading = field_names.difference(existing), False else: # Replace any existing "immediate load" field names. self.deferred_loading = frozenset(field_names), False def set_annotation_mask(self, names): """Set the mask of annotations that will be returned by the SELECT.""" if names is None: self.annotation_select_mask = None else: self.annotation_select_mask = set(names) self._annotation_select_cache = None def append_annotation_mask(self, names): if self.annotation_select_mask is not None: self.set_annotation_mask(self.annotation_select_mask.union(names)) def set_extra_mask(self, names): """ Set the mask of extra select items that will be returned by SELECT. Don't remove them from the Query since they might be used later. """ if names is None: self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None def set_values(self, fields): self.select_related = False self.clear_deferred_loading() self.clear_select_fields() if fields: field_names = [] extra_names = [] annotation_names = [] if not self.extra and not self.annotations: # Shortcut - if there are no extra or annotations, then # the values() clause must be just field names. field_names = list(fields) else: self.default_cols = False for f in fields: if f in self.extra_select: extra_names.append(f) elif f in self.annotation_select: annotation_names.append(f) else: field_names.append(f) self.set_extra_mask(extra_names) self.set_annotation_mask(annotation_names) selected = frozenset(field_names + extra_names + annotation_names) else: field_names = [f.attname for f in self.model._meta.concrete_fields] selected = frozenset(field_names) # Selected annotations must be known before setting the GROUP BY # clause. if self.group_by is True: self.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() elif self.group_by: # Resolve GROUP BY annotation references if they are not part of # the selected fields anymore. group_by = [] for expr in self.group_by: if isinstance(expr, Ref) and expr.refs not in selected: expr = self.annotations[expr.refs] group_by.append(expr) self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) @property def annotation_select(self): """ Return the dictionary of aggregate columns that are not masked and should be used in the SELECT clause. Cache this result for performance. """ if self._annotation_select_cache is not None: return self._annotation_select_cache elif not self.annotations: return {} elif self.annotation_select_mask is not None: self._annotation_select_cache = { k: v for k, v in self.annotations.items() if k in self.annotation_select_mask } return self._annotation_select_cache else: return self.annotations @property def extra_select(self): if self._extra_select_cache is not None: return self._extra_select_cache if not self.extra: return {} elif self.extra_select_mask is not None: self._extra_select_cache = { k: v for k, v in self.extra.items() if k in self.extra_select_mask } return self._extra_select_cache else: return self.extra def trim_start(self, names_with_path): """ Trim joins from the start of the join path. The candidates for trim are the PathInfos in names_with_path structure that are m2m joins. Also set the select column so the start matches the join. This method is meant to be used for generating the subquery joins & cols in split_exclude(). Return a lookup usable for doing outerq.filter(lookup=self) and a boolean indicating if the joins in the prefix contain a LEFT OUTER join. _""" all_paths = [] for _, paths in names_with_path: all_paths.extend(paths) contains_louter = False # Trim and operate only on tables that were generated for # the lookup part of the query. That is, avoid trimming # joins generated for F() expressions. lookup_tables = [ t for t in self.alias_map if t in self._lookup_joins or t == self.base_table ] for trimmed_paths, path in enumerate(all_paths): if path.m2m: break if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER: contains_louter = True alias = lookup_tables[trimmed_paths] self.unref_alias(alias) # The path.join_field is a Rel, lets get the other side's field join_field = path.join_field.field # Build the filter prefix. paths_in_prefix = trimmed_paths trimmed_prefix = [] for name, path in names_with_path: if paths_in_prefix - len(path) < 0: break trimmed_prefix.append(name) paths_in_prefix -= len(path) trimmed_prefix.append(join_field.foreign_related_fields[0].name) trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix) # Lets still see if we can trim the first join from the inner query # (that is, self). We can't do this for: # - LEFT JOINs because we would miss those rows that have nothing on # the outer side, # - INNER JOINs from filtered relations because we would miss their # filters. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]] if first_join.join_type != LOUTER and not first_join.filtered_relation: select_fields = [r[0] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths + 1] self.unref_alias(lookup_tables[trimmed_paths]) extra_restriction = join_field.get_extra_restriction( None, lookup_tables[trimmed_paths + 1] ) if extra_restriction: self.where.add(extra_restriction, AND) else: # TODO: It might be possible to trim more joins from the start of the # inner query if it happens to have a longer join chain containing the # values in select_fields. Lets punt this one for now. select_fields = [r[1] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths] # The found starting point is likely a join_class instead of a # base_table_class reference. But the first entry in the query's FROM # clause must not be a JOIN. for table in self.alias_map: if self.alias_refcount[table] > 0: self.alias_map[table] = self.base_table_class( self.alias_map[table].table_name, table, ) break self.set_select([f.get_col(select_alias) for f in select_fields]) return trimmed_prefix, contains_louter def is_nullable(self, field): """ Check if the given field should be treated as nullable. Some backends treat '' as null and Django treats such fields as nullable for those backends. In such situations field.null can be False even if we should treat the field as nullable. """ # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have # (nor should it have) knowledge of which connection is going to be # used. The proper fix would be to defer all decisions where # is_nullable() is needed to the compiler stage, but that is not easy # to do currently. return field.null or ( field.empty_strings_allowed and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ) def get_order_dir(field, default="ASC"): """ Return the field name and direction for an order specification. For example, '-foo' is returned as ('foo', 'DESC'). The 'default' param is used to indicate which way no prefix (or a '+' prefix) should sort. The '-' prefix always sorts the opposite way. """ dirn = ORDER_DIR[default] if field[0] == "-": return field[1:], dirn[1] return field, dirn[0] def add_to_dict(data, key, value): """ Add "value" to the set of values for "key", whether or not "key" already exists. """ if key in data: data[key].add(value) else: data[key] = {value} def is_reverse_o2o(field): """ Check if the given field is reverse-o2o. The field is expected to be some sort of relation field or related object. """ return field.is_relation and field.one_to_one and not field.concrete class JoinPromoter: """ A class to abstract away join promotion problems for complex filter conditions. """ def __init__(self, connector, num_children, negated): self.connector = connector self.negated = negated if self.negated: if connector == AND: self.effective_connector = OR else: self.effective_connector = AND else: self.effective_connector = self.connector self.num_children = num_children # Maps of table alias to how many times it is seen as required for # inner and/or outer joins. self.votes = Counter() def __repr__(self): return ( f"{self.__class__.__qualname__}(connector={self.connector!r}, " f"num_children={self.num_children!r}, negated={self.negated!r})" ) def add_votes(self, votes): """ Add single vote per item to self.votes. Parameter can be any iterable. """ self.votes.update(votes) def update_join_types(self, query): """ Change join types so that the generated query is as efficient as possible, but still correct. So, change as many joins as possible to INNER, but don't make OUTER joins INNER if that could remove results from the query. """ to_promote = set() to_demote = set() # The effective_connector is used so that NOT (a AND b) is treated # similarly to (a OR b) for join promotion. for table, votes in self.votes.items(): # We must use outer joins in OR case when the join isn't contained # in all of the joins. Otherwise the INNER JOIN itself could remove # valid results. Consider the case where a model with rel_a and # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now, # if rel_a join doesn't produce any results is null (for example # reverse foreign key or null value in direct foreign key), and # there is a matching row in rel_b with col=2, then an INNER join # to rel_a would remove a valid match from the query. So, we need # to promote any existing INNER to LOUTER (it is possible this # promotion in turn will be demoted later on). if self.effective_connector == "OR" and votes < self.num_children: to_promote.add(table) # If connector is AND and there is a filter that can match only # when there is a joinable row, then use INNER. For example, in # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL # as join output, then the col=1 or col=2 can't match (as # NULL=anything is always false). # For the OR case, if all children voted for a join to be inner, # then we can use INNER for the join. For example: # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell) # then if rel_a doesn't produce any rows, the whole condition # can't match. Hence we can safely use INNER join. if self.effective_connector == "AND" or ( self.effective_connector == "OR" and votes == self.num_children ): to_demote.add(table) # Finally, what happens in cases where we have: # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0 # Now, we first generate the OR clause, and promote joins for it # in the first if branch above. Both rel_a and rel_b are promoted # to LOUTER joins. After that we do the AND case. The OR case # voted no inner joins but the rel_a__col__gte=0 votes inner join # for rel_a. We demote it back to INNER join (in AND case a single # vote is enough). The demotion is OK, if rel_a doesn't produce # rows, then the rel_a__col__gte=0 clause can't be true, and thus # the whole clause must be false. So, it is safe to use INNER # join. # Note that in this example we could just as well have the __gte # clause and the OR clause swapped. Or we could replace the __gte # clause with an OR clause containing rel_a__col=1|rel_a__col=2, # and again we could safely demote to INNER. query.promote_joins(to_promote) query.demote_joins(to_demote) return to_demote
0f7058f60f295da2330ca18774a03c94f46f6d5f680f76c4c8ccc47298d03961
import collections import json import re from functools import partial from itertools import chain from django.core.exceptions import EmptyResultSet, FieldError from django.db import DatabaseError, NotSupportedError from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value from django.db.models.functions import Cast, Random from django.db.models.query_utils import select_related_descend from django.db.models.sql.constants import ( CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE, ) from django.db.models.sql.query import Query, get_order_dir from django.db.transaction import TransactionManagementError from django.utils.functional import cached_property from django.utils.hashable import make_hashable from django.utils.regex_helper import _lazy_re_compile class SQLCompiler: # Multiline ordering SQL clause may appear from RawSQL. ordering_parts = _lazy_re_compile( r"^(.*)\s(?:ASC|DESC).*", re.MULTILINE | re.DOTALL, ) def __init__(self, query, connection, using, elide_empty=True): self.query = query self.connection = connection self.using = using # Some queries, e.g. coalesced aggregation, need to be executed even if # they would return an empty result set. self.elide_empty = elide_empty self.quote_cache = {"*": "*"} # The select, klass_info, and annotations are needed by QuerySet.iterator() # these are set as a side-effect of executing the query. Note that we calculate # separately a list of extra select columns needed for grammatical correctness # of the query, but these columns are not included in self.select. self.select = None self.annotation_col_map = None self.klass_info = None self._meta_ordering = None def __repr__(self): return ( f"<{self.__class__.__qualname__} " f"model={self.query.model.__qualname__} " f"connection={self.connection!r} using={self.using!r}>" ) def setup_query(self): if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map): self.query.get_initial_alias() self.select, self.klass_info, self.annotation_col_map = self.get_select() self.col_count = len(self.select) def pre_sql_setup(self): """ Do any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ self.setup_query() order_by = self.get_order_by() self.where, self.having = self.query.where.split_having() extra_select = self.get_extra_select(order_by, self.select) self.has_extra_select = bool(extra_select) group_by = self.get_group_by(self.select + extra_select, order_by) return extra_select, order_by, group_by def get_group_by(self, select, order_by): """ Return a list of 2-tuples of form (sql, params). The logic of what exactly the GROUP BY clause contains is hard to describe in other words than "if it passes the test suite, then it is correct". """ # Some examples: # SomeModel.objects.annotate(Count('somecol')) # GROUP BY: all fields of the model # # SomeModel.objects.values('name').annotate(Count('somecol')) # GROUP BY: name # # SomeModel.objects.annotate(Count('somecol')).values('name') # GROUP BY: all cols of the model # # SomeModel.objects.values('name', 'pk') # .annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # In fact, the self.query.group_by is the minimal set to GROUP BY. It # can't be ever restricted to a smaller set, but additional columns in # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately # the end result is that it is impossible to force the query to have # a chosen GROUP BY clause - you can almost do this by using the form: # .values(*wanted_cols).annotate(AnAggregate()) # but any later annotations, extra selects, values calls that # refer some column outside of the wanted_cols, order_by, or even # filter calls can alter the GROUP BY clause. # The query.group_by is either None (no GROUP BY at all), True # (group by select fields), or a list of expressions to be added # to the group by. if self.query.group_by is None: return [] expressions = [] if self.query.group_by is not True: # If the group by is set to a list (by .values() call most likely), # then we need to add everything in it to the GROUP BY clause. # Backwards compatibility hack for setting query.group_by. Remove # when we have public API way of forcing the GROUP BY clause. # Converts string references to expressions. for expr in self.query.group_by: if not hasattr(expr, "as_sql"): expressions.append(self.query.resolve_ref(expr)) else: expressions.append(expr) # Note that even if the group_by is set, it is only the minimal # set to group by. So, we need to add cols in select, order_by, and # having into the select in any case. ref_sources = {expr.source for expr in expressions if isinstance(expr, Ref)} for expr, _, _ in select: # Skip members of the select clause that are already included # by reference. if expr in ref_sources: continue cols = expr.get_group_by_cols() for col in cols: expressions.append(col) if not self._meta_ordering: for expr, (sql, params, is_ref) in order_by: # Skip references to the SELECT clause, as all expressions in # the SELECT clause are already part of the GROUP BY. if not is_ref: expressions.extend(expr.get_group_by_cols()) having_group_by = self.having.get_group_by_cols() if self.having else () for expr in having_group_by: expressions.append(expr) result = [] seen = set() expressions = self.collapse_group_by(expressions, having_group_by) for expr in expressions: sql, params = self.compile(expr) sql, params = expr.select_format(self, sql, params) params_hash = make_hashable(params) if (sql, params_hash) not in seen: result.append((sql, params)) seen.add((sql, params_hash)) return result def collapse_group_by(self, expressions, having): # If the DB can group by primary key, then group by the primary key of # query's main model. Note that for PostgreSQL the GROUP BY clause must # include the primary key of every table, but for MySQL it is enough to # have the main table's primary key. if self.connection.features.allows_group_by_pk: # Determine if the main model's primary key is in the query. pk = None for expr in expressions: # Is this a reference to query's base table primary key? If the # expression isn't a Col-like, then skip the expression. if ( getattr(expr, "target", None) == self.query.model._meta.pk and getattr(expr, "alias", None) == self.query.base_table ): pk = expr break # If the main model's primary key is in the query, group by that # field, HAVING expressions, and expressions associated with tables # that don't have a primary key included in the grouped columns. if pk: pk_aliases = { expr.alias for expr in expressions if hasattr(expr, "target") and expr.target.primary_key } expressions = [pk] + [ expr for expr in expressions if expr in having or ( getattr(expr, "alias", None) is not None and expr.alias not in pk_aliases ) ] elif self.connection.features.allows_group_by_selected_pks: # Filter out all expressions associated with a table's primary key # present in the grouped columns. This is done by identifying all # tables that have their primary key included in the grouped # columns and removing non-primary key columns referring to them. # Unmanaged models are excluded because they could be representing # database views on which the optimization might not be allowed. pks = { expr for expr in expressions if ( hasattr(expr, "target") and expr.target.primary_key and self.connection.features.allows_group_by_selected_pks_on_model( expr.target.model ) ) } aliases = {expr.alias for expr in pks} expressions = [ expr for expr in expressions if expr in pks or getattr(expr, "alias", None) not in aliases ] return expressions def get_select(self): """ Return three values: - a list of 3-tuples of (expression, (sql, params), alias) - a klass_info structure, - a dictionary of annotations The (sql, params) is what the expression will produce, and alias is the "AS alias" for the column (possibly None). The klass_info structure contains the following information: - The base model of the query. - Which columns for that model are present in the query (by position of the select clause). - related_klass_infos: [f, klass_info] to descent into The annotations is a dictionary of {'attname': column position} values. """ select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items(): annotations[alias] = select_idx select.append((RawSQL(sql, params), alias)) select_idx += 1 assert not (self.query.select and self.query.default_cols) if self.query.default_cols: cols = self.get_default_columns() else: # self.query.select is a special case. These columns never go to # any model. cols = self.query.select if cols: select_list = [] for col in cols: select_list.append(select_idx) select.append((col, None)) select_idx += 1 klass_info = { "model": self.query.model, "select_fields": select_list, } for alias, annotation in self.query.annotation_select.items(): annotations[alias] = select_idx select.append((annotation, alias)) select_idx += 1 if self.query.select_related: related_klass_infos = self.get_related_selections(select) klass_info["related_klass_infos"] = related_klass_infos def get_select_from_parent(klass_info): for ki in klass_info["related_klass_infos"]: if ki["from_parent"]: ki["select_fields"] = ( klass_info["select_fields"] + ki["select_fields"] ) get_select_from_parent(ki) get_select_from_parent(klass_info) ret = [] for col, alias in select: try: sql, params = self.compile(col) except EmptyResultSet: empty_result_set_value = getattr( col, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: # Select a predicate that's always False. sql, params = "0", () else: sql, params = self.compile(Value(empty_result_set_value)) else: sql, params = col.select_format(self, sql, params) ret.append((col, (sql, params), alias)) return ret, klass_info, annotations def _order_by_pairs(self): if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by elif self.query.order_by: ordering = self.query.order_by elif (meta := self.query.get_meta()) and meta.ordering: ordering = meta.ordering self._meta_ordering = ordering else: ordering = [] if self.query.standard_ordering: default_order, _ = ORDER_DIR["ASC"] else: default_order, _ = ORDER_DIR["DESC"] for field in ordering: if hasattr(field, "resolve_expression"): if isinstance(field, Value): # output_field must be resolved for constants. field = Cast(field, field.output_field) if not isinstance(field, OrderBy): field = field.asc() if not self.query.standard_ordering: field = field.copy() field.reverse_ordering() yield field, False continue if field == "?": # random yield OrderBy(Random()), False continue col, order = get_order_dir(field, default_order) descending = order == "DESC" if col in self.query.annotation_select: # Reference to expression in SELECT clause yield ( OrderBy( Ref(col, self.query.annotation_select[col]), descending=descending, ), True, ) continue if col in self.query.annotations: # References to an expression which is masked out of the SELECT # clause. if self.query.combinator and self.select: # Don't use the resolved annotation because other # combinated queries might define it differently. expr = F(col) else: expr = self.query.annotations[col] if isinstance(expr, Value): # output_field must be resolved for constants. expr = Cast(expr, expr.output_field) yield OrderBy(expr, descending=descending), False continue if "." in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split(".", 1) yield ( OrderBy( RawSQL( "%s.%s" % (self.quote_name_unless_alias(table), col), [] ), descending=descending, ), False, ) continue if self.query.extra and col in self.query.extra: if col in self.query.extra_select: yield ( OrderBy( Ref(col, RawSQL(*self.query.extra[col])), descending=descending, ), True, ) else: yield ( OrderBy(RawSQL(*self.query.extra[col]), descending=descending), False, ) else: if self.query.combinator and self.select: # Don't use the first model's field because other # combinated queries might define it differently. yield OrderBy(F(col), descending=descending), False else: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. yield from self.find_ordering_name( field, self.query.get_meta(), default_order=default_order, ) def get_order_by(self): """ Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for the ORDER BY clause. The order_by clause can alter the select clause (for example it can add aliases to clauses that do not yet have one, or it can add totally new select clauses). """ result = [] seen = set() for expr, is_ref in self._order_by_pairs(): resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None) if self.query.combinator and self.select: src = resolved.get_source_expressions()[0] expr_src = expr.get_source_expressions()[0] # Relabel order by columns to raw numbers if this is a combined # query; necessary since the columns can't be referenced by the # fully qualified name and the simple column names may collide. for idx, (sel_expr, _, col_alias) in enumerate(self.select): if is_ref and col_alias == src.refs: src = src.source elif col_alias and not ( isinstance(expr_src, F) and col_alias == expr_src.name ): continue if src == sel_expr: resolved.set_source_expressions([RawSQL("%d" % (idx + 1), ())]) break else: if col_alias: raise DatabaseError( "ORDER BY term does not match any column in the result set." ) # Add column used in ORDER BY clause to the selected # columns and to each combined query. order_by_idx = len(self.query.select) + 1 col_name = f"__orderbycol{order_by_idx}" for q in self.query.combined_queries: q.add_annotation(expr_src, col_name) self.query.add_select_col(resolved, col_name) resolved.set_source_expressions([RawSQL(f"{order_by_idx}", ())]) sql, params = self.compile(resolved) # Don't add the same column twice, but the order direction is # not taken into account so we strip it. When this entire method # is refactored into expressions, then we can check each part as we # generate it. without_ordering = self.ordering_parts.search(sql)[1] params_hash = make_hashable(params) if (without_ordering, params_hash) in seen: continue seen.add((without_ordering, params_hash)) result.append((resolved, (sql, params, is_ref))) return result def get_extra_select(self, order_by, select): extra_select = [] if self.query.distinct and not self.query.distinct_fields: select_sql = [t[1] for t in select] for expr, (sql, params, is_ref) in order_by: without_ordering = self.ordering_parts.search(sql)[1] if not is_ref and (without_ordering, params) not in select_sql: extra_select.append((expr, (without_ordering, params), None)) return extra_select def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ( (name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select or ( self.query.external_aliases.get(name) and name not in self.query.table_map ) ): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def compile(self, node): vendor_impl = getattr(node, "as_" + self.connection.vendor, None) if vendor_impl: sql, params = vendor_impl(self, self.connection) else: sql, params = node.as_sql(self, self.connection) return sql, params def get_combinator_sql(self, combinator, all): features = self.connection.features compilers = [ query.get_compiler(self.using, self.connection, self.elide_empty) for query in self.query.combined_queries if not query.is_empty() ] if not features.supports_slicing_ordering_in_compound: for query, compiler in zip(self.query.combined_queries, compilers): if query.low_mark or query.high_mark: raise DatabaseError( "LIMIT/OFFSET not allowed in subqueries of compound statements." ) if compiler.get_order_by(): raise DatabaseError( "ORDER BY not allowed in subqueries of compound statements." ) parts = () for compiler in compilers: try: # If the columns list is limited, then all combined queries # must have the same columns list. Set the selects defined on # the query on all combined queries, if not already set. if not compiler.query.values_select and self.query.values_select: compiler.query = compiler.query.clone() compiler.query.set_values( ( *self.query.extra_select, *self.query.values_select, *self.query.annotation_select, ) ) part_sql, part_args = compiler.as_sql() if compiler.query.combinator: # Wrap in a subquery if wrapping in parentheses isn't # supported. if not features.supports_parentheses_in_compound: part_sql = "SELECT * FROM ({})".format(part_sql) # Add parentheses when combining with compound query if not # already added for all compound queries. elif ( self.query.subquery or not features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) elif ( self.query.subquery and features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) parts += ((part_sql, part_args),) except EmptyResultSet: # Omit the empty queryset with UNION and with DIFFERENCE if the # first queryset is nonempty. if combinator == "union" or (combinator == "difference" and parts): continue raise if not parts: raise EmptyResultSet combinator_sql = self.connection.ops.set_operators[combinator] if all and combinator == "union": combinator_sql += " ALL" braces = "{}" if not self.query.subquery and features.supports_slicing_ordering_in_compound: braces = "({})" sql_parts, args_parts = zip( *((braces.format(sql), args) for sql, args in parts) ) result = [" {} ".format(combinator_sql).join(sql_parts)] params = [] for part in args_parts: params.extend(part) return result, params def as_sql(self, with_limits=True, with_col_aliases=False): """ Create the SQL for this query. Return the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ refcounts_before = self.query.alias_refcount.copy() try: extra_select, order_by, group_by = self.pre_sql_setup() for_update_part = None # Is a LIMIT/OFFSET clause needed? with_limit_offset = with_limits and ( self.query.high_mark is not None or self.query.low_mark ) combinator = self.query.combinator features = self.connection.features if combinator: if not getattr(features, "supports_select_{}".format(combinator)): raise NotSupportedError( "{} is not supported on this database backend.".format( combinator ) ) result, params = self.get_combinator_sql( combinator, self.query.combinator_all ) else: distinct_fields, distinct_params = self.get_distinct() # This must come after 'select', 'ordering', and 'distinct' # (see docstring of get_from_clause() for details). from_, f_params = self.get_from_clause() try: where, w_params = ( self.compile(self.where) if self.where is not None else ("", []) ) except EmptyResultSet: if self.elide_empty: raise # Use a predicate that's always False. where, w_params = "0 = 1", [] having, h_params = ( self.compile(self.having) if self.having is not None else ("", []) ) result = ["SELECT"] params = [] if self.query.distinct: distinct_result, distinct_params = self.connection.ops.distinct_sql( distinct_fields, distinct_params, ) result += distinct_result params += distinct_params out_cols = [] col_idx = 1 for _, (s_sql, s_params), alias in self.select + extra_select: if alias: s_sql = "%s AS %s" % ( s_sql, self.connection.ops.quote_name(alias), ) elif with_col_aliases: s_sql = "%s AS %s" % ( s_sql, self.connection.ops.quote_name("col%d" % col_idx), ) col_idx += 1 params.extend(s_params) out_cols.append(s_sql) result += [", ".join(out_cols)] if from_: result += ["FROM", *from_] elif self.connection.features.bare_select_suffix: result += [self.connection.features.bare_select_suffix] params.extend(f_params) if self.query.select_for_update and features.has_select_for_update: if ( self.connection.get_autocommit() # Don't raise an exception when database doesn't # support transactions, as it's a noop. and features.supports_transactions ): raise TransactionManagementError( "select_for_update cannot be used outside of a transaction." ) if ( with_limit_offset and not features.supports_select_for_update_with_limit ): raise NotSupportedError( "LIMIT/OFFSET is not supported with " "select_for_update on this database backend." ) nowait = self.query.select_for_update_nowait skip_locked = self.query.select_for_update_skip_locked of = self.query.select_for_update_of no_key = self.query.select_for_no_key_update # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the # backend doesn't support it, raise NotSupportedError to # prevent a possible deadlock. if nowait and not features.has_select_for_update_nowait: raise NotSupportedError( "NOWAIT is not supported on this database backend." ) elif skip_locked and not features.has_select_for_update_skip_locked: raise NotSupportedError( "SKIP LOCKED is not supported on this database backend." ) elif of and not features.has_select_for_update_of: raise NotSupportedError( "FOR UPDATE OF is not supported on this database backend." ) elif no_key and not features.has_select_for_no_key_update: raise NotSupportedError( "FOR NO KEY UPDATE is not supported on this " "database backend." ) for_update_part = self.connection.ops.for_update_sql( nowait=nowait, skip_locked=skip_locked, of=self.get_select_for_update_of_arguments(), no_key=no_key, ) if for_update_part and features.for_update_after_from: result.append(for_update_part) if where: result.append("WHERE %s" % where) params.extend(w_params) grouping = [] for g_sql, g_params in group_by: grouping.append(g_sql) params.extend(g_params) if grouping: if distinct_fields: raise NotImplementedError( "annotate() + distinct(fields) is not implemented." ) order_by = order_by or self.connection.ops.force_no_ordering() result.append("GROUP BY %s" % ", ".join(grouping)) if self._meta_ordering: order_by = None if having: result.append("HAVING %s" % having) params.extend(h_params) if self.query.explain_info: result.insert( 0, self.connection.ops.explain_query_prefix( self.query.explain_info.format, **self.query.explain_info.options, ), ) if order_by: ordering = [] for _, (o_sql, o_params, _) in order_by: ordering.append(o_sql) params.extend(o_params) result.append("ORDER BY %s" % ", ".join(ordering)) if with_limit_offset: result.append( self.connection.ops.limit_offset_sql( self.query.low_mark, self.query.high_mark ) ) if for_update_part and not features.for_update_after_from: result.append(for_update_part) if self.query.subquery and extra_select: # If the query is used as a subquery, the extra selects would # result in more columns than the left-hand side expression is # expecting. This can happen when a subquery uses a combination # of order_by() and distinct(), forcing the ordering expressions # to be selected as well. Wrap the query in another subquery # to exclude extraneous selects. sub_selects = [] sub_params = [] for index, (select, _, alias) in enumerate(self.select, start=1): if not alias and with_col_aliases: alias = "col%d" % index if alias: sub_selects.append( "%s.%s" % ( self.connection.ops.quote_name("subquery"), self.connection.ops.quote_name(alias), ) ) else: select_clone = select.relabeled_clone( {select.alias: "subquery"} ) subselect, subparams = select_clone.as_sql( self, self.connection ) sub_selects.append(subselect) sub_params.extend(subparams) return "SELECT %s FROM (%s) subquery" % ( ", ".join(sub_selects), " ".join(result), ), tuple(sub_params + params) return " ".join(result), tuple(params) finally: # Finally do cleanup - get rid of the joins we created above. self.query.reset_refcounts(refcounts_before) def get_default_columns(self, start_alias=None, opts=None, from_parent=None): """ Compute the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Return a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, return a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: if (opts := self.query.get_meta()) is None: return result only_load = self.deferred_to_columns() start_alias = start_alias or self.query.get_initial_alias() # The 'seen_models' is used to optimize checking the needed parent # alias for a given field. This also includes None -> start_alias to # be used by local fields. seen_models = {None: start_alias} for field in opts.concrete_fields: model = field.model._meta.concrete_model # A proxy model will have a different model and concrete_model. We # will assign None if the field belongs to this model. if model == opts.model: model = None if ( from_parent and model is not None and issubclass( from_parent._meta.concrete_model, model._meta.concrete_model ) ): # Avoid loading data for already loaded parents. # We end up here in the case select_related() resolution # proceeds from parent model to child model. In that case the # parent model data is already present in the SELECT clause, # and we want to avoid reloading the same data again. continue if field.model in only_load and field.attname not in only_load[field.model]: continue alias = self.query.join_parent_model(opts, model, start_alias, seen_models) column = field.get_col(alias) result.append(column) return result def get_distinct(self): """ Return a quoted list of fields to use in DISTINCT ON part of the query. This method can alter the tables in the query, and thus it must be called before get_from_clause(). """ result = [] params = [] opts = self.query.get_meta() for name in self.query.distinct_fields: parts = name.split(LOOKUP_SEP) _, targets, alias, joins, path, _, transform_function = self._setup_joins( parts, opts, None ) targets, alias, _ = self.query.trim_joins(targets, joins, path) for target in targets: if name in self.query.annotation_select: result.append(self.connection.ops.quote_name(name)) else: r, p = self.compile(transform_function(target, alias)) result.append(r) params.append(p) return result, params def find_ordering_name( self, name, opts, alias=None, default_order="ASC", already_seen=None ): """ Return the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) descending = order == "DESC" pieces = name.split(LOOKUP_SEP) ( field, targets, alias, joins, path, opts, transform_function, ) = self._setup_joins(pieces, opts, alias) # If we get to this point and the field is a relation to another model, # append the default ordering for that model unless it is the pk # shortcut or the attribute name of the field that is specified. if ( field.is_relation and opts.ordering and getattr(field, "attname", None) != pieces[-1] and name != "pk" ): # Firstly, avoid infinite loops. already_seen = already_seen or set() join_tuple = tuple( getattr(self.query.alias_map[j], "join_cols", None) for j in joins ) if join_tuple in already_seen: raise FieldError("Infinite loop caused by ordering.") already_seen.add(join_tuple) results = [] for item in opts.ordering: if hasattr(item, "resolve_expression") and not isinstance( item, OrderBy ): item = item.desc() if descending else item.asc() if isinstance(item, OrderBy): results.append( (item.prefix_references(f"{name}{LOOKUP_SEP}"), False) ) continue results.extend( (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref) for expr, is_ref in self.find_ordering_name( item, opts, alias, order, already_seen ) ) return results targets, alias, _ = self.query.trim_joins(targets, joins, path) return [ (OrderBy(transform_function(t, alias), descending=descending), False) for t in targets ] def _setup_joins(self, pieces, opts, alias): """ Helper method for get_order_by() and get_distinct(). get_ordering() and get_distinct() must produce same target columns on same input, as the prefixes of get_ordering() and get_distinct() must match. Executing SQL where this is not true is an error. """ alias = alias or self.query.get_initial_alias() field, targets, opts, joins, path, transform_function = self.query.setup_joins( pieces, opts, alias ) alias = joins[-1] return field, targets, alias, joins, path, opts, transform_function def get_from_clause(self): """ Return a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Subclasses, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables that are needed. This means the select columns, ordering, and distinct must be done first. """ result = [] params = [] for alias in tuple(self.query.alias_map): if not self.query.alias_refcount[alias]: continue try: from_clause = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue clause_sql, clause_params = self.compile(from_clause) result.append(clause_sql) params.extend(clause_params) for t in self.query.extra_tables: alias, _ = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # call increments the refcount, so an alias refcount of one means # this is the only reference). if ( alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1 ): result.append(", %s" % self.quote_name_unless_alias(alias)) return result, params def get_related_selections( self, select, opts=None, root_alias=None, cur_depth=1, requested=None, restricted=None, ): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ def _get_field_choices(): direct_choices = (f.name for f in opts.fields if f.is_relation) reverse_choices = ( f.field.related_query_name() for f in opts.related_objects if f.field.unique ) return chain( direct_choices, reverse_choices, self.query._filtered_relations ) related_klass_infos = [] if not restricted and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return related_klass_infos if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() only_load = self.deferred_to_columns() # Setup for the case when only particular related fields should be # included in the related selection. fields_found = set() if requested is None: restricted = isinstance(self.query.select_related, dict) if restricted: requested = self.query.select_related def get_related_klass_infos(klass_info, related_klass_infos): klass_info["related_klass_infos"] = related_klass_infos for f in opts.fields: field_model = f.model._meta.concrete_model fields_found.add(f.name) if restricted: next = requested.get(f.name, {}) if not f.is_relation: # If a non-related field is used like a relation, # or if a single non-relational field is given. if next or f.name in requested: raise FieldError( "Non-relational field given in select_related: '%s'. " "Choices are: %s" % ( f.name, ", ".join(_get_field_choices()) or "(none)", ) ) else: next = False if not select_related_descend( f, restricted, requested, only_load.get(field_model) ): continue klass_info = { "model": f.remote_field.model, "field": f, "reverse": False, "local_setter": f.set_cached_value, "remote_setter": f.remote_field.set_cached_value if f.unique else lambda x, y: None, "from_parent": False, } related_klass_infos.append(klass_info) select_fields = [] _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias) alias = joins[-1] columns = self.get_default_columns( start_alias=alias, opts=f.remote_field.model._meta ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_klass_infos = self.get_related_selections( select, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) if restricted: related_fields = [ (o.field, o.related_model) for o in opts.related_objects if o.field.unique and not o.many_to_many ] for f, model in related_fields: if not select_related_descend( f, restricted, requested, only_load.get(model), reverse=True ): continue related_field_name = f.related_query_name() fields_found.add(related_field_name) join_info = self.query.setup_joins( [related_field_name], opts, root_alias ) alias = join_info.joins[-1] from_parent = issubclass(model, opts.model) and model is not opts.model klass_info = { "model": model, "field": f, "reverse": True, "local_setter": f.remote_field.set_cached_value, "remote_setter": f.set_cached_value, "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] columns = self.get_default_columns( start_alias=alias, opts=model._meta, from_parent=opts.model ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next = requested.get(f.related_query_name(), {}) next_klass_infos = self.get_related_selections( select, model._meta, alias, cur_depth + 1, next, restricted ) get_related_klass_infos(klass_info, next_klass_infos) def local_setter(obj, from_obj): # Set a reverse fk object when relation is non-empty. if from_obj: f.remote_field.set_cached_value(from_obj, obj) def remote_setter(name, obj, from_obj): setattr(from_obj, name, obj) for name in list(requested): # Filtered relations work only on the topmost level. if cur_depth > 1: break if name in self.query._filtered_relations: fields_found.add(name) f, _, join_opts, joins, _, _ = self.query.setup_joins( [name], opts, root_alias ) model = join_opts.model alias = joins[-1] from_parent = ( issubclass(model, opts.model) and model is not opts.model ) klass_info = { "model": model, "field": f, "reverse": True, "local_setter": local_setter, "remote_setter": partial(remote_setter, name), "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] columns = self.get_default_columns( start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_requested = requested.get(name, {}) next_klass_infos = self.get_related_selections( select, opts=model._meta, root_alias=alias, cur_depth=cur_depth + 1, requested=next_requested, restricted=restricted, ) get_related_klass_infos(klass_info, next_klass_infos) fields_not_found = set(requested).difference(fields_found) if fields_not_found: invalid_fields = ("'%s'" % s for s in fields_not_found) raise FieldError( "Invalid field name(s) given in select_related: %s. " "Choices are: %s" % ( ", ".join(invalid_fields), ", ".join(_get_field_choices()) or "(none)", ) ) return related_klass_infos def get_select_for_update_of_arguments(self): """ Return a quoted list of arguments for the SELECT FOR UPDATE OF part of the query. """ def _get_parent_klass_info(klass_info): concrete_model = klass_info["model"]._meta.concrete_model for parent_model, parent_link in concrete_model._meta.parents.items(): parent_list = parent_model._meta.get_parent_list() yield { "model": parent_model, "field": parent_link, "reverse": False, "select_fields": [ select_index for select_index in klass_info["select_fields"] # Selected columns from a model or its parents. if ( self.select[select_index][0].target.model == parent_model or self.select[select_index][0].target.model in parent_list ) ], } def _get_first_selected_col_from_model(klass_info): """ Find the first selected column from a model. If it doesn't exist, don't lock a model. select_fields is filled recursively, so it also contains fields from the parent models. """ concrete_model = klass_info["model"]._meta.concrete_model for select_index in klass_info["select_fields"]: if self.select[select_index][0].target.model == concrete_model: return self.select[select_index][0] def _get_field_choices(): """Yield all allowed field paths in breadth-first search order.""" queue = collections.deque([(None, self.klass_info)]) while queue: parent_path, klass_info = queue.popleft() if parent_path is None: path = [] yield "self" else: field = klass_info["field"] if klass_info["reverse"]: field = field.remote_field path = parent_path + [field.name] yield LOOKUP_SEP.join(path) queue.extend( (path, klass_info) for klass_info in _get_parent_klass_info(klass_info) ) queue.extend( (path, klass_info) for klass_info in klass_info.get("related_klass_infos", []) ) if not self.klass_info: return [] result = [] invalid_names = [] for name in self.query.select_for_update_of: klass_info = self.klass_info if name == "self": col = _get_first_selected_col_from_model(klass_info) else: for part in name.split(LOOKUP_SEP): klass_infos = ( *klass_info.get("related_klass_infos", []), *_get_parent_klass_info(klass_info), ) for related_klass_info in klass_infos: field = related_klass_info["field"] if related_klass_info["reverse"]: field = field.remote_field if field.name == part: klass_info = related_klass_info break else: klass_info = None break if klass_info is None: invalid_names.append(name) continue col = _get_first_selected_col_from_model(klass_info) if col is not None: if self.connection.features.select_for_update_of_column: result.append(self.compile(col)[0]) else: result.append(self.quote_name_unless_alias(col.alias)) if invalid_names: raise FieldError( "Invalid field name(s) given in select_for_update(of=(...)): %s. " "Only relational fields followed in the query are allowed. " "Choices are: %s." % ( ", ".join(invalid_names), ", ".join(_get_field_choices()), ) ) return result def deferred_to_columns(self): """ Convert the self.deferred_loading data structure to mapping of table names to sets of column names which are to be loaded. Return the dictionary. """ columns = {} self.query.deferred_to_data(columns) return columns def get_converters(self, expressions): converters = {} for i, expression in enumerate(expressions): if expression: backend_converters = self.connection.ops.get_db_converters(expression) field_converters = expression.get_db_converters(self.connection) if backend_converters or field_converters: converters[i] = (backend_converters + field_converters, expression) return converters def apply_converters(self, rows, converters): connection = self.connection converters = list(converters.items()) for row in map(list, rows): for pos, (convs, expression) in converters: value = row[pos] for converter in convs: value = converter(value, expression, connection) row[pos] = value yield row def results_iter( self, results=None, tuple_expected=False, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE, ): """Return an iterator over the results from executing this query.""" if results is None: results = self.execute_sql( MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size ) fields = [s[0] for s in self.select[0 : self.col_count]] converters = self.get_converters(fields) rows = chain.from_iterable(results) if converters: rows = self.apply_converters(rows, converters) if tuple_expected: rows = map(tuple, rows) return rows def has_results(self): """ Backends (e.g. NoSQL) can override this in order to use optimized versions of "query has any results." """ return bool(self.execute_sql(SINGLE)) def execute_sql( self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): """ Run the query against the database and return the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ result_type = result_type or NO_RESULTS try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return iter([]) else: return if chunked_fetch: cursor = self.connection.chunked_cursor() else: cursor = self.connection.cursor() try: cursor.execute(sql, params) except Exception: # Might fail for server-side cursors (e.g. connection closed) cursor.close() raise if result_type == CURSOR: # Give the caller the cursor to process and close. return cursor if result_type == SINGLE: try: val = cursor.fetchone() if val: return val[0 : self.col_count] return val finally: # done with the cursor cursor.close() if result_type == NO_RESULTS: cursor.close() return result = cursor_iter( cursor, self.connection.features.empty_fetchmany_value, self.col_count if self.has_extra_select else None, chunk_size, ) if not chunked_fetch or not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. Use chunked_fetch if requested, # unless the database doesn't support it. return list(result) return result def as_subquery_condition(self, alias, columns, compiler): qn = compiler.quote_name_unless_alias qn2 = self.connection.ops.quote_name for index, select_col in enumerate(self.query.select): lhs_sql, lhs_params = self.compile(select_col) rhs = "%s.%s" % (qn(alias), qn2(columns[index])) self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), "AND") sql, params = self.as_sql() return "EXISTS (%s)" % sql, params def explain_query(self): result = list(self.execute_sql()) # Some backends return 1 item tuples with strings, and others return # tuples with integers and strings. Flatten them out into strings. format_ = self.query.explain_info.format output_formatter = json.dumps if format_ and format_.lower() == "json" else str for row in result[0]: if not isinstance(row, str): yield " ".join(output_formatter(c) for c in row) else: yield row class SQLInsertCompiler(SQLCompiler): returning_fields = None returning_params = () def field_as_sql(self, field, val): """ Take a field and a value intended to be saved on that field, and return placeholder SQL and accompanying params. Check for raw values, expressions, and fields with get_placeholder() defined in that order. When field is None, consider the value raw and use it as the placeholder, with no corresponding parameters returned. """ if field is None: # A field value of None means the value is raw. sql, params = val, [] elif hasattr(val, "as_sql"): # This is an expression, let's compile it. sql, params = self.compile(val) elif hasattr(field, "get_placeholder"): # Some fields (e.g. geo fields) need special munging before # they can be inserted. sql, params = field.get_placeholder(val, self, self.connection), [val] else: # Return the common case for the placeholder sql, params = "%s", [val] # The following hook is only used by Oracle Spatial, which sometimes # needs to yield 'NULL' and [] as its placeholder and params instead # of '%s' and [None]. The 'NULL' placeholder is produced earlier by # OracleOperations.get_geom_placeholder(). The following line removes # the corresponding None parameter. See ticket #10888. params = self.connection.ops.modify_insert_params(sql, params) return sql, params def prepare_value(self, field, value): """ Prepare a value to be used in a query by resolving it if it is an expression and otherwise calling the field's get_db_prep_save(). """ if hasattr(value, "resolve_expression"): value = value.resolve_expression( self.query, allow_joins=False, for_save=True ) # Don't allow values containing Col expressions. They refer to # existing columns on a row, but in the case of insert the row # doesn't exist yet. if value.contains_column_references: raise ValueError( 'Failed to insert expression "%s" on %s. F() expressions ' "can only be used to update, not to insert." % (value, field) ) if value.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, value) ) if value.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query (%s=%r)." % (field.name, value) ) else: value = field.get_db_prep_save(value, connection=self.connection) return value def pre_save_val(self, field, obj): """ Get the given field's value off the given obj. pre_save() is used for things like auto_now on DateTimeField. Skip it if this is a raw query. """ if self.query.raw: return getattr(obj, field.attname) return field.pre_save(obj, add=True) def assemble_as_sql(self, fields, value_rows): """ Take a sequence of N fields and a sequence of M rows of values, and generate placeholder SQL and parameters for each field and value. Return a pair containing: * a sequence of M rows of N SQL placeholder strings, and * a sequence of M rows of corresponding parameter values. Each placeholder string may contain any number of '%s' interpolation strings, and each parameter row will contain exactly as many params as the total number of '%s's in the corresponding placeholder row. """ if not value_rows: return [], [] # list of (sql, [params]) tuples for each object to be saved # Shape: [n_objs][n_fields][2] rows_of_fields_as_sql = ( (self.field_as_sql(field, v) for field, v in zip(fields, row)) for row in value_rows ) # tuple like ([sqls], [[params]s]) for each object to be saved # Shape: [n_objs][2][n_fields] sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql) # Extract separate lists for placeholders and params. # Each of these has shape [n_objs][n_fields] placeholder_rows, param_rows = zip(*sql_and_param_pair_rows) # Params for each field are still lists, and need to be flattened. param_rows = [[p for ps in row for p in ps] for row in param_rows] return placeholder_rows, param_rows def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.get_meta() insert_statement = self.connection.ops.insert_statement( on_conflict=self.query.on_conflict, ) result = ["%s %s" % (insert_statement, qn(opts.db_table))] fields = self.query.fields or [opts.pk] result.append("(%s)" % ", ".join(qn(f.column) for f in fields)) if self.query.fields: value_rows = [ [ self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields ] for obj in self.query.objs ] else: # An empty object. value_rows = [ [self.connection.ops.pk_default_value()] for _ in self.query.objs ] fields = [None] # Currently the backends just accept values when generating bulk # queries and generate their own placeholders. Doing that isn't # necessary and it should be possible to use placeholders and # expressions in bulk inserts too. can_bulk = ( not self.returning_fields and self.connection.features.has_bulk_insert ) placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows) on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql( fields, self.query.on_conflict, self.query.update_fields, self.query.unique_fields, ) if ( self.returning_fields and self.connection.features.can_return_columns_from_insert ): if self.connection.features.can_return_rows_from_bulk_insert: result.append( self.connection.ops.bulk_insert_sql(fields, placeholder_rows) ) params = param_rows else: result.append("VALUES (%s)" % ", ".join(placeholder_rows[0])) params = [param_rows[0]] if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) # Skip empty r_sql to allow subclasses to customize behavior for # 3rd party backends. Refs #19096. r_sql, self.returning_params = self.connection.ops.return_insert_columns( self.returning_fields ) if r_sql: result.append(r_sql) params += [self.returning_params] return [(" ".join(result), tuple(chain.from_iterable(params)))] if can_bulk: result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows)) if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [(" ".join(result), tuple(p for ps in param_rows for p in ps))] else: if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [ (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals) for p, vals in zip(placeholder_rows, param_rows) ] def execute_sql(self, returning_fields=None): assert not ( returning_fields and len(self.query.objs) != 1 and not self.connection.features.can_return_rows_from_bulk_insert ) opts = self.query.get_meta() self.returning_fields = returning_fields with self.connection.cursor() as cursor: for sql, params in self.as_sql(): cursor.execute(sql, params) if not self.returning_fields: return [] if ( self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1 ): rows = self.connection.ops.fetch_returned_insert_rows(cursor) elif self.connection.features.can_return_columns_from_insert: assert len(self.query.objs) == 1 rows = [ self.connection.ops.fetch_returned_insert_columns( cursor, self.returning_params, ) ] else: rows = [ ( self.connection.ops.last_insert_id( cursor, opts.db_table, opts.pk.column, ), ) ] cols = [field.get_col(opts.db_table) for field in self.returning_fields] converters = self.get_converters(cols) if converters: rows = list(self.apply_converters(rows, converters)) return rows class SQLDeleteCompiler(SQLCompiler): @cached_property def single_alias(self): # Ensure base table is in aliases. self.query.get_initial_alias() return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1 @classmethod def _expr_refs_base_model(cls, expr, base_model): if isinstance(expr, Query): return expr.model == base_model if not hasattr(expr, "get_source_expressions"): return False return any( cls._expr_refs_base_model(source_expr, base_model) for source_expr in expr.get_source_expressions() ) @cached_property def contains_self_reference_subquery(self): return any( self._expr_refs_base_model(expr, self.query.model) for expr in chain( self.query.annotations.values(), self.query.where.children ) ) def _as_sql(self, query): result = ["DELETE FROM %s" % self.quote_name_unless_alias(query.base_table)] where, params = self.compile(query.where) if where: result.append("WHERE %s" % where) return " ".join(result), tuple(params) def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ if self.single_alias and not self.contains_self_reference_subquery: return self._as_sql(self.query) innerq = self.query.clone() innerq.__class__ = Query innerq.clear_select_clause() pk = self.query.model._meta.pk innerq.select = [pk.get_col(self.query.get_initial_alias())] outerq = Query(self.query.model) if not self.connection.features.update_can_self_select: # Force the materialization of the inner query to allow reference # to the target table on MySQL. sql, params = innerq.get_compiler(connection=self.connection).as_sql() innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params) outerq.add_filter("pk__in", innerq) return self._as_sql(outerq) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ self.pre_sql_setup() if not self.query.values: return "", () qn = self.quote_name_unless_alias values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, "resolve_expression"): val = val.resolve_expression( self.query, allow_joins=False, for_save=True ) if val.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, val) ) if val.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query " "(%s=%r)." % (field.name, val) ) elif hasattr(val, "prepare_database_save"): if field.remote_field: val = field.get_db_prep_save( val.prepare_database_save(field), connection=self.connection, ) else: raise TypeError( "Tried to update field %s with a model instance, %r. " "Use a value compatible with %s." % (field, val, field.__class__.__name__) ) else: val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, "get_placeholder"): placeholder = field.get_placeholder(val, self, self.connection) else: placeholder = "%s" name = field.column if hasattr(val, "as_sql"): sql, params = self.compile(val) values.append("%s = %s" % (qn(name), placeholder % sql)) update_params.extend(params) elif val is not None: values.append("%s = %s" % (qn(name), placeholder)) update_params.append(val) else: values.append("%s = NULL" % qn(name)) table = self.query.base_table result = [ "UPDATE %s SET" % qn(table), ", ".join(values), ] where, params = self.compile(self.query.where) if where: result.append("WHERE %s" % where) return " ".join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, munge the "where" conditions to match the format required for (portable) SQL updates. If multiple updates are required, pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ refcounts_before = self.query.alias_refcount.copy() # Ensure base table is in the query self.query.get_initial_alias() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return query = self.query.chain(klass=Query) query.select_related = False query.clear_ordering(force=True) query.extra = {} query.select = [] meta = query.get_meta() fields = [meta.pk.name] related_ids_index = [] for related in self.query.related_updates: if all( path.join_field.primary_key for path in meta.get_path_to_parent(related) ): # If a primary key chain exists to the targeted related update, # then the meta.pk value can be used for it. related_ids_index.append((related, 0)) else: # This branch will only be reached when updating a field of an # ancestor that is not part of the primary key chain of a MTI # tree. related_ids_index.append((related, len(fields))) fields.append(related._meta.pk.name) query.add_fields(fields) super().pre_sql_setup() must_pre_select = ( count > 1 and not self.connection.features.update_can_self_select ) # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.clear_where() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] related_ids = collections.defaultdict(list) for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend(r[0] for r in rows) for parent, index in related_ids_index: related_ids[parent].extend(r[index] for r in rows) self.query.add_filter("pk__in", idents) self.query.related_ids = related_ids else: # The fast path. Filters and updates in one query. self.query.add_filter("pk__in", query) self.query.reset_refcounts(refcounts_before) class SQLAggregateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ sql, params = [], [] for annotation in self.query.annotation_select.values(): ann_sql, ann_params = self.compile(annotation) ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params) sql.append(ann_sql) params.extend(ann_params) self.col_count = len(self.query.annotation_select) sql = ", ".join(sql) params = tuple(params) inner_query_sql, inner_query_params = self.query.inner_query.get_compiler( self.using, elide_empty=self.elide_empty, ).as_sql(with_col_aliases=True) sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql) params = params + inner_query_params return sql, params def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close()
926fceebdd4ddb1ad7075efad54161bd23476f9bdce2acd60267d339c2ec98c1
import logging import operator from datetime import datetime from django.conf import settings from django.db.backends.ddl_references import ( Columns, Expressions, ForeignKeyName, IndexName, Statement, Table, ) from django.db.backends.utils import names_digest, split_identifier from django.db.models import Deferrable, Index from django.db.models.sql import Query from django.db.transaction import TransactionManagementError, atomic from django.utils import timezone logger = logging.getLogger("django.db.backends.schema") def _is_relevant_relation(relation, altered_field): """ When altering the given field, must constraints on its model from the given relation be temporarily dropped? """ field = relation.field if field.many_to_many: # M2M reverse field return False if altered_field.primary_key and field.to_fields == [None]: # Foreign key constraint on the primary key, which is being altered. return True # Is the constraint targeting the field being altered? return altered_field.name in field.to_fields def _all_related_fields(model): # Related fields must be returned in a deterministic order. return sorted( model._meta._get_fields( forward=False, reverse=True, include_hidden=True, include_parents=False, ), key=operator.attrgetter("name"), ) def _related_non_m2m_objects(old_field, new_field): # Filter out m2m objects from reverse relations. # Return (old_relation, new_relation) tuples. related_fields = zip( ( obj for obj in _all_related_fields(old_field.model) if _is_relevant_relation(obj, old_field) ), ( obj for obj in _all_related_fields(new_field.model) if _is_relevant_relation(obj, new_field) ), ) for old_rel, new_rel in related_fields: yield old_rel, new_rel yield from _related_non_m2m_objects( old_rel.remote_field, new_rel.remote_field, ) class BaseDatabaseSchemaEditor: """ This class and its subclasses are responsible for emitting schema-changing statements to the databases - model creation/removal/alteration, field renaming, index fiddling, and so on. """ # Overrideable SQL templates sql_create_table = "CREATE TABLE %(table)s (%(definition)s)" sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s" sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s" sql_delete_table = "DROP TABLE %(table)s CASCADE" sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s" sql_alter_column = "ALTER TABLE %(table)s %(changes)s" sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s" sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL" sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL" sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s" sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT" sql_alter_column_no_default_null = sql_alter_column_no_default sql_alter_column_collate = "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s" sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE" sql_rename_column = ( "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s" ) sql_update_with_default = ( "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL" ) sql_unique_constraint = "UNIQUE (%(columns)s)%(deferrable)s" sql_check_constraint = "CHECK (%(check)s)" sql_delete_constraint = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s" sql_constraint = "CONSTRAINT %(name)s %(constraint)s" sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)" sql_delete_check = sql_delete_constraint sql_create_unique = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s " "UNIQUE (%(columns)s)%(deferrable)s" ) sql_delete_unique = sql_delete_constraint sql_create_fk = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) " "REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s" ) sql_create_inline_fk = None sql_create_column_inline_fk = None sql_delete_fk = sql_delete_constraint sql_create_index = ( "CREATE INDEX %(name)s ON %(table)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_create_unique_index = ( "CREATE UNIQUE INDEX %(name)s ON %(table)s " "(%(columns)s)%(include)s%(condition)s" ) sql_rename_index = "ALTER INDEX %(old_name)s RENAME TO %(new_name)s" sql_delete_index = "DROP INDEX %(name)s" sql_create_pk = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)" ) sql_delete_pk = sql_delete_constraint sql_delete_procedure = "DROP PROCEDURE %(procedure)s" def __init__(self, connection, collect_sql=False, atomic=True): self.connection = connection self.collect_sql = collect_sql if self.collect_sql: self.collected_sql = [] self.atomic_migration = self.connection.features.can_rollback_ddl and atomic # State-managing methods def __enter__(self): self.deferred_sql = [] if self.atomic_migration: self.atomic = atomic(self.connection.alias) self.atomic.__enter__() return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: for sql in self.deferred_sql: self.execute(sql) if self.atomic_migration: self.atomic.__exit__(exc_type, exc_value, traceback) # Core utility functions def execute(self, sql, params=()): """Execute the given SQL statement, with optional parameters.""" # Don't perform the transactional DDL check if SQL is being collected # as it's not going to be executed anyway. if ( not self.collect_sql and self.connection.in_atomic_block and not self.connection.features.can_rollback_ddl ): raise TransactionManagementError( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) # Account for non-string statement objects. sql = str(sql) # Log the command we're running, then run it logger.debug( "%s; (params %r)", sql, params, extra={"params": params, "sql": sql} ) if self.collect_sql: ending = "" if sql.rstrip().endswith(";") else ";" if params is not None: self.collected_sql.append( (sql % tuple(map(self.quote_value, params))) + ending ) else: self.collected_sql.append(sql + ending) else: with self.connection.cursor() as cursor: cursor.execute(sql, params) def quote_name(self, name): return self.connection.ops.quote_name(name) def table_sql(self, model): """Take a model and return its table definition.""" # Add any unique_togethers (always deferred, as some fields might be # created afterward, like geometry fields with some backends). for field_names in model._meta.unique_together: fields = [model._meta.get_field(field) for field in field_names] self.deferred_sql.append(self._create_unique_sql(model, fields)) # Create column SQL, add FK deferreds if needed. column_sqls = [] params = [] for field in model._meta.local_fields: # SQL. definition, extra_params = self.column_sql(model, field) if definition is None: continue # Check constraints can go on the column SQL here. db_params = field.db_parameters(connection=self.connection) if db_params["check"]: definition += " " + self.sql_check_constraint % db_params # Autoincrement SQL (for backends with inline variant). col_type_suffix = field.db_type_suffix(connection=self.connection) if col_type_suffix: definition += " %s" % col_type_suffix params.extend(extra_params) # FK. if field.remote_field and field.db_constraint: to_table = field.remote_field.model._meta.db_table to_column = field.remote_field.model._meta.get_field( field.remote_field.field_name ).column if self.sql_create_inline_fk: definition += " " + self.sql_create_inline_fk % { "to_table": self.quote_name(to_table), "to_column": self.quote_name(to_column), } elif self.connection.features.supports_foreign_keys: self.deferred_sql.append( self._create_fk_sql( model, field, "_fk_%(to_table)s_%(to_column)s" ) ) # Add the SQL to our big list. column_sqls.append( "%s %s" % ( self.quote_name(field.column), definition, ) ) # Autoincrement SQL (for backends with post table definition # variant). if field.get_internal_type() in ( "AutoField", "BigAutoField", "SmallAutoField", ): autoinc_sql = self.connection.ops.autoinc_sql( model._meta.db_table, field.column ) if autoinc_sql: self.deferred_sql.extend(autoinc_sql) constraints = [ constraint.constraint_sql(model, self) for constraint in model._meta.constraints ] sql = self.sql_create_table % { "table": self.quote_name(model._meta.db_table), "definition": ", ".join( constraint for constraint in (*column_sqls, *constraints) if constraint ), } if model._meta.db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql( model._meta.db_tablespace ) if tablespace_sql: sql += " " + tablespace_sql return sql, params # Field <-> database mapping functions def _iter_column_sql( self, column_db_type, params, model, field, field_db_params, include_default ): yield column_db_type if collation := field_db_params.get("collation"): yield self._collate_sql(collation) # Work out nullability. null = field.null # Include a default value, if requested. include_default = ( include_default and not self.skip_default(field) and # Don't include a default value if it's a nullable field and the # default cannot be dropped in the ALTER COLUMN statement (e.g. # MySQL longtext and longblob). not (null and self.skip_default_on_alter(field)) ) if include_default: default_value = self.effective_default(field) if default_value is not None: column_default = "DEFAULT " + self._column_default_sql(field) if self.connection.features.requires_literal_defaults: # Some databases can't take defaults as a parameter (Oracle). # If this is the case, the individual schema backend should # implement prepare_default(). yield column_default % self.prepare_default(default_value) else: yield column_default params.append(default_value) # Oracle treats the empty string ('') as null, so coerce the null # option whenever '' is a possible value. if ( field.empty_strings_allowed and not field.primary_key and self.connection.features.interprets_empty_strings_as_nulls ): null = True if not null: yield "NOT NULL" elif not self.connection.features.implied_column_null: yield "NULL" if field.primary_key: yield "PRIMARY KEY" elif field.unique: yield "UNIQUE" # Optionally add the tablespace if it's an implicitly indexed column. tablespace = field.db_tablespace or model._meta.db_tablespace if ( tablespace and self.connection.features.supports_tablespaces and field.unique ): yield self.connection.ops.tablespace_sql(tablespace, inline=True) def column_sql(self, model, field, include_default=False): """ Return the column definition for a field. The field must already have had set_attributes_from_name() called. """ # Get the column's type and use that as the basis of the SQL. field_db_params = field.db_parameters(connection=self.connection) column_db_type = field_db_params["type"] # Check for fields that aren't actually columns (e.g. M2M). if column_db_type is None: return None, None params = [] return ( " ".join( # This appends to the params being returned. self._iter_column_sql( column_db_type, params, model, field, field_db_params, include_default, ) ), params, ) def skip_default(self, field): """ Some backends don't accept default values for certain columns types (i.e. MySQL longtext and longblob). """ return False def skip_default_on_alter(self, field): """ Some backends don't accept default values for certain columns types (i.e. MySQL longtext and longblob) in the ALTER COLUMN statement. """ return False def prepare_default(self, value): """ Only used for backends which have requires_literal_defaults feature """ raise NotImplementedError( "subclasses of BaseDatabaseSchemaEditor for backends which have " "requires_literal_defaults must provide a prepare_default() method" ) def _column_default_sql(self, field): """ Return the SQL to use in a DEFAULT clause. The resulting string should contain a '%s' placeholder for a default value. """ return "%s" @staticmethod def _effective_default(field): # This method allows testing its logic without a connection. if field.has_default(): default = field.get_default() elif not field.null and field.blank and field.empty_strings_allowed: if field.get_internal_type() == "BinaryField": default = b"" else: default = "" elif getattr(field, "auto_now", False) or getattr(field, "auto_now_add", False): internal_type = field.get_internal_type() if internal_type == "DateTimeField": default = timezone.now() else: default = datetime.now() if internal_type == "DateField": default = default.date() elif internal_type == "TimeField": default = default.time() else: default = None return default def effective_default(self, field): """Return a field's effective database default value.""" return field.get_db_prep_save(self._effective_default(field), self.connection) def quote_value(self, value): """ Return a quoted version of the value so it's safe to use in an SQL string. This is not safe against injection from user code; it is intended only for use in making SQL scripts or preparing default values for particularly tricky backends (defaults are not user-defined, though, so this is safe). """ raise NotImplementedError() # Actions def create_model(self, model): """ Create a table and any accompanying indexes or unique constraints for the given `model`. """ sql, params = self.table_sql(model) # Prevent using [] as params, in the case a literal '%' is used in the # definition. self.execute(sql, params or None) # Add any field index and index_together's (deferred as SQLite # _remake_table needs it). self.deferred_sql.extend(self._model_indexes_sql(model)) # Make M2M tables for field in model._meta.local_many_to_many: if field.remote_field.through._meta.auto_created: self.create_model(field.remote_field.through) def delete_model(self, model): """Delete a model from the database.""" # Handle auto-created intermediary models for field in model._meta.local_many_to_many: if field.remote_field.through._meta.auto_created: self.delete_model(field.remote_field.through) # Delete the table self.execute( self.sql_delete_table % { "table": self.quote_name(model._meta.db_table), } ) # Remove all deferred statements referencing the deleted table. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_table( model._meta.db_table ): self.deferred_sql.remove(sql) def add_index(self, model, index): """Add an index on a model.""" if ( index.contains_expressions and not self.connection.features.supports_expression_indexes ): return None # Index.create_sql returns interpolated SQL which makes params=None a # necessity to avoid escaping attempts on execution. self.execute(index.create_sql(model, self), params=None) def remove_index(self, model, index): """Remove an index from a model.""" if ( index.contains_expressions and not self.connection.features.supports_expression_indexes ): return None self.execute(index.remove_sql(model, self)) def rename_index(self, model, old_index, new_index): if self.connection.features.can_rename_index: self.execute( self._rename_index_sql(model, old_index.name, new_index.name), params=None, ) else: self.remove_index(model, old_index) self.add_index(model, new_index) def add_constraint(self, model, constraint): """Add a constraint to a model.""" sql = constraint.create_sql(model, self) if sql: # Constraint.create_sql returns interpolated SQL which makes # params=None a necessity to avoid escaping attempts on execution. self.execute(sql, params=None) def remove_constraint(self, model, constraint): """Remove a constraint from a model.""" sql = constraint.remove_sql(model, self) if sql: self.execute(sql) def alter_unique_together(self, model, old_unique_together, new_unique_together): """ Deal with a model changing its unique_together. The input unique_togethers must be doubly-nested, not the single-nested ["foo", "bar"] format. """ olds = {tuple(fields) for fields in old_unique_together} news = {tuple(fields) for fields in new_unique_together} # Deleted uniques for fields in olds.difference(news): self._delete_composed_index( model, fields, {"unique": True, "primary_key": False}, self.sql_delete_unique, ) # Created uniques for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names] self.execute(self._create_unique_sql(model, fields)) def alter_index_together(self, model, old_index_together, new_index_together): """ Deal with a model changing its index_together. The input index_togethers must be doubly-nested, not the single-nested ["foo", "bar"] format. """ olds = {tuple(fields) for fields in old_index_together} news = {tuple(fields) for fields in new_index_together} # Deleted indexes for fields in olds.difference(news): self._delete_composed_index( model, fields, {"index": True, "unique": False}, self.sql_delete_index, ) # Created indexes for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names] self.execute(self._create_index_sql(model, fields=fields, suffix="_idx")) def _delete_composed_index(self, model, fields, constraint_kwargs, sql): meta_constraint_names = { constraint.name for constraint in model._meta.constraints } meta_index_names = {constraint.name for constraint in model._meta.indexes} columns = [model._meta.get_field(field).column for field in fields] constraint_names = self._constraint_names( model, columns, exclude=meta_constraint_names | meta_index_names, **constraint_kwargs, ) if ( constraint_kwargs.get("unique") is True and constraint_names and self.connection.features.allows_multiple_constraints_on_same_fields ): # Constraint matching the unique_together name. default_name = str( self._unique_constraint_name(model._meta.db_table, columns, quote=False) ) if default_name in constraint_names: constraint_names = [default_name] if len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of constraints for %s(%s)" % ( len(constraint_names), model._meta.db_table, ", ".join(columns), ) ) self.execute(self._delete_constraint_sql(sql, model, constraint_names[0])) def alter_db_table(self, model, old_db_table, new_db_table): """Rename the table a model points to.""" if old_db_table == new_db_table or ( self.connection.features.ignores_table_name_case and old_db_table.lower() == new_db_table.lower() ): return self.execute( self.sql_rename_table % { "old_table": self.quote_name(old_db_table), "new_table": self.quote_name(new_db_table), } ) # Rename all references to the old table name. for sql in self.deferred_sql: if isinstance(sql, Statement): sql.rename_table_references(old_db_table, new_db_table) def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace): """Move a model's table between tablespaces.""" self.execute( self.sql_retablespace_table % { "table": self.quote_name(model._meta.db_table), "old_tablespace": self.quote_name(old_db_tablespace), "new_tablespace": self.quote_name(new_db_tablespace), } ) def add_field(self, model, field): """ Create a field on a model. Usually involves adding a column, but may involve adding a table instead (for M2M fields). """ # Special-case implicit M2M tables if field.many_to_many and field.remote_field.through._meta.auto_created: return self.create_model(field.remote_field.through) # Get the column's definition definition, params = self.column_sql(model, field, include_default=True) # It might not actually have a column behind it if definition is None: return # Check constraints can go on the column SQL here db_params = field.db_parameters(connection=self.connection) if db_params["check"]: definition += " " + self.sql_check_constraint % db_params if ( field.remote_field and self.connection.features.supports_foreign_keys and field.db_constraint ): constraint_suffix = "_fk_%(to_table)s_%(to_column)s" # Add FK constraint inline, if supported. if self.sql_create_column_inline_fk: to_table = field.remote_field.model._meta.db_table to_column = field.remote_field.model._meta.get_field( field.remote_field.field_name ).column namespace, _ = split_identifier(model._meta.db_table) definition += " " + self.sql_create_column_inline_fk % { "name": self._fk_constraint_name(model, field, constraint_suffix), "namespace": "%s." % self.quote_name(namespace) if namespace else "", "column": self.quote_name(field.column), "to_table": self.quote_name(to_table), "to_column": self.quote_name(to_column), "deferrable": self.connection.ops.deferrable_sql(), } # Otherwise, add FK constraints later. else: self.deferred_sql.append( self._create_fk_sql(model, field, constraint_suffix) ) # Build the SQL and run it sql = self.sql_create_column % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), "definition": definition, } self.execute(sql, params) # Drop the default if we need to # (Django usually does not use in-database defaults) if ( not self.skip_default_on_alter(field) and self.effective_default(field) is not None ): changes_sql, params = self._alter_column_default_sql( model, None, field, drop=True ) sql = self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": changes_sql, } self.execute(sql, params) # Add an index, if required self.deferred_sql.extend(self._field_indexes_sql(model, field)) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() def remove_field(self, model, field): """ Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """ # Special-case implicit M2M tables if field.many_to_many and field.remote_field.through._meta.auto_created: return self.delete_model(field.remote_field.through) # It might not actually have a column behind it if field.db_parameters(connection=self.connection)["type"] is None: return # Drop any FK constraints, MySQL requires explicit deletion if field.remote_field: fk_names = self._constraint_names(model, [field.column], foreign_key=True) for fk_name in fk_names: self.execute(self._delete_fk_sql(model, fk_name)) # Delete the column sql = self.sql_delete_column % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), } self.execute(sql) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() # Remove all deferred statements referencing the deleted column. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_column( model._meta.db_table, field.column ): self.deferred_sql.remove(sql) def alter_field(self, model, old_field, new_field, strict=False): """ Allow a field's type, uniqueness, nullability, default, column, constraints, etc. to be modified. `old_field` is required to compute the necessary changes. If `strict` is True, raise errors if the old column does not match `old_field` precisely. """ if not self._field_should_be_altered(old_field, new_field): return # Ensure this field is even column-based old_db_params = old_field.db_parameters(connection=self.connection) old_type = old_db_params["type"] new_db_params = new_field.db_parameters(connection=self.connection) new_type = new_db_params["type"] if (old_type is None and old_field.remote_field is None) or ( new_type is None and new_field.remote_field is None ): raise ValueError( "Cannot alter field %s into %s - they do not properly define " "db_type (are you using a badly-written custom field?)" % (old_field, new_field), ) elif ( old_type is None and new_type is None and ( old_field.remote_field.through and new_field.remote_field.through and old_field.remote_field.through._meta.auto_created and new_field.remote_field.through._meta.auto_created ) ): return self._alter_many_to_many(model, old_field, new_field, strict) elif ( old_type is None and new_type is None and ( old_field.remote_field.through and new_field.remote_field.through and not old_field.remote_field.through._meta.auto_created and not new_field.remote_field.through._meta.auto_created ) ): # Both sides have through models; this is a no-op. return elif old_type is None or new_type is None: raise ValueError( "Cannot alter field %s into %s - they are not compatible types " "(you cannot alter to or from M2M fields, or add or remove " "through= on M2M fields)" % (old_field, new_field) ) self._alter_field( model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict, ) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): """Perform a "physical" (non-ManyToMany) field update.""" # Drop any FK constraints, we'll remake them later fks_dropped = set() if ( self.connection.features.supports_foreign_keys and old_field.remote_field and old_field.db_constraint ): fk_names = self._constraint_names( model, [old_field.column], foreign_key=True ) if strict and len(fk_names) != 1: raise ValueError( "Found wrong number (%s) of foreign key constraints for %s.%s" % ( len(fk_names), model._meta.db_table, old_field.column, ) ) for fk_name in fk_names: fks_dropped.add((old_field.column,)) self.execute(self._delete_fk_sql(model, fk_name)) # Has unique been removed? if old_field.unique and ( not new_field.unique or self._field_became_primary_key(old_field, new_field) ): # Find the unique constraint for this field meta_constraint_names = { constraint.name for constraint in model._meta.constraints } constraint_names = self._constraint_names( model, [old_field.column], unique=True, primary_key=False, exclude=meta_constraint_names, ) if strict and len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of unique constraints for %s.%s" % ( len(constraint_names), model._meta.db_table, old_field.column, ) ) for constraint_name in constraint_names: self.execute(self._delete_unique_sql(model, constraint_name)) # Drop incoming FK constraints if the field is a primary key or unique, # which might be a to_field target, and things are going to change. old_collation = old_db_params.get("collation") new_collation = new_db_params.get("collation") drop_foreign_keys = ( self.connection.features.supports_foreign_keys and ( (old_field.primary_key and new_field.primary_key) or (old_field.unique and new_field.unique) ) and ((old_type != new_type) or (old_collation != new_collation)) ) if drop_foreign_keys: # '_meta.related_field' also contains M2M reverse fields, these # will be filtered out for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field): rel_fk_names = self._constraint_names( new_rel.related_model, [new_rel.field.column], foreign_key=True ) for fk_name in rel_fk_names: self.execute(self._delete_fk_sql(new_rel.related_model, fk_name)) # Removed an index? (no strict check, as multiple indexes are possible) # Remove indexes if db_index switched to False or a unique constraint # will now be used in lieu of an index. The following lines from the # truth table show all True cases; the rest are False: # # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique # ------------------------------------------------------------------------------ # True | False | False | False # True | False | False | True # True | False | True | True if ( old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique) ): # Find the index for this field meta_index_names = {index.name for index in model._meta.indexes} # Retrieve only BTREE indexes since this is what's created with # db_index=True. index_names = self._constraint_names( model, [old_field.column], index=True, type_=Index.suffix, exclude=meta_index_names, ) for index_name in index_names: # The only way to check if an index was created with # db_index=True or with Index(['field'], name='foo') # is to look at its name (refs #28053). self.execute(self._delete_index_sql(model, index_name)) # Change check constraints? if old_db_params["check"] != new_db_params["check"] and old_db_params["check"]: meta_constraint_names = { constraint.name for constraint in model._meta.constraints } constraint_names = self._constraint_names( model, [old_field.column], check=True, exclude=meta_constraint_names, ) if strict and len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of check constraints for %s.%s" % ( len(constraint_names), model._meta.db_table, old_field.column, ) ) for constraint_name in constraint_names: self.execute(self._delete_check_sql(model, constraint_name)) # Have they renamed the column? if old_field.column != new_field.column: self.execute( self._rename_field_sql( model._meta.db_table, old_field, new_field, new_type ) ) # Rename all references to the renamed column. for sql in self.deferred_sql: if isinstance(sql, Statement): sql.rename_column_references( model._meta.db_table, old_field.column, new_field.column ) # Next, start accumulating actions to do actions = [] null_actions = [] post_actions = [] # Type suffix change? (e.g. auto increment). old_type_suffix = old_field.db_type_suffix(connection=self.connection) new_type_suffix = new_field.db_type_suffix(connection=self.connection) # Collation change? if old_collation != new_collation: # Collation change handles also a type change. fragment = self._alter_column_collation_sql( model, new_field, new_type, new_collation ) actions.append(fragment) # Type change? elif (old_type, old_type_suffix) != (new_type, new_type_suffix): fragment, other_actions = self._alter_column_type_sql( model, old_field, new_field, new_type ) actions.append(fragment) post_actions.extend(other_actions) # When changing a column NULL constraint to NOT NULL with a given # default value, we need to perform 4 steps: # 1. Add a default for new incoming writes # 2. Update existing NULL rows with new default # 3. Replace NULL constraint with NOT NULL # 4. Drop the default again. # Default change? needs_database_default = False if old_field.null and not new_field.null: old_default = self.effective_default(old_field) new_default = self.effective_default(new_field) if ( not self.skip_default_on_alter(new_field) and old_default != new_default and new_default is not None ): needs_database_default = True actions.append( self._alter_column_default_sql(model, old_field, new_field) ) # Nullability change? if old_field.null != new_field.null: fragment = self._alter_column_null_sql(model, old_field, new_field) if fragment: null_actions.append(fragment) # Only if we have a default and there is a change from NULL to NOT NULL four_way_default_alteration = new_field.has_default() and ( old_field.null and not new_field.null ) if actions or null_actions: if not four_way_default_alteration: # If we don't have to do a 4-way default alteration we can # directly run a (NOT) NULL alteration actions = actions + null_actions # Combine actions together if we can (e.g. postgres) if self.connection.features.supports_combined_alters and actions: sql, params = tuple(zip(*actions)) actions = [(", ".join(sql), sum(params, []))] # Apply those actions for sql, params in actions: self.execute( self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": sql, }, params, ) if four_way_default_alteration: # Update existing rows with default value self.execute( self.sql_update_with_default % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(new_field.column), "default": "%s", }, [new_default], ) # Since we didn't run a NOT NULL change before we need to do it # now for sql, params in null_actions: self.execute( self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": sql, }, params, ) if post_actions: for sql, params in post_actions: self.execute(sql, params) # If primary_key changed to False, delete the primary key constraint. if old_field.primary_key and not new_field.primary_key: self._delete_primary_key(model, strict) # Added a unique? if self._unique_should_be_added(old_field, new_field): self.execute(self._create_unique_sql(model, [new_field])) # Added an index? Add an index if db_index switched to True or a unique # constraint will no longer be used in lieu of an index. The following # lines from the truth table show all True cases; the rest are False: # # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique # ------------------------------------------------------------------------------ # False | False | True | False # False | True | True | False # True | True | True | False if ( (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique ): self.execute(self._create_index_sql(model, fields=[new_field])) # Type alteration on primary key? Then we need to alter the column # referring to us. rels_to_update = [] if drop_foreign_keys: rels_to_update.extend(_related_non_m2m_objects(old_field, new_field)) # Changed to become primary key? if self._field_became_primary_key(old_field, new_field): # Make the new one self.execute(self._create_primary_key_sql(model, new_field)) # Update all referencing columns rels_to_update.extend(_related_non_m2m_objects(old_field, new_field)) # Handle our type alters on the other end of rels from the PK stuff above for old_rel, new_rel in rels_to_update: rel_db_params = new_rel.field.db_parameters(connection=self.connection) rel_type = rel_db_params["type"] rel_collation = rel_db_params.get("collation") old_rel_db_params = old_rel.field.db_parameters(connection=self.connection) old_rel_collation = old_rel_db_params.get("collation") if old_rel_collation != rel_collation: # Collation change handles also a type change. fragment = self._alter_column_collation_sql( new_rel.related_model, new_rel.field, rel_type, rel_collation, ) other_actions = [] else: fragment, other_actions = self._alter_column_type_sql( new_rel.related_model, old_rel.field, new_rel.field, rel_type ) self.execute( self.sql_alter_column % { "table": self.quote_name(new_rel.related_model._meta.db_table), "changes": fragment[0], }, fragment[1], ) for sql, params in other_actions: self.execute(sql, params) # Does it have a foreign key? if ( self.connection.features.supports_foreign_keys and new_field.remote_field and ( fks_dropped or not old_field.remote_field or not old_field.db_constraint ) and new_field.db_constraint ): self.execute( self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s") ) # Rebuild FKs that pointed to us if we previously had to drop them if drop_foreign_keys: for _, rel in rels_to_update: if rel.field.db_constraint: self.execute( self._create_fk_sql(rel.related_model, rel.field, "_fk") ) # Does it have check constraints we need to add? if old_db_params["check"] != new_db_params["check"] and new_db_params["check"]: constraint_name = self._create_index_name( model._meta.db_table, [new_field.column], suffix="_check" ) self.execute( self._create_check_sql(model, constraint_name, new_db_params["check"]) ) # Drop the default if we need to # (Django usually does not use in-database defaults) if needs_database_default: changes_sql, params = self._alter_column_default_sql( model, old_field, new_field, drop=True ) sql = self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": changes_sql, } self.execute(sql, params) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() def _alter_column_null_sql(self, model, old_field, new_field): """ Hook to specialize column null alteration. Return a (sql, params) fragment to set a column to null or non-null as required by new_field, or None if no changes are required. """ if ( self.connection.features.interprets_empty_strings_as_nulls and new_field.empty_strings_allowed ): # The field is nullable in the database anyway, leave it alone. return else: new_db_params = new_field.db_parameters(connection=self.connection) sql = ( self.sql_alter_column_null if new_field.null else self.sql_alter_column_not_null ) return ( sql % { "column": self.quote_name(new_field.column), "type": new_db_params["type"], }, [], ) def _alter_column_default_sql(self, model, old_field, new_field, drop=False): """ Hook to specialize column default alteration. Return a (sql, params) fragment to add or drop (depending on the drop argument) a default to new_field's column. """ new_default = self.effective_default(new_field) default = self._column_default_sql(new_field) params = [new_default] if drop: params = [] elif self.connection.features.requires_literal_defaults: # Some databases (Oracle) can't take defaults as a parameter # If this is the case, the SchemaEditor for that database should # implement prepare_default(). default = self.prepare_default(new_default) params = [] new_db_params = new_field.db_parameters(connection=self.connection) if drop: if new_field.null: sql = self.sql_alter_column_no_default_null else: sql = self.sql_alter_column_no_default else: sql = self.sql_alter_column_default return ( sql % { "column": self.quote_name(new_field.column), "type": new_db_params["type"], "default": default, }, params, ) def _alter_column_type_sql(self, model, old_field, new_field, new_type): """ Hook to specialize column type alteration for different backends, for cases when a creation type is different to an alteration type (e.g. SERIAL in PostgreSQL, PostGIS fields). Return a two-tuple of: an SQL fragment of (sql, params) to insert into an ALTER TABLE statement and a list of extra (sql, params) tuples to run once the field is altered. """ return ( ( self.sql_alter_column_type % { "column": self.quote_name(new_field.column), "type": new_type, }, [], ), [], ) def _alter_column_collation_sql(self, model, new_field, new_type, new_collation): return ( self.sql_alter_column_collate % { "column": self.quote_name(new_field.column), "type": new_type, "collation": " " + self._collate_sql(new_collation) if new_collation else "", }, [], ) def _alter_many_to_many(self, model, old_field, new_field, strict): """Alter M2Ms to repoint their to= endpoints.""" # Rename the through table if ( old_field.remote_field.through._meta.db_table != new_field.remote_field.through._meta.db_table ): self.alter_db_table( old_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) # Repoint the FK to the other side self.alter_field( new_field.remote_field.through, # The field that points to the target model is needed, so we can # tell alter_field to change it - this is m2m_reverse_field_name() # (as opposed to m2m_field_name(), which points to our model). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_reverse_field_name() ), ) self.alter_field( new_field.remote_field.through, # for self-referential models we need to alter field from the other end too old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()), new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()), ) def _create_index_name(self, table_name, column_names, suffix=""): """ Generate a unique name for an index/unique constraint. The name is divided into 3 parts: the table name, the column names, and a unique digest and suffix. """ _, table_name = split_identifier(table_name) hash_suffix_part = "%s%s" % ( names_digest(table_name, *column_names, length=8), suffix, ) max_length = self.connection.ops.max_name_length() or 200 # If everything fits into max_length, use that name. index_name = "%s_%s_%s" % (table_name, "_".join(column_names), hash_suffix_part) if len(index_name) <= max_length: return index_name # Shorten a long suffix. if len(hash_suffix_part) > max_length / 3: hash_suffix_part = hash_suffix_part[: max_length // 3] other_length = (max_length - len(hash_suffix_part)) // 2 - 1 index_name = "%s_%s_%s" % ( table_name[:other_length], "_".join(column_names)[:other_length], hash_suffix_part, ) # Prepend D if needed to prevent the name from starting with an # underscore or a number (not permitted on Oracle). if index_name[0] == "_" or index_name[0].isdigit(): index_name = "D%s" % index_name[:-1] return index_name def _get_index_tablespace_sql(self, model, fields, db_tablespace=None): if db_tablespace is None: if len(fields) == 1 and fields[0].db_tablespace: db_tablespace = fields[0].db_tablespace elif settings.DEFAULT_INDEX_TABLESPACE: db_tablespace = settings.DEFAULT_INDEX_TABLESPACE elif model._meta.db_tablespace: db_tablespace = model._meta.db_tablespace if db_tablespace is not None: return " " + self.connection.ops.tablespace_sql(db_tablespace) return "" def _index_condition_sql(self, condition): if condition: return " WHERE " + condition return "" def _index_include_sql(self, model, columns): if not columns or not self.connection.features.supports_covering_indexes: return "" return Statement( " INCLUDE (%(columns)s)", columns=Columns(model._meta.db_table, columns, self.quote_name), ) def _create_index_sql( self, model, *, fields=None, name=None, suffix="", using="", db_tablespace=None, col_suffixes=(), sql=None, opclasses=(), condition=None, include=None, expressions=None, ): """ Return the SQL statement to create the index for one or several fields or expressions. `sql` can be specified if the syntax differs from the standard (GIS indexes, ...). """ fields = fields or [] expressions = expressions or [] compiler = Query(model, alias_cols=False).get_compiler( connection=self.connection, ) tablespace_sql = self._get_index_tablespace_sql( model, fields, db_tablespace=db_tablespace ) columns = [field.column for field in fields] sql_create_index = sql or self.sql_create_index table = model._meta.db_table def create_index_name(*args, **kwargs): nonlocal name if name is None: name = self._create_index_name(*args, **kwargs) return self.quote_name(name) return Statement( sql_create_index, table=Table(table, self.quote_name), name=IndexName(table, columns, suffix, create_index_name), using=using, columns=( self._index_columns(table, columns, col_suffixes, opclasses) if columns else Expressions(table, expressions, compiler, self.quote_value) ), extra=tablespace_sql, condition=self._index_condition_sql(condition), include=self._index_include_sql(model, include), ) def _delete_index_sql(self, model, name, sql=None): return Statement( sql or self.sql_delete_index, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name(name), ) def _rename_index_sql(self, model, old_name, new_name): return Statement( self.sql_rename_index, table=Table(model._meta.db_table, self.quote_name), old_name=self.quote_name(old_name), new_name=self.quote_name(new_name), ) def _index_columns(self, table, columns, col_suffixes, opclasses): return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes) def _model_indexes_sql(self, model): """ Return a list of all index SQL statements (field indexes, index_together, Meta.indexes) for the specified model. """ if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] output = [] for field in model._meta.local_fields: output.extend(self._field_indexes_sql(model, field)) for field_names in model._meta.index_together: fields = [model._meta.get_field(field) for field in field_names] output.append(self._create_index_sql(model, fields=fields, suffix="_idx")) for index in model._meta.indexes: if ( not index.contains_expressions or self.connection.features.supports_expression_indexes ): output.append(index.create_sql(model, self)) return output def _field_indexes_sql(self, model, field): """ Return a list of all index SQL statements for the specified field. """ output = [] if self._field_should_be_indexed(model, field): output.append(self._create_index_sql(model, fields=[field])) return output def _field_should_be_altered(self, old_field, new_field): _, old_path, old_args, old_kwargs = old_field.deconstruct() _, new_path, new_args, new_kwargs = new_field.deconstruct() # Don't alter when: # - changing only a field name # - changing an attribute that doesn't affect the schema # - adding only a db_column and the column name is not changed for attr in old_field.non_db_attrs: old_kwargs.pop(attr, None) for attr in new_field.non_db_attrs: new_kwargs.pop(attr, None) return self.quote_name(old_field.column) != self.quote_name( new_field.column ) or (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs) def _field_should_be_indexed(self, model, field): return field.db_index and not field.unique def _field_became_primary_key(self, old_field, new_field): return not old_field.primary_key and new_field.primary_key def _unique_should_be_added(self, old_field, new_field): return ( not new_field.primary_key and new_field.unique and (not old_field.unique or old_field.primary_key) ) def _rename_field_sql(self, table, old_field, new_field, new_type): return self.sql_rename_column % { "table": self.quote_name(table), "old_column": self.quote_name(old_field.column), "new_column": self.quote_name(new_field.column), "type": new_type, } def _create_fk_sql(self, model, field, suffix): table = Table(model._meta.db_table, self.quote_name) name = self._fk_constraint_name(model, field, suffix) column = Columns(model._meta.db_table, [field.column], self.quote_name) to_table = Table(field.target_field.model._meta.db_table, self.quote_name) to_column = Columns( field.target_field.model._meta.db_table, [field.target_field.column], self.quote_name, ) deferrable = self.connection.ops.deferrable_sql() return Statement( self.sql_create_fk, table=table, name=name, column=column, to_table=to_table, to_column=to_column, deferrable=deferrable, ) def _fk_constraint_name(self, model, field, suffix): def create_fk_name(*args, **kwargs): return self.quote_name(self._create_index_name(*args, **kwargs)) return ForeignKeyName( model._meta.db_table, [field.column], split_identifier(field.target_field.model._meta.db_table)[1], [field.target_field.column], suffix, create_fk_name, ) def _delete_fk_sql(self, model, name): return self._delete_constraint_sql(self.sql_delete_fk, model, name) def _deferrable_constraint_sql(self, deferrable): if deferrable is None: return "" if deferrable == Deferrable.DEFERRED: return " DEFERRABLE INITIALLY DEFERRED" if deferrable == Deferrable.IMMEDIATE: return " DEFERRABLE INITIALLY IMMEDIATE" def _unique_sql( self, model, fields, name, condition=None, deferrable=None, include=None, opclasses=None, expressions=None, ): if ( deferrable and not self.connection.features.supports_deferrable_unique_constraints ): return None if condition or include or opclasses or expressions: # Databases support conditional, covering, and functional unique # constraints via a unique index. sql = self._create_unique_sql( model, fields, name=name, condition=condition, include=include, opclasses=opclasses, expressions=expressions, ) if sql: self.deferred_sql.append(sql) return None constraint = self.sql_unique_constraint % { "columns": ", ".join([self.quote_name(field.column) for field in fields]), "deferrable": self._deferrable_constraint_sql(deferrable), } return self.sql_constraint % { "name": self.quote_name(name), "constraint": constraint, } def _create_unique_sql( self, model, fields, name=None, condition=None, deferrable=None, include=None, opclasses=None, expressions=None, ): if ( ( deferrable and not self.connection.features.supports_deferrable_unique_constraints ) or (condition and not self.connection.features.supports_partial_indexes) or (include and not self.connection.features.supports_covering_indexes) or ( expressions and not self.connection.features.supports_expression_indexes ) ): return None compiler = Query(model, alias_cols=False).get_compiler( connection=self.connection ) table = model._meta.db_table columns = [field.column for field in fields] if name is None: name = self._unique_constraint_name(table, columns, quote=True) else: name = self.quote_name(name) if condition or include or opclasses or expressions: sql = self.sql_create_unique_index else: sql = self.sql_create_unique if columns: columns = self._index_columns( table, columns, col_suffixes=(), opclasses=opclasses ) else: columns = Expressions(table, expressions, compiler, self.quote_value) return Statement( sql, table=Table(table, self.quote_name), name=name, columns=columns, condition=self._index_condition_sql(condition), deferrable=self._deferrable_constraint_sql(deferrable), include=self._index_include_sql(model, include), ) def _unique_constraint_name(self, table, columns, quote=True): if quote: def create_unique_name(*args, **kwargs): return self.quote_name(self._create_index_name(*args, **kwargs)) else: create_unique_name = self._create_index_name return IndexName(table, columns, "_uniq", create_unique_name) def _delete_unique_sql( self, model, name, condition=None, deferrable=None, include=None, opclasses=None, expressions=None, ): if ( ( deferrable and not self.connection.features.supports_deferrable_unique_constraints ) or (condition and not self.connection.features.supports_partial_indexes) or (include and not self.connection.features.supports_covering_indexes) or ( expressions and not self.connection.features.supports_expression_indexes ) ): return None if condition or include or opclasses or expressions: sql = self.sql_delete_index else: sql = self.sql_delete_unique return self._delete_constraint_sql(sql, model, name) def _check_sql(self, name, check): return self.sql_constraint % { "name": self.quote_name(name), "constraint": self.sql_check_constraint % {"check": check}, } def _create_check_sql(self, model, name, check): return Statement( self.sql_create_check, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name(name), check=check, ) def _delete_check_sql(self, model, name): return self._delete_constraint_sql(self.sql_delete_check, model, name) def _delete_constraint_sql(self, template, model, name): return Statement( template, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name(name), ) def _constraint_names( self, model, column_names=None, unique=None, primary_key=None, index=None, foreign_key=None, check=None, type_=None, exclude=None, ): """Return all constraint names matching the columns and conditions.""" if column_names is not None: column_names = [ self.connection.introspection.identifier_converter(name) for name in column_names ] with self.connection.cursor() as cursor: constraints = self.connection.introspection.get_constraints( cursor, model._meta.db_table ) result = [] for name, infodict in constraints.items(): if column_names is None or column_names == infodict["columns"]: if unique is not None and infodict["unique"] != unique: continue if primary_key is not None and infodict["primary_key"] != primary_key: continue if index is not None and infodict["index"] != index: continue if check is not None and infodict["check"] != check: continue if foreign_key is not None and not infodict["foreign_key"]: continue if type_ is not None and infodict["type"] != type_: continue if not exclude or name not in exclude: result.append(name) return result def _delete_primary_key(self, model, strict=False): constraint_names = self._constraint_names(model, primary_key=True) if strict and len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of PK constraints for %s" % ( len(constraint_names), model._meta.db_table, ) ) for constraint_name in constraint_names: self.execute(self._delete_primary_key_sql(model, constraint_name)) def _create_primary_key_sql(self, model, field): return Statement( self.sql_create_pk, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name( self._create_index_name( model._meta.db_table, [field.column], suffix="_pk" ) ), columns=Columns(model._meta.db_table, [field.column], self.quote_name), ) def _delete_primary_key_sql(self, model, name): return self._delete_constraint_sql(self.sql_delete_pk, model, name) def _collate_sql(self, collation): return "COLLATE " + self.quote_name(collation) def remove_procedure(self, procedure_name, param_types=()): sql = self.sql_delete_procedure % { "procedure": self.quote_name(procedure_name), "param_types": ",".join(param_types), } self.execute(sql)
7ab974beda27913d52aec9e166c7616671f793a335b100868f44b6fc7c553cae
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_pk = True related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True supports_forward_references = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True can_release_savepoints = True atomic_transactions = False can_clone_databases = True supports_temporal_subtraction = True supports_select_intersection = False supports_select_difference = False supports_slicing_ordering_in_compound = True supports_index_on_text_field = False supports_update_conflicts = True create_test_procedure_without_params_sql = """ CREATE PROCEDURE test_procedure () BEGIN DECLARE V_I INTEGER; SET V_I = 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE test_procedure (P_I INTEGER) BEGIN DECLARE V_I INTEGER; SET V_I = P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ # Neither MySQL nor MariaDB support partial indexes. supports_partial_indexes = False # COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an # indexed expression. collate_as_index_expression = True supports_order_by_nulls_modifier = False order_by_nulls_first = True supports_logical_xor = True @cached_property def minimum_database_version(self): if self.connection.mysql_is_mariadb: return (10, 4) else: return (5, 7) @cached_property def bare_select_suffix(self): if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): return " FROM DUAL" return "" @cached_property def test_collations(self): charset = "utf8" if self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 6, ): # utf8 is an alias for utf8mb3 in MariaDB 10.6+. charset = "utf8mb3" return { "ci": f"{charset}_general_ci", "non_default": f"{charset}_esperanto_ci", "swedish_ci": f"{charset}_swedish_ci", } test_now_utc_template = "UTC_TIMESTAMP" @cached_property def django_test_skips(self): skips = { "This doesn't work on MySQL.": { "db_functions.comparison.test_greatest.GreatestTests." "test_coalesce_workaround", "db_functions.comparison.test_least.LeastTests." "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", "model_fields.test_charfield.TestCharField.test_emoji", }, "MySQL doesn't support functional indexes on a function that " "returns JSON": { "schema.tests.SchemaTests.test_func_index_json_key_transform", }, "MySQL supports multiplying and dividing DurationFields by a " "scalar value but it's not implemented (#25287).": { "expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide", }, "UPDATE ... ORDER BY syntax on MySQL/MariaDB does not support ordering by" "related fields.": { "update.tests.AdvancedTests." "test_update_ordered_by_inline_m2m_annotation", "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation", }, } if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode: skips.update( { "GROUP BY optimization does not work properly when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #31331.": { "aggregation.tests.AggregateTestCase." "test_aggregation_subquery_annotation_multivalued", "annotations.tests.NonAggregateAnnotationTestCase." "test_annotation_aggregate_with_m2o", }, } ) if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): skips.update( { "Casting to datetime/time is not supported by MySQL < 8.0. " "(#30224)": { "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_time_from_python", "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_datetime_from_python", }, "MySQL < 8.0 returns string type instead of datetime/time. " "(#30224)": { "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_time_from_database", "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_datetime_from_database", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { "schema.tests.SchemaTests." "test_alter_not_unique_field_to_primary_key", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 12, ) < self.connection.mysql_version < (10, 5): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { "schema.tests.SchemaTests." "test_alter_pk_with_self_referential_field", }, } ) if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): skips.update( { "Parenthesized combined queries are not supported on MySQL < 8.": { "queries.test_qs_combinators.QuerySetSetOperationTests." "test_union_in_subquery", "queries.test_qs_combinators.QuerySetSetOperationTests." "test_union_in_subquery_related_outerref", "queries.test_qs_combinators.QuerySetSetOperationTests." "test_union_in_with_ordering", } } ) if not self.supports_explain_analyze: skips.update( { "MariaDB and MySQL >= 8.0.18 specific.": { "queries.test_explain.ExplainTests.test_mysql_analyze", }, } ) return skips @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" return self.connection.mysql_server_data["default_storage_engine"] @cached_property def allows_auto_pk_0(self): """ Autoincrement primary key can be set to 0 if it doesn't generate new autoincrement values. """ return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode @cached_property def update_can_self_select(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 3, 2, ) @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != "MyISAM" @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BinaryField": "TextField", "BooleanField": "IntegerField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", } @cached_property def can_return_columns_from_insert(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 5, 0, ) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") ) @cached_property def has_zoneinfo_database(self): return self.connection.mysql_server_data["has_zoneinfo_database"] @cached_property def is_sql_auto_is_null_enabled(self): return self.connection.mysql_server_data["sql_auto_is_null"] @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property( operator.attrgetter("supports_over_clause") ) @cached_property def supports_column_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) supports_table_check_constraints = property( operator.attrgetter("supports_column_check_constraints") ) @cached_property def can_introspect_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) @cached_property def has_select_for_update_skip_locked(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 6) return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_nowait(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_of(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 1) ) @cached_property def supports_explain_analyze(self): return self.connection.mysql_is_mariadb or self.connection.mysql_version >= ( 8, 0, 18, ) @cached_property def supported_explain_formats(self): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. formats = {"JSON", "TEXT", "TRADITIONAL"} if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 8, 0, 16, ): formats.add("TREE") return formats @cached_property def supports_transactions(self): """ All storage engines except MyISAM support transactions. """ return self._mysql_storage_engine != "MyISAM" uses_savepoints = property(operator.attrgetter("supports_transactions")) can_release_savepoints = property(operator.attrgetter("supports_transactions")) @cached_property def ignores_table_name_case(self): return self.connection.mysql_server_data["lower_case_table_names"] @cached_property def supports_default_in_lead_lag(self): # To be added in https://jira.mariadb.org/browse/MDEV-12981. return not self.connection.mysql_is_mariadb @cached_property def supports_json_field(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (5, 7, 8) @cached_property def can_introspect_json_field(self): if self.connection.mysql_is_mariadb: return self.supports_json_field and self.can_introspect_check_constraints return self.supports_json_field @cached_property def supports_index_column_ordering(self): if self._mysql_storage_engine != "InnoDB": return False if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 8) return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self): return ( not self.connection.mysql_is_mariadb and self._mysql_storage_engine != "MyISAM" and self.connection.mysql_version >= (8, 0, 13) ) @cached_property def can_rename_index(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 5, 2) return True
9a1886a0f7d92ffad8505b28ff5bc50986cba393713e9570cb8a3cca757be7a6
import copy from collections import defaultdict from django.conf import settings from django.template.backends.django import get_template_tag_modules from . import Error, Tags, register E001 = Error( "You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' " "in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option.", id="templates.E001", ) E002 = Error( "'string_if_invalid' in TEMPLATES OPTIONS must be a string but got: {} ({}).", id="templates.E002", ) E003 = Error( "{} is used for multiple template tag modules: {}", id="templates.E003", ) @register(Tags.templates) def check_setting_app_dirs_loaders(app_configs, **kwargs): return ( [E001] if any( conf.get("APP_DIRS") and "loaders" in conf.get("OPTIONS", {}) for conf in settings.TEMPLATES ) else [] ) @register(Tags.templates) def check_string_if_invalid_is_string(app_configs, **kwargs): errors = [] for conf in settings.TEMPLATES: string_if_invalid = conf.get("OPTIONS", {}).get("string_if_invalid", "") if not isinstance(string_if_invalid, str): error = copy.copy(E002) error.msg = error.msg.format( string_if_invalid, type(string_if_invalid).__name__ ) errors.append(error) return errors @register(Tags.templates) def check_for_template_tags_with_the_same_name(app_configs, **kwargs): errors = [] libraries = defaultdict(set) for conf in settings.TEMPLATES: custom_libraries = conf.get("OPTIONS", {}).get("libraries", {}) for module_name, module_path in custom_libraries.items(): libraries[module_name].add(module_path) for module_name, module_path in get_template_tag_modules(): libraries[module_name].add(module_path) for library_name, items in libraries.items(): if len(items) > 1: errors.append( Error( E003.msg.format( repr(library_name), ", ".join(repr(item) for item in sorted(items)), ), id=E003.id, ) ) return errors
11b9ae802776c8001dac1130a06956af7a1feecae44c45bc348effa6f2350913
""" Base classes for writing management commands (named commands which can be executed through ``django-admin`` or ``manage.py``). """ import argparse import os import sys from argparse import ArgumentParser, HelpFormatter from io import TextIOBase import django from django.core import checks from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style, no_style from django.db import DEFAULT_DB_ALIAS, connections ALL_CHECKS = "__all__" class CommandError(Exception): """ Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. """ def __init__(self, *args, returncode=1, **kwargs): self.returncode = returncode super().__init__(*args, **kwargs) class SystemCheckError(CommandError): """ The system check framework detected unrecoverable errors. """ pass class CommandParser(ArgumentParser): """ Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically. """ def __init__( self, *, missing_args_message=None, called_from_command_line=None, **kwargs ): self.missing_args_message = missing_args_message self.called_from_command_line = called_from_command_line super().__init__(**kwargs) def parse_args(self, args=None, namespace=None): # Catch missing argument for a better error message if self.missing_args_message and not ( args or any(not arg.startswith("-") for arg in args) ): self.error(self.missing_args_message) return super().parse_args(args, namespace) def error(self, message): if self.called_from_command_line: super().error(message) else: raise CommandError("Error: %s" % message) def handle_default_options(options): """ Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands. """ if options.settings: os.environ["DJANGO_SETTINGS_MODULE"] = options.settings if options.pythonpath: sys.path.insert(0, options.pythonpath) def no_translations(handle_func): """Decorator that forces a command to run with translations deactivated.""" def wrapper(*args, **kwargs): from django.utils import translation saved_locale = translation.get_language() translation.deactivate_all() try: res = handle_func(*args, **kwargs) finally: if saved_locale is not None: translation.activate(saved_locale) return res return wrapper class DjangoHelpFormatter(HelpFormatter): """ Customized formatter so that command-specific arguments appear in the --help output before arguments common to all commands. """ show_last = { "--version", "--verbosity", "--traceback", "--settings", "--pythonpath", "--no-color", "--force-color", "--skip-checks", } def _reordered_actions(self, actions): return sorted( actions, key=lambda a: set(a.option_strings) & self.show_last != set() ) def add_usage(self, usage, actions, *args, **kwargs): super().add_usage(usage, self._reordered_actions(actions), *args, **kwargs) def add_arguments(self, actions): super().add_arguments(self._reordered_actions(actions)) class OutputWrapper(TextIOBase): """ Wrapper around stdout/stderr """ @property def style_func(self): return self._style_func @style_func.setter def style_func(self, style_func): if style_func and self.isatty(): self._style_func = style_func else: self._style_func = lambda x: x def __init__(self, out, ending="\n"): self._out = out self.style_func = None self.ending = ending def __getattr__(self, name): return getattr(self._out, name) def flush(self): if hasattr(self._out, "flush"): self._out.flush() def isatty(self): return hasattr(self._out, "isatty") and self._out.isatty() def write(self, msg="", style_func=None, ending=None): ending = self.ending if ending is None else ending if ending and not msg.endswith(ending): msg += ending style_func = style_func or self.style_func self._out.write(style_func(msg)) class BaseCommand: """ The base class from which all management commands ultimately derive. Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don't need to change any of that behavior, consider using one of the subclasses defined in this file. If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows: 1. ``django-admin`` or ``manage.py`` loads the command class and calls its ``run_from_argv()`` method. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get an ``ArgumentParser`` for the arguments, parses them, performs any environment changes requested by options like ``pythonpath``, and then calls the ``execute()`` method, passing the parsed arguments. 3. The ``execute()`` method attempts to carry out the command by calling the ``handle()`` method with the parsed arguments; any output produced by ``handle()`` will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``. 4. If ``handle()`` or ``execute()`` raised any exception (e.g. ``CommandError``), ``run_from_argv()`` will instead print an error message to ``stderr``. Thus, the ``handle()`` method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in ``handle()``, or perform some additional parsing work in ``handle()`` and then delegate from it to more specialized methods as needed. Several attributes affect behavior at various steps along the way: ``help`` A short description of the command, which will be printed in help messages. ``output_transaction`` A boolean indicating whether the command outputs SQL statements; if ``True``, the output will automatically be wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is ``False``. ``requires_migrations_checks`` A boolean; if ``True``, the command prints a warning if the set of migrations on disk don't match the migrations in the database. ``requires_system_checks`` A list or tuple of tags, e.g. [Tags.staticfiles, Tags.models]. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value '__all__' can be used to specify that all system checks should be performed. Default value is '__all__'. To validate an individual application's models rather than all applications' models, call ``self.check(app_configs)`` from ``handle()``, where ``app_configs`` is the list of application's configuration provided by the app registry. ``stealth_options`` A tuple of any options the command uses which aren't defined by the argument parser. """ # Metadata about this command. help = "" # Configuration shortcuts that alter various logic. _called_from_command_line = False output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;" requires_migrations_checks = False requires_system_checks = "__all__" # Arguments, common to all commands, which aren't defined by the argument # parser. base_stealth_options = ("stderr", "stdout") # Command-specific options not defined by the argument parser. stealth_options = () suppressed_base_arguments = set() def __init__(self, stdout=None, stderr=None, no_color=False, force_color=False): self.stdout = OutputWrapper(stdout or sys.stdout) self.stderr = OutputWrapper(stderr or sys.stderr) if no_color and force_color: raise CommandError("'no_color' and 'force_color' can't be used together.") if no_color: self.style = no_style() else: self.style = color_style(force_color) self.stderr.style_func = self.style.ERROR if ( not isinstance(self.requires_system_checks, (list, tuple)) and self.requires_system_checks != ALL_CHECKS ): raise TypeError("requires_system_checks must be a list or tuple.") def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version. """ return django.get_version() def create_parser(self, prog_name, subcommand, **kwargs): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ kwargs.setdefault("formatter_class", DjangoHelpFormatter) parser = CommandParser( prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None, missing_args_message=getattr(self, "missing_args_message", None), called_from_command_line=getattr(self, "_called_from_command_line", None), **kwargs, ) self.add_base_argument( parser, "--version", action="version", version=self.get_version(), help="Show program's version number and exit.", ) self.add_base_argument( parser, "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help=( "Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, " "3=very verbose output" ), ) self.add_base_argument( parser, "--settings", help=( "The Python path to a settings module, e.g. " '"myproject.settings.main". If this isn\'t provided, the ' "DJANGO_SETTINGS_MODULE environment variable will be used." ), ) self.add_base_argument( parser, "--pythonpath", help=( "A directory to add to the Python path, e.g. " '"/home/djangoprojects/myproject".' ), ) self.add_base_argument( parser, "--traceback", action="store_true", help="Raise on CommandError exceptions.", ) self.add_base_argument( parser, "--no-color", action="store_true", help="Don't colorize the command output.", ) self.add_base_argument( parser, "--force-color", action="store_true", help="Force colorization of the command output.", ) if self.requires_system_checks: parser.add_argument( "--skip-checks", action="store_true", help="Skip system checks.", ) self.add_arguments(parser) return parser def add_arguments(self, parser): """ Entry point for subclassed commands to add custom arguments. """ pass def add_base_argument(self, parser, *args, **kwargs): """ Call the parser's add_argument() method, suppressing the help text according to BaseCommand.suppressed_base_arguments. """ for arg in args: if arg in self.suppressed_base_arguments: kwargs["help"] = argparse.SUPPRESS break parser.add_argument(*args, **kwargs) def print_help(self, prog_name, subcommand): """ Print the help message for this command, derived from ``self.usage()``. """ parser = self.create_parser(prog_name, subcommand) parser.print_help() def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. """ self._called_from_command_line = True parser = self.create_parser(argv[0], argv[1]) options = parser.parse_args(argv[2:]) cmd_options = vars(options) # Move positional args out of options to mimic legacy optparse args = cmd_options.pop("args", ()) handle_default_options(options) try: self.execute(*args, **cmd_options) except CommandError as e: if options.traceback: raise # SystemCheckError takes care of its own formatting. if isinstance(e, SystemCheckError): self.stderr.write(str(e), lambda x: x) else: self.stderr.write("%s: %s" % (e.__class__.__name__, e)) sys.exit(e.returncode) finally: try: connections.close_all() except ImproperlyConfigured: # Ignore if connections aren't setup at this point (e.g. no # configured settings). pass def execute(self, *args, **options): """ Try to execute this command, performing system checks if needed (as controlled by the ``requires_system_checks`` attribute, except if force-skipped). """ if options["force_color"] and options["no_color"]: raise CommandError( "The --no-color and --force-color options can't be used together." ) if options["force_color"]: self.style = color_style(force_color=True) elif options["no_color"]: self.style = no_style() self.stderr.style_func = None if options.get("stdout"): self.stdout = OutputWrapper(options["stdout"]) if options.get("stderr"): self.stderr = OutputWrapper(options["stderr"]) if self.requires_system_checks and not options["skip_checks"]: if self.requires_system_checks == ALL_CHECKS: self.check() else: self.check(tags=self.requires_system_checks) if self.requires_migrations_checks: self.check_migrations() output = self.handle(*args, **options) if output: if self.output_transaction: connection = connections[options.get("database", DEFAULT_DB_ALIAS)] output = "%s\n%s\n%s" % ( self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()), output, self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()), ) self.stdout.write(output) return output def check( self, app_configs=None, tags=None, display_num_errors=False, include_deployment_checks=False, fail_level=checks.ERROR, databases=None, ): """ Use the system check framework to validate entire Django project. Raise CommandError for any serious message (error or critical errors). If there are only light messages (like warnings), print them to stderr and don't raise an exception. """ all_issues = checks.run_checks( app_configs=app_configs, tags=tags, include_deployment_checks=include_deployment_checks, databases=databases, ) header, body, footer = "", "", "" visible_issue_count = 0 # excludes silenced warnings if all_issues: debugs = [ e for e in all_issues if e.level < checks.INFO and not e.is_silenced() ] infos = [ e for e in all_issues if checks.INFO <= e.level < checks.WARNING and not e.is_silenced() ] warnings = [ e for e in all_issues if checks.WARNING <= e.level < checks.ERROR and not e.is_silenced() ] errors = [ e for e in all_issues if checks.ERROR <= e.level < checks.CRITICAL and not e.is_silenced() ] criticals = [ e for e in all_issues if checks.CRITICAL <= e.level and not e.is_silenced() ] sorted_issues = [ (criticals, "CRITICALS"), (errors, "ERRORS"), (warnings, "WARNINGS"), (infos, "INFOS"), (debugs, "DEBUGS"), ] for issues, group_name in sorted_issues: if issues: visible_issue_count += len(issues) formatted = ( self.style.ERROR(str(e)) if e.is_serious() else self.style.WARNING(str(e)) for e in issues ) formatted = "\n".join(sorted(formatted)) body += "\n%s:\n%s\n" % (group_name, formatted) if visible_issue_count: header = "System check identified some issues:\n" if display_num_errors: if visible_issue_count: footer += "\n" footer += "System check identified %s (%s silenced)." % ( "no issues" if visible_issue_count == 0 else "1 issue" if visible_issue_count == 1 else "%s issues" % visible_issue_count, len(all_issues) - visible_issue_count, ) if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer raise SystemCheckError(msg) else: msg = header + body + footer if msg: if visible_issue_count: self.stderr.write(msg, lambda x: x) else: self.stdout.write(msg) def check_migrations(self): """ Print a warning if the set of migrations on disk don't match the migrations in the database. """ from django.db.migrations.executor import MigrationExecutor try: executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) except ImproperlyConfigured: # No databases are configured (or the dummy one) return plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) if plan: apps_waiting_migration = sorted( {migration.app_label for migration, backwards in plan} ) self.stdout.write( self.style.NOTICE( "\nYou have %(unapplied_migration_count)s unapplied migration(s). " "Your project may not work properly until you apply the " "migrations for app(s): %(apps_waiting_migration)s." % { "unapplied_migration_count": len(plan), "apps_waiting_migration": ", ".join(apps_waiting_migration), } ) ) self.stdout.write( self.style.NOTICE("Run 'python manage.py migrate' to apply them.") ) def handle(self, *args, **options): """ The actual logic of the command. Subclasses must implement this method. """ raise NotImplementedError( "subclasses of BaseCommand must provide a handle() method" ) class AppCommand(BaseCommand): """ A management command which takes one or more installed application labels as arguments, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_app_config()``, which will be called once for each application. """ missing_args_message = "Enter at least one application label." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="+", help="One or more application label.", ) def handle(self, *app_labels, **options): from django.apps import apps try: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] except (LookupError, ImportError) as e: raise CommandError( "%s. Are you sure your INSTALLED_APPS setting is correct?" % e ) output = [] for app_config in app_configs: app_output = self.handle_app_config(app_config, **options) if app_output: output.append(app_output) return "\n".join(output) def handle_app_config(self, app_config, **options): """ Perform the command's actions for app_config, an AppConfig instance corresponding to an application label given on the command line. """ raise NotImplementedError( "Subclasses of AppCommand must provide a handle_app_config() method." ) class LabelCommand(BaseCommand): """ A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_label()``, which will be called once for each label. If the arguments should be names of installed applications, use ``AppCommand`` instead. """ label = "label" missing_args_message = "Enter at least one %s." % label def add_arguments(self, parser): parser.add_argument("args", metavar=self.label, nargs="+") def handle(self, *labels, **options): output = [] for label in labels: label_output = self.handle_label(label, **options) if label_output: output.append(label_output) return "\n".join(output) def handle_label(self, label, **options): """ Perform the command's actions for ``label``, which will be the string as given on the command line. """ raise NotImplementedError( "subclasses of LabelCommand must provide a handle_label() method" )
bfd243e45791fb6ad677ab4430d09e3b52f0db62668129a27b8734e2fff2c996
import logging import sys import tempfile import traceback from asgiref.sync import ThreadSensitiveContext, sync_to_async from django.conf import settings from django.core import signals from django.core.exceptions import RequestAborted, RequestDataTooBig from django.core.handlers import base from django.http import ( FileResponse, HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseServerError, QueryDict, parse_cookie, ) from django.urls import set_script_prefix from django.utils.functional import cached_property logger = logging.getLogger("django.request") class ASGIRequest(HttpRequest): """ Custom request subclass that decodes from an ASGI-standard request dict and wraps request body handling. """ # Number of seconds until a Request gives up on trying to read a request # body and aborts. body_receive_timeout = 60 def __init__(self, scope, body_file): self.scope = scope self._post_parse_error = False self._read_started = False self.resolver_match = None self.script_name = self.scope.get("root_path", "") if self.script_name and scope["path"].startswith(self.script_name): # TODO: Better is-prefix checking, slash handling? self.path_info = scope["path"][len(self.script_name) :] else: self.path_info = scope["path"] # The Django path is different from ASGI scope path args, it should # combine with script name. if self.script_name: self.path = "%s/%s" % ( self.script_name.rstrip("/"), self.path_info.replace("/", "", 1), ) else: self.path = scope["path"] # HTTP basics. self.method = self.scope["method"].upper() # Ensure query string is encoded correctly. query_string = self.scope.get("query_string", "") if isinstance(query_string, bytes): query_string = query_string.decode() self.META = { "REQUEST_METHOD": self.method, "QUERY_STRING": query_string, "SCRIPT_NAME": self.script_name, "PATH_INFO": self.path_info, # WSGI-expecting code will need these for a while "wsgi.multithread": True, "wsgi.multiprocess": True, } if self.scope.get("client"): self.META["REMOTE_ADDR"] = self.scope["client"][0] self.META["REMOTE_HOST"] = self.META["REMOTE_ADDR"] self.META["REMOTE_PORT"] = self.scope["client"][1] if self.scope.get("server"): self.META["SERVER_NAME"] = self.scope["server"][0] self.META["SERVER_PORT"] = str(self.scope["server"][1]) else: self.META["SERVER_NAME"] = "unknown" self.META["SERVER_PORT"] = "0" # Headers go into META. for name, value in self.scope.get("headers", []): name = name.decode("latin1") if name == "content-length": corrected_name = "CONTENT_LENGTH" elif name == "content-type": corrected_name = "CONTENT_TYPE" else: corrected_name = "HTTP_%s" % name.upper().replace("-", "_") # HTTP/2 say only ASCII chars are allowed in headers, but decode # latin1 just in case. value = value.decode("latin1") if corrected_name in self.META: value = self.META[corrected_name] + "," + value self.META[corrected_name] = value # Pull out request encoding, if provided. self._set_content_type_params(self.META) # Directly assign the body file to be our stream. self._stream = body_file # Other bits. self.resolver_match = None @cached_property def GET(self): return QueryDict(self.META["QUERY_STRING"]) def _get_scheme(self): return self.scope.get("scheme") or super()._get_scheme() def _get_post(self): if not hasattr(self, "_post"): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_files(self): if not hasattr(self, "_files"): self._load_post_and_files() return self._files POST = property(_get_post, _set_post) FILES = property(_get_files) @cached_property def COOKIES(self): return parse_cookie(self.META.get("HTTP_COOKIE", "")) def close(self): super().close() self._stream.close() class ASGIHandler(base.BaseHandler): """Handler for ASGI requests.""" request_class = ASGIRequest # Size to chunk response bodies into for multiple response messages. chunk_size = 2**16 def __init__(self): super().__init__() self.load_middleware(is_async=True) async def __call__(self, scope, receive, send): """ Async entrypoint - parses the request and hands off to get_response. """ # Serve only HTTP connections. # FIXME: Allow to override this. if scope["type"] != "http": raise ValueError( "Django can only handle ASGI/HTTP connections, not %s." % scope["type"] ) async with ThreadSensitiveContext(): await self.handle(scope, receive, send) async def handle(self, scope, receive, send): """ Handles the ASGI request. Called via the __call__ method. """ # Receive the HTTP request body as a stream object. try: body_file = await self.read_body(receive) except RequestAborted: return # Request is complete and can be served. set_script_prefix(self.get_script_prefix(scope)) await sync_to_async(signals.request_started.send, thread_sensitive=True)( sender=self.__class__, scope=scope ) # Get the request and check for basic issues. request, error_response = self.create_request(scope, body_file) if request is None: body_file.close() await self.send_response(error_response, send) return # Get the response, using the async mode of BaseHandler. response = await self.get_response_async(request) response._handler_class = self.__class__ # Increase chunk size on file responses (ASGI servers handles low-level # chunking). if isinstance(response, FileResponse): response.block_size = self.chunk_size # Send the response. await self.send_response(response, send) async def read_body(self, receive): """Reads an HTTP body from an ASGI connection.""" # Use the tempfile that auto rolls-over to a disk file as it fills up. body_file = tempfile.SpooledTemporaryFile( max_size=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, mode="w+b" ) while True: message = await receive() if message["type"] == "http.disconnect": body_file.close() # Early client disconnect. raise RequestAborted() # Add a body chunk from the message, if provided. if "body" in message: body_file.write(message["body"]) # Quit out if that's the end. if not message.get("more_body", False): break body_file.seek(0) return body_file def create_request(self, scope, body_file): """ Create the Request object and returns either (request, None) or (None, response) if there is an error response. """ try: return self.request_class(scope, body_file), None except UnicodeDecodeError: logger.warning( "Bad Request (UnicodeDecodeError)", exc_info=sys.exc_info(), extra={"status_code": 400}, ) return None, HttpResponseBadRequest() except RequestDataTooBig: return None, HttpResponse("413 Payload too large", status=413) def handle_uncaught_exception(self, request, resolver, exc_info): """Last-chance handler for exceptions.""" # There's no WSGI server to catch the exception further up # if this fails, so translate it into a plain text response. try: return super().handle_uncaught_exception(request, resolver, exc_info) except Exception: return HttpResponseServerError( traceback.format_exc() if settings.DEBUG else "Internal Server Error", content_type="text/plain", ) async def send_response(self, response, send): """Encode and send a response out over ASGI.""" # Collect cookies into headers. Have to preserve header case as there # are some non-RFC compliant clients that require e.g. Content-Type. response_headers = [] for header, value in response.items(): if isinstance(header, str): header = header.encode("ascii") if isinstance(value, str): value = value.encode("latin1") response_headers.append((bytes(header), bytes(value))) for c in response.cookies.values(): response_headers.append( (b"Set-Cookie", c.output(header="").encode("ascii").strip()) ) # Initial response message. await send( { "type": "http.response.start", "status": response.status_code, "headers": response_headers, } ) # Streaming responses need to be pinned to their iterator. if response.streaming: # Access `__iter__` and not `streaming_content` directly in case # it has been overridden in a subclass. for part in response: for chunk, _ in self.chunk_bytes(part): await send( { "type": "http.response.body", "body": chunk, # Ignore "more" as there may be more parts; instead, # use an empty final closing message with False. "more_body": True, } ) # Final closing message. await send({"type": "http.response.body"}) # Other responses just need chunking. else: # Yield chunks of response. for chunk, last in self.chunk_bytes(response.content): await send( { "type": "http.response.body", "body": chunk, "more_body": not last, } ) await sync_to_async(response.close, thread_sensitive=True)() @classmethod def chunk_bytes(cls, data): """ Chunks some data up so it can be sent in reasonable size messages. Yields (chunk, last_chunk) tuples. """ position = 0 if not data: yield data, True return while position < len(data): yield ( data[position : position + cls.chunk_size], (position + cls.chunk_size) >= len(data), ) position += cls.chunk_size def get_script_prefix(self, scope): """ Return the script prefix to use from either the scope or a setting. """ if settings.FORCE_SCRIPT_NAME: return settings.FORCE_SCRIPT_NAME return scope.get("root_path", "") or ""
23944127b11a8b06dad1be108595c286e1e341c0bc88e72e08a594121de2ae2e
from io import BytesIO from django.conf import settings from django.core import signals from django.core.handlers import base from django.http import HttpRequest, QueryDict, parse_cookie from django.urls import set_script_prefix from django.utils.encoding import repercent_broken_unicode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile _slashes_re = _lazy_re_compile(rb"/+") class LimitedStream: """Wrap another stream to disallow reading it past a number of bytes.""" def __init__(self, stream, limit): self.stream = stream self.remaining = limit self.buffer = b"" def _read_limited(self, size=None): if size is None or size > self.remaining: size = self.remaining if size == 0: return b"" result = self.stream.read(size) self.remaining -= len(result) return result def read(self, size=None): if size is None: result = self.buffer + self._read_limited() self.buffer = b"" elif size < len(self.buffer): result = self.buffer[:size] self.buffer = self.buffer[size:] else: # size >= len(self.buffer) result = self.buffer + self._read_limited(size - len(self.buffer)) self.buffer = b"" return result def readline(self, size=None): while b"\n" not in self.buffer and (size is None or len(self.buffer) < size): if size: # since size is not None here, len(self.buffer) < size chunk = self._read_limited(size - len(self.buffer)) else: chunk = self._read_limited() if not chunk: break self.buffer += chunk sio = BytesIO(self.buffer) if size: line = sio.readline(size) else: line = sio.readline() self.buffer = sio.read() return line def close(self): pass class WSGIRequest(HttpRequest): def __init__(self, environ): script_name = get_script_name(environ) # If PATH_INFO is empty (e.g. accessing the SCRIPT_NAME URL without a # trailing slash), operate as if '/' was requested. path_info = get_path_info(environ) or "/" self.environ = environ self.path_info = path_info # be careful to only replace the first slash in the path because of # http://test/something and http://test//something being different as # stated in https://www.ietf.org/rfc/rfc2396.txt self.path = "%s/%s" % (script_name.rstrip("/"), path_info.replace("/", "", 1)) self.META = environ self.META["PATH_INFO"] = path_info self.META["SCRIPT_NAME"] = script_name self.method = environ["REQUEST_METHOD"].upper() # Set content_type, content_params, and encoding. self._set_content_type_params(environ) try: content_length = int(environ.get("CONTENT_LENGTH")) except (ValueError, TypeError): content_length = 0 self._stream = LimitedStream(self.environ["wsgi.input"], content_length) self._read_started = False self.resolver_match = None def _get_scheme(self): return self.environ.get("wsgi.url_scheme") @cached_property def GET(self): # The WSGI spec says 'QUERY_STRING' may be absent. raw_query_string = get_bytes_from_wsgi(self.environ, "QUERY_STRING", "") return QueryDict(raw_query_string, encoding=self._encoding) def _get_post(self): if not hasattr(self, "_post"): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post @cached_property def COOKIES(self): raw_cookie = get_str_from_wsgi(self.environ, "HTTP_COOKIE", "") return parse_cookie(raw_cookie) @property def FILES(self): if not hasattr(self, "_files"): self._load_post_and_files() return self._files POST = property(_get_post, _set_post) class WSGIHandler(base.BaseHandler): request_class = WSGIRequest def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.load_middleware() def __call__(self, environ, start_response): set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__, environ=environ) request = self.request_class(environ) response = self.get_response(request) response._handler_class = self.__class__ status = "%d %s" % (response.status_code, response.reason_phrase) response_headers = [ *response.items(), *(("Set-Cookie", c.output(header="")) for c in response.cookies.values()), ] start_response(status, response_headers) if getattr(response, "file_to_stream", None) is not None and environ.get( "wsgi.file_wrapper" ): # If `wsgi.file_wrapper` is used the WSGI server does not call # .close on the response, but on the file wrapper. Patch it to use # response.close instead which takes care of closing all files. response.file_to_stream.close = response.close response = environ["wsgi.file_wrapper"]( response.file_to_stream, response.block_size ) return response def get_path_info(environ): """Return the HTTP request's PATH_INFO as a string.""" path_info = get_bytes_from_wsgi(environ, "PATH_INFO", "/") return repercent_broken_unicode(path_info).decode() def get_script_name(environ): """ Return the equivalent of the HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite is used, return what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything). """ if settings.FORCE_SCRIPT_NAME is not None: return settings.FORCE_SCRIPT_NAME # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = get_bytes_from_wsgi(environ, "SCRIPT_URL", "") or get_bytes_from_wsgi( environ, "REDIRECT_URL", "" ) if script_url: if b"//" in script_url: # mod_wsgi squashes multiple successive slashes in PATH_INFO, # do the same with script_url before manipulating paths (#17133). script_url = _slashes_re.sub(b"/", script_url) path_info = get_bytes_from_wsgi(environ, "PATH_INFO", "") script_name = script_url[: -len(path_info)] if path_info else script_url else: script_name = get_bytes_from_wsgi(environ, "SCRIPT_NAME", "") return script_name.decode() def get_bytes_from_wsgi(environ, key, default): """ Get a value from the WSGI environ dictionary as bytes. key and default should be strings. """ value = environ.get(key, default) # Non-ASCII values in the WSGI environ are arbitrarily decoded with # ISO-8859-1. This is wrong for Django websites where UTF-8 is the default. # Re-encode to recover the original bytestring. return value.encode("iso-8859-1") def get_str_from_wsgi(environ, key, default): """ Get a value from the WSGI environ dictionary as str. key and default should be str objects. """ value = get_bytes_from_wsgi(environ, key, default) return value.decode(errors="replace")
1c3201dc725d5eb2a183fe4a88cfdbcef5cc22934e691f3c323988619f933b9e
import glob import os import re import sys from functools import total_ordering from itertools import dropwhile from pathlib import Path import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.temp import NamedTemporaryFile from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import ( find_command, handle_extensions, is_ignored_path, popen_wrapper, ) from django.utils.encoding import DEFAULT_LOCALE_ENCODING from django.utils.functional import cached_property from django.utils.jslex import prepare_js_for_gettext from django.utils.regex_helper import _lazy_re_compile from django.utils.text import get_text_list from django.utils.translation import templatize plural_forms_re = _lazy_re_compile( r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL ) STATUS_OK = 0 NO_LOCALE_DIR = object() def check_programs(*programs): for program in programs: if find_command(program) is None: raise CommandError( "Can't find %s. Make sure you have GNU gettext tools 0.15 or " "newer installed." % program ) def is_valid_locale(locale): return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z].*$", locale) @total_ordering class TranslatableFile: def __init__(self, dirpath, file_name, locale_dir): self.file = file_name self.dirpath = dirpath self.locale_dir = locale_dir def __repr__(self): return "<%s: %s>" % ( self.__class__.__name__, os.sep.join([self.dirpath, self.file]), ) def __eq__(self, other): return self.path == other.path def __lt__(self, other): return self.path < other.path @property def path(self): return os.path.join(self.dirpath, self.file) class BuildFile: """ Represent the state of a translatable file during the build process. """ def __init__(self, command, domain, translatable): self.command = command self.domain = domain self.translatable = translatable @cached_property def is_templatized(self): if self.domain == "djangojs": return self.command.gettext_version < (0, 18, 3) elif self.domain == "django": file_ext = os.path.splitext(self.translatable.file)[1] return file_ext != ".py" return False @cached_property def path(self): return self.translatable.path @cached_property def work_path(self): """ Path to a file which is being fed into GNU gettext pipeline. This may be either a translatable or its preprocessed version. """ if not self.is_templatized: return self.path extension = { "djangojs": "c", "django": "py", }.get(self.domain) filename = "%s.%s" % (self.translatable.file, extension) return os.path.join(self.translatable.dirpath, filename) def preprocess(self): """ Preprocess (if necessary) a translatable file before passing it to xgettext GNU gettext utility. """ if not self.is_templatized: return with open(self.path, encoding="utf-8") as fp: src_data = fp.read() if self.domain == "djangojs": content = prepare_js_for_gettext(src_data) elif self.domain == "django": content = templatize(src_data, origin=self.path[2:]) with open(self.work_path, "w", encoding="utf-8") as fp: fp.write(content) def postprocess_messages(self, msgs): """ Postprocess messages generated by xgettext GNU gettext utility. Transform paths as if these messages were generated from original translatable files rather than from preprocessed versions. """ if not self.is_templatized: return msgs # Remove '.py' suffix if os.name == "nt": # Preserve '.\' prefix on Windows to respect gettext behavior old_path = self.work_path new_path = self.path else: old_path = self.work_path[2:] new_path = self.path[2:] return re.sub( r"^(#: .*)(" + re.escape(old_path) + r")", lambda match: match[0].replace(old_path, new_path), msgs, flags=re.MULTILINE, ) def cleanup(self): """ Remove a preprocessed copy of a translatable file (if any). """ if self.is_templatized: # This check is needed for the case of a symlinked file and its # source being processed inside a single group (locale dir); # removing either of those two removes both. if os.path.exists(self.work_path): os.unlink(self.work_path) def normalize_eols(raw_contents): """ Take a block of raw text that will be passed through str.splitlines() to get universal newlines treatment. Return the resulting block of text with normalized `\n` EOL sequences ready to be written to disk using current platform's native EOLs. """ lines_list = raw_contents.splitlines() # Ensure last line has its EOL if lines_list and lines_list[-1]: lines_list.append("") return "\n".join(lines_list) def write_pot_file(potfile, msgs): """ Write the `potfile` with the `msgs` contents, making sure its format is valid. """ pot_lines = msgs.splitlines() if os.path.exists(potfile): # Strip the header lines = dropwhile(len, pot_lines) else: lines = [] found, header_read = False, False for line in pot_lines: if not found and not header_read: if "charset=CHARSET" in line: found = True line = line.replace("charset=CHARSET", "charset=UTF-8") if not line and not found: header_read = True lines.append(line) msgs = "\n".join(lines) # Force newlines of POT files to '\n' to work around # https://savannah.gnu.org/bugs/index.php?52395 with open(potfile, "a", encoding="utf-8", newline="\n") as fp: fp.write(msgs) class Command(BaseCommand): help = ( "Runs over the entire source tree of the current directory and pulls out all " "strings marked for translation. It creates (or updates) a message file in the " "conf/locale (in the django tree) or locale (for projects and applications) " "directory.\n\nYou must run this command with one of either the --locale, " "--exclude, or --all options." ) translatable_file_class = TranslatableFile build_file_class = BuildFile requires_system_checks = [] msgmerge_options = ["-q", "--backup=none", "--previous", "--update"] msguniq_options = ["--to-code=utf-8"] msgattrib_options = ["--no-obsolete"] xgettext_options = ["--from-code=UTF-8", "--add-comments=Translators"] def add_arguments(self, parser): parser.add_argument( "--locale", "-l", default=[], action="append", help=( "Creates or updates the message files for the given locale(s) (e.g. " "pt_BR). Can be used multiple times." ), ) parser.add_argument( "--exclude", "-x", default=[], action="append", help="Locales to exclude. Default is none. Can be used multiple times.", ) parser.add_argument( "--domain", "-d", default="django", help='The domain of the message files (default: "django").', ) parser.add_argument( "--all", "-a", action="store_true", help="Updates the message files for all existing locales.", ) parser.add_argument( "--extension", "-e", dest="extensions", action="append", help='The file extension(s) to examine (default: "html,txt,py", or "js" ' 'if the domain is "djangojs"). Separate multiple extensions with ' "commas, or use -e multiple times.", ) parser.add_argument( "--symlinks", "-s", action="store_true", help="Follows symlinks to directories when examining source code " "and templates for translation strings.", ) parser.add_argument( "--ignore", "-i", action="append", dest="ignore_patterns", default=[], metavar="PATTERN", help="Ignore files or directories matching this glob-style pattern. " "Use multiple times to ignore more.", ) parser.add_argument( "--no-default-ignore", action="store_false", dest="use_default_ignore_patterns", help=( "Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and " "'*.pyc'." ), ) parser.add_argument( "--no-wrap", action="store_true", help="Don't break long message lines into several lines.", ) parser.add_argument( "--no-location", action="store_true", help="Don't write '#: filename:line' lines.", ) parser.add_argument( "--add-location", choices=("full", "file", "never"), const="full", nargs="?", help=( "Controls '#: filename:line' lines. If the option is 'full' " "(the default if not given), the lines include both file name " "and line number. If it's 'file', the line number is omitted. If " "it's 'never', the lines are suppressed (same as --no-location). " "--add-location requires gettext 0.19 or newer." ), ) parser.add_argument( "--no-obsolete", action="store_true", help="Remove obsolete message strings.", ) parser.add_argument( "--keep-pot", action="store_true", help="Keep .pot file after making messages. Useful when debugging.", ) def handle(self, *args, **options): locale = options["locale"] exclude = options["exclude"] self.domain = options["domain"] self.verbosity = options["verbosity"] process_all = options["all"] extensions = options["extensions"] self.symlinks = options["symlinks"] ignore_patterns = options["ignore_patterns"] if options["use_default_ignore_patterns"]: ignore_patterns += ["CVS", ".*", "*~", "*.pyc"] self.ignore_patterns = list(set(ignore_patterns)) # Avoid messing with mutable class variables if options["no_wrap"]: self.msgmerge_options = self.msgmerge_options[:] + ["--no-wrap"] self.msguniq_options = self.msguniq_options[:] + ["--no-wrap"] self.msgattrib_options = self.msgattrib_options[:] + ["--no-wrap"] self.xgettext_options = self.xgettext_options[:] + ["--no-wrap"] if options["no_location"]: self.msgmerge_options = self.msgmerge_options[:] + ["--no-location"] self.msguniq_options = self.msguniq_options[:] + ["--no-location"] self.msgattrib_options = self.msgattrib_options[:] + ["--no-location"] self.xgettext_options = self.xgettext_options[:] + ["--no-location"] if options["add_location"]: if self.gettext_version < (0, 19): raise CommandError( "The --add-location option requires gettext 0.19 or later. " "You have %s." % ".".join(str(x) for x in self.gettext_version) ) arg_add_location = "--add-location=%s" % options["add_location"] self.msgmerge_options = self.msgmerge_options[:] + [arg_add_location] self.msguniq_options = self.msguniq_options[:] + [arg_add_location] self.msgattrib_options = self.msgattrib_options[:] + [arg_add_location] self.xgettext_options = self.xgettext_options[:] + [arg_add_location] self.no_obsolete = options["no_obsolete"] self.keep_pot = options["keep_pot"] if self.domain not in ("django", "djangojs"): raise CommandError( "currently makemessages only supports domains " "'django' and 'djangojs'" ) if self.domain == "djangojs": exts = extensions or ["js"] else: exts = extensions or ["html", "txt", "py"] self.extensions = handle_extensions(exts) if (not locale and not exclude and not process_all) or self.domain is None: raise CommandError( "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1]) ) if self.verbosity > 1: self.stdout.write( "examining files with the extensions: %s" % get_text_list(list(self.extensions), "and") ) self.invoked_for_django = False self.locale_paths = [] self.default_locale_path = None if os.path.isdir(os.path.join("conf", "locale")): self.locale_paths = [os.path.abspath(os.path.join("conf", "locale"))] self.default_locale_path = self.locale_paths[0] self.invoked_for_django = True else: if self.settings_available: self.locale_paths.extend(settings.LOCALE_PATHS) # Allow to run makemessages inside an app dir if os.path.isdir("locale"): self.locale_paths.append(os.path.abspath("locale")) if self.locale_paths: self.default_locale_path = self.locale_paths[0] os.makedirs(self.default_locale_path, exist_ok=True) # Build locale list looks_like_locale = re.compile(r"[a-z]{2}") locale_dirs = filter( os.path.isdir, glob.glob("%s/*" % self.default_locale_path) ) all_locales = [ lang_code for lang_code in map(os.path.basename, locale_dirs) if looks_like_locale.match(lang_code) ] # Account for excluded locales if process_all: locales = all_locales else: locales = locale or all_locales locales = set(locales).difference(exclude) if locales: check_programs("msguniq", "msgmerge", "msgattrib") check_programs("xgettext") try: potfiles = self.build_potfiles() # Build po files for each selected locale for locale in locales: if not is_valid_locale(locale): # Try to guess what valid locale it could be # Valid examples are: en_GB, shi_Latn_MA and nl_NL-x-informal # Search for characters followed by a non character (i.e. separator) match = re.match( r"^(?P<language>[a-zA-Z]+)" r"(?P<separator>[^a-zA-Z])" r"(?P<territory>.+)$", locale, ) if match: locale_parts = match.groupdict() language = locale_parts["language"].lower() territory = ( locale_parts["territory"][:2].upper() + locale_parts["territory"][2:] ) proposed_locale = f"{language}_{territory}" else: # It could be a language in uppercase proposed_locale = locale.lower() # Recheck if the proposed locale is valid if is_valid_locale(proposed_locale): self.stdout.write( "invalid locale %s, did you mean %s?" % ( locale, proposed_locale, ), ) else: self.stdout.write("invalid locale %s" % locale) continue if self.verbosity > 0: self.stdout.write("processing locale %s" % locale) for potfile in potfiles: self.write_po_file(potfile, locale) finally: if not self.keep_pot: self.remove_potfiles() @cached_property def gettext_version(self): # Gettext tools will output system-encoded bytestrings instead of UTF-8, # when looking up the version. It's especially a problem on Windows. out, err, status = popen_wrapper( ["xgettext", "--version"], stdout_encoding=DEFAULT_LOCALE_ENCODING, ) m = re.search(r"(\d+)\.(\d+)\.?(\d+)?", out) if m: return tuple(int(d) for d in m.groups() if d is not None) else: raise CommandError("Unable to get gettext version. Is it installed?") @cached_property def settings_available(self): try: settings.LOCALE_PATHS except ImproperlyConfigured: if self.verbosity > 1: self.stderr.write("Running without configured settings.") return False return True def build_potfiles(self): """ Build pot files and apply msguniq to them. """ file_list = self.find_files(".") self.remove_potfiles() self.process_files(file_list) potfiles = [] for path in self.locale_paths: potfile = os.path.join(path, "%s.pot" % self.domain) if not os.path.exists(potfile): continue args = ["msguniq"] + self.msguniq_options + [potfile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msguniq\n%s" % errors ) elif self.verbosity > 0: self.stdout.write(errors) msgs = normalize_eols(msgs) with open(potfile, "w", encoding="utf-8") as fp: fp.write(msgs) potfiles.append(potfile) return potfiles def remove_potfiles(self): for path in self.locale_paths: pot_path = os.path.join(path, "%s.pot" % self.domain) if os.path.exists(pot_path): os.unlink(pot_path) def find_files(self, root): """ Get all files in the given root. Also check that there is a matching locale dir for each file. """ all_files = [] ignored_roots = [] if self.settings_available: ignored_roots = [ os.path.normpath(p) for p in (settings.MEDIA_ROOT, settings.STATIC_ROOT) if p ] for dirpath, dirnames, filenames in os.walk( root, topdown=True, followlinks=self.symlinks ): for dirname in dirnames[:]: if ( is_ignored_path( os.path.normpath(os.path.join(dirpath, dirname)), self.ignore_patterns, ) or os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots ): dirnames.remove(dirname) if self.verbosity > 1: self.stdout.write("ignoring directory %s" % dirname) elif dirname == "locale": dirnames.remove(dirname) self.locale_paths.insert( 0, os.path.join(os.path.abspath(dirpath), dirname) ) for filename in filenames: file_path = os.path.normpath(os.path.join(dirpath, filename)) file_ext = os.path.splitext(filename)[1] if file_ext not in self.extensions or is_ignored_path( file_path, self.ignore_patterns ): if self.verbosity > 1: self.stdout.write( "ignoring file %s in %s" % (filename, dirpath) ) else: locale_dir = None for path in self.locale_paths: if os.path.abspath(dirpath).startswith(os.path.dirname(path)): locale_dir = path break locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR all_files.append( self.translatable_file_class(dirpath, filename, locale_dir) ) return sorted(all_files) def process_files(self, file_list): """ Group translatable files by locale directory and run pot file build process for each group. """ file_groups = {} for translatable in file_list: file_group = file_groups.setdefault(translatable.locale_dir, []) file_group.append(translatable) for locale_dir, files in file_groups.items(): self.process_locale_dir(locale_dir, files) def process_locale_dir(self, locale_dir, files): """ Extract translatable literals from the specified files, creating or updating the POT file for a given locale directory. Use the xgettext GNU gettext utility. """ build_files = [] for translatable in files: if self.verbosity > 1: self.stdout.write( "processing file %s in %s" % (translatable.file, translatable.dirpath) ) if self.domain not in ("djangojs", "django"): continue build_file = self.build_file_class(self, self.domain, translatable) try: build_file.preprocess() except UnicodeDecodeError as e: self.stdout.write( "UnicodeDecodeError: skipped file %s in %s (reason: %s)" % ( translatable.file, translatable.dirpath, e, ) ) continue except BaseException: # Cleanup before exit. for build_file in build_files: build_file.cleanup() raise build_files.append(build_file) if self.domain == "djangojs": is_templatized = build_file.is_templatized args = [ "xgettext", "-d", self.domain, "--language=%s" % ("C" if is_templatized else "JavaScript",), "--keyword=gettext_noop", "--keyword=gettext_lazy", "--keyword=ngettext_lazy:1,2", "--keyword=pgettext:1c,2", "--keyword=npgettext:1c,2,3", "--output=-", ] elif self.domain == "django": args = [ "xgettext", "-d", self.domain, "--language=Python", "--keyword=gettext_noop", "--keyword=gettext_lazy", "--keyword=ngettext_lazy:1,2", "--keyword=pgettext:1c,2", "--keyword=npgettext:1c,2,3", "--keyword=pgettext_lazy:1c,2", "--keyword=npgettext_lazy:1c,2,3", "--output=-", ] else: return input_files = [bf.work_path for bf in build_files] with NamedTemporaryFile(mode="w+") as input_files_list: input_files_list.write("\n".join(input_files)) input_files_list.flush() args.extend(["--files-from", input_files_list.name]) args.extend(self.xgettext_options) msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: for build_file in build_files: build_file.cleanup() raise CommandError( "errors happened while running xgettext on %s\n%s" % ("\n".join(input_files), errors) ) elif self.verbosity > 0: # Print warnings self.stdout.write(errors) if msgs: if locale_dir is NO_LOCALE_DIR: for build_file in build_files: build_file.cleanup() file_path = os.path.normpath(build_files[0].path) raise CommandError( "Unable to find a locale path to store translations for " "file %s. Make sure the 'locale' directory exists in an " "app or LOCALE_PATHS setting is set." % file_path ) for build_file in build_files: msgs = build_file.postprocess_messages(msgs) potfile = os.path.join(locale_dir, "%s.pot" % self.domain) write_pot_file(potfile, msgs) for build_file in build_files: build_file.cleanup() def write_po_file(self, potfile, locale): """ Create or update the PO file for self.domain and `locale`. Use contents of the existing `potfile`. Use msgmerge and msgattrib GNU gettext utilities. """ basedir = os.path.join(os.path.dirname(potfile), locale, "LC_MESSAGES") os.makedirs(basedir, exist_ok=True) pofile = os.path.join(basedir, "%s.po" % self.domain) if os.path.exists(pofile): args = ["msgmerge"] + self.msgmerge_options + [pofile, potfile] _, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msgmerge\n%s" % errors ) elif self.verbosity > 0: self.stdout.write(errors) msgs = Path(pofile).read_text(encoding="utf-8") else: with open(potfile, encoding="utf-8") as fp: msgs = fp.read() if not self.invoked_for_django: msgs = self.copy_plural_forms(msgs, locale) msgs = normalize_eols(msgs) msgs = msgs.replace( "#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % self.domain, "" ) with open(pofile, "w", encoding="utf-8") as fp: fp.write(msgs) if self.no_obsolete: args = ["msgattrib"] + self.msgattrib_options + ["-o", pofile, pofile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msgattrib\n%s" % errors ) elif self.verbosity > 0: self.stdout.write(errors) def copy_plural_forms(self, msgs, locale): """ Copy plural forms header contents from a Django catalog of locale to the msgs string, inserting it at the right place. msgs should be the contents of a newly created .po file. """ django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) if self.domain == "djangojs": domains = ("djangojs", "django") else: domains = ("django",) for domain in domains: django_po = os.path.join( django_dir, "conf", "locale", locale, "LC_MESSAGES", "%s.po" % domain ) if os.path.exists(django_po): with open(django_po, encoding="utf-8") as fp: m = plural_forms_re.search(fp.read()) if m: plural_form_line = m["value"] if self.verbosity > 1: self.stdout.write("copying plural forms: %s" % plural_form_line) lines = [] found = False for line in msgs.splitlines(): if not found and (not line or plural_forms_re.search(line)): line = plural_form_line found = True lines.append(line) msgs = "\n".join(lines) break return msgs
e5d3d4c45f8bf0f797886cd38b3013257098a000c46a973ecbdfcf52fcee90f8
import os import sys import warnings from itertools import takewhile from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError, no_translations from django.core.management.utils import run_formatters from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, router from django.db.migrations import Migration from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader from django.db.migrations.migration import SwappableTuple from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import ( InteractiveMigrationQuestioner, MigrationQuestioner, NonInteractiveMigrationQuestioner, ) from django.db.migrations.state import ProjectState from django.db.migrations.utils import get_migration_name_timestamp from django.db.migrations.writer import MigrationWriter class Command(BaseCommand): help = "Creates new migration(s) for apps." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="*", help="Specify the app label(s) to create migrations for.", ) parser.add_argument( "--dry-run", action="store_true", help="Just show what migrations would be made; don't actually write them.", ) parser.add_argument( "--merge", action="store_true", help="Enable fixing of migration conflicts.", ) parser.add_argument( "--empty", action="store_true", help="Create an empty migration.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "-n", "--name", help="Use this name for migration file(s).", ) parser.add_argument( "--no-header", action="store_false", dest="include_header", help="Do not add header comments to new migration file(s).", ) parser.add_argument( "--check", action="store_true", dest="check_changes", help="Exit with a non-zero status if model changes are missing migrations.", ) parser.add_argument( "--scriptable", action="store_true", dest="scriptable", help=( "Divert log output and input prompts to stderr, writing only " "paths of generated migration files to stdout." ), ) parser.add_argument( "--update", action="store_true", dest="update", help=( "Merge model changes into the latest migration and optimize the " "resulting operations." ), ) @property def log_output(self): return self.stderr if self.scriptable else self.stdout def log(self, msg): self.log_output.write(msg) @no_translations def handle(self, *app_labels, **options): self.written_files = [] self.verbosity = options["verbosity"] self.interactive = options["interactive"] self.dry_run = options["dry_run"] self.merge = options["merge"] self.empty = options["empty"] self.migration_name = options["name"] if self.migration_name and not self.migration_name.isidentifier(): raise CommandError("The migration name must be a valid Python identifier.") self.include_header = options["include_header"] check_changes = options["check_changes"] self.scriptable = options["scriptable"] self.update = options["update"] # If logs and prompts are diverted to stderr, remove the ERROR style. if self.scriptable: self.stderr.style_func = None # Make sure the app they asked for exists app_labels = set(app_labels) has_bad_labels = False for app_label in app_labels: try: apps.get_app_config(app_label) except LookupError as err: self.stderr.write(str(err)) has_bad_labels = True if has_bad_labels: sys.exit(2) # Load the current graph state. Pass in None for the connection so # the loader doesn't try to resolve replaced migrations from DB. loader = MigrationLoader(None, ignore_no_migrations=True) # Raise an error if any migrations are applied before their dependencies. consistency_check_labels = {config.label for config in apps.get_app_configs()} # Non-default databases are only checked if database routers used. aliases_to_check = ( connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS] ) for alias in sorted(aliases_to_check): connection = connections[alias] if connection.settings_dict["ENGINE"] != "django.db.backends.dummy" and any( # At least one model must be migrated to the database. router.allow_migrate( connection.alias, app_label, model_name=model._meta.object_name ) for app_label in consistency_check_labels for model in apps.get_app_config(app_label).get_models() ): try: loader.check_consistent_history(connection) except OperationalError as error: warnings.warn( "Got an error checking a consistent migration history " "performed for database connection '%s': %s" % (alias, error), RuntimeWarning, ) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() # If app_labels is specified, filter out conflicting migrations for # unspecified apps. if app_labels: conflicts = { app_label: conflict for app_label, conflict in conflicts.items() if app_label in app_labels } if conflicts and not self.merge: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they want to merge and there's nothing to merge, then politely exit if self.merge and not conflicts: self.log("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) if self.interactive: questioner = InteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=self.dry_run, prompt_output=self.log_output, ) else: questioner = NonInteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=self.dry_run, verbosity=self.verbosity, log=self.log, ) # Set up autodetector autodetector = MigrationAutodetector( loader.project_state(), ProjectState.from_apps(apps), questioner, ) # If they want to make an empty migration, make one for each app if self.empty: if not app_labels: raise CommandError( "You must supply at least one app label when using --empty." ) # Make a fake changes() result we can pass to arrange_for_graph changes = {app: [Migration("custom", app)] for app in app_labels} changes = autodetector.arrange_for_graph( changes=changes, graph=loader.graph, migration_name=self.migration_name, ) self.write_migration_files(changes) return # Detect changes changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name=self.migration_name, ) if not changes: # No changes? Tell them. if self.verbosity >= 1: if app_labels: if len(app_labels) == 1: self.log("No changes detected in app '%s'" % app_labels.pop()) else: self.log( "No changes detected in apps '%s'" % ("', '".join(app_labels)) ) else: self.log("No changes detected") else: if self.update: self.write_to_last_migration_files(changes) else: self.write_migration_files(changes) if check_changes: sys.exit(1) def write_to_last_migration_files(self, changes): loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) new_changes = {} update_previous_migration_paths = {} for app_label, app_migrations in changes.items(): # Find last migration. leaf_migration_nodes = loader.graph.leaf_nodes(app=app_label) if len(leaf_migration_nodes) == 0: raise CommandError( f"App {app_label} has no migration, cannot update last migration." ) leaf_migration_node = leaf_migration_nodes[0] # Multiple leaf nodes have already been checked earlier in command. leaf_migration = loader.graph.nodes[leaf_migration_node] # Updated migration cannot be a squash migration, a dependency of # another migration, and cannot be already applied. if leaf_migration.replaces: raise CommandError( f"Cannot update squash migration '{leaf_migration}'." ) if leaf_migration_node in loader.applied_migrations: raise CommandError( f"Cannot update applied migration '{leaf_migration}'." ) depending_migrations = [ migration for migration in loader.disk_migrations.values() if leaf_migration_node in migration.dependencies ] if depending_migrations: formatted_migrations = ", ".join( [f"'{migration}'" for migration in depending_migrations] ) raise CommandError( f"Cannot update migration '{leaf_migration}' that migrations " f"{formatted_migrations} depend on." ) # Build new migration. for migration in app_migrations: leaf_migration.operations.extend(migration.operations) for dependency in migration.dependencies: if isinstance(dependency, SwappableTuple): if settings.AUTH_USER_MODEL == dependency.setting: leaf_migration.dependencies.append( ("__setting__", "AUTH_USER_MODEL") ) else: leaf_migration.dependencies.append(dependency) elif dependency[0] != migration.app_label: leaf_migration.dependencies.append(dependency) # Optimize migration. optimizer = MigrationOptimizer() leaf_migration.operations = optimizer.optimize( leaf_migration.operations, app_label ) # Update name. previous_migration_path = MigrationWriter(leaf_migration).path suggested_name = ( leaf_migration.name[:4] + "_" + leaf_migration.suggest_name() ) if leaf_migration.name == suggested_name: new_name = leaf_migration.name + "_updated" else: new_name = suggested_name leaf_migration.name = new_name # Register overridden migration. new_changes[app_label] = [leaf_migration] update_previous_migration_paths[app_label] = previous_migration_path self.write_migration_files(new_changes, update_previous_migration_paths) def write_migration_files(self, changes, update_previous_migration_paths=None): """ Take a changes dict and write them out as migration files. """ directory_created = {} for app_label, app_migrations in changes.items(): if self.verbosity >= 1: self.log(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label)) for migration in app_migrations: # Describe the migration writer = MigrationWriter(migration, self.include_header) if self.verbosity >= 1: # Display a relative path if it's below the current working # directory, or an absolute path otherwise. migration_string = self.get_relative_path(writer.path) self.log(" %s\n" % self.style.MIGRATE_LABEL(migration_string)) for operation in migration.operations: self.log(" - %s" % operation.describe()) if self.scriptable: self.stdout.write(migration_string) if not self.dry_run: # Write the migrations file to the disk. migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label): os.makedirs(migrations_directory, exist_ok=True) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "w", encoding="utf-8") as fh: fh.write(migration_string) self.written_files.append(writer.path) if update_previous_migration_paths: prev_path = update_previous_migration_paths[app_label] rel_prev_path = self.get_relative_path(prev_path) if writer.needs_manual_porting: migration_path = self.get_relative_path(writer.path) self.log( self.style.WARNING( f"Updated migration {migration_path} requires " f"manual porting.\n" f"Previous migration {rel_prev_path} was kept and " f"must be deleted after porting functions manually." ) ) else: os.remove(prev_path) self.log(f"Deleted {rel_prev_path}") elif self.verbosity == 3: # Alternatively, makemigrations --dry-run --verbosity 3 # will log the migrations rather than saving the file to # the disk. self.log( self.style.MIGRATE_HEADING( "Full migrations file '%s':" % writer.filename ) ) self.log(writer.as_string()) run_formatters(self.written_files) @staticmethod def get_relative_path(path): try: migration_string = os.path.relpath(path) except ValueError: migration_string = path if migration_string.startswith(".."): migration_string = path return migration_string def handle_merge(self, loader, conflicts): """ Handles merging together conflicted migrations interactively, if it's safe; otherwise, advises on how to fix it. """ if self.interactive: questioner = InteractiveMigrationQuestioner(prompt_output=self.log_output) else: questioner = MigrationQuestioner(defaults={"ask_merge": True}) for app_label, migration_names in conflicts.items(): # Grab out the migrations in question, and work out their # common ancestor. merge_migrations = [] for migration_name in migration_names: migration = loader.get_migration(app_label, migration_name) migration.ancestry = [ mig for mig in loader.graph.forwards_plan((app_label, migration_name)) if mig[0] == migration.app_label ] merge_migrations.append(migration) def all_items_equal(seq): return all(item == seq[0] for item in seq[1:]) merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations)) common_ancestor_count = sum( 1 for common_ancestor_generation in takewhile( all_items_equal, merge_migrations_generations ) ) if not common_ancestor_count: raise ValueError( "Could not find common ancestor of %s" % migration_names ) # Now work out the operations along each divergent branch for migration in merge_migrations: migration.branch = migration.ancestry[common_ancestor_count:] migrations_ops = ( loader.get_migration(node_app, node_name).operations for node_app, node_name in migration.branch ) migration.merged_operations = sum(migrations_ops, []) # In future, this could use some of the Optimizer code # (can_optimize_through) to automatically see if they're # mergeable. For now, we always just prompt the user. if self.verbosity > 0: self.log(self.style.MIGRATE_HEADING("Merging %s" % app_label)) for migration in merge_migrations: self.log(self.style.MIGRATE_LABEL(" Branch %s" % migration.name)) for operation in migration.merged_operations: self.log(" - %s" % operation.describe()) if questioner.ask_merge(app_label): # If they still want to merge it, then write out an empty # file depending on the migrations needing merging. numbers = [ MigrationAutodetector.parse_number(migration.name) for migration in merge_migrations ] try: biggest_number = max(x for x in numbers if x is not None) except ValueError: biggest_number = 1 subclass = type( "Migration", (Migration,), { "dependencies": [ (app_label, migration.name) for migration in merge_migrations ], }, ) parts = ["%04i" % (biggest_number + 1)] if self.migration_name: parts.append(self.migration_name) else: parts.append("merge") leaf_names = "_".join( sorted(migration.name for migration in merge_migrations) ) if len(leaf_names) > 47: parts.append(get_migration_name_timestamp()) else: parts.append(leaf_names) migration_name = "_".join(parts) new_migration = subclass(migration_name, app_label) writer = MigrationWriter(new_migration, self.include_header) if not self.dry_run: # Write the merge migrations file to the disk with open(writer.path, "w", encoding="utf-8") as fh: fh.write(writer.as_string()) run_formatters([writer.path]) if self.verbosity > 0: self.log("\nCreated new merge migration %s" % writer.path) if self.scriptable: self.stdout.write(writer.path) elif self.verbosity == 3: # Alternatively, makemigrations --merge --dry-run --verbosity 3 # will log the merge migrations rather than saving the file # to the disk. self.log( self.style.MIGRATE_HEADING( "Full merge migrations file '%s':" % writer.filename ) ) self.log(writer.as_string())
bec266f2bf2657178ae5d10c209d4b2708dbf9924d3cecb1686f786cb534d17e
import psycopg2 from django.db.models import ( CharField, Expression, Field, FloatField, Func, Lookup, TextField, Value, ) from django.db.models.expressions import CombinedExpression, register_combinable_fields from django.db.models.functions import Cast, Coalesce class SearchVectorExact(Lookup): lookup_name = "exact" def process_rhs(self, qn, connection): if not isinstance(self.rhs, (SearchQuery, CombinedSearchQuery)): config = getattr(self.lhs, "config", None) self.rhs = SearchQuery(self.rhs, config=config) rhs, rhs_params = super().process_rhs(qn, connection) return rhs, rhs_params def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return "%s @@ %s" % (lhs, rhs), params class SearchVectorField(Field): def db_type(self, connection): return "tsvector" class SearchQueryField(Field): def db_type(self, connection): return "tsquery" class SearchConfig(Expression): def __init__(self, config): super().__init__() if not hasattr(config, "resolve_expression"): config = Value(config) self.config = config @classmethod def from_parameter(cls, config): if config is None or isinstance(config, cls): return config return cls(config) def get_source_expressions(self): return [self.config] def set_source_expressions(self, exprs): (self.config,) = exprs def as_sql(self, compiler, connection): sql, params = compiler.compile(self.config) return "%s::regconfig" % sql, params class SearchVectorCombinable: ADD = "||" def _combine(self, other, connector, reversed): if not isinstance(other, SearchVectorCombinable): raise TypeError( "SearchVector can only be combined with other SearchVector " "instances, got %s." % type(other).__name__ ) if reversed: return CombinedSearchVector(other, connector, self, self.config) return CombinedSearchVector(self, connector, other, self.config) register_combinable_fields( SearchVectorField, SearchVectorCombinable.ADD, SearchVectorField, SearchVectorField ) class SearchVector(SearchVectorCombinable, Func): function = "to_tsvector" arg_joiner = " || ' ' || " output_field = SearchVectorField() def __init__(self, *expressions, config=None, weight=None): super().__init__(*expressions) self.config = SearchConfig.from_parameter(config) if weight is not None and not hasattr(weight, "resolve_expression"): weight = Value(weight) self.weight = weight def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): resolved = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) if self.config: resolved.config = self.config.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return resolved def as_sql(self, compiler, connection, function=None, template=None): clone = self.copy() clone.set_source_expressions( [ Coalesce( expression if isinstance(expression.output_field, (CharField, TextField)) else Cast(expression, TextField()), Value(""), ) for expression in clone.get_source_expressions() ] ) config_sql = None config_params = [] if template is None: if clone.config: config_sql, config_params = compiler.compile(clone.config) template = "%(function)s(%(config)s, %(expressions)s)" else: template = clone.template sql, params = super(SearchVector, clone).as_sql( compiler, connection, function=function, template=template, config=config_sql, ) extra_params = [] if clone.weight: weight_sql, extra_params = compiler.compile(clone.weight) sql = "setweight({}, {})".format(sql, weight_sql) return sql, config_params + params + extra_params class CombinedSearchVector(SearchVectorCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config super().__init__(lhs, connector, rhs, output_field) class SearchQueryCombinable: BITAND = "&&" BITOR = "||" def _combine(self, other, connector, reversed): if not isinstance(other, SearchQueryCombinable): raise TypeError( "SearchQuery can only be combined with other SearchQuery " "instances, got %s." % type(other).__name__ ) if reversed: return CombinedSearchQuery(other, connector, self, self.config) return CombinedSearchQuery(self, connector, other, self.config) # On Combinable, these are not implemented to reduce confusion with Q. In # this case we are actually (ab)using them to do logical combination so # it's consistent with other usage in Django. def __or__(self, other): return self._combine(other, self.BITOR, False) def __ror__(self, other): return self._combine(other, self.BITOR, True) def __and__(self, other): return self._combine(other, self.BITAND, False) def __rand__(self, other): return self._combine(other, self.BITAND, True) class SearchQuery(SearchQueryCombinable, Func): output_field = SearchQueryField() SEARCH_TYPES = { "plain": "plainto_tsquery", "phrase": "phraseto_tsquery", "raw": "to_tsquery", "websearch": "websearch_to_tsquery", } def __init__( self, value, output_field=None, *, config=None, invert=False, search_type="plain", ): self.function = self.SEARCH_TYPES.get(search_type) if self.function is None: raise ValueError("Unknown search_type argument '%s'." % search_type) if not hasattr(value, "resolve_expression"): value = Value(value) expressions = (value,) self.config = SearchConfig.from_parameter(config) if self.config is not None: expressions = (self.config,) + expressions self.invert = invert super().__init__(*expressions, output_field=output_field) def as_sql(self, compiler, connection, function=None, template=None): sql, params = super().as_sql(compiler, connection, function, template) if self.invert: sql = "!!(%s)" % sql return sql, params def __invert__(self): clone = self.copy() clone.invert = not self.invert return clone def __str__(self): result = super().__str__() return ("~%s" % result) if self.invert else result class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config super().__init__(lhs, connector, rhs, output_field) def __str__(self): return "(%s)" % super().__str__() class SearchRank(Func): function = "ts_rank" output_field = FloatField() def __init__( self, vector, query, weights=None, normalization=None, cover_density=False, ): if not hasattr(vector, "resolve_expression"): vector = SearchVector(vector) if not hasattr(query, "resolve_expression"): query = SearchQuery(query) expressions = (vector, query) if weights is not None: if not hasattr(weights, "resolve_expression"): weights = Value(weights) expressions = (weights,) + expressions if normalization is not None: if not hasattr(normalization, "resolve_expression"): normalization = Value(normalization) expressions += (normalization,) if cover_density: self.function = "ts_rank_cd" super().__init__(*expressions) class SearchHeadline(Func): function = "ts_headline" template = "%(function)s(%(expressions)s%(options)s)" output_field = TextField() def __init__( self, expression, query, *, config=None, start_sel=None, stop_sel=None, max_words=None, min_words=None, short_word=None, highlight_all=None, max_fragments=None, fragment_delimiter=None, ): if not hasattr(query, "resolve_expression"): query = SearchQuery(query) options = { "StartSel": start_sel, "StopSel": stop_sel, "MaxWords": max_words, "MinWords": min_words, "ShortWord": short_word, "HighlightAll": highlight_all, "MaxFragments": max_fragments, "FragmentDelimiter": fragment_delimiter, } self.options = { option: value for option, value in options.items() if value is not None } expressions = (expression, query) if config is not None: config = SearchConfig.from_parameter(config) expressions = (config,) + expressions super().__init__(*expressions) def as_sql(self, compiler, connection, function=None, template=None): options_sql = "" options_params = [] if self.options: # getquoted() returns a quoted bytestring of the adapted value. options_params.append( ", ".join( "%s=%s" % ( option, psycopg2.extensions.adapt(value).getquoted().decode(), ) for option, value in self.options.items() ) ) options_sql = ", %s" sql, params = super().as_sql( compiler, connection, function=function, template=template, options=options_sql, ) return sql, params + options_params SearchVectorField.register_lookup(SearchVectorExact) class TrigramBase(Func): output_field = FloatField() def __init__(self, expression, string, **extra): if not hasattr(string, "resolve_expression"): string = Value(string) super().__init__(expression, string, **extra) class TrigramWordBase(Func): output_field = FloatField() def __init__(self, string, expression, **extra): if not hasattr(string, "resolve_expression"): string = Value(string) super().__init__(string, expression, **extra) class TrigramSimilarity(TrigramBase): function = "SIMILARITY" class TrigramDistance(TrigramBase): function = "" arg_joiner = " <-> " class TrigramWordDistance(TrigramWordBase): function = "" arg_joiner = " <<-> " class TrigramStrictWordDistance(TrigramWordBase): function = "" arg_joiner = " <<<-> " class TrigramWordSimilarity(TrigramWordBase): function = "WORD_SIMILARITY" class TrigramStrictWordSimilarity(TrigramWordBase): function = "STRICT_WORD_SIMILARITY"
761450f9e064bdfec93d74ace7199368a766f3b9adc00106f20e615e4e3c1c52
from psycopg2.extras import DateRange, DateTimeRange, DateTimeTZRange, NumericRange from django.apps import AppConfig from django.core.signals import setting_changed from django.db import connections from django.db.backends.signals import connection_created from django.db.migrations.writer import MigrationWriter from django.db.models import CharField, OrderBy, TextField from django.db.models.functions import Collate from django.db.models.indexes import IndexExpression from django.utils.translation import gettext_lazy as _ from .indexes import OpClass from .lookups import ( SearchLookup, TrigramSimilar, TrigramStrictWordSimilar, TrigramWordSimilar, Unaccent, ) from .serializers import RangeSerializer from .signals import register_type_handlers RANGE_TYPES = (DateRange, DateTimeRange, DateTimeTZRange, NumericRange) def uninstall_if_needed(setting, value, enter, **kwargs): """ Undo the effects of PostgresConfig.ready() when django.contrib.postgres is "uninstalled" by override_settings(). """ if ( not enter and setting == "INSTALLED_APPS" and "django.contrib.postgres" not in set(value) ): connection_created.disconnect(register_type_handlers) CharField._unregister_lookup(Unaccent) TextField._unregister_lookup(Unaccent) CharField._unregister_lookup(SearchLookup) TextField._unregister_lookup(SearchLookup) CharField._unregister_lookup(TrigramSimilar) TextField._unregister_lookup(TrigramSimilar) CharField._unregister_lookup(TrigramWordSimilar) TextField._unregister_lookup(TrigramWordSimilar) CharField._unregister_lookup(TrigramStrictWordSimilar) TextField._unregister_lookup(TrigramStrictWordSimilar) # Disconnect this receiver until the next time this app is installed # and ready() connects it again to prevent unnecessary processing on # each setting change. setting_changed.disconnect(uninstall_if_needed) MigrationWriter.unregister_serializer(RANGE_TYPES) class PostgresConfig(AppConfig): name = "django.contrib.postgres" verbose_name = _("PostgreSQL extensions") def ready(self): setting_changed.connect(uninstall_if_needed) # Connections may already exist before we are called. for conn in connections.all(initialized_only=True): if conn.vendor == "postgresql": conn.introspection.data_types_reverse.update( { 3904: "django.contrib.postgres.fields.IntegerRangeField", 3906: "django.contrib.postgres.fields.DecimalRangeField", 3910: "django.contrib.postgres.fields.DateTimeRangeField", 3912: "django.contrib.postgres.fields.DateRangeField", 3926: "django.contrib.postgres.fields.BigIntegerRangeField", } ) if conn.connection is not None: register_type_handlers(conn) connection_created.connect(register_type_handlers) CharField.register_lookup(Unaccent) TextField.register_lookup(Unaccent) CharField.register_lookup(SearchLookup) TextField.register_lookup(SearchLookup) CharField.register_lookup(TrigramSimilar) TextField.register_lookup(TrigramSimilar) CharField.register_lookup(TrigramWordSimilar) TextField.register_lookup(TrigramWordSimilar) CharField.register_lookup(TrigramStrictWordSimilar) TextField.register_lookup(TrigramStrictWordSimilar) MigrationWriter.register_serializer(RANGE_TYPES, RangeSerializer) IndexExpression.register_wrappers(OrderBy, OpClass, Collate)
eaa1a4f8875b1280582a550cd88c501385c6ca9d7065a9cfe3eff2a08c7254fa
from django.db.models import Transform from django.db.models.lookups import PostgresOperatorLookup from .search import SearchVector, SearchVectorExact, SearchVectorField class DataContains(PostgresOperatorLookup): lookup_name = "contains" postgres_operator = "@>" class ContainedBy(PostgresOperatorLookup): lookup_name = "contained_by" postgres_operator = "<@" class Overlap(PostgresOperatorLookup): lookup_name = "overlap" postgres_operator = "&&" class HasKey(PostgresOperatorLookup): lookup_name = "has_key" postgres_operator = "?" prepare_rhs = False class HasKeys(PostgresOperatorLookup): lookup_name = "has_keys" postgres_operator = "?&" def get_prep_lookup(self): return [str(item) for item in self.rhs] class HasAnyKeys(HasKeys): lookup_name = "has_any_keys" postgres_operator = "?|" class Unaccent(Transform): bilateral = True lookup_name = "unaccent" function = "UNACCENT" class SearchLookup(SearchVectorExact): lookup_name = "search" def process_lhs(self, qn, connection): if not isinstance(self.lhs.output_field, SearchVectorField): config = getattr(self.rhs, "config", None) self.lhs = SearchVector(self.lhs, config=config) lhs, lhs_params = super().process_lhs(qn, connection) return lhs, lhs_params class TrigramSimilar(PostgresOperatorLookup): lookup_name = "trigram_similar" postgres_operator = "%%" class TrigramWordSimilar(PostgresOperatorLookup): lookup_name = "trigram_word_similar" postgres_operator = "%%>" class TrigramStrictWordSimilar(PostgresOperatorLookup): lookup_name = "trigram_strict_word_similar" postgres_operator = "%%>>"
031213a8cef87113bc54b2f28c0fb1dae285d1619b9399b3cba6549392d864bd
from django.conf import settings from django.contrib import admin, messages from django.contrib.admin.options import IS_POPUP_VAR from django.contrib.admin.utils import unquote from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import ( AdminPasswordChangeForm, UserChangeForm, UserCreationForm, ) from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import escape from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters csrf_protect_m = method_decorator(csrf_protect) sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) @admin.register(Group) class GroupAdmin(admin.ModelAdmin): search_fields = ("name",) ordering = ("name",) filter_horizontal = ("permissions",) def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == "permissions": qs = kwargs.get("queryset", db_field.remote_field.model.objects) # Avoid a major performance hit resolving permission names which # triggers a content_type load: kwargs["queryset"] = qs.select_related("content_type") return super().formfield_for_manytomany(db_field, request=request, **kwargs) @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = "admin/auth/user/add_form.html" change_user_password_template = None fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("first_name", "last_name", "email")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", "password1", "password2"), }, ), ) form = UserChangeForm add_form = UserCreationForm change_password_form = AdminPasswordChangeForm list_display = ("username", "email", "first_name", "last_name", "is_staff") list_filter = ("is_staff", "is_superuser", "is_active", "groups") search_fields = ("username", "first_name", "last_name", "email") ordering = ("username",) filter_horizontal = ( "groups", "user_permissions", ) def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: defaults["form"] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): return [ path( "<id>/password/", self.admin_site.admin_view(self.user_change_password), name="auth_user_password_change", ), ] + super().get_urls() def lookup_allowed(self, lookup, value): # Don't allow lookups involving passwords. return not lookup.startswith("password") and super().lookup_allowed( lookup, value ) @sensitive_post_parameters_m @csrf_protect_m def add_view(self, request, form_url="", extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._add_view(request, form_url, extra_context) def _add_view(self, request, form_url="", extra_context=None): # It's an error for a user to have add permission but NOT change # permission for users. If we allowed such users to add users, they # could create superusers, which would mean they would essentially have # the permission to change users. To avoid the problem entirely, we # disallow users from adding users if they don't have change # permission. if not self.has_change_permission(request): if self.has_add_permission(request) and settings.DEBUG: # Raise Http404 in debug mode so that the user gets a helpful # error message. raise Http404( 'Your user does not have the "Change user" permission. In ' "order to add users, Django requires that your user " 'account have both the "Add user" and "Change user" ' "permissions set." ) raise PermissionDenied if extra_context is None: extra_context = {} username_field = self.opts.get_field(self.model.USERNAME_FIELD) defaults = { "auto_populated_fields": (), "username_help_text": username_field.help_text, } extra_context.update(defaults) return super().add_view(request, form_url, extra_context) @sensitive_post_parameters_m def user_change_password(self, request, id, form_url=""): user = self.get_object(request, unquote(id)) if not self.has_change_permission(request, user): raise PermissionDenied if user is None: raise Http404( _("%(name)s object with primary key %(key)r does not exist.") % { "name": self.opts.verbose_name, "key": escape(id), } ) if request.method == "POST": form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() change_message = self.construct_change_message(request, form, None) self.log_change(request, user, change_message) msg = gettext("Password changed successfully.") messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( "%s:%s_%s_change" % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk,), ) ) else: form = self.change_password_form(user) fieldsets = [(None, {"fields": list(form.base_fields)})] adminForm = admin.helpers.AdminForm(form, fieldsets, {}) context = { "title": _("Change password: %s") % escape(user.get_username()), "adminForm": adminForm, "form_url": form_url, "form": form, "is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), "is_popup_var": IS_POPUP_VAR, "add": True, "change": False, "has_delete_permission": False, "has_change_permission": True, "has_absolute_url": False, "opts": self.opts, "original": user, "save_as": False, "show_save": True, **self.admin_site.each_context(request), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or "admin/auth/user/change_password.html", context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow further modification of the user just added i.e. the # 'Save' button should behave like the 'Save and continue editing' # button except in two scenarios: # * The user has pressed the 'Save and add another' button # * We are adding a user in a popup if "_addanother" not in request.POST and IS_POPUP_VAR not in request.POST: request.POST = request.POST.copy() request.POST["_continue"] = 1 return super().response_add(request, obj, post_url_continue)
d782e6d31aa3e2de48aa4a476e9ae735c4d25baff336533b86e172f8f7fd7090
""" This module allows importing AbstractBaseUser even when django.contrib.auth is not in INSTALLED_APPS. """ import unicodedata import warnings from django.contrib.auth import password_validation from django.contrib.auth.hashers import ( check_password, is_password_usable, make_password, ) from django.db import models from django.utils.crypto import get_random_string, salted_hmac from django.utils.deprecation import RemovedInDjango51Warning from django.utils.translation import gettext_lazy as _ class BaseUserManager(models.Manager): @classmethod def normalize_email(cls, email): """ Normalize the email address by lowercasing the domain part of it. """ email = email or "" try: email_name, domain_part = email.strip().rsplit("@", 1) except ValueError: pass else: email = email_name + "@" + domain_part.lower() return email def make_random_password( self, length=10, allowed_chars="abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789", ): """ Generate a random password with the given length and given allowed_chars. The default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ warnings.warn( "BaseUserManager.make_random_password() is deprecated.", category=RemovedInDjango51Warning, stacklevel=2, ) return get_random_string(length, allowed_chars) def get_by_natural_key(self, username): return self.get(**{self.model.USERNAME_FIELD: username}) class AbstractBaseUser(models.Model): password = models.CharField(_("password"), max_length=128) last_login = models.DateTimeField(_("last login"), blank=True, null=True) is_active = True REQUIRED_FIELDS = [] # Stores the raw password if set_password() is called so that it can # be passed to password_changed() after the model is saved. _password = None class Meta: abstract = True def __str__(self): return self.get_username() def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._password is not None: password_validation.password_changed(self._password, self) self._password = None def get_username(self): """Return the username for this User.""" return getattr(self, self.USERNAME_FIELD) def clean(self): setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username())) def natural_key(self): return (self.get_username(),) @property def is_anonymous(self): """ Always return False. This is a way of comparing User objects to anonymous users. """ return False @property def is_authenticated(self): """ Always return True. This is a way to tell if the user has been authenticated in templates. """ return True def set_password(self, raw_password): self.password = make_password(raw_password) self._password = raw_password def check_password(self, raw_password): """ Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) # Password hash upgrades shouldn't be considered password changes. self._password = None self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) def set_unusable_password(self): # Set a value that will never be a valid hash self.password = make_password(None) def has_usable_password(self): """ Return False if set_unusable_password() has been called for this user. """ return is_password_usable(self.password) def get_session_auth_hash(self): """ Return an HMAC of the password field. """ key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" return salted_hmac( key_salt, self.password, algorithm="sha256", ).hexdigest() @classmethod def get_email_field_name(cls): try: return cls.EMAIL_FIELD except AttributeError: return "email" @classmethod def normalize_username(cls, username): return ( unicodedata.normalize("NFKC", username) if isinstance(username, str) else username )
a1fea80df65622963821b8a4e1f6b422571853b0ca18d2da3dcc8933a1708455
import copy import json import re from functools import partial, update_wrapper from urllib.parse import quote as urlquote from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import helpers, widgets from django.contrib.admin.checks import ( BaseModelAdminChecks, InlineModelAdminChecks, ModelAdminChecks, ) from django.contrib.admin.decorators import display from django.contrib.admin.exceptions import DisallowedModelAdminToField from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( NestedObjects, construct_change_message, flatten_fieldsets, get_deleted_objects, lookup_spawns_duplicates, model_format_dict, model_ngettext, quote, unquote, ) from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple from django.contrib.auth import get_permission_codename from django.core.exceptions import ( FieldDoesNotExist, FieldError, PermissionDenied, ValidationError, ) from django.core.paginator import Paginator from django.db import models, router, transaction from django.db.models.constants import LOOKUP_SEP from django.forms.formsets import DELETION_FIELD_NAME, all_valid from django.forms.models import ( BaseInlineFormSet, inlineformset_factory, modelform_defines_fields, modelform_factory, modelformset_factory, ) from django.forms.widgets import CheckboxSelectMultiple, SelectMultiple from django.http import HttpResponseRedirect from django.http.response import HttpResponseBase from django.template.response import SimpleTemplateResponse, TemplateResponse from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.html import format_html from django.utils.http import urlencode from django.utils.safestring import mark_safe from django.utils.text import ( capfirst, format_lazy, get_text_list, smart_split, unescape_string_literal, ) from django.utils.translation import gettext as _ from django.utils.translation import ngettext from django.views.decorators.csrf import csrf_protect from django.views.generic import RedirectView IS_POPUP_VAR = "_popup" TO_FIELD_VAR = "_to_field" HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_style): return "radiolist" if radio_style == VERTICAL else "radiolist inline" class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { "form_class": forms.SplitDateTimeField, "widget": widgets.AdminSplitDateTime, }, models.DateField: {"widget": widgets.AdminDateWidget}, models.TimeField: {"widget": widgets.AdminTimeWidget}, models.TextField: {"widget": widgets.AdminTextareaWidget}, models.URLField: {"widget": widgets.AdminURLFieldWidget}, models.IntegerField: {"widget": widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {"widget": widgets.AdminBigIntegerFieldWidget}, models.CharField: {"widget": widgets.AdminTextInputWidget}, models.ImageField: {"widget": widgets.AdminFileWidget}, models.FileField: {"widget": widgets.AdminFileWidget}, models.EmailField: {"widget": widgets.AdminEmailInputWidget}, models.UUIDField: {"widget": widgets.AdminUUIDInputWidget}, } csrf_protect_m = method_decorator(csrf_protect) class BaseModelAdmin(metaclass=forms.MediaDefiningClass): """Functionality common to both ModelAdmin and InlineAdmin.""" autocomplete_fields = () raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly_fields = () ordering = None sortable_by = None view_on_site = True show_full_result_count = True checks_class = BaseModelAdminChecks def check(self, **kwargs): return self.checks_class().check(self, **kwargs) def __init__(self): # Merge FORMFIELD_FOR_DBFIELD_DEFAULTS with the formfield_overrides # rather than simply overwriting. overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS) for k, v in self.formfield_overrides.items(): overrides.setdefault(k, {}).update(v) self.formfield_overrides = overrides def formfield_for_dbfield(self, db_field, request, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ # If the field specifies choices, we don't need to look for special # admin widgets - we just need to use a select widget of some kind. if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = {**self.formfield_overrides[db_field.__class__], **kwargs} # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: related_modeladmin = self.admin_site._registry.get( db_field.remote_field.model ) wrapper_kwargs = {} if related_modeladmin: wrapper_kwargs.update( can_add_related=related_modeladmin.has_add_permission(request), can_change_related=related_modeladmin.has_change_permission( request ), can_delete_related=related_modeladmin.has_delete_permission( request ), can_view_related=related_modeladmin.has_view_permission( request ), ) formfield.widget = widgets.RelatedFieldWidgetWrapper( formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs, ) return formfield # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in self.formfield_overrides: kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs} return db_field.formfield(**kwargs) # For any other type of field, just call its formfield() method. return db_field.formfield(**kwargs) def formfield_for_choice_field(self, db_field, request, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if "widget" not in kwargs: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) if "choices" not in kwargs: kwargs["choices"] = db_field.get_choices( include_blank=db_field.blank, blank_choice=[("", _("None"))] ) return db_field.formfield(**kwargs) def get_field_queryset(self, db, db_field, request): """ If the ModelAdmin specifies ordering, the queryset should respect that ordering. Otherwise don't specify the queryset, let the field decide (return None in that case). """ related_admin = self.admin_site._registry.get(db_field.remote_field.model) if related_admin is not None: ordering = related_admin.get_ordering(request) if ordering is not None and ordering != (): return db_field.remote_field.model._default_manager.using(db).order_by( *ordering ) return None def formfield_for_foreignkey(self, db_field, request, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get("using") if "widget" not in kwargs: if db_field.name in self.get_autocomplete_fields(request): kwargs["widget"] = AutocompleteSelect( db_field, self.admin_site, using=db ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ForeignKeyRawIdWidget( db_field.remote_field, self.admin_site, using=db ) elif db_field.name in self.radio_fields: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) kwargs["empty_label"] = ( kwargs.get("empty_label", _("None")) if db_field.blank else None ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset return db_field.formfield(**kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widget" not in kwargs: autocomplete_fields = self.get_autocomplete_fields(request) if db_field.name in autocomplete_fields: kwargs["widget"] = AutocompleteSelectMultiple( db_field, self.admin_site, using=db, ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ManyToManyRawIdWidget( db_field.remote_field, self.admin_site, using=db, ) elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]: kwargs["widget"] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset form_field = db_field.formfield(**kwargs) if ( isinstance(form_field.widget, SelectMultiple) and form_field.widget.allow_multiple_selected and not isinstance( form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple) ) ): msg = _( "Hold down “Control”, or “Command” on a Mac, to select more than one." ) help_text = form_field.help_text form_field.help_text = ( format_lazy("{} {}", help_text, msg) if help_text else msg ) return form_field def get_autocomplete_fields(self, request): """ Return a list of ForeignKey and/or ManyToMany fields which should use an autocomplete widget. """ return self.autocomplete_fields def get_view_on_site_url(self, obj=None): if obj is None or not self.view_on_site: return None if callable(self.view_on_site): return self.view_on_site(obj) elif hasattr(obj, "get_absolute_url"): # use the ContentType lookup if view_on_site is True return reverse( "admin:view_on_site", kwargs={ "content_type_id": get_content_type_for_model(obj).pk, "object_id": obj.pk, }, current_app=self.admin_site.name, ) def get_empty_value_display(self): """ Return the empty_value_display set on ModelAdmin or AdminSite. """ try: return mark_safe(self.empty_value_display) except AttributeError: return mark_safe(self.admin_site.empty_value_display) def get_exclude(self, request, obj=None): """ Hook for specifying exclude. """ return self.exclude def get_fields(self, request, obj=None): """ Hook for specifying fields. """ if self.fields: return self.fields # _get_form_for_get_fields() is implemented in subclasses. form = self._get_form_for_get_fields(request, obj) return [*form.base_fields, *self.get_readonly_fields(request, obj)] def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ if self.fieldsets: return self.fieldsets return [(None, {"fields": self.get_fields(request, obj)})] def get_inlines(self, request, obj): """Hook for specifying custom inlines.""" return self.inlines def get_ordering(self, request): """ Hook for specifying field ordering. """ return self.ordering or () # otherwise we might try to *None, which is bad ;) def get_readonly_fields(self, request, obj=None): """ Hook for specifying custom readonly fields. """ return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): """ Hook for specifying custom prepopulated fields. """ return self.prepopulated_fields def get_queryset(self, request): """ Return a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs def get_sortable_by(self, request): """Hook for specifying which fields can be sorted in the changelist.""" return ( self.sortable_by if self.sortable_by is not None else self.get_list_display(request) ) def lookup_allowed(self, lookup, value): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for fk_lookup in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(fk_lookup): fk_lookup = fk_lookup() if (lookup, value) in widgets.url_params_from_lookup_dict( fk_lookup ).items(): return True relation_parts = [] prev_field = None for part in lookup.split(LOOKUP_SEP): try: field = model._meta.get_field(part) except FieldDoesNotExist: # Lookups on nonexistent fields are ok, since they're ignored # later. break # It is allowed to filter on values that would be found from local # model anyways. For example, if you filter on employee__department__id, # then the id value would be found already from employee__department_id. if not prev_field or ( prev_field.is_relation and field not in prev_field.path_infos[-1].target_fields ): relation_parts.append(part) if not getattr(field, "path_infos", None): # This is not a relational field, so further parts # must be transforms. break prev_field = field model = field.path_infos[-1].to_opts.model if len(relation_parts) <= 1: # Either a local field filter, or no fields at all. return True valid_lookups = {self.date_hierarchy} for filter_item in self.list_filter: if isinstance(filter_item, type) and issubclass( filter_item, SimpleListFilter ): valid_lookups.add(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.add(filter_item[0]) else: valid_lookups.add(filter_item) # Is it a valid relational lookup? return not { LOOKUP_SEP.join(relation_parts), LOOKUP_SEP.join(relation_parts + [part]), }.isdisjoint(valid_lookups) def to_field_allowed(self, request, to_field): """ Return True if the model associated with this admin should be allowed to be referenced by the specified field. """ try: field = self.opts.get_field(to_field) except FieldDoesNotExist: return False # Always allow referencing the primary key since it's already possible # to get this information from the change view URL. if field.primary_key: return True # Allow reverse relationships to models defining m2m fields if they # target the specified field. for many_to_many in self.opts.many_to_many: if many_to_many.m2m_target_field_name() == to_field: return True # Make sure at least one of the models registered for this site # references this field through a FK or a M2M relationship. registered_models = set() for model, admin in self.admin_site._registry.items(): registered_models.add(model) for inline in admin.inlines: registered_models.add(inline.model) related_objects = ( f for f in self.opts.get_fields(include_hidden=True) if (f.auto_created and not f.concrete) ) for related_object in related_objects: related_model = related_object.related_model remote_field = related_object.field.remote_field if ( any(issubclass(model, related_model) for model in registered_models) and hasattr(remote_field, "get_related_field") and remote_field.get_related_field() == field ): return True return False def has_add_permission(self, request): """ Return True if the given request has permission to add an object. Can be overridden by the user in subclasses. """ opts = self.opts codename = get_permission_codename("add", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_change_permission(self, request, obj=None): """ Return True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to change the `obj` model instance. If `obj` is None, this should return True if the given request has permission to change *any* object of the given type. """ opts = self.opts codename = get_permission_codename("change", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): """ Return True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ opts = self.opts codename = get_permission_codename("delete", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_view_permission(self, request, obj=None): """ Return True if the given request has permission to view the given Django model instance. The default implementation doesn't examine the `obj` parameter. If overridden by the user in subclasses, it should return True if the given request has permission to view the `obj` model instance. If `obj` is None, it should return True if the request has permission to view any object of the given type. """ opts = self.opts codename_view = get_permission_codename("view", opts) codename_change = get_permission_codename("change", opts) return request.user.has_perm( "%s.%s" % (opts.app_label, codename_view) ) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change)) def has_view_or_change_permission(self, request, obj=None): return self.has_view_permission(request, obj) or self.has_change_permission( request, obj ) def has_module_permission(self, request): """ Return True if the given request has any permission in the given app label. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to view the module on the admin index page and access the module's index page. Overriding it does not restrict access to the add, change or delete views. Use `ModelAdmin.has_(add|change|delete)_permission` for that. """ return request.user.has_module_perms(self.opts.app_label) class ModelAdmin(BaseModelAdmin): """Encapsulate all admin options and functionality for a given model.""" list_display = ("__str__",) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable = () search_fields = () search_help_text = None date_hierarchy = None save_as = False save_as_continue = True save_on_top = False paginator = Paginator preserve_filters = True inlines = () # Custom templates (designed to be over-ridden in subclasses) add_form_template = None change_form_template = None change_list_template = None delete_confirmation_template = None delete_selected_confirmation_template = None object_history_template = None popup_response_template = None # Actions actions = () action_form = helpers.ActionForm actions_on_top = True actions_on_bottom = False actions_selection_counter = True checks_class = ModelAdminChecks def __init__(self, model, admin_site): self.model = model self.opts = model._meta self.admin_site = admin_site super().__init__() def __str__(self): return "%s.%s" % (self.opts.app_label, self.__class__.__name__) def __repr__(self): return ( f"<{self.__class__.__qualname__}: model={self.model.__qualname__} " f"site={self.admin_site!r}>" ) def get_inline_instances(self, request, obj=None): inline_instances = [] for inline_class in self.get_inlines(request, obj): inline = inline_class(self.model, self.admin_site) if request: if not ( inline.has_view_or_change_permission(request, obj) or inline.has_add_permission(request, obj) or inline.has_delete_permission(request, obj) ): continue if not inline.has_add_permission(request, obj): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_urls(self): from django.urls import path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) wrapper.model_admin = self return update_wrapper(wrapper, view) info = self.opts.app_label, self.opts.model_name return [ path("", wrap(self.changelist_view), name="%s_%s_changelist" % info), path("add/", wrap(self.add_view), name="%s_%s_add" % info), path( "<path:object_id>/history/", wrap(self.history_view), name="%s_%s_history" % info, ), path( "<path:object_id>/delete/", wrap(self.delete_view), name="%s_%s_delete" % info, ), path( "<path:object_id>/change/", wrap(self.change_view), name="%s_%s_change" % info, ), # For backwards compatibility (was the change url before 1.9) path( "<path:object_id>/", wrap( RedirectView.as_view( pattern_name="%s:%s_%s_change" % ((self.admin_site.name,) + info) ) ), ), ] @property def urls(self): return self.get_urls() @property def media(self): extra = "" if settings.DEBUG else ".min" js = [ "vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "core.js", "admin/RelatedObjectLookups.js", "actions.js", "urlify.js", "prepopulate.js", "vendor/xregexp/xregexp%s.js" % extra, ] return forms.Media(js=["admin/js/%s" % url for url in js]) def get_model_perms(self, request): """ Return a dict of all perms for this model. This dict has the keys ``add``, ``change``, ``delete``, and ``view`` mapping to the True/False for each of those actions. """ return { "add": self.has_add_permission(request), "change": self.has_change_permission(request), "delete": self.has_delete_permission(request), "view": self.has_view_permission(request), } def _get_form_for_get_fields(self, request, obj): return self.get_form(request, obj, fields=None) def get_form(self, request, obj=None, change=False, **kwargs): """ Return a Form class for use in the admin add view. This is used by add_view and change_view. """ if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) readonly_fields = self.get_readonly_fields(request, obj) exclude.extend(readonly_fields) # Exclude all fields if it's a change form and the user doesn't have # the change permission. if ( change and hasattr(request, "user") and not self.has_change_permission(request, obj) ): exclude.extend(fields) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # ModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we pass None to be consistent with the # default on modelform_factory exclude = exclude or None # Remove declared form fields which are in readonly_fields. new_attrs = dict.fromkeys( f for f in readonly_fields if f in self.form.declared_fields ) form = type(self.form.__name__, (self.form,), new_attrs) defaults = { "form": form, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS try: return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError( "%s. Check fields/fieldsets/exclude attributes of class %s." % (e, self.__class__.__name__) ) def get_changelist(self, request, **kwargs): """ Return the ChangeList class for use on the changelist page. """ from django.contrib.admin.views.main import ChangeList return ChangeList def get_changelist_instance(self, request): """ Return a `ChangeList` instance based on `request`. May raise `IncorrectLookupParameters`. """ list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) # Add the action checkboxes if any actions are available. if self.get_actions(request): list_display = ["action_checkbox", *list_display] sortable_by = self.get_sortable_by(request) ChangeList = self.get_changelist(request) return ChangeList( request, self.model, list_display, list_display_links, self.get_list_filter(request), self.date_hierarchy, self.get_search_fields(request), self.get_list_select_related(request), self.list_per_page, self.list_max_show_all, self.list_editable, self, sortable_by, self.search_help_text, ) def get_object(self, request, object_id, from_field=None): """ Return an instance matching the field and value provided, the primary key is used if no field is provided. Return ``None`` if no match is found or the object_id fails validation. """ queryset = self.get_queryset(request) model = queryset.model field = ( model._meta.pk if from_field is None else model._meta.get_field(from_field) ) try: object_id = field.to_python(object_id) return queryset.get(**{field.name: object_id}) except (model.DoesNotExist, ValidationError, ValueError): return None def get_changelist_form(self, request, **kwargs): """ Return a Form class for use in the Formset on the changelist page. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults.get("fields") is None and not modelform_defines_fields( defaults.get("form") ): defaults["fields"] = forms.ALL_FIELDS return modelform_factory(self.model, **defaults) def get_changelist_formset(self, request, **kwargs): """ Return a FormSet class for use on the changelist page if list_editable is used. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } return modelformset_factory( self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults, ) def get_formsets_with_inlines(self, request, obj=None): """ Yield formsets and the corresponding inlines. """ for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj), inline def get_paginator( self, request, queryset, per_page, orphans=0, allow_empty_first_page=True ): return self.paginator(queryset, per_page, orphans, allow_empty_first_page) def log_addition(self, request, obj, message): """ Log that an object has been successfully added. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import ADDITION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=ADDITION, change_message=message, ) def log_change(self, request, obj, message): """ Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import CHANGE, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=CHANGE, change_message=message, ) def log_deletion(self, request, obj, object_repr): """ Log that an object will be deleted. Note that this method must be called before the deletion. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import DELETION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=object_repr, action_flag=DELETION, ) @display(description=mark_safe('<input type="checkbox" id="action-toggle">')) def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, str(obj.pk)) @staticmethod def _get_action_description(func, name): return getattr(func, "short_description", capfirst(name.replace("_", " "))) def _get_base_actions(self): """Return the list of actions, prior to any request-based filtering.""" actions = [] base_actions = (self.get_action(action) for action in self.actions or []) # get_action might have returned None, so filter any of those out. base_actions = [action for action in base_actions if action] base_action_names = {name for _, name, _ in base_actions} # Gather actions from the admin site first for (name, func) in self.admin_site.actions: if name in base_action_names: continue description = self._get_action_description(func, name) actions.append((func, name, description)) # Add actions from this ModelAdmin. actions.extend(base_actions) return actions def _filter_actions_by_permissions(self, request, actions): """Filter out any actions that the user doesn't have access to.""" filtered_actions = [] for action in actions: callable = action[0] if not hasattr(callable, "allowed_permissions"): filtered_actions.append(action) continue permission_checks = ( getattr(self, "has_%s_permission" % permission) for permission in callable.allowed_permissions ) if any(has_permission(request) for has_permission in permission_checks): filtered_actions.append(action) return filtered_actions def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is set to None that means actions are disabled on # this page. if self.actions is None or IS_POPUP_VAR in request.GET: return {} actions = self._filter_actions_by_permissions(request, self._get_base_actions()) return {name: (func, name, desc) for func, name, desc in actions} def get_action_choices(self, request, default_choices=models.BLANK_CHOICE_DASH): """ Return a list of choices for use in a form object. Each choice is a tuple (name, description). """ choices = [] + default_choices for func, name, description in self.get_actions(request).values(): choice = (name, description % model_format_dict(self.opts)) choices.append(choice) return choices def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None description = self._get_action_description(func, action) return func, action, description def get_list_display(self, request): """ Return a sequence containing the fields to be displayed on the changelist. """ return self.list_display def get_list_display_links(self, request, list_display): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if ( self.list_display_links or self.list_display_links is None or not list_display ): return self.list_display_links else: # Use only the first item in list_display as link return list(list_display)[:1] def get_list_filter(self, request): """ Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page. """ return self.list_filter def get_list_select_related(self, request): """ Return a list of fields to add to the select_related() part of the changelist items query. """ return self.list_select_related def get_search_fields(self, request): """ Return a sequence containing the fields to be searched whenever somebody submits a search query. """ return self.search_fields def get_search_results(self, request, queryset, search_term): """ Return a tuple containing a queryset to implement the search and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith("^"): return "%s__istartswith" % field_name[1:] elif field_name.startswith("="): return "%s__iexact" % field_name[1:] elif field_name.startswith("@"): return "%s__search" % field_name[1:] # Use field_name if it includes a lookup. opts = queryset.model._meta lookup_fields = field_name.split(LOOKUP_SEP) # Go through the fields, following all relations. prev_field = None for path_part in lookup_fields: if path_part == "pk": path_part = opts.pk.name try: field = opts.get_field(path_part) except FieldDoesNotExist: # Use valid query lookups. if prev_field and prev_field.get_lookup(path_part): return field_name else: prev_field = field if hasattr(field, "path_infos"): # Update opts to follow the relation. opts = field.path_infos[-1].to_opts # Otherwise, use the field with icontains. return "%s__icontains" % field_name may_have_duplicates = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [ construct_search(str(search_field)) for search_field in search_fields ] term_queries = [] for bit in smart_split(search_term): if bit.startswith(('"', "'")) and bit[0] == bit[-1]: bit = unescape_string_literal(bit) or_queries = models.Q( *((orm_lookup, bit) for orm_lookup in orm_lookups), _connector=models.Q.OR, ) term_queries.append(or_queries) queryset = queryset.filter(models.Q(*term_queries)) may_have_duplicates |= any( lookup_spawns_duplicates(self.opts, search_spec) for search_spec in orm_lookups ) return queryset, may_have_duplicates def get_preserved_filters(self, request): """ Return the preserved filters querystring. """ match = request.resolver_match if self.preserve_filters and match: current_url = "%s:%s" % (match.app_name, match.url_name) changelist_url = "admin:%s_%s_changelist" % ( self.opts.app_label, self.opts.model_name, ) if current_url == changelist_url: preserved_filters = request.GET.urlencode() else: preserved_filters = request.GET.get("_changelist_filters") if preserved_filters: return urlencode({"_changelist_filters": preserved_filters}) return "" def construct_change_message(self, request, form, formsets, add=False): """ Construct a JSON structure describing changes from a changed object. """ return construct_change_message(form, formsets, add) def message_user( self, request, message, level=messages.INFO, extra_tags="", fail_silently=False ): """ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend. Exposes almost the same API as messages.add_message(), but accepts the positional arguments in a different order to maintain backwards compatibility. For convenience, it accepts the `level` argument as a string rather than the usual level number. """ if not isinstance(level, int): # attempt to get the level if passed a string try: level = getattr(messages.constants, level.upper()) except AttributeError: levels = messages.constants.DEFAULT_TAGS.values() levels_repr = ", ".join("`%s`" % level for level in levels) raise ValueError( "Bad message level string: `%s`. Possible values are: %s" % (level, levels_repr) ) messages.add_message( request, level, message, extra_tags=extra_tags, fail_silently=fail_silently ) def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() def delete_model(self, request, obj): """ Given a model instance delete it from the database. """ obj.delete() def delete_queryset(self, request, queryset): """Given a queryset, delete it from the database.""" queryset.delete() def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change) def render_change_form( self, request, context, add=False, change=False, form_url="", obj=None ): app_label = self.opts.app_label preserved_filters = self.get_preserved_filters(request) form_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, form_url ) view_on_site_url = self.get_view_on_site_url(obj) has_editable_inline_admin_formsets = False for inline in context["inline_admin_formsets"]: if ( inline.has_add_permission or inline.has_change_permission or inline.has_delete_permission ): has_editable_inline_admin_formsets = True break context.update( { "add": add, "change": change, "has_view_permission": self.has_view_permission(request, obj), "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_editable_inline_admin_formsets": ( has_editable_inline_admin_formsets ), "has_file_field": context["adminform"].form.is_multipart() or any( admin_formset.formset.is_multipart() for admin_formset in context["inline_admin_formsets"] ), "has_absolute_url": view_on_site_url is not None, "absolute_url": view_on_site_url, "form_url": form_url, "opts": self.opts, "content_type_id": get_content_type_for_model(self.model).pk, "save_as": self.save_as, "save_on_top": self.save_on_top, "to_field_var": TO_FIELD_VAR, "is_popup_var": IS_POPUP_VAR, "app_label": app_label, } ) if add and self.add_form_template is not None: form_template = self.add_form_template else: form_template = self.change_form_template request.current_app = self.admin_site.name return TemplateResponse( request, form_template or [ "admin/%s/%s/change_form.html" % (app_label, self.opts.model_name), "admin/%s/change_form.html" % app_label, "admin/change_form.html", ], context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. """ opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(quote(obj.pk),), current_app=self.admin_site.name, ) # Add a link to the object's change form if the user can edit the obj. if self.has_change_permission(request, obj): obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj) else: obj_repr = str(obj) msg_dict = { "name": opts.verbose_name, "obj": obj_repr, } # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) popup_response_data = json.dumps( { "value": str(value), "obj": str(obj), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) elif "_continue" in request.POST or ( # Redirecting after "Save as new". "_saveasnew" in request.POST and self.save_as_continue and self.has_change_permission(request, obj) ): msg = _("The {name} “{obj}” was added successfully.") if self.has_change_permission(request, obj): msg += " " + _("You may edit it again below.") self.message_user(request, format_html(msg, **msg_dict), messages.SUCCESS) if post_url_continue is None: post_url_continue = obj_url post_url_continue = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, post_url_continue, ) return HttpResponseRedirect(post_url_continue) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was added successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_add(request, obj) def response_change(self, request, obj): """ Determine the HttpResponse for the change_view stage. """ if IS_POPUP_VAR in request.POST: opts = obj._meta to_field = request.POST.get(TO_FIELD_VAR) attr = str(to_field) if to_field else opts.pk.attname value = request.resolver_match.kwargs["object_id"] new_value = obj.serializable_value(attr) popup_response_data = json.dumps( { "action": "change", "value": str(value), "obj": str(obj), "new_value": str(new_value), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) opts = self.opts preserved_filters = self.get_preserved_filters(request) msg_dict = { "name": opts.verbose_name, "obj": format_html('<a href="{}">{}</a>', urlquote(request.path), obj), } if "_continue" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may edit it " "again below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_saveasnew" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may edit it again " "below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(obj.pk,), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_add" % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was changed successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_change(request, obj) def _response_post_save(self, request, obj): if self.has_view_or_change_permission(request): post_url = reverse( "admin:%s_%s_changelist" % (self.opts.app_label, self.opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def response_post_save_add(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when adding a new object. """ return self._response_post_save(request, obj) def response_post_save_change(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when editing an existing object. """ return self._response_post_save(request, obj) def response_action(self, request, queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try: action_index = int(request.POST.get("index", 0)) except ValueError: action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({"action": data.getlist("action")[action_index]}) except IndexError: # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data["action"] select_across = action_form.cleaned_data["select_across"] func = self.get_actions(request)[action][0] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform # the action explicitly on all objects. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected and not select_across: # Reminder that something needs to be selected or nothing will happen msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) return None if not select_across: # Perform the action only on the selected objects queryset = queryset.filter(pk__in=selected) response = func(self, request, queryset) # Actions may return an HttpResponse-like object, which will be # used as the response from the POST. If not, we'll be a good # little HTTP citizen and redirect back to the changelist page. if isinstance(response, HttpResponseBase): return response else: return HttpResponseRedirect(request.get_full_path()) else: msg = _("No action selected.") self.message_user(request, msg, messages.WARNING) return None def response_delete(self, request, obj_display, obj_id): """ Determine the HttpResponse for the delete_view stage. """ if IS_POPUP_VAR in request.POST: popup_response_data = json.dumps( { "action": "delete", "value": str(obj_id), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (self.opts.app_label, self.opts.model_name), "admin/%s/popup_response.html" % self.opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) self.message_user( request, _("The %(name)s “%(obj)s” was deleted successfully.") % { "name": self.opts.verbose_name, "obj": obj_display, }, messages.SUCCESS, ) if self.has_change_permission(request, None): post_url = reverse( "admin:%s_%s_changelist" % (self.opts.app_label, self.opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def render_delete_form(self, request, context): app_label = self.opts.app_label request.current_app = self.admin_site.name context.update( to_field_var=TO_FIELD_VAR, is_popup_var=IS_POPUP_VAR, media=self.media, ) return TemplateResponse( request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format( app_label, self.opts.model_name ), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html", ], context, ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = ( self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ) inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) if can_edit_parent: has_add_permission = inline.has_add_permission(request, obj) has_change_permission = inline.has_change_permission(request, obj) has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and overide formset settings. has_add_permission = ( has_change_permission ) = has_delete_permission = False formset.extra = formset.max_num = 0 has_view_permission = inline.has_view_permission(request, obj) prepopulated = dict(inline.get_prepopulated_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet( inline, formset, fieldsets, prepopulated, readonly, model_admin=self, has_add_permission=has_add_permission, has_change_permission=has_change_permission, has_delete_permission=has_delete_permission, has_view_permission=has_view_permission, ) inline_admin_formsets.append(inline_admin_formset) return inline_admin_formsets def get_changeform_initial_data(self, request): """ Get the initial form data from the request's GET params. """ initial = dict(request.GET.items()) for k in initial: try: f = self.opts.get_field(k) except FieldDoesNotExist: continue # We have to special-case M2Ms as a list of comma-separated PKs. if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") return initial def _get_obj_does_not_exist_redirect(self, request, opts, object_id): """ Create a message informing the user that the object doesn't exist and return a redirect to the admin index page. """ msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % { "name": opts.verbose_name, "key": unquote(object_id), } self.message_user(request, msg, messages.WARNING) url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(url) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url="", extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context) def _changeform_view(self, request, object_id, form_url, extra_context): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) if request.method == "POST" and "_saveasnew" in request.POST: object_id = None add = object_id is None if add: if not self.has_add_permission(request): raise PermissionDenied obj = None else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == "POST": if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect( request, self.opts, object_id ) fieldsets = self.get_fieldsets(request, obj) ModelForm = self.get_form( request, obj, change=not add, fields=flatten_fieldsets(fieldsets) ) if request.method == "POST": form = ModelForm(request.POST, request.FILES, instance=obj) formsets, inline_instances = self._create_formsets( request, form.instance, change=not add, ) form_validated = form.is_valid() if form_validated: new_object = self.save_form(request, form, change=not add) else: new_object = form.instance if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, not add) self.save_related(request, form, formsets, not add) change_message = self.construct_change_message( request, form, formsets, add ) if add: self.log_addition(request, new_object, change_message) return self.response_add(request, new_object) else: self.log_change(request, new_object, change_message) return self.response_change(request, new_object) else: form_validated = False else: if add: initial = self.get_changeform_initial_data(request) form = ModelForm(initial=initial) formsets, inline_instances = self._create_formsets( request, form.instance, change=False ) else: form = ModelForm(instance=obj) formsets, inline_instances = self._create_formsets( request, obj, change=True ) if not add and not self.has_change_permission(request, obj): readonly_fields = flatten_fieldsets(fieldsets) else: readonly_fields = self.get_readonly_fields(request, obj) adminForm = helpers.AdminForm( form, list(fieldsets), # Clear prepopulated fields on a view-only form to avoid a crash. self.get_prepopulated_fields(request, obj) if add or self.has_change_permission(request, obj) else {}, readonly_fields, model_admin=self, ) media = self.media + adminForm.media inline_formsets = self.get_inline_formsets( request, formsets, inline_instances, obj ) for inline_formset in inline_formsets: media = media + inline_formset.media if add: title = _("Add %s") elif self.has_change_permission(request, obj): title = _("Change %s") else: title = _("View %s") context = { **self.admin_site.each_context(request), "title": title % self.opts.verbose_name, "subtitle": str(obj) if obj else None, "adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, "media": media, "inline_admin_formsets": inline_formsets, "errors": helpers.AdminErrorList(form, formsets), "preserved_filters": self.get_preserved_filters(request), } # Hide the "Save" and "Save and continue" buttons if "Save as New" was # previously chosen to prevent the interface from getting confusing. if ( request.method == "POST" and not form_validated and "_saveasnew" in request.POST ): context["show_save"] = False context["show_save_and_continue"] = False # Use the change template instead of the add template. add = False context.update(extra_context or {}) return self.render_change_form( request, context, add=add, change=not add, obj=obj, form_url=form_url ) def add_view(self, request, form_url="", extra_context=None): return self.changeform_view(request, None, form_url, extra_context) def change_view(self, request, object_id, form_url="", extra_context=None): return self.changeform_view(request, object_id, form_url, extra_context) def _get_edited_object_pks(self, request, prefix): """Return POST data values of list_editable primary keys.""" pk_pattern = re.compile( r"{}-\d+-{}$".format(re.escape(prefix), self.opts.pk.name) ) return [value for key, value in request.POST.items() if pk_pattern.match(key)] def _get_list_editable_queryset(self, request, prefix): """ Based on POST data, return a queryset of the objects that were edited via list_editable. """ object_pks = self._get_edited_object_pks(request, prefix) queryset = self.get_queryset(request) validate = queryset.model._meta.pk.to_python try: for pk in object_pks: validate(pk) except ValidationError: # Disable the optimization if the POST data was tampered with. return queryset return queryset.filter(pk__in=object_pks) @csrf_protect_m def changelist_view(self, request, extra_context=None): """ The 'change list' admin view for this model. """ from django.contrib.admin.views.main import ERROR_FLAG app_label = self.opts.app_label if not self.has_view_or_change_permission(request): raise PermissionDenied try: cl = self.get_changelist_instance(request) except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET: return SimpleTemplateResponse( "admin/invalid_setup.html", { "title": _("Database error"), }, ) return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1") # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this # isn't an action the POST will fall through to the bulk edit check, # below. action_failed = False selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) actions = self.get_actions(request) # Actions with no confirmation if ( actions and request.method == "POST" and "index" in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True else: msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) action_failed = True # Actions with confirmation if ( actions and request.method == "POST" and helpers.ACTION_CHECKBOX_NAME in request.POST and "index" not in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True if action_failed: # Redirect back to the changelist page to avoid resubmitting the # form if the user refreshes the browser or uses the "No, take # me back" button on the action confirmation page. return HttpResponseRedirect(request.get_full_path()) # If we're allowing changelist editing, we need to construct a formset # for the changelist given all the fields to be edited. Then we'll # use the formset to validate/process POSTed data. formset = cl.formset = None # Handle POSTed bulk-edit data. if request.method == "POST" and cl.list_editable and "_save" in request.POST: if not self.has_change_permission(request): raise PermissionDenied FormSet = self.get_changelist_formset(request) modified_objects = self._get_list_editable_queryset( request, FormSet.get_default_prefix() ) formset = cl.formset = FormSet( request.POST, request.FILES, queryset=modified_objects ) if formset.is_valid(): changecount = 0 for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) self.save_related(request, form, formsets=[], change=True) change_msg = self.construct_change_message(request, form, None) self.log_change(request, obj, change_msg) changecount += 1 if changecount: msg = ngettext( "%(count)s %(name)s was changed successfully.", "%(count)s %(name)s were changed successfully.", changecount, ) % { "count": changecount, "name": model_ngettext(self.opts, changecount), } self.message_user(request, msg, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) # Handle GET -- construct a formset for display. elif cl.list_editable and self.has_change_permission(request): FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. if formset: media = self.media + formset.media else: media = self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) media += action_form.media else: action_form = None selection_note_all = ngettext( "%(total_count)s selected", "All %(total_count)s selected", cl.result_count ) context = { **self.admin_site.each_context(request), "module_name": str(self.opts.verbose_name_plural), "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)}, "selection_note_all": selection_note_all % {"total_count": cl.result_count}, "title": cl.title, "subtitle": None, "is_popup": cl.is_popup, "to_field": cl.to_field, "cl": cl, "media": media, "has_add_permission": self.has_add_permission(request), "opts": cl.opts, "action_form": action_form, "actions_on_top": self.actions_on_top, "actions_on_bottom": self.actions_on_bottom, "actions_selection_counter": self.actions_selection_counter, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_list_template or [ "admin/%s/%s/change_list.html" % (app_label, self.opts.model_name), "admin/%s/change_list.html" % app_label, "admin/change_list.html", ], context, ) def get_deleted_objects(self, objs, request): """ Hook for customizing the delete process for the delete view and the "delete selected" action. """ return get_deleted_objects(objs, request, self.admin_site) @csrf_protect_m def delete_view(self, request, object_id, extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._delete_view(request, object_id, extra_context) def _delete_view(self, request, object_id, extra_context): "The 'delete' admin view for this model." app_label = self.opts.app_label to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) obj = self.get_object(request, unquote(object_id), to_field) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(request, self.opts, object_id) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. ( deleted_objects, model_count, perms_needed, protected, ) = self.get_deleted_objects([obj], request) if request.POST and not protected: # The user has confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = str(obj) attr = str(to_field) if to_field else self.opts.pk.attname obj_id = obj.serializable_value(attr) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) return self.response_delete(request, obj_display, obj_id) object_name = str(self.opts.verbose_name) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") context = { **self.admin_site.each_context(request), "title": title, "subtitle": None, "object_name": object_name, "object": obj, "deleted_objects": deleted_objects, "model_count": dict(model_count).items(), "perms_lacking": perms_needed, "protected": protected, "opts": self.opts, "app_label": app_label, "preserved_filters": self.get_preserved_filters(request), "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, **(extra_context or {}), } return self.render_delete_form(request, context) def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry from django.contrib.admin.views.main import PAGE_VAR # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: return self._get_obj_does_not_exist_redirect( request, model._meta, object_id ) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. app_label = self.opts.app_label action_list = ( LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model), ) .select_related() .order_by("action_time") ) paginator = self.get_paginator(request, action_list, 100) page_number = request.GET.get(PAGE_VAR, 1) page_obj = paginator.get_page(page_number) page_range = paginator.get_elided_page_range(page_obj.number) context = { **self.admin_site.each_context(request), "title": _("Change history: %s") % obj, "subtitle": None, "action_list": page_obj, "page_range": page_range, "page_var": PAGE_VAR, "pagination_required": paginator.count > 100, "module_name": str(capfirst(self.opts.verbose_name_plural)), "object": obj, "opts": self.opts, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, self.opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html", ], context, ) def get_formset_kwargs(self, request, obj, inline, prefix): formset_params = { "instance": obj, "prefix": prefix, "queryset": inline.get_queryset(request), } if request.method == "POST": formset_params.update( { "data": request.POST.copy(), "files": request.FILES, "save_as_new": "_saveasnew" in request.POST, } ) return formset_params def _create_formsets(self, request, obj, change): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = {} get_formsets_args = [request] if change: get_formsets_args.append(obj) for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = self.get_formset_kwargs(request, obj, inline, prefix) formset = FormSet(**formset_params) def user_deleted_form(request, obj, formset, index): """Return whether or not the user deleted the form.""" return ( inline.has_delete_permission(request, obj) and "{}-{}-DELETE".format(formset.prefix, index) in request.POST ) # Bypass validation of each view-only inline form (since the form's # data won't be in request.POST), unless the form was deleted. if not inline.has_change_permission(request, obj if change else None): for index, form in enumerate(formset.initial_forms): if user_deleted_form(request, obj, formset, index): continue form._errors = {} form.cleaned_data = form.initial formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseInlineFormSet extra = 3 min_num = None max_num = None template = None verbose_name = None verbose_name_plural = None can_delete = True show_change_link = False checks_class = InlineModelAdminChecks classes = None def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) super().__init__() if self.verbose_name_plural is None: if self.verbose_name is None: self.verbose_name_plural = self.opts.verbose_name_plural else: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) if self.verbose_name is None: self.verbose_name = self.opts.verbose_name @property def media(self): extra = "" if settings.DEBUG else ".min" js = ["vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "inlines.js"] if self.filter_vertical or self.filter_horizontal: js.extend(["SelectBox.js", "SelectFilter2.js"]) if self.classes and "collapse" in self.classes: js.append("collapse.js") return forms.Media(js=["admin/js/%s" % url for url in js]) def get_extra(self, request, obj=None, **kwargs): """Hook for customizing the number of extra inline forms.""" return self.extra def get_min_num(self, request, obj=None, **kwargs): """Hook for customizing the min number of inline forms.""" return self.min_num def get_max_num(self, request, obj=None, **kwargs): """Hook for customizing the max number of extra inline forms.""" return self.max_num def get_formset(self, request, obj=None, **kwargs): """Return a BaseInlineFormSet class for use in admin add/change views.""" if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) exclude.extend(self.get_readonly_fields(request, obj)) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # If exclude is an empty list we use None, since that's the actual # default. exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), "extra": self.get_extra(request, obj, **kwargs), "min_num": self.get_min_num(request, obj, **kwargs), "max_num": self.get_max_num(request, obj, **kwargs), "can_delete": can_delete, **kwargs, } base_model_form = defaults["form"] can_change = self.has_change_permission(request, obj) if request else True can_add = self.has_add_permission(request, obj) if request else True class DeleteProtectedModelForm(base_model_form): def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance._state.adding: return collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance # representation, suitable to be an item in a # list. _("%(class_name)s %(instance)s") % {"class_name": p._meta.verbose_name, "instance": p} ) params = { "class_name": self._meta.model._meta.verbose_name, "instance": self.instance, "related_objects": get_text_list(objs, _("and")), } msg = _( "Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s" ) raise ValidationError( msg, code="deleting_protected", params=params ) def is_valid(self): result = super().is_valid() self.hand_clean_DELETE() return result def has_changed(self): # Protect against unauthorized edits. if not can_change and not self.instance._state.adding: return False if not can_add and self.instance._state.adding: return False return super().has_changed() defaults["form"] = DeleteProtectedModelForm if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS return inlineformset_factory(self.parent_model, self.model, **defaults) def _get_form_for_get_fields(self, request, obj=None): return self.get_formset(request, obj, fields=None).form def get_queryset(self, request): queryset = super().get_queryset(request) if not self.has_view_or_change_permission(request): queryset = queryset.none() return queryset def _has_any_perms_for_target_model(self, request, perms): """ This method is called only when the ModelAdmin's model is for an ManyToManyField's implicit through model (if self.opts.auto_created). Return True if the user has any of the given permissions ('add', 'change', etc.) for the model that points to the through model. """ opts = self.opts # Find the target model of an auto-created many-to-many relationship. for field in opts.fields: if field.remote_field and field.remote_field.model != self.parent_model: opts = field.remote_field.model._meta break return any( request.user.has_perm( "%s.%s" % (opts.app_label, get_permission_codename(perm, opts)) ) for perm in perms ) def has_add_permission(self, request, obj): if self.opts.auto_created: # Auto-created intermediate models don't have their own # permissions. The user needs to have the change permission for the # related model in order to be able to do anything with the # intermediate model. return self._has_any_perms_for_target_model(request, ["change"]) return super().has_add_permission(request) def has_change_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_change_permission(request) def has_delete_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_delete_permission(request, obj) def has_view_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). The 'change' permission # also implies the 'view' permission. return self._has_any_perms_for_target_model(request, ["view", "change"]) return super().has_view_permission(request) class StackedInline(InlineModelAdmin): template = "admin/edit_inline/stacked.html" class TabularInline(InlineModelAdmin): template = "admin/edit_inline/tabular.html"
1703f879042681e23e2149ab250757cf03aa68d8a788a00a119c52cb13c864e8
from urllib.parse import urlparse from urllib.request import url2pathname from asgiref.sync import sync_to_async from django.conf import settings from django.contrib.staticfiles import utils from django.contrib.staticfiles.views import serve from django.core.handlers.asgi import ASGIHandler from django.core.handlers.exception import response_for_exception from django.core.handlers.wsgi import WSGIHandler, get_path_info from django.http import Http404 class StaticFilesHandlerMixin: """ Common methods used by WSGI and ASGI handlers. """ # May be used to differentiate between handler types (e.g. in a # request_finished signal) handles_files = True def load_middleware(self): # Middleware are already loaded for self.application; no need to reload # them for self. pass def get_base_url(self): utils.check_settings() return settings.STATIC_URL def _should_handle(self, path): """ Check if the path should be handled. Ignore the path if: * the host is provided as part of the base_url * the request's path isn't under the media path (or equal) """ return path.startswith(self.base_url[2]) and not self.base_url[1] def file_path(self, url): """ Return the relative path to the media file on disk for the given URL. """ relative_url = url[len(self.base_url[2]) :] return url2pathname(relative_url) def serve(self, request): """Serve the request path.""" return serve(request, self.file_path(request.path), insecure=True) def get_response(self, request): try: return self.serve(request) except Http404 as e: return response_for_exception(request, e) async def get_response_async(self, request): try: return await sync_to_async(self.serve, thread_sensitive=False)(request) except Http404 as e: return await sync_to_async(response_for_exception, thread_sensitive=False)( request, e ) class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler): """ WSGI middleware that intercepts calls to the static files directory, as defined by the STATIC_URL setting, and serves those files. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super().__init__() def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) return super().__call__(environ, start_response) class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler): """ ASGI application which wraps another and intercepts requests for static files, passing them off to Django's static file serving. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) async def __call__(self, scope, receive, send): # Only even look at HTTP requests if scope["type"] == "http" and self._should_handle(scope["path"]): # Serve static content # (the one thing super() doesn't do is __call__, apparently) return await super().__call__(scope, receive, send) # Hand off to the main app return await self.application(scope, receive, send) async def get_response_async(self, request): response = await super().get_response_async(request) response._resource_closers.append(request.close) return response
4f5cbe74182ce6b8a2570288c84e9237688fb0aedab93bca071a76c1c83ebb59
import json import os import posixpath import re from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit from django.conf import settings from django.contrib.staticfiles.utils import check_settings, matches_patterns from django.core.exceptions import ImproperlyConfigured from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage, get_storage_class from django.utils.crypto import md5 from django.utils.functional import LazyObject class StaticFilesStorage(FileSystemStorage): """ Standard file system storage for static files. The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. """ def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: self.base_location = None self.location = None def path(self, name): if not self.location: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path." ) return super().path(name) class HashedFilesMixin: default_template = """url("%(url)s")""" max_post_process_passes = 5 patterns = ( ( "*.css", ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", ( r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""", """@import url("%(url)s")""", ), ( ( r"(?m)(?P<matched>)^(/\*#[ \t]" r"(?-i:sourceMappingURL)=(?P<url>.*)[ \t]*\*/)$" ), "/*# sourceMappingURL=%(url)s */", ), ), ), ( "*.js", ( ( r"(?m)(?P<matched>)^(//# (?-i:sourceMappingURL)=(?P<url>.*))$", "//# sourceMappingURL=%(url)s", ), ), ), ) keep_intermediate_files = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._patterns = {} self.hashed_files = {} for extension, patterns in self.patterns: for pattern in patterns: if isinstance(pattern, (tuple, list)): pattern, template = pattern else: template = self.default_template compiled = re.compile(pattern, re.IGNORECASE) self._patterns.setdefault(extension, []).append((compiled, template)) def file_hash(self, name, content=None): """ Return a hash of the file with the given name and optional content. """ if content is None: return None hasher = md5(usedforsecurity=False) for chunk in content.chunks(): hasher.update(chunk) return hasher.hexdigest()[:12] def hashed_name(self, name, content=None, filename=None): # `filename` is the name of file to hash if `content` isn't given. # `name` is the base name to construct the new hashed filename from. parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name opened = content is None if opened: if not self.exists(filename): raise ValueError( "The file '%s' could not be found with %r." % (filename, self) ) try: content = self.open(filename) except OSError: # Handle directory paths and fragments return name try: file_hash = self.file_hash(clean_name, content) finally: if opened: content.close() path, filename = os.path.split(clean_name) root, ext = os.path.splitext(filename) file_hash = (".%s" % file_hash) if file_hash else "" hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) def _url(self, hashed_name_func, name, force=False, hashed_files=None): """ Return the non-hashed URL in DEBUG mode. """ if settings.DEBUG and not force: hashed_name, fragment = name, "" else: clean_name, fragment = urldefrag(name) if urlsplit(clean_name).path.endswith("/"): # don't hash paths hashed_name = name else: args = (clean_name,) if hashed_files is not None: args += (hashed_files,) hashed_name = hashed_name_func(*args) final_url = super().url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax query_fragment = "?#" in name # [sic!] if fragment or query_fragment: urlparts = list(urlsplit(final_url)) if fragment and not urlparts[4]: urlparts[4] = fragment if query_fragment and not urlparts[3]: urlparts[2] += "?" final_url = urlunsplit(urlparts) return unquote(final_url) def url(self, name, force=False): """ Return the non-hashed URL in DEBUG mode. """ return self._url(self.stored_name, name, force) def url_converter(self, name, hashed_files, template=None): """ Return the custom URL converter for the given file name. """ if template is None: template = self.default_template def converter(matchobj): """ Convert the matched URL to a normalized and hashed URL. This requires figuring out which files the matched URL resolves to and calling the url() method of the storage. """ matches = matchobj.groupdict() matched = matches["matched"] url = matches["url"] # Ignore absolute/protocol-relative and data-uri URLs. if re.match(r"^[a-z]+:", url): return matched # Ignore absolute URLs that don't point to a static file (dynamic # CSS / JS?). Note that STATIC_URL cannot be empty. if url.startswith("/") and not url.startswith(settings.STATIC_URL): return matched # Strip off the fragment so a path-like fragment won't interfere. url_path, fragment = urldefrag(url) # Ignore URLs without a path if not url_path: return matched if url_path.startswith("/"): # Otherwise the condition above would have returned prematurely. assert url_path.startswith(settings.STATIC_URL) target_name = url_path[len(settings.STATIC_URL) :] else: # We're using the posixpath module to mix paths and URLs conveniently. source_name = name if os.sep == "/" else name.replace(os.sep, "/") target_name = posixpath.join(posixpath.dirname(source_name), url_path) # Determine the hashed name of the target file with the storage backend. hashed_url = self._url( self._stored_name, unquote(target_name), force=True, hashed_files=hashed_files, ) transformed_url = "/".join( url_path.split("/")[:-1] + hashed_url.split("/")[-1:] ) # Restore the fragment that was stripped off earlier. if fragment: transformed_url += ("?#" if "?#" in url else "#") + fragment # Return the hashed version to the file matches["url"] = unquote(transformed_url) return template % matches return converter def post_process(self, paths, dry_run=False, **options): """ Post process the given dictionary of files (called from collectstatic). Processing is actually two separate operations: 1. renaming files to include a hash of their content for cache-busting, and copying those files to the target storage. 2. adjusting files which contain references to other files so they refer to the cache-busting filenames. If either of these are performed on a file, then that file is considered post-processed. """ # don't even dare to process the files if we're in dry run mode if dry_run: return # where to store the new paths hashed_files = {} # build a list of adjustable files adjustable_paths = [ path for path in paths if matches_patterns(path, self._patterns) ] # Adjustable files to yield at end, keyed by the original path. processed_adjustable_paths = {} # Do a single pass first. Post-process all files once, yielding not # adjustable files and exceptions, and collecting adjustable files. for name, hashed_name, processed, _ in self._post_process( paths, adjustable_paths, hashed_files ): if name not in adjustable_paths or isinstance(processed, Exception): yield name, hashed_name, processed else: processed_adjustable_paths[name] = (name, hashed_name, processed) paths = {path: paths[path] for path in adjustable_paths} substitutions = False for i in range(self.max_post_process_passes): substitutions = False for name, hashed_name, processed, subst in self._post_process( paths, adjustable_paths, hashed_files ): # Overwrite since hashed_name may be newer. processed_adjustable_paths[name] = (name, hashed_name, processed) substitutions = substitutions or subst if not substitutions: break if substitutions: yield "All", None, RuntimeError("Max post-process passes exceeded.") # Store the processed paths self.hashed_files.update(hashed_files) # Yield adjustable files with final, hashed name. yield from processed_adjustable_paths.values() def _post_process(self, paths, adjustable_paths, hashed_files): # Sort the files by directory level def path_level(name): return len(name.split(os.sep)) for name in sorted(paths, key=path_level, reverse=True): substitutions = True # use the original, local file, not the copied-but-unprocessed # file, which might be somewhere far away, like S3 storage, path = paths[name] with storage.open(path) as original_file: cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) # generate the hash with the original content, even for # adjustable files. if hash_key not in hashed_files: hashed_name = self.hashed_name(name, original_file) else: hashed_name = hashed_files[hash_key] # then get the original's file content.. if hasattr(original_file, "seek"): original_file.seek(0) hashed_file_exists = self.exists(hashed_name) processed = False # ..to apply each replacement pattern to the content if name in adjustable_paths: old_hashed_name = hashed_name content = original_file.read().decode("utf-8") for extension, patterns in self._patterns.items(): if matches_patterns(path, (extension,)): for pattern, template in patterns: converter = self.url_converter( name, hashed_files, template ) try: content = pattern.sub(converter, content) except ValueError as exc: yield name, None, exc, False if hashed_file_exists: self.delete(hashed_name) # then save the processed result content_file = ContentFile(content.encode()) if self.keep_intermediate_files: # Save intermediate file for reference self._save(hashed_name, content_file) hashed_name = self.hashed_name(name, content_file) if self.exists(hashed_name): self.delete(hashed_name) saved_name = self._save(hashed_name, content_file) hashed_name = self.clean_name(saved_name) # If the file hash stayed the same, this file didn't change if old_hashed_name == hashed_name: substitutions = False processed = True if not processed: # or handle the case in which neither processing nor # a change to the original file happened if not hashed_file_exists: processed = True saved_name = self._save(hashed_name, original_file) hashed_name = self.clean_name(saved_name) # and then set the cache accordingly hashed_files[hash_key] = hashed_name yield name, hashed_name, processed, substitutions def clean_name(self, name): return name.replace("\\", "/") def hash_key(self, name): return name def _stored_name(self, name, hashed_files): # Normalize the path to avoid multiple names for the same file like # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same # path. name = posixpath.normpath(name) cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = hashed_files.get(hash_key) if cache_name is None: cache_name = self.clean_name(self.hashed_name(name)) return cache_name def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = self.hashed_files.get(hash_key) if cache_name: return cache_name # No cached name found, recalculate it from the files. intermediate_name = name for i in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) if intermediate_name == cache_name: # Store the hashed name if there was a miss. self.hashed_files[hash_key] = cache_name return cache_name else: # Move on to the next intermediate file. intermediate_name = cache_name # If the cache name can't be determined after the max number of passes, # the intermediate files on disk may be corrupt; avoid an infinite loop. raise ValueError("The name '%s' could not be hashed with %r." % (name, self)) class ManifestFilesMixin(HashedFilesMixin): manifest_version = "1.0" # the manifest format standard manifest_name = "staticfiles.json" manifest_strict = True keep_intermediate_files = False def __init__(self, *args, manifest_storage=None, **kwargs): super().__init__(*args, **kwargs) if manifest_storage is None: manifest_storage = self self.manifest_storage = manifest_storage self.hashed_files = self.load_manifest() def read_manifest(self): try: with self.manifest_storage.open(self.manifest_name) as manifest: return manifest.read().decode() except FileNotFoundError: return None def load_manifest(self): content = self.read_manifest() if content is None: return {} try: stored = json.loads(content) except json.JSONDecodeError: pass else: version = stored.get("version") if version == "1.0": return stored.get("paths", {}) raise ValueError( "Couldn't load manifest '%s' (version %s)" % (self.manifest_name, self.manifest_version) ) def post_process(self, *args, **kwargs): self.hashed_files = {} yield from super().post_process(*args, **kwargs) if not kwargs.get("dry_run"): self.save_manifest() def save_manifest(self): payload = {"paths": self.hashed_files, "version": self.manifest_version} if self.manifest_storage.exists(self.manifest_name): self.manifest_storage.delete(self.manifest_name) contents = json.dumps(payload).encode() self.manifest_storage._save(self.manifest_name, ContentFile(contents)) def stored_name(self, name): parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() hash_key = self.hash_key(clean_name) cache_name = self.hashed_files.get(hash_key) if cache_name is None: if self.manifest_strict: raise ValueError( "Missing staticfiles manifest entry for '%s'" % clean_name ) cache_name = self.clean_name(self.hashed_name(name)) unparsed_name = list(parsed_name) unparsed_name[2] = cache_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage): """ A static file system storage backend which also saves hashed copies of the files it saves. """ pass class ConfiguredStorage(LazyObject): def _setup(self): self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() staticfiles_storage = ConfiguredStorage()
960c09d3187e9a3315c098bf5291c7ecc4cab631ffeedc484322c6f86d82e3e0
import json from django.contrib.gis.gdal import CoordTransform, SpatialReference from django.core.serializers.base import SerializerDoesNotExist from django.core.serializers.json import Serializer as JSONSerializer class Serializer(JSONSerializer): """ Convert a queryset to GeoJSON, http://geojson.org/ """ def _init_options(self): super()._init_options() self.geometry_field = self.json_kwargs.pop("geometry_field", None) self.id_field = self.json_kwargs.pop("id_field", None) self.srid = self.json_kwargs.pop("srid", 4326) if ( self.selected_fields is not None and self.geometry_field is not None and self.geometry_field not in self.selected_fields ): self.selected_fields = [*self.selected_fields, self.geometry_field] def start_serialization(self): self._init_options() self._cts = {} # cache of CoordTransform's self.stream.write( '{"type": "FeatureCollection", ' '"crs": {"type": "name", "properties": {"name": "EPSG:%d"}},' ' "features": [' % self.srid ) def end_serialization(self): self.stream.write("]}") def start_object(self, obj): super().start_object(obj) self._geometry = None if self.geometry_field is None: # Find the first declared geometry field for field in obj._meta.fields: if hasattr(field, "geom_type"): self.geometry_field = field.name break def get_dump_object(self, obj): data = { "type": "Feature", "id": obj.pk if self.id_field is None else getattr(obj, self.id_field), "properties": self._current, } if ( self.selected_fields is None or "pk" in self.selected_fields ) and "pk" not in data["properties"]: data["properties"]["pk"] = obj._meta.pk.value_to_string(obj) if self._geometry: if self._geometry.srid != self.srid: # If needed, transform the geometry in the srid of the global # geojson srid. if self._geometry.srid not in self._cts: srs = SpatialReference(self.srid) self._cts[self._geometry.srid] = CoordTransform( self._geometry.srs, srs ) self._geometry.transform(self._cts[self._geometry.srid]) data["geometry"] = json.loads(self._geometry.geojson) else: data["geometry"] = None return data def handle_field(self, obj, field): if field.name == self.geometry_field: self._geometry = field.value_from_object(obj) else: super().handle_field(obj, field) class Deserializer: def __init__(self, *args, **kwargs): raise SerializerDoesNotExist("geojson is a serialization-only serializer")
1df6dcb86779569eb083031f3f6f90f07f8823ac95141d36bdec1ea6ddb33cf1
import logging import os import re from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int from ctypes.util import find_library from django.contrib.gis.gdal.error import GDALException from django.core.exceptions import ImproperlyConfigured logger = logging.getLogger("django.contrib.gis") # Custom library path set? try: from django.conf import settings lib_path = settings.GDAL_LIBRARY_PATH except (AttributeError, ImportError, ImproperlyConfigured, OSError): lib_path = None if lib_path: lib_names = None elif os.name == "nt": # Windows NT shared libraries lib_names = [ "gdal305", "gdal304", "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", ] elif os.name == "posix": # *NIX library names. lib_names = [ "gdal", "GDAL", "gdal3.5.0", "gdal3.4.0", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", ] else: raise ImproperlyConfigured('GDAL is unsupported on OS "%s".' % os.name) # Using the ctypes `find_library` utility to find the # path to the GDAL library from the list of library names. if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if lib_path is not None: break if lib_path is None: raise ImproperlyConfigured( 'Could not find the GDAL library (tried "%s"). Is GDAL installed? ' "If it is, try setting GDAL_LIBRARY_PATH in your settings." % '", "'.join(lib_names) ) # This loads the GDAL/OGR C library lgdal = CDLL(lib_path) # On Windows, the GDAL binaries have some OSR routines exported with # STDCALL, while others are not. Thus, the library will also need to # be loaded up as WinDLL for said OSR functions that require the # different calling convention. if os.name == "nt": from ctypes import WinDLL lwingdal = WinDLL(lib_path) def std_call(func): """ Return the correct STDCALL function for certain OSR routines on Win32 platforms. """ if os.name == "nt": return lwingdal[func] else: return lgdal[func] # #### Version-information functions. #### # Return GDAL library version information with the given key. _version_info = std_call("GDALVersionInfo") _version_info.argtypes = [c_char_p] _version_info.restype = c_char_p def gdal_version(): "Return only the GDAL version number information." return _version_info(b"RELEASE_NAME") def gdal_full_version(): "Return the full GDAL version information." return _version_info(b"") def gdal_version_info(): ver = gdal_version() m = re.match(rb"^(?P<major>\d+)\.(?P<minor>\d+)(?:\.(?P<subminor>\d+))?", ver) if not m: raise GDALException('Could not parse GDAL version string "%s"' % ver) major, minor, subminor = m.groups() return (int(major), int(minor), subminor and int(subminor)) GDAL_VERSION = gdal_version_info() # Set library error handling so as errors are logged CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p) def err_handler(error_class, error_number, message): logger.error("GDAL_ERROR %d: %s", error_number, message) err_handler = CPLErrorHandler(err_handler) def function(name, args, restype): func = std_call(name) func.argtypes = args func.restype = restype return func set_error_handler = function("CPLSetErrorHandler", [CPLErrorHandler], CPLErrorHandler) set_error_handler(err_handler)
046919c95a92434549d652fe4add6ea906596d24bff5075d6fd0484beebe02f0
""" This object provides quoting for GEOS geometries into PostgreSQL/PostGIS. """ from psycopg2 import Binary from psycopg2.extensions import ISQLQuote from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster from django.contrib.gis.geos import GEOSGeometry class PostGISAdapter: def __init__(self, obj, geography=False): """ Initialize on the spatial object. """ self.is_geometry = isinstance(obj, (GEOSGeometry, PostGISAdapter)) # Getting the WKB (in string form, to allow easy pickling of # the adaptor) and the SRID from the geometry or raster. if self.is_geometry: self.ewkb = bytes(obj.ewkb) self._adapter = Binary(self.ewkb) else: self.ewkb = to_pgraster(obj) self.srid = obj.srid self.geography = geography def __conform__(self, proto): """Does the given protocol conform to what Psycopg2 expects?""" if proto == ISQLQuote: return self else: raise Exception( "Error implementing psycopg2 protocol. Is psycopg2 installed?" ) def __eq__(self, other): return isinstance(other, PostGISAdapter) and self.ewkb == other.ewkb def __hash__(self): return hash(self.ewkb) def __str__(self): return self.getquoted().decode() @classmethod def _fix_polygon(cls, poly): return poly def prepare(self, conn): """ This method allows escaping the binary in the style required by the server's `standard_conforming_string` setting. """ if self.is_geometry: self._adapter.prepare(conn) def getquoted(self): """ Return a properly quoted string for use in PostgreSQL/PostGIS. """ if self.is_geometry: # Psycopg will figure out whether to use E'\\000' or '\000'. return b"%s(%s)" % ( b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB", self._adapter.getquoted(), ) else: # For rasters, add explicit type cast to WKB string. return b"'%s'::raster" % self.ewkb.encode()
310b12d9b86bf72d34957a0b8f8144002a8875d7b6e4119636176c78b2ab2fd3
import datetime import importlib import io import os import shutil import sys from unittest import mock from django.apps import apps from django.core.management import CommandError, call_command from django.db import ( ConnectionHandler, DatabaseError, OperationalError, connection, connections, models, ) from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.utils import truncate_name from django.db.migrations.exceptions import InconsistentMigrationHistory from django.db.migrations.recorder import MigrationRecorder from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.utils import captured_stdout from django.utils import timezone from django.utils.version import get_docs_version from .models import UnicodeModel, UnserializableModel from .routers import TestRouter from .test_base import MigrationTestBase HAS_BLACK = shutil.which("black") class MigrateTests(MigrationTestBase): """ Tests running the migrate command. """ databases = {"default", "other"} @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_migrate(self): """ Tests basic usage of the migrate command. """ # No tables are created self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") # Run the migrations to 0001 only stdout = io.StringIO() call_command( "migrate", "migrations", "0001", verbosity=2, stdout=stdout, no_color=True ) stdout = stdout.getvalue() self.assertIn( "Target specific migration: 0001_initial, from migrations", stdout ) self.assertIn("Applying migrations.0001_initial... OK", stdout) self.assertIn("Running pre-migrate handlers for application migrations", stdout) self.assertIn( "Running post-migrate handlers for application migrations", stdout ) # The correct tables exist self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") self.assertTableNotExists("migrations_book") # Run migrations all the way call_command("migrate", verbosity=0) # The correct tables exist self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableExists("migrations_book") # Unmigrate everything stdout = io.StringIO() call_command( "migrate", "migrations", "zero", verbosity=2, stdout=stdout, no_color=True ) stdout = stdout.getvalue() self.assertIn("Unapply all migrations: migrations", stdout) self.assertIn("Unapplying migrations.0002_second... OK", stdout) self.assertIn("Running pre-migrate handlers for application migrations", stdout) self.assertIn( "Running post-migrate handlers for application migrations", stdout ) # Tables are gone self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "migrations.migrations_test_apps.migrated_app", ] ) def test_migrate_with_system_checks(self): out = io.StringIO() call_command("migrate", skip_checks=False, no_color=True, stdout=out) self.assertIn("Apply all migrations: migrated_app", out.getvalue()) @override_settings( INSTALLED_APPS=[ "migrations", "migrations.migrations_test_apps.unmigrated_app_syncdb", ] ) def test_app_without_migrations(self): msg = "App 'unmigrated_app_syncdb' does not have migrations." with self.assertRaisesMessage(CommandError, msg): call_command("migrate", app_label="unmigrated_app_syncdb") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_clashing_prefix"} ) def test_ambiguous_prefix(self): msg = ( "More than one migration matches 'a' in app 'migrations'. Please " "be more specific." ) with self.assertRaisesMessage(CommandError, msg): call_command("migrate", app_label="migrations", migration_name="a") @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_unknown_prefix(self): msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'." with self.assertRaisesMessage(CommandError, msg): call_command( "migrate", app_label="migrations", migration_name="nonexistent" ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"} ) def test_migrate_initial_false(self): """ `Migration.initial = False` skips fake-initial detection. """ # Make sure no tables are created self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Run the migrations to 0001 only call_command("migrate", "migrations", "0001", verbosity=0) # Fake rollback call_command("migrate", "migrations", "zero", fake=True, verbosity=0) # Make sure fake-initial detection does not run with self.assertRaises(DatabaseError): call_command( "migrate", "migrations", "0001", fake_initial=True, verbosity=0 ) call_command("migrate", "migrations", "0001", fake=True, verbosity=0) # Real rollback call_command("migrate", "migrations", "zero", verbosity=0) # Make sure it's all gone self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations"}, DATABASE_ROUTERS=["migrations.routers.TestRouter"], ) def test_migrate_fake_initial(self): """ --fake-initial only works if all tables created in the initial migration of an app exists. Database routers must be obeyed when doing that check. """ # Make sure no tables are created for db in self.databases: self.assertTableNotExists("migrations_author", using=db) self.assertTableNotExists("migrations_tribble", using=db) # Run the migrations to 0001 only call_command("migrate", "migrations", "0001", verbosity=0) call_command("migrate", "migrations", "0001", verbosity=0, database="other") # Make sure the right tables exist self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Also check the "other" database self.assertTableNotExists("migrations_author", using="other") self.assertTableExists("migrations_tribble", using="other") # Fake a roll-back call_command("migrate", "migrations", "zero", fake=True, verbosity=0) call_command( "migrate", "migrations", "zero", fake=True, verbosity=0, database="other" ) # Make sure the tables still exist self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble", using="other") # Try to run initial migration with self.assertRaises(DatabaseError): call_command("migrate", "migrations", "0001", verbosity=0) # Run initial migration with an explicit --fake-initial out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: False ): call_command( "migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1, ) call_command( "migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other", ) self.assertIn("migrations.0001_initial... faked", out.getvalue().lower()) try: # Run migrations all the way. call_command("migrate", verbosity=0) call_command("migrate", verbosity=0, database="other") self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableExists("migrations_book") self.assertTableNotExists("migrations_author", using="other") self.assertTableNotExists("migrations_tribble", using="other") self.assertTableNotExists("migrations_book", using="other") # Fake a roll-back. call_command("migrate", "migrations", "zero", fake=True, verbosity=0) call_command( "migrate", "migrations", "zero", fake=True, verbosity=0, database="other", ) self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableExists("migrations_book") # Run initial migration. with self.assertRaises(DatabaseError): call_command("migrate", "migrations", verbosity=0) # Run initial migration with an explicit --fake-initial. with self.assertRaises(DatabaseError): # Fails because "migrations_tribble" does not exist but needs # to in order to make --fake-initial work. call_command("migrate", "migrations", fake_initial=True, verbosity=0) # Fake an apply. call_command("migrate", "migrations", fake=True, verbosity=0) call_command( "migrate", "migrations", fake=True, verbosity=0, database="other" ) finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) call_command("migrate", "migrations", "zero", verbosity=0, database="other") # Make sure it's all gone for db in self.databases: self.assertTableNotExists("migrations_author", using=db) self.assertTableNotExists("migrations_tribble", using=db) self.assertTableNotExists("migrations_book", using=db) @skipUnlessDBFeature("ignores_table_name_case") def test_migrate_fake_initial_case_insensitive(self): with override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_fake_initial_case_insensitive.initial", } ): call_command("migrate", "migrations", "0001", verbosity=0) call_command("migrate", "migrations", "zero", fake=True, verbosity=0) with override_settings( MIGRATION_MODULES={ "migrations": ( "migrations.test_fake_initial_case_insensitive.fake_initial" ), } ): out = io.StringIO() call_command( "migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1, no_color=True, ) self.assertIn( "migrations.0001_initial... faked", out.getvalue().lower(), ) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_fake_split_initial" } ) def test_migrate_fake_split_initial(self): """ Split initial migrations can be faked with --fake-initial. """ try: call_command("migrate", "migrations", "0002", verbosity=0) call_command("migrate", "migrations", "zero", fake=True, verbosity=0) out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: False ): call_command( "migrate", "migrations", "0002", fake_initial=True, stdout=out, verbosity=1, ) value = out.getvalue().lower() self.assertIn("migrations.0001_initial... faked", value) self.assertIn("migrations.0002_second... faked", value) finally: # Fake an apply. call_command("migrate", "migrations", fake=True, verbosity=0) # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"} ) def test_migrate_conflict_exit(self): """ migrate exits if it detects a conflict. """ msg = ( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (0002_conflicting_second, 0002_second in " "migrations).\n" "To fix them run 'python manage.py makemigrations --merge'" ) with self.assertRaisesMessage(CommandError, msg): call_command("migrate", "migrations") @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations", } ) def test_migrate_check(self): with self.assertRaises(SystemExit): call_command("migrate", "migrations", "0001", check_unapplied=True) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_plan", } ) def test_migrate_check_plan(self): out = io.StringIO() with self.assertRaises(SystemExit): call_command( "migrate", "migrations", "0001", check_unapplied=True, plan=True, stdout=out, no_color=True, ) self.assertEqual( "Planned operations:\n" "migrations.0001_initial\n" " Create model Salamander\n" " Raw Python operation -> Grow salamander tail.\n", out.getvalue(), ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_showmigrations_list(self): """ showmigrations --list displays migrations and whether or not they're applied. """ out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: True ): call_command( "showmigrations", format="list", stdout=out, verbosity=0, no_color=False ) self.assertEqual( "\x1b[1mmigrations\n\x1b[0m [ ] 0001_initial\n [ ] 0002_second\n", out.getvalue().lower(), ) call_command("migrate", "migrations", "0001", verbosity=0) out = io.StringIO() # Giving the explicit app_label tests for selective `show_list` in the command call_command( "showmigrations", "migrations", format="list", stdout=out, verbosity=0, no_color=True, ) self.assertEqual( "migrations\n [x] 0001_initial\n [ ] 0002_second\n", out.getvalue().lower() ) out = io.StringIO() # Applied datetimes are displayed at verbosity 2+. call_command( "showmigrations", "migrations", stdout=out, verbosity=2, no_color=True ) migration1 = MigrationRecorder(connection).migration_qs.get( app="migrations", name="0001_initial" ) self.assertEqual( "migrations\n" " [x] 0001_initial (applied at %s)\n" " [ ] 0002_second\n" % migration1.applied.strftime("%Y-%m-%d %H:%M:%S"), out.getvalue().lower(), ) # Cleanup by unmigrating everything call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_showmigrations_list_squashed(self): out = io.StringIO() call_command( "showmigrations", format="list", stdout=out, verbosity=2, no_color=True ) self.assertEqual( "migrations\n [ ] 0001_squashed_0002 (2 squashed migrations)\n", out.getvalue().lower(), ) out = io.StringIO() call_command( "migrate", "migrations", "0001_squashed_0002", stdout=out, verbosity=2, no_color=True, ) try: self.assertIn( "operations to perform:\n" " target specific migration: 0001_squashed_0002, from migrations\n" "running pre-migrate handlers for application migrations\n" "running migrations:\n" " applying migrations.0001_squashed_0002... ok (", out.getvalue().lower(), ) out = io.StringIO() call_command( "showmigrations", format="list", stdout=out, verbosity=2, no_color=True ) self.assertEqual( "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n", out.getvalue().lower(), ) finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"} ) def test_showmigrations_plan(self): """ Tests --plan output of showmigrations command """ out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[ ] migrations.0001_initial\n" "[ ] migrations.0003_third\n" "[ ] migrations.0002_second\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[ ] migrations.0001_initial\n" "[ ] migrations.0003_third ... (migrations.0001_initial)\n" "[ ] migrations.0002_second ... (migrations.0001_initial, " "migrations.0003_third)\n", out.getvalue().lower(), ) call_command("migrate", "migrations", "0003", verbosity=0) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[x] migrations.0001_initial\n" "[x] migrations.0003_third\n" "[ ] migrations.0002_second\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[x] migrations.0001_initial\n" "[x] migrations.0003_third ... (migrations.0001_initial)\n" "[ ] migrations.0002_second ... (migrations.0001_initial, " "migrations.0003_third)\n", out.getvalue().lower(), ) # Cleanup by unmigrating everything call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_plan"} ) def test_migrate_plan(self): """Tests migrate --plan output.""" out = io.StringIO() # Show the plan up to the third migration. call_command( "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0001_initial\n" " Create model Salamander\n" " Raw Python operation -> Grow salamander tail.\n" "migrations.0002_second\n" " Create model Book\n" " Raw SQL operation -> ['SELECT * FROM migrations_book']\n" "migrations.0003_third\n" " Create model Author\n" " Raw SQL operation -> ['SELECT * FROM migrations_author']\n", out.getvalue(), ) try: # Migrate to the third migration. call_command("migrate", "migrations", "0003", verbosity=0) out = io.StringIO() # Show the plan for when there is nothing to apply. call_command( "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n No planned migration operations.\n", out.getvalue(), ) out = io.StringIO() # Show the plan for reverse migration back to 0001. call_command( "migrate", "migrations", "0001", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0003_third\n" " Undo Create model Author\n" " Raw SQL operation -> ['SELECT * FROM migrations_book']\n" "migrations.0002_second\n" " Undo Create model Book\n" " Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n", out.getvalue(), ) out = io.StringIO() # Show the migration plan to fourth, with truncated details. call_command( "migrate", "migrations", "0004", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0004_fourth\n" " Raw SQL operation -> SELECT * FROM migrations_author WHE…\n", out.getvalue(), ) # Show the plan when an operation is irreversible. # Migrate to the fourth migration. call_command("migrate", "migrations", "0004", verbosity=0) out = io.StringIO() call_command( "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0004_fourth\n" " Raw SQL operation -> IRREVERSIBLE\n", out.getvalue(), ) out = io.StringIO() call_command( "migrate", "migrations", "0005", plan=True, stdout=out, no_color=True ) # Operation is marked as irreversible only in the revert plan. self.assertEqual( "Planned operations:\n" "migrations.0005_fifth\n" " Raw Python operation\n" " Raw Python operation\n" " Raw Python operation -> Feed salamander.\n", out.getvalue(), ) call_command("migrate", "migrations", "0005", verbosity=0) out = io.StringIO() call_command( "migrate", "migrations", "0004", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0005_fifth\n" " Raw Python operation -> IRREVERSIBLE\n" " Raw Python operation -> IRREVERSIBLE\n" " Raw Python operation\n", out.getvalue(), ) finally: # Cleanup by unmigrating everything: fake the irreversible, then # migrate all to zero. call_command("migrate", "migrations", "0003", fake=True, verbosity=0) call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"} ) def test_showmigrations_no_migrations(self): out = io.StringIO() call_command("showmigrations", stdout=out, no_color=True) self.assertEqual("migrations\n (no migrations)\n", out.getvalue().lower()) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app"] ) def test_showmigrations_unmigrated_app(self): out = io.StringIO() call_command("showmigrations", "unmigrated_app", stdout=out, no_color=True) try: self.assertEqual( "unmigrated_app\n (no migrations)\n", out.getvalue().lower() ) finally: # unmigrated_app.SillyModel has a foreign key to # 'migrations.Tribble', but that model is only defined in a # migration, so the global app registry never sees it and the # reference is left dangling. Remove it to avoid problems in # subsequent tests. apps._pending_operations.pop(("migrations", "tribble"), None) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"} ) def test_showmigrations_plan_no_migrations(self): """ Tests --plan output of showmigrations command without migrations """ out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, no_color=True) self.assertEqual("(no migrations)\n", out.getvalue().lower()) out = io.StringIO() call_command( "showmigrations", format="plan", stdout=out, verbosity=2, no_color=True ) self.assertEqual("(no migrations)\n", out.getvalue().lower()) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"} ) def test_showmigrations_plan_squashed(self): """ Tests --plan output of showmigrations command with squashed migrations. """ out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[ ] migrations.1_auto\n" "[ ] migrations.2_auto\n" "[ ] migrations.3_squashed_5\n" "[ ] migrations.6_auto\n" "[ ] migrations.7_auto\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[ ] migrations.1_auto\n" "[ ] migrations.2_auto ... (migrations.1_auto)\n" "[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n" "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n" "[ ] migrations.7_auto ... (migrations.6_auto)\n", out.getvalue().lower(), ) call_command("migrate", "migrations", "3_squashed_5", verbosity=0) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[x] migrations.1_auto\n" "[x] migrations.2_auto\n" "[x] migrations.3_squashed_5\n" "[ ] migrations.6_auto\n" "[ ] migrations.7_auto\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[x] migrations.1_auto\n" "[x] migrations.2_auto ... (migrations.1_auto)\n" "[x] migrations.3_squashed_5 ... (migrations.2_auto)\n" "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n" "[ ] migrations.7_auto ... (migrations.6_auto)\n", out.getvalue().lower(), ) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.mutate_state_b", "migrations.migrations_test_apps.alter_fk.author_app", "migrations.migrations_test_apps.alter_fk.book_app", ] ) def test_showmigrations_plan_single_app_label(self): """ `showmigrations --plan app_label` output with a single app_label. """ # Single app with no dependencies on other apps. out = io.StringIO() call_command("showmigrations", "mutate_state_b", format="plan", stdout=out) self.assertEqual( "[ ] mutate_state_b.0001_initial\n[ ] mutate_state_b.0002_add_field\n", out.getvalue(), ) # Single app with dependencies. out = io.StringIO() call_command("showmigrations", "author_app", format="plan", stdout=out) self.assertEqual( "[ ] author_app.0001_initial\n" "[ ] book_app.0001_initial\n" "[ ] author_app.0002_alter_id\n", out.getvalue(), ) # Some migrations already applied. call_command("migrate", "author_app", "0001", verbosity=0) out = io.StringIO() call_command("showmigrations", "author_app", format="plan", stdout=out) self.assertEqual( "[X] author_app.0001_initial\n" "[ ] book_app.0001_initial\n" "[ ] author_app.0002_alter_id\n", out.getvalue(), ) # Cleanup by unmigrating author_app. call_command("migrate", "author_app", "zero", verbosity=0) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.mutate_state_b", "migrations.migrations_test_apps.alter_fk.author_app", "migrations.migrations_test_apps.alter_fk.book_app", ] ) def test_showmigrations_plan_multiple_app_labels(self): """ `showmigrations --plan app_label` output with multiple app_labels. """ # Multiple apps: author_app depends on book_app; mutate_state_b doesn't # depend on other apps. out = io.StringIO() call_command( "showmigrations", "mutate_state_b", "author_app", format="plan", stdout=out ) self.assertEqual( "[ ] author_app.0001_initial\n" "[ ] book_app.0001_initial\n" "[ ] author_app.0002_alter_id\n" "[ ] mutate_state_b.0001_initial\n" "[ ] mutate_state_b.0002_add_field\n", out.getvalue(), ) # Multiple apps: args order shouldn't matter (the same result is # expected as above). out = io.StringIO() call_command( "showmigrations", "author_app", "mutate_state_b", format="plan", stdout=out ) self.assertEqual( "[ ] author_app.0001_initial\n" "[ ] book_app.0001_initial\n" "[ ] author_app.0002_alter_id\n" "[ ] mutate_state_b.0001_initial\n" "[ ] mutate_state_b.0002_add_field\n", out.getvalue(), ) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app"] ) def test_showmigrations_plan_app_label_no_migrations(self): out = io.StringIO() call_command( "showmigrations", "unmigrated_app", format="plan", stdout=out, no_color=True ) try: self.assertEqual("(no migrations)\n", out.getvalue()) finally: # unmigrated_app.SillyModel has a foreign key to # 'migrations.Tribble', but that model is only defined in a # migration, so the global app registry never sees it and the # reference is left dangling. Remove it to avoid problems in # subsequent tests. apps._pending_operations.pop(("migrations", "tribble"), None) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_sqlmigrate_forwards(self): """ sqlmigrate outputs forward looking SQL. """ out = io.StringIO() call_command("sqlmigrate", "migrations", "0001", stdout=out) lines = out.getvalue().splitlines() if connection.features.can_rollback_ddl: self.assertEqual(lines[0], connection.ops.start_transaction_sql()) self.assertEqual(lines[-1], connection.ops.end_transaction_sql()) lines = lines[1:-1] self.assertEqual( lines[:3], [ "--", "-- Create model Author", "--", ], ) self.assertIn( "create table %s" % connection.ops.quote_name("migrations_author").lower(), lines[3].lower(), ) pos = lines.index("--", 3) self.assertEqual( lines[pos : pos + 3], [ "--", "-- Create model Tribble", "--", ], ) self.assertIn( "create table %s" % connection.ops.quote_name("migrations_tribble").lower(), lines[pos + 3].lower(), ) pos = lines.index("--", pos + 3) self.assertEqual( lines[pos : pos + 3], [ "--", "-- Add field bool to tribble", "--", ], ) pos = lines.index("--", pos + 3) self.assertEqual( lines[pos : pos + 3], [ "--", "-- Alter unique_together for author (1 constraint(s))", "--", ], ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_sqlmigrate_backwards(self): """ sqlmigrate outputs reverse looking SQL. """ # Cannot generate the reverse SQL unless we've applied the migration. call_command("migrate", "migrations", verbosity=0) out = io.StringIO() call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True) lines = out.getvalue().splitlines() try: if connection.features.can_rollback_ddl: self.assertEqual(lines[0], connection.ops.start_transaction_sql()) self.assertEqual(lines[-1], connection.ops.end_transaction_sql()) lines = lines[1:-1] self.assertEqual( lines[:3], [ "--", "-- Alter unique_together for author (1 constraint(s))", "--", ], ) pos = lines.index("--", 3) self.assertEqual( lines[pos : pos + 3], [ "--", "-- Add field bool to tribble", "--", ], ) pos = lines.index("--", pos + 3) self.assertEqual( lines[pos : pos + 3], [ "--", "-- Create model Tribble", "--", ], ) next_pos = lines.index("--", pos + 3) drop_table_sql = ( "drop table %s" % connection.ops.quote_name("migrations_tribble").lower() ) for line in lines[pos + 3 : next_pos]: if drop_table_sql in line.lower(): break else: self.fail("DROP TABLE (tribble) not found.") pos = next_pos self.assertEqual( lines[pos : pos + 3], [ "--", "-- Create model Author", "--", ], ) drop_table_sql = ( "drop table %s" % connection.ops.quote_name("migrations_author").lower() ) for line in lines[pos + 3 :]: if drop_table_sql in line.lower(): break else: self.fail("DROP TABLE (author) not found.") finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"} ) def test_sqlmigrate_for_non_atomic_migration(self): """ Transaction wrappers aren't shown for non-atomic migrations. """ out = io.StringIO() call_command("sqlmigrate", "migrations", "0001", stdout=out) output = out.getvalue().lower() queries = [q.strip() for q in output.splitlines()] if connection.ops.start_transaction_sql(): self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries) self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_sqlmigrate_for_non_transactional_databases(self): """ Transaction wrappers aren't shown for databases that don't support transactional DDL. """ out = io.StringIO() with mock.patch.object(connection.features, "can_rollback_ddl", False): call_command("sqlmigrate", "migrations", "0001", stdout=out) output = out.getvalue().lower() queries = [q.strip() for q in output.splitlines()] start_transaction_sql = connection.ops.start_transaction_sql() if start_transaction_sql: self.assertNotIn(start_transaction_sql.lower(), queries) self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_sqlmigrate_ambiguous_prefix_squashed_migrations(self): msg = ( "More than one migration matches '0001' in app 'migrations'. " "Please be more specific." ) with self.assertRaisesMessage(CommandError, msg): call_command("sqlmigrate", "migrations", "0001") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_sqlmigrate_squashed_migration(self): out = io.StringIO() call_command("sqlmigrate", "migrations", "0001_squashed_0002", stdout=out) output = out.getvalue().lower() self.assertIn("-- create model author", output) self.assertIn("-- create model book", output) self.assertNotIn("-- create model tribble", output) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_sqlmigrate_replaced_migration(self): out = io.StringIO() call_command("sqlmigrate", "migrations", "0001_initial", stdout=out) output = out.getvalue().lower() self.assertIn("-- create model author", output) self.assertIn("-- create model tribble", output) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_no_operations"} ) def test_sqlmigrate_no_operations(self): err = io.StringIO() call_command("sqlmigrate", "migrations", "0001_initial", stderr=err) self.assertEqual(err.getvalue(), "No operations found.\n") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_noop"} ) def test_sqlmigrate_noop(self): out = io.StringIO() call_command("sqlmigrate", "migrations", "0001", stdout=out) lines = out.getvalue().splitlines() if connection.features.can_rollback_ddl: lines = lines[1:-1] self.assertEqual( lines, [ "--", "-- Raw SQL operation", "--", "-- (no-op)", ], ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_manual_porting"} ) def test_sqlmigrate_unrepresentable(self): out = io.StringIO() call_command("sqlmigrate", "migrations", "0002", stdout=out) lines = out.getvalue().splitlines() if connection.features.can_rollback_ddl: lines = lines[1:-1] self.assertEqual( lines, [ "--", "-- Raw Python operation", "--", "-- THIS OPERATION CANNOT BE WRITTEN AS SQL", ], ) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_app", "migrations.migrations_test_apps.migrated_unapplied_app", "migrations.migrations_test_apps.unmigrated_app", ], ) def test_regression_22823_unmigrated_fk_to_migrated_model(self): """ Assuming you have 3 apps, `A`, `B`, and `C`, such that: * `A` has migrations * `B` has a migration we want to apply * `C` has no migrations, but has an FK to `A` When we try to migrate "B", an exception occurs because the "B" was not included in the ProjectState that is used to detect soft-applied migrations (#22823). """ call_command("migrate", "migrated_unapplied_app", verbosity=0) # unmigrated_app.SillyModel has a foreign key to 'migrations.Tribble', # but that model is only defined in a migration, so the global app # registry never sees it and the reference is left dangling. Remove it # to avoid problems in subsequent tests. apps._pending_operations.pop(("migrations", "tribble"), None) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app_syncdb"] ) def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self): """ For an app without migrations, editor.execute() is used for executing the syncdb deferred SQL. """ stdout = io.StringIO() with mock.patch.object(BaseDatabaseSchemaEditor, "execute") as execute: call_command( "migrate", run_syncdb=True, verbosity=1, stdout=stdout, no_color=True ) create_table_count = len( [call for call in execute.mock_calls if "CREATE TABLE" in str(call)] ) self.assertEqual(create_table_count, 2) # There's at least one deferred SQL for creating the foreign key # index. self.assertGreater(len(execute.mock_calls), 2) stdout = stdout.getvalue() self.assertIn("Synchronize unmigrated apps: unmigrated_app_syncdb", stdout) self.assertIn("Creating tables...", stdout) table_name = truncate_name( "unmigrated_app_syncdb_classroom", connection.ops.max_name_length() ) self.assertIn("Creating table %s" % table_name, stdout) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_migrate_syncdb_app_with_migrations(self): msg = "Can't use run_syncdb with app 'migrations' as it has migrations." with self.assertRaisesMessage(CommandError, msg): call_command("migrate", "migrations", run_syncdb=True, verbosity=0) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.unmigrated_app_syncdb", "migrations.migrations_test_apps.unmigrated_app_simple", ] ) def test_migrate_syncdb_app_label(self): """ Running migrate --run-syncdb with an app_label only creates tables for the specified app. """ stdout = io.StringIO() with mock.patch.object(BaseDatabaseSchemaEditor, "execute") as execute: call_command( "migrate", "unmigrated_app_syncdb", run_syncdb=True, stdout=stdout ) create_table_count = len( [call for call in execute.mock_calls if "CREATE TABLE" in str(call)] ) self.assertEqual(create_table_count, 2) self.assertGreater(len(execute.mock_calls), 2) self.assertIn( "Synchronize unmigrated app: unmigrated_app_syncdb", stdout.getvalue() ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_migrate_record_replaced(self): """ Running a single squashed migration should record all of the original replaced migrations as run. """ recorder = MigrationRecorder(connection) out = io.StringIO() call_command("migrate", "migrations", verbosity=0) call_command("showmigrations", "migrations", stdout=out, no_color=True) self.assertEqual( "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n", out.getvalue().lower(), ) applied_migrations = recorder.applied_migrations() self.assertIn(("migrations", "0001_initial"), applied_migrations) self.assertIn(("migrations", "0002_second"), applied_migrations) self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations) # Rollback changes call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_migrate_record_squashed(self): """ Running migrate for a squashed migration should record as run if all of the replaced migrations have been run (#25231). """ recorder = MigrationRecorder(connection) recorder.record_applied("migrations", "0001_initial") recorder.record_applied("migrations", "0002_second") out = io.StringIO() call_command("showmigrations", "migrations", stdout=out, no_color=True) self.assertEqual( "migrations\n" " [-] 0001_squashed_0002 (2 squashed migrations) " "run 'manage.py migrate' to finish recording.\n", out.getvalue().lower(), ) out = io.StringIO() call_command("migrate", "migrations", verbosity=0) call_command("showmigrations", "migrations", stdout=out, no_color=True) self.assertEqual( "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n", out.getvalue().lower(), ) self.assertIn( ("migrations", "0001_squashed_0002"), recorder.applied_migrations() ) # No changes were actually applied so there is nothing to rollback def test_migrate_partially_applied_squashed_migration(self): """ Migrating to a squashed migration specified by name should succeed even if it is partially applied. """ with self.temporary_migration_module(module="migrations.test_migrations"): recorder = MigrationRecorder(connection) try: call_command("migrate", "migrations", "0001_initial", verbosity=0) call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=0, ) call_command( "migrate", "migrations", "0001_squashed_0002_second", verbosity=0, ) applied_migrations = recorder.applied_migrations() self.assertIn(("migrations", "0002_second"), applied_migrations) finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_migrate_backward_to_squashed_migration(self): try: call_command("migrate", "migrations", "0001_squashed_0002", verbosity=0) self.assertTableExists("migrations_author") self.assertTableExists("migrations_book") call_command("migrate", "migrations", "0001_initial", verbosity=0) self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_book") finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_migrate_inconsistent_history(self): """ Running migrate with some migrations applied before their dependencies should not be allowed. """ recorder = MigrationRecorder(connection) recorder.record_applied("migrations", "0002_second") msg = ( "Migration migrations.0002_second is applied before its dependency " "migrations.0001_initial" ) with self.assertRaisesMessage(InconsistentMigrationHistory, msg): call_command("migrate") applied_migrations = recorder.applied_migrations() self.assertNotIn(("migrations", "0001_initial"), applied_migrations) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_unapplied_app", "migrations.migrations_test_apps.migrated_app", ] ) def test_migrate_not_reflected_changes(self): class NewModel1(models.Model): class Meta: app_label = "migrated_app" class NewModel2(models.Model): class Meta: app_label = "migrated_unapplied_app" out = io.StringIO() try: call_command("migrate", verbosity=0) call_command("migrate", stdout=out, no_color=True) self.assertEqual( "operations to perform:\n" " apply all migrations: migrated_app, migrated_unapplied_app\n" "running migrations:\n" " no migrations to apply.\n" " your models in app(s): 'migrated_app', " "'migrated_unapplied_app' have changes that are not yet " "reflected in a migration, and so won't be applied.\n" " run 'manage.py makemigrations' to make new migrations, and " "then re-run 'manage.py migrate' to apply them.\n", out.getvalue().lower(), ) finally: # Unmigrate everything. call_command("migrate", "migrated_app", "zero", verbosity=0) call_command("migrate", "migrated_unapplied_app", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_squashed_no_replaces", } ) def test_migrate_prune(self): """ With prune=True, references to migration files deleted from the migrations module (such as after being squashed) are removed from the django_migrations table. """ recorder = MigrationRecorder(connection) recorder.record_applied("migrations", "0001_initial") recorder.record_applied("migrations", "0002_second") recorder.record_applied("migrations", "0001_squashed_0002") out = io.StringIO() try: call_command("migrate", "migrations", prune=True, stdout=out, no_color=True) self.assertEqual( out.getvalue(), "Pruning migrations:\n" " Pruning migrations.0001_initial OK\n" " Pruning migrations.0002_second OK\n", ) applied_migrations = [ migration for migration in recorder.applied_migrations() if migration[0] == "migrations" ] self.assertEqual(applied_migrations, [("migrations", "0001_squashed_0002")]) finally: recorder.record_unapplied("migrations", "0001_initial") recorder.record_unapplied("migrations", "0001_second") recorder.record_unapplied("migrations", "0001_squashed_0002") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_prune_deleted_squashed_migrations_in_replaces(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_squashed" ) as migration_dir: try: call_command("migrate", "migrations", verbosity=0) # Delete the replaced migrations. os.remove(os.path.join(migration_dir, "0001_initial.py")) os.remove(os.path.join(migration_dir, "0002_second.py")) # --prune cannot be used before removing the "replaces" # attribute. call_command( "migrate", "migrations", prune=True, stdout=out, no_color=True, ) self.assertEqual( out.getvalue(), "Pruning migrations:\n" " Cannot use --prune because the following squashed " "migrations have their 'replaces' attributes and may not " "be recorded as applied:\n" " migrations.0001_squashed_0002\n" " Re-run 'manage.py migrate' if they are not marked as " "applied, and remove 'replaces' attributes in their " "Migration classes.\n", ) finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_prune_no_migrations_to_prune(self): out = io.StringIO() call_command("migrate", "migrations", prune=True, stdout=out, no_color=True) self.assertEqual( out.getvalue(), "Pruning migrations:\n No migrations to prune.\n", ) out = io.StringIO() call_command( "migrate", "migrations", prune=True, stdout=out, no_color=True, verbosity=0, ) self.assertEqual(out.getvalue(), "") def test_prune_no_app_label(self): msg = "Migrations can be pruned only when an app is specified." with self.assertRaisesMessage(CommandError, msg): call_command("migrate", prune=True) class MakeMigrationsTests(MigrationTestBase): """ Tests running the makemigrations command. """ def setUp(self): super().setUp() self._old_models = apps.app_configs["migrations"].models.copy() def tearDown(self): apps.app_configs["migrations"].models = self._old_models apps.all_models["migrations"] = self._old_models apps.clear_cache() super().tearDown() def test_files_content(self): self.assertTableNotExists("migrations_unicodemodel") apps.register_model("migrations", UnicodeModel) with self.temporary_migration_module() as migration_dir: call_command("makemigrations", "migrations", verbosity=0) # Check for empty __init__.py file in migrations folder init_file = os.path.join(migration_dir, "__init__.py") self.assertTrue(os.path.exists(init_file)) with open(init_file) as fp: content = fp.read() self.assertEqual(content, "") # Check for existing 0001_initial.py file in migration folder initial_file = os.path.join(migration_dir, "0001_initial.py") self.assertTrue(os.path.exists(initial_file)) with open(initial_file, encoding="utf-8") as fp: content = fp.read() self.assertIn("migrations.CreateModel", content) self.assertIn("initial = True", content) self.assertIn("úñí©óðé µóðéø", content) # Meta.verbose_name self.assertIn("úñí©óðé µóðéøß", content) # Meta.verbose_name_plural self.assertIn("ÚÑÍ¢ÓÐÉ", content) # title.verbose_name self.assertIn("“Ðjáñgó”", content) # title.default def test_makemigrations_order(self): """ makemigrations should recognize number-only migrations (0001.py). """ module = "migrations.test_migrations_order" with self.temporary_migration_module(module=module) as migration_dir: if hasattr(importlib, "invalidate_caches"): # importlib caches os.listdir() on some platforms like macOS # (#23850). importlib.invalidate_caches() call_command( "makemigrations", "migrations", "--empty", "-n", "a", "-v", "0" ) self.assertTrue(os.path.exists(os.path.join(migration_dir, "0002_a.py"))) def test_makemigrations_empty_connections(self): empty_connections = ConnectionHandler({"default": {}}) with mock.patch( "django.core.management.commands.makemigrations.connections", new=empty_connections, ): # with no apps out = io.StringIO() call_command("makemigrations", stdout=out) self.assertIn("No changes detected", out.getvalue()) # with an app with self.temporary_migration_module() as migration_dir: call_command("makemigrations", "migrations", verbosity=0) init_file = os.path.join(migration_dir, "__init__.py") self.assertTrue(os.path.exists(init_file)) @override_settings(INSTALLED_APPS=["migrations", "migrations2"]) def test_makemigrations_consistency_checks_respect_routers(self): """ The history consistency checks in makemigrations respect settings.DATABASE_ROUTERS. """ def patched_has_table(migration_recorder): if migration_recorder.connection is connections["other"]: raise Exception("Other connection") else: return mock.DEFAULT self.assertTableNotExists("migrations_unicodemodel") apps.register_model("migrations", UnicodeModel) with mock.patch.object( MigrationRecorder, "has_table", autospec=True, side_effect=patched_has_table ) as has_table: with self.temporary_migration_module() as migration_dir: call_command("makemigrations", "migrations", verbosity=0) initial_file = os.path.join(migration_dir, "0001_initial.py") self.assertTrue(os.path.exists(initial_file)) self.assertEqual(has_table.call_count, 1) # 'default' is checked # Router says not to migrate 'other' so consistency shouldn't # be checked. with self.settings(DATABASE_ROUTERS=["migrations.routers.TestRouter"]): call_command("makemigrations", "migrations", verbosity=0) self.assertEqual(has_table.call_count, 2) # 'default' again # With a router that doesn't prohibit migrating 'other', # consistency is checked. with self.settings( DATABASE_ROUTERS=["migrations.routers.DefaultOtherRouter"] ): with self.assertRaisesMessage(Exception, "Other connection"): call_command("makemigrations", "migrations", verbosity=0) self.assertEqual(has_table.call_count, 4) # 'default' and 'other' # With a router that doesn't allow migrating on any database, # no consistency checks are made. with self.settings(DATABASE_ROUTERS=["migrations.routers.TestRouter"]): with mock.patch.object( TestRouter, "allow_migrate", return_value=False ) as allow_migrate: call_command("makemigrations", "migrations", verbosity=0) allow_migrate.assert_any_call( "other", "migrations", model_name="UnicodeModel" ) # allow_migrate() is called with the correct arguments. self.assertGreater(len(allow_migrate.mock_calls), 0) called_aliases = set() for mock_call in allow_migrate.mock_calls: _, call_args, call_kwargs = mock_call connection_alias, app_name = call_args called_aliases.add(connection_alias) # Raises an error if invalid app_name/model_name occurs. apps.get_app_config(app_name).get_model(call_kwargs["model_name"]) self.assertEqual(called_aliases, set(connections)) self.assertEqual(has_table.call_count, 4) def test_failing_migration(self): # If a migration fails to serialize, it shouldn't generate an empty file. #21280 apps.register_model("migrations", UnserializableModel) with self.temporary_migration_module() as migration_dir: with self.assertRaisesMessage(ValueError, "Cannot serialize"): call_command("makemigrations", "migrations", verbosity=0) initial_file = os.path.join(migration_dir, "0001_initial.py") self.assertFalse(os.path.exists(initial_file)) def test_makemigrations_conflict_exit(self): """ makemigrations exits if it detects a conflict. """ with self.temporary_migration_module( module="migrations.test_migrations_conflict" ): with self.assertRaises(CommandError) as context: call_command("makemigrations") self.assertEqual( str(context.exception), "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (0002_conflicting_second, 0002_second in " "migrations).\n" "To fix them run 'python manage.py makemigrations --merge'", ) def test_makemigrations_merge_no_conflict(self): """ makemigrations exits if in merge mode with no conflicts. """ out = io.StringIO() with self.temporary_migration_module(module="migrations.test_migrations"): call_command("makemigrations", merge=True, stdout=out) self.assertIn("No conflicts detected to merge.", out.getvalue()) def test_makemigrations_empty_no_app_specified(self): """ makemigrations exits if no app is specified with 'empty' mode. """ msg = "You must supply at least one app label when using --empty." with self.assertRaisesMessage(CommandError, msg): call_command("makemigrations", empty=True) def test_makemigrations_empty_migration(self): """ makemigrations properly constructs an empty migration. """ with self.temporary_migration_module() as migration_dir: call_command("makemigrations", "migrations", empty=True, verbosity=0) # Check for existing 0001_initial.py file in migration folder initial_file = os.path.join(migration_dir, "0001_initial.py") self.assertTrue(os.path.exists(initial_file)) with open(initial_file, encoding="utf-8") as fp: content = fp.read() # Remove all whitespace to check for empty dependencies and operations content = content.replace(" ", "") self.assertIn( "dependencies=[]" if HAS_BLACK else "dependencies=[\n]", content ) self.assertIn( "operations=[]" if HAS_BLACK else "operations=[\n]", content ) @override_settings(MIGRATION_MODULES={"migrations": None}) def test_makemigrations_disabled_migrations_for_app(self): """ makemigrations raises a nice error when migrations are disabled for an app. """ msg = ( "Django can't create migrations for app 'migrations' because migrations " "have been disabled via the MIGRATION_MODULES setting." ) with self.assertRaisesMessage(ValueError, msg): call_command("makemigrations", "migrations", empty=True, verbosity=0) def test_makemigrations_no_changes_no_apps(self): """ makemigrations exits when there are no changes and no apps are specified. """ out = io.StringIO() call_command("makemigrations", stdout=out) self.assertIn("No changes detected", out.getvalue()) def test_makemigrations_no_changes(self): """ makemigrations exits when there are no changes to an app. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ): call_command("makemigrations", "migrations", stdout=out) self.assertIn("No changes detected in app 'migrations'", out.getvalue()) def test_makemigrations_no_apps_initial(self): """ makemigrations should detect initial is needed on empty migration modules if no app provided. """ out = io.StringIO() with self.temporary_migration_module(module="migrations.test_migrations_empty"): call_command("makemigrations", stdout=out) self.assertIn("0001_initial.py", out.getvalue()) def test_makemigrations_no_init(self): """Migration directories without an __init__.py file are allowed.""" out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_init" ): call_command("makemigrations", stdout=out) self.assertIn("0001_initial.py", out.getvalue()) def test_makemigrations_migrations_announce(self): """ makemigrations announces the migration at the default verbosity level. """ out = io.StringIO() with self.temporary_migration_module(): call_command("makemigrations", "migrations", stdout=out) self.assertIn("Migrations for 'migrations'", out.getvalue()) def test_makemigrations_no_common_ancestor(self): """ makemigrations fails to merge migrations with no common ancestor. """ with self.assertRaises(ValueError) as context: with self.temporary_migration_module( module="migrations.test_migrations_no_ancestor" ): call_command("makemigrations", "migrations", merge=True) exception_message = str(context.exception) self.assertIn("Could not find common ancestor of", exception_message) self.assertIn("0002_second", exception_message) self.assertIn("0002_conflicting_second", exception_message) def test_makemigrations_interactive_reject(self): """ makemigrations enters and exits interactive mode properly. """ # Monkeypatch interactive questioner to auto reject with mock.patch("builtins.input", mock.Mock(return_value="N")): with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: with captured_stdout(): call_command( "makemigrations", "migrations", name="merge", merge=True, interactive=True, verbosity=0, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertFalse(os.path.exists(merge_file)) def test_makemigrations_interactive_accept(self): """ makemigrations enters interactive mode and merges properly. """ # Monkeypatch interactive questioner to auto accept with mock.patch("builtins.input", mock.Mock(return_value="y")): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: call_command( "makemigrations", "migrations", name="merge", merge=True, interactive=True, stdout=out, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertTrue(os.path.exists(merge_file)) self.assertIn("Created new merge migration", out.getvalue()) def test_makemigrations_default_merge_name(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: call_command( "makemigrations", "migrations", merge=True, interactive=False, stdout=out, ) merge_file = os.path.join( migration_dir, "0003_merge_0002_conflicting_second_0002_second.py", ) self.assertIs(os.path.exists(merge_file), True) with open(merge_file, encoding="utf-8") as fp: content = fp.read() if HAS_BLACK: target_str = '("migrations", "0002_conflicting_second")' else: target_str = "('migrations', '0002_conflicting_second')" self.assertIn(target_str, content) self.assertIn("Created new merge migration %s" % merge_file, out.getvalue()) @mock.patch("django.db.migrations.utils.datetime") def test_makemigrations_auto_merge_name(self, mock_datetime): mock_datetime.datetime.now.return_value = datetime.datetime(2016, 1, 2, 3, 4) with mock.patch("builtins.input", mock.Mock(return_value="y")): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict_long_name" ) as migration_dir: call_command( "makemigrations", "migrations", merge=True, interactive=True, stdout=out, ) merge_file = os.path.join(migration_dir, "0003_merge_20160102_0304.py") self.assertTrue(os.path.exists(merge_file)) self.assertIn("Created new merge migration", out.getvalue()) def test_makemigrations_non_interactive_not_null_addition(self): """ Non-interactive makemigrations fails when a default is missing on a new not-null field. """ class SillyModel(models.Model): silly_field = models.BooleanField(default=False) silly_int = models.IntegerField() class Meta: app_label = "migrations" with self.assertRaises(SystemExit): with self.temporary_migration_module( module="migrations.test_migrations_no_default" ): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=False) self.assertIn( "Field 'silly_int' on model 'sillymodel' not migrated: it is " "impossible to add a non-nullable field without specifying a " "default.", out.getvalue(), ) def test_makemigrations_interactive_not_null_addition(self): """ makemigrations messages when adding a NOT NULL field in interactive mode. """ class Author(models.Model): silly_field = models.BooleanField(null=False) class Meta: app_label = "migrations" input_msg = ( "It is impossible to add a non-nullable field 'silly_field' to " "author without specifying a default. This is because the " "database needs something to populate existing rows.\n" "Please select a fix:\n" " 1) Provide a one-off default now (will be set on all existing " "rows with a null value for this column)\n" " 2) Quit and manually define a default value in models.py." ) with self.temporary_migration_module(module="migrations.test_migrations"): # 2 - quit. with mock.patch("builtins.input", return_value="2"): with captured_stdout() as out, self.assertRaises(SystemExit): call_command("makemigrations", "migrations", interactive=True) self.assertIn(input_msg, out.getvalue()) # 1 - provide a default. with mock.patch("builtins.input", return_value="1"): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=True) output = out.getvalue() self.assertIn(input_msg, output) self.assertIn("Please enter the default value as valid Python.", output) self.assertIn( "The datetime and django.utils.timezone modules are " "available, so it is possible to provide e.g. timezone.now as " "a value", output, ) self.assertIn("Type 'exit' to exit this prompt", output) def test_makemigrations_non_interactive_not_null_alteration(self): """ Non-interactive makemigrations fails when a default is missing on a field changed to not-null. """ class Author(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() age = models.IntegerField(default=0) class Meta: app_label = "migrations" with self.temporary_migration_module(module="migrations.test_migrations"): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=False) self.assertIn("Alter field slug on author", out.getvalue()) self.assertIn( "Field 'slug' on model 'author' given a default of NOT PROVIDED " "and must be corrected.", out.getvalue(), ) def test_makemigrations_interactive_not_null_alteration(self): """ makemigrations messages when changing a NULL field to NOT NULL in interactive mode. """ class Author(models.Model): slug = models.SlugField(null=False) class Meta: app_label = "migrations" input_msg = ( "It is impossible to change a nullable field 'slug' on author to " "non-nullable without providing a default. This is because the " "database needs something to populate existing rows.\n" "Please select a fix:\n" " 1) Provide a one-off default now (will be set on all existing " "rows with a null value for this column)\n" " 2) Ignore for now. Existing rows that contain NULL values will " "have to be handled manually, for example with a RunPython or " "RunSQL operation.\n" " 3) Quit and manually define a default value in models.py." ) with self.temporary_migration_module(module="migrations.test_migrations"): # No message appears if --dry-run. with captured_stdout() as out: call_command( "makemigrations", "migrations", interactive=True, dry_run=True, ) self.assertNotIn(input_msg, out.getvalue()) # 3 - quit. with mock.patch("builtins.input", return_value="3"): with captured_stdout() as out, self.assertRaises(SystemExit): call_command("makemigrations", "migrations", interactive=True) self.assertIn(input_msg, out.getvalue()) # 1 - provide a default. with mock.patch("builtins.input", return_value="1"): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=True) output = out.getvalue() self.assertIn(input_msg, output) self.assertIn("Please enter the default value as valid Python.", output) self.assertIn( "The datetime and django.utils.timezone modules are " "available, so it is possible to provide e.g. timezone.now as " "a value", output, ) self.assertIn("Type 'exit' to exit this prompt", output) def test_makemigrations_non_interactive_no_model_rename(self): """ makemigrations adds and removes a possible model rename in non-interactive mode. """ class RenamedModel(models.Model): silly_field = models.BooleanField(default=False) class Meta: app_label = "migrations" out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_default" ): call_command("makemigrations", "migrations", interactive=False, stdout=out) self.assertIn("Delete model SillyModel", out.getvalue()) self.assertIn("Create model RenamedModel", out.getvalue()) def test_makemigrations_non_interactive_no_field_rename(self): """ makemigrations adds and removes a possible field rename in non-interactive mode. """ class SillyModel(models.Model): silly_rename = models.BooleanField(default=False) class Meta: app_label = "migrations" out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_default" ): call_command("makemigrations", "migrations", interactive=False, stdout=out) self.assertIn("Remove field silly_field from sillymodel", out.getvalue()) self.assertIn("Add field silly_rename to sillymodel", out.getvalue()) @mock.patch("builtins.input", return_value="Y") def test_makemigrations_model_rename_interactive(self, mock_input): class RenamedModel(models.Model): silly_field = models.BooleanField(default=False) class Meta: app_label = "migrations" with self.temporary_migration_module( module="migrations.test_migrations_no_default", ): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=True) self.assertIn("Rename model SillyModel to RenamedModel", out.getvalue()) @mock.patch("builtins.input", return_value="Y") def test_makemigrations_field_rename_interactive(self, mock_input): class SillyModel(models.Model): silly_rename = models.BooleanField(default=False) class Meta: app_label = "migrations" with self.temporary_migration_module( module="migrations.test_migrations_no_default", ): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=True) self.assertIn( "Rename field silly_field on sillymodel to silly_rename", out.getvalue(), ) def test_makemigrations_handle_merge(self): """ makemigrations properly merges the conflicting migrations with --noinput. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: call_command( "makemigrations", "migrations", name="merge", merge=True, interactive=False, stdout=out, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertTrue(os.path.exists(merge_file)) output = out.getvalue() self.assertIn("Merging migrations", output) self.assertIn("Branch 0002_second", output) self.assertIn("Branch 0002_conflicting_second", output) self.assertIn("Created new merge migration", output) def test_makemigration_merge_dry_run(self): """ makemigrations respects --dry-run option when fixing migration conflicts (#24427). """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: call_command( "makemigrations", "migrations", name="merge", dry_run=True, merge=True, interactive=False, stdout=out, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertFalse(os.path.exists(merge_file)) output = out.getvalue() self.assertIn("Merging migrations", output) self.assertIn("Branch 0002_second", output) self.assertIn("Branch 0002_conflicting_second", output) self.assertNotIn("Created new merge migration", output) def test_makemigration_merge_dry_run_verbosity_3(self): """ `makemigrations --merge --dry-run` writes the merge migration file to stdout with `verbosity == 3` (#24427). """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: call_command( "makemigrations", "migrations", name="merge", dry_run=True, merge=True, interactive=False, stdout=out, verbosity=3, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertFalse(os.path.exists(merge_file)) output = out.getvalue() self.assertIn("Merging migrations", output) self.assertIn("Branch 0002_second", output) self.assertIn("Branch 0002_conflicting_second", output) self.assertNotIn("Created new merge migration", output) # Additional output caused by verbosity 3 # The complete merge migration file that would be written self.assertIn("class Migration(migrations.Migration):", output) self.assertIn("dependencies = [", output) self.assertIn("('migrations', '0002_second')", output) self.assertIn("('migrations', '0002_conflicting_second')", output) self.assertIn("operations = [", output) self.assertIn("]", output) def test_makemigrations_dry_run(self): """ `makemigrations --dry-run` should not ask for defaults. """ class SillyModel(models.Model): silly_field = models.BooleanField(default=False) silly_date = models.DateField() # Added field without a default silly_auto_now = models.DateTimeField(auto_now_add=True) class Meta: app_label = "migrations" out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_default" ): call_command("makemigrations", "migrations", dry_run=True, stdout=out) # Output the expected changes directly, without asking for defaults self.assertIn("Add field silly_date to sillymodel", out.getvalue()) def test_makemigrations_dry_run_verbosity_3(self): """ Allow `makemigrations --dry-run` to output the migrations file to stdout (with verbosity == 3). """ class SillyModel(models.Model): silly_field = models.BooleanField(default=False) silly_char = models.CharField(default="") class Meta: app_label = "migrations" out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_default" ): call_command( "makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3 ) # Normal --dry-run output self.assertIn("- Add field silly_char to sillymodel", out.getvalue()) # Additional output caused by verbosity 3 # The complete migrations file that would be written self.assertIn("class Migration(migrations.Migration):", out.getvalue()) self.assertIn("dependencies = [", out.getvalue()) self.assertIn("('migrations', '0001_initial'),", out.getvalue()) self.assertIn("migrations.AddField(", out.getvalue()) self.assertIn("model_name='sillymodel',", out.getvalue()) self.assertIn("name='silly_char',", out.getvalue()) def test_makemigrations_scriptable(self): """ With scriptable=True, log output is diverted to stderr, and only the paths of generated migration files are written to stdout. """ out = io.StringIO() err = io.StringIO() with self.temporary_migration_module( module="migrations.migrations.test_migrations", ) as migration_dir: call_command( "makemigrations", "migrations", scriptable=True, stdout=out, stderr=err, ) initial_file = os.path.join(migration_dir, "0001_initial.py") self.assertEqual(out.getvalue(), f"{initial_file}\n") self.assertIn(" - Create model ModelWithCustomBase\n", err.getvalue()) @mock.patch("builtins.input", return_value="Y") def test_makemigrations_scriptable_merge(self, mock_input): out = io.StringIO() err = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_conflict", ) as migration_dir: call_command( "makemigrations", "migrations", merge=True, name="merge", scriptable=True, stdout=out, stderr=err, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertEqual(out.getvalue(), f"{merge_file}\n") self.assertIn(f"Created new merge migration {merge_file}", err.getvalue()) def test_makemigrations_migrations_modules_path_not_exist(self): """ makemigrations creates migrations when specifying a custom location for migration files using MIGRATION_MODULES if the custom path doesn't already exist. """ class SillyModel(models.Model): silly_field = models.BooleanField(default=False) class Meta: app_label = "migrations" out = io.StringIO() migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar" with self.temporary_migration_module(module=migration_module) as migration_dir: call_command("makemigrations", "migrations", stdout=out) # Migrations file is actually created in the expected path. initial_file = os.path.join(migration_dir, "0001_initial.py") self.assertTrue(os.path.exists(initial_file)) # Command output indicates the migration is created. self.assertIn(" - Create model SillyModel", out.getvalue()) @override_settings(MIGRATION_MODULES={"migrations": "some.nonexistent.path"}) def test_makemigrations_migrations_modules_nonexistent_toplevel_package(self): msg = ( "Could not locate an appropriate location to create migrations " "package some.nonexistent.path. Make sure the toplevel package " "exists and can be imported." ) with self.assertRaisesMessage(ValueError, msg): call_command("makemigrations", "migrations", empty=True, verbosity=0) def test_makemigrations_interactive_by_default(self): """ The user is prompted to merge by default if there are conflicts and merge is True. Answer negative to differentiate it from behavior when --noinput is specified. """ # Monkeypatch interactive questioner to auto reject out = io.StringIO() with mock.patch("builtins.input", mock.Mock(return_value="N")): with self.temporary_migration_module( module="migrations.test_migrations_conflict" ) as migration_dir: call_command( "makemigrations", "migrations", name="merge", merge=True, stdout=out ) merge_file = os.path.join(migration_dir, "0003_merge.py") # This will fail if interactive is False by default self.assertFalse(os.path.exists(merge_file)) self.assertNotIn("Created new merge migration", out.getvalue()) @override_settings( INSTALLED_APPS=[ "migrations", "migrations.migrations_test_apps.unspecified_app_with_conflict", ] ) def test_makemigrations_unspecified_app_with_conflict_no_merge(self): """ makemigrations does not raise a CommandError when an unspecified app has conflicting migrations. """ with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ): call_command("makemigrations", "migrations", merge=False, verbosity=0) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_app", "migrations.migrations_test_apps.unspecified_app_with_conflict", ] ) def test_makemigrations_unspecified_app_with_conflict_merge(self): """ makemigrations does not create a merge for an unspecified app even if it has conflicting migrations. """ # Monkeypatch interactive questioner to auto accept with mock.patch("builtins.input", mock.Mock(return_value="y")): out = io.StringIO() with self.temporary_migration_module( app_label="migrated_app" ) as migration_dir: call_command( "makemigrations", "migrated_app", name="merge", merge=True, interactive=True, stdout=out, ) merge_file = os.path.join(migration_dir, "0003_merge.py") self.assertFalse(os.path.exists(merge_file)) self.assertIn("No conflicts detected to merge.", out.getvalue()) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_app", "migrations.migrations_test_apps.conflicting_app_with_dependencies", ] ) def test_makemigrations_merge_dont_output_dependency_operations(self): """ makemigrations --merge does not output any operations from apps that don't belong to a given app. """ # Monkeypatch interactive questioner to auto accept with mock.patch("builtins.input", mock.Mock(return_value="N")): out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: False ): call_command( "makemigrations", "conflicting_app_with_dependencies", merge=True, interactive=True, stdout=out, ) self.assertEqual( out.getvalue().lower(), "merging conflicting_app_with_dependencies\n" " branch 0002_conflicting_second\n" " - create model something\n" " branch 0002_second\n" " - delete model tribble\n" " - remove field silly_field from author\n" " - add field rating to author\n" " - create model book\n" "\n" "merging will only work if the operations printed above do not " "conflict\n" "with each other (working on different fields or models)\n" "should these migration branches be merged? [y/n] ", ) def test_makemigrations_with_custom_name(self): """ makemigrations --name generate a custom migration name. """ with self.temporary_migration_module() as migration_dir: def cmd(migration_count, migration_name, *args): call_command( "makemigrations", "migrations", "--verbosity", "0", "--name", migration_name, *args, ) migration_file = os.path.join( migration_dir, "%s_%s.py" % (migration_count, migration_name) ) # Check for existing migration file in migration folder self.assertTrue(os.path.exists(migration_file)) with open(migration_file, encoding="utf-8") as fp: content = fp.read() content = content.replace(" ", "") return content # generate an initial migration migration_name_0001 = "my_initial_migration" content = cmd("0001", migration_name_0001) self.assertIn( "dependencies=[]" if HAS_BLACK else "dependencies=[\n]", content ) # importlib caches os.listdir() on some platforms like macOS # (#23850). if hasattr(importlib, "invalidate_caches"): importlib.invalidate_caches() # generate an empty migration migration_name_0002 = "my_custom_migration" content = cmd("0002", migration_name_0002, "--empty") if HAS_BLACK: template_str = 'dependencies=[\n("migrations","0001_%s"),\n]' else: template_str = "dependencies=[\n('migrations','0001_%s'),\n]" self.assertIn( template_str % migration_name_0001, content, ) self.assertIn("operations=[]" if HAS_BLACK else "operations=[\n]", content) def test_makemigrations_with_invalid_custom_name(self): msg = "The migration name must be a valid Python identifier." with self.assertRaisesMessage(CommandError, msg): call_command( "makemigrations", "migrations", "--name", "invalid name", "--empty" ) def test_makemigrations_check(self): """ makemigrations --check should exit with a non-zero status when there are changes to an app requiring migrations. """ with self.temporary_migration_module(): with self.assertRaises(SystemExit): call_command("makemigrations", "--check", "migrations", verbosity=0) with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ): call_command("makemigrations", "--check", "migrations", verbosity=0) def test_makemigrations_migration_path_output(self): """ makemigrations should print the relative paths to the migrations unless they are outside of the current tree, in which case the absolute path should be shown. """ out = io.StringIO() apps.register_model("migrations", UnicodeModel) with self.temporary_migration_module() as migration_dir: call_command("makemigrations", "migrations", stdout=out) self.assertIn( os.path.join(migration_dir, "0001_initial.py"), out.getvalue() ) def test_makemigrations_migration_path_output_valueerror(self): """ makemigrations prints the absolute path if os.path.relpath() raises a ValueError when it's impossible to obtain a relative path, e.g. on Windows if Django is installed on a different drive than where the migration files are created. """ out = io.StringIO() with self.temporary_migration_module() as migration_dir: with mock.patch("os.path.relpath", side_effect=ValueError): call_command("makemigrations", "migrations", stdout=out) self.assertIn(os.path.join(migration_dir, "0001_initial.py"), out.getvalue()) def test_makemigrations_inconsistent_history(self): """ makemigrations should raise InconsistentMigrationHistory exception if there are some migrations applied before their dependencies. """ recorder = MigrationRecorder(connection) recorder.record_applied("migrations", "0002_second") msg = ( "Migration migrations.0002_second is applied before its dependency " "migrations.0001_initial" ) with self.temporary_migration_module(module="migrations.test_migrations"): with self.assertRaisesMessage(InconsistentMigrationHistory, msg): call_command("makemigrations") def test_makemigrations_inconsistent_history_db_failure(self): msg = ( "Got an error checking a consistent migration history performed " "for database connection 'default': could not connect to server" ) with mock.patch( "django.db.migrations.loader.MigrationLoader.check_consistent_history", side_effect=OperationalError("could not connect to server"), ): with self.temporary_migration_module(): with self.assertWarns(RuntimeWarning) as cm: call_command("makemigrations", verbosity=0) self.assertEqual(str(cm.warning), msg) @mock.patch("builtins.input", return_value="1") @mock.patch( "django.db.migrations.questioner.sys.stdin", mock.MagicMock(encoding=sys.getdefaultencoding()), ) def test_makemigrations_auto_now_add_interactive(self, *args): """ makemigrations prompts the user when adding auto_now_add to an existing model. """ class Entry(models.Model): title = models.CharField(max_length=255) creation_date = models.DateTimeField(auto_now_add=True) class Meta: app_label = "migrations" input_msg = ( "It is impossible to add the field 'creation_date' with " "'auto_now_add=True' to entry without providing a default. This " "is because the database needs something to populate existing " "rows.\n" " 1) Provide a one-off default now which will be set on all " "existing rows\n" " 2) Quit and manually define a default value in models.py." ) # Monkeypatch interactive questioner to auto accept prompt_stdout = io.StringIO() with self.temporary_migration_module(module="migrations.test_auto_now_add"): call_command( "makemigrations", "migrations", interactive=True, stdout=prompt_stdout ) prompt_output = prompt_stdout.getvalue() self.assertIn(input_msg, prompt_output) self.assertIn("Please enter the default value as valid Python.", prompt_output) self.assertIn( "Accept the default 'timezone.now' by pressing 'Enter' or provide " "another value.", prompt_output, ) self.assertIn("Type 'exit' to exit this prompt", prompt_output) self.assertIn("Add field creation_date to entry", prompt_output) @mock.patch("builtins.input", return_value="2") def test_makemigrations_auto_now_add_interactive_quit(self, mock_input): class Author(models.Model): publishing_date = models.DateField(auto_now_add=True) class Meta: app_label = "migrations" with self.temporary_migration_module(module="migrations.test_migrations"): with captured_stdout(): with self.assertRaises(SystemExit): call_command("makemigrations", "migrations", interactive=True) def test_makemigrations_non_interactive_auto_now_add_addition(self): """ Non-interactive makemigrations fails when a default is missing on a new field when auto_now_add=True. """ class Entry(models.Model): creation_date = models.DateTimeField(auto_now_add=True) class Meta: app_label = "migrations" with self.temporary_migration_module(module="migrations.test_auto_now_add"): with self.assertRaises(SystemExit), captured_stdout() as out: call_command("makemigrations", "migrations", interactive=False) self.assertIn( "Field 'creation_date' on model 'entry' not migrated: it is " "impossible to add a field with 'auto_now_add=True' without " "specifying a default.", out.getvalue(), ) def test_makemigrations_interactive_unique_callable_default_addition(self): """ makemigrations prompts the user when adding a unique field with a callable default. """ class Book(models.Model): created = models.DateTimeField(unique=True, default=timezone.now) class Meta: app_label = "migrations" version = get_docs_version() input_msg = ( f"Callable default on unique field book.created will not generate " f"unique values upon migrating.\n" f"Please choose how to proceed:\n" f" 1) Continue making this migration as the first step in writing " f"a manual migration to generate unique values described here: " f"https://docs.djangoproject.com/en/{version}/howto/" f"writing-migrations/#migrations-that-add-unique-fields.\n" f" 2) Quit and edit field options in models.py.\n" ) with self.temporary_migration_module(module="migrations.test_migrations"): # 2 - quit. with mock.patch("builtins.input", return_value="2"): with captured_stdout() as out, self.assertRaises(SystemExit): call_command("makemigrations", "migrations", interactive=True) out_value = out.getvalue() self.assertIn(input_msg, out_value) self.assertNotIn("Add field created to book", out_value) # 1 - continue. with mock.patch("builtins.input", return_value="1"): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=True) out_value = out.getvalue() self.assertIn(input_msg, out_value) self.assertIn("Add field created to book", out_value) def test_makemigrations_non_interactive_unique_callable_default_addition(self): class Book(models.Model): created = models.DateTimeField(unique=True, default=timezone.now) class Meta: app_label = "migrations" with self.temporary_migration_module(module="migrations.test_migrations"): with captured_stdout() as out: call_command("makemigrations", "migrations", interactive=False) out_value = out.getvalue() self.assertIn("Add field created to book", out_value) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}, ) def test_makemigrations_continues_number_sequence_after_squash(self): with self.temporary_migration_module( module="migrations.test_migrations_squashed" ): with captured_stdout() as out: call_command( "makemigrations", "migrations", interactive=False, empty=True, ) out_value = out.getvalue() self.assertIn("0003_auto", out_value) def test_makemigrations_update(self): with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: migration_file = os.path.join(migration_dir, "0002_second.py") with open(migration_file) as fp: initial_content = fp.read() with captured_stdout() as out: call_command("makemigrations", "migrations", update=True) self.assertFalse( any( filename.startswith("0003") for filename in os.listdir(migration_dir) ) ) self.assertIs(os.path.exists(migration_file), False) new_migration_file = os.path.join( migration_dir, "0002_delete_tribble_author_rating_modelwithcustombase_and_more.py", ) with open(new_migration_file) as fp: self.assertNotEqual(initial_content, fp.read()) self.assertIn(f"Deleted {migration_file}", out.getvalue()) def test_makemigrations_update_existing_name(self): with self.temporary_migration_module( module="migrations.test_auto_now_add" ) as migration_dir: migration_file = os.path.join(migration_dir, "0001_initial.py") with open(migration_file) as fp: initial_content = fp.read() with captured_stdout() as out: call_command("makemigrations", "migrations", update=True) self.assertIs(os.path.exists(migration_file), False) new_migration_file = os.path.join( migration_dir, "0001_initial_updated.py", ) with open(new_migration_file) as fp: self.assertNotEqual(initial_content, fp.read()) self.assertIn(f"Deleted {migration_file}", out.getvalue()) def test_makemigrations_update_applied_migration(self): recorder = MigrationRecorder(connection) recorder.record_applied("migrations", "0001_initial") recorder.record_applied("migrations", "0002_second") with self.temporary_migration_module(module="migrations.test_migrations"): msg = "Cannot update applied migration 'migrations.0002_second'." with self.assertRaisesMessage(CommandError, msg): call_command("makemigrations", "migrations", update=True) def test_makemigrations_update_no_migration(self): with self.temporary_migration_module(module="migrations.test_migrations_empty"): msg = "App migrations has no migration, cannot update last migration." with self.assertRaisesMessage(CommandError, msg): call_command("makemigrations", "migrations", update=True) def test_makemigrations_update_squash_migration(self): with self.temporary_migration_module( module="migrations.test_migrations_squashed" ): msg = "Cannot update squash migration 'migrations.0001_squashed_0002'." with self.assertRaisesMessage(CommandError, msg): call_command("makemigrations", "migrations", update=True) def test_makemigrations_update_manual_porting(self): with self.temporary_migration_module( module="migrations.test_migrations_plan" ) as migration_dir: with captured_stdout() as out: call_command("makemigrations", "migrations", update=True) # Previous migration exists. previous_migration_file = os.path.join(migration_dir, "0005_fifth.py") self.assertIs(os.path.exists(previous_migration_file), True) # New updated migration exists. files = [f for f in os.listdir(migration_dir) if f.startswith("0005_auto")] updated_migration_file = os.path.join(migration_dir, files[0]) self.assertIs(os.path.exists(updated_migration_file), True) self.assertIn( f"Updated migration {updated_migration_file} requires manual porting.\n" f"Previous migration {previous_migration_file} was kept and must be " f"deleted after porting functions manually.", out.getvalue(), ) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.alter_fk.author_app", "migrations.migrations_test_apps.alter_fk.book_app", ] ) def test_makemigrations_update_dependency_migration(self): with self.temporary_migration_module(app_label="book_app"): msg = ( "Cannot update migration 'book_app.0001_initial' that migrations " "'author_app.0002_alter_id' depend on." ) with self.assertRaisesMessage(CommandError, msg): call_command("makemigrations", "book_app", update=True) class SquashMigrationsTests(MigrationTestBase): """ Tests running the squashmigrations command. """ def test_squashmigrations_squashes(self): """ squashmigrations squashes migrations. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", interactive=False, stdout=out, no_color=True, ) squashed_migration_file = os.path.join( migration_dir, "0001_squashed_0002_second.py" ) self.assertTrue(os.path.exists(squashed_migration_file)) self.assertEqual( out.getvalue(), "Will squash the following migrations:\n" " - 0001_initial\n" " - 0002_second\n" "Optimizing...\n" " Optimized from 8 operations to 2 operations.\n" "Created new squashed migration %s\n" " You should commit this migration but leave the old ones in place;\n" " the new migration will be used for new installs. Once you are sure\n" " all instances of the codebase have applied the migrations you " "squashed,\n" " you can delete them.\n" % squashed_migration_file, ) def test_squashmigrations_initial_attribute(self): with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=0 ) squashed_migration_file = os.path.join( migration_dir, "0001_squashed_0002_second.py" ) with open(squashed_migration_file, encoding="utf-8") as fp: content = fp.read() self.assertIn("initial = True", content) def test_squashmigrations_optimizes(self): """ squashmigrations optimizes operations. """ out = io.StringIO() with self.temporary_migration_module(module="migrations.test_migrations"): call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out, ) self.assertIn("Optimized from 8 operations to 2 operations.", out.getvalue()) def test_ticket_23799_squashmigrations_no_optimize(self): """ squashmigrations --no-optimize doesn't optimize operations. """ out = io.StringIO() with self.temporary_migration_module(module="migrations.test_migrations"): call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=1, no_optimize=True, stdout=out, ) self.assertIn("Skipping optimization", out.getvalue()) def test_squashmigrations_valid_start(self): """ squashmigrations accepts a starting migration. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", "0003", interactive=False, verbosity=1, stdout=out, ) squashed_migration_file = os.path.join( migration_dir, "0002_second_squashed_0003_third.py" ) with open(squashed_migration_file, encoding="utf-8") as fp: content = fp.read() if HAS_BLACK: test_str = ' ("migrations", "0001_initial")' else: test_str = " ('migrations', '0001_initial')" self.assertIn(test_str, content) self.assertNotIn("initial = True", content) out = out.getvalue() self.assertNotIn(" - 0001_initial", out) self.assertIn(" - 0002_second", out) self.assertIn(" - 0003_third", out) def test_squashmigrations_invalid_start(self): """ squashmigrations doesn't accept a starting migration after the ending migration. """ with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ): msg = ( "The migration 'migrations.0003_third' cannot be found. Maybe " "it comes after the migration 'migrations.0002_second'" ) with self.assertRaisesMessage(CommandError, msg): call_command( "squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0, ) def test_squashed_name_with_start_migration_name(self): """--squashed-name specifies the new migration's name.""" squashed_name = "squashed_name" with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0001", "0002", squashed_name=squashed_name, interactive=False, verbosity=0, ) squashed_migration_file = os.path.join( migration_dir, "0001_%s.py" % squashed_name ) self.assertTrue(os.path.exists(squashed_migration_file)) def test_squashed_name_without_start_migration_name(self): """--squashed-name also works if a start migration is omitted.""" squashed_name = "squashed_name" with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0001", squashed_name=squashed_name, interactive=False, verbosity=0, ) squashed_migration_file = os.path.join( migration_dir, "0001_%s.py" % squashed_name ) self.assertTrue(os.path.exists(squashed_migration_file)) def test_squashed_name_exists(self): msg = "Migration 0001_initial already exists. Use a different name." with self.temporary_migration_module(module="migrations.test_migrations"): with self.assertRaisesMessage(CommandError, msg): call_command( "squashmigrations", "migrations", "0001", "0002", squashed_name="initial", interactive=False, verbosity=0, ) def test_squashmigrations_manual_porting(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_manual_porting", ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", interactive=False, stdout=out, no_color=True, ) squashed_migration_file = os.path.join( migration_dir, "0001_squashed_0002_second.py", ) self.assertTrue(os.path.exists(squashed_migration_file)) black_warning = "" if HAS_BLACK: black_warning = ( "Squashed migration couldn't be formatted using the " '"black" command. You can call it manually.\n' ) self.assertEqual( out.getvalue(), f"Will squash the following migrations:\n" f" - 0001_initial\n" f" - 0002_second\n" f"Optimizing...\n" f" No optimizations possible.\n" f"Created new squashed migration {squashed_migration_file}\n" f" You should commit this migration but leave the old ones in place;\n" f" the new migration will be used for new installs. Once you are sure\n" f" all instances of the codebase have applied the migrations you " f"squashed,\n" f" you can delete them.\n" f"Manual porting required\n" f" Your migrations contained functions that must be manually copied " f"over,\n" f" as we could not safely copy their implementation.\n" f" See the comment at the top of the squashed migration for details.\n" + black_warning, ) class AppLabelErrorTests(TestCase): """ This class inherits TestCase because MigrationTestBase uses `available_apps = ['migrations']` which means that it's the only installed app. 'django.contrib.auth' must be in INSTALLED_APPS for some of these tests. """ nonexistent_app_error = "No installed app with label 'nonexistent_app'." did_you_mean_auth_error = ( "No installed app with label 'django.contrib.auth'. Did you mean 'auth'?" ) def test_makemigrations_nonexistent_app_label(self): err = io.StringIO() with self.assertRaises(SystemExit): call_command("makemigrations", "nonexistent_app", stderr=err) self.assertIn(self.nonexistent_app_error, err.getvalue()) def test_makemigrations_app_name_specified_as_label(self): err = io.StringIO() with self.assertRaises(SystemExit): call_command("makemigrations", "django.contrib.auth", stderr=err) self.assertIn(self.did_you_mean_auth_error, err.getvalue()) def test_migrate_nonexistent_app_label(self): with self.assertRaisesMessage(CommandError, self.nonexistent_app_error): call_command("migrate", "nonexistent_app") def test_migrate_app_name_specified_as_label(self): with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error): call_command("migrate", "django.contrib.auth") def test_showmigrations_nonexistent_app_label(self): err = io.StringIO() with self.assertRaises(SystemExit): call_command("showmigrations", "nonexistent_app", stderr=err) self.assertIn(self.nonexistent_app_error, err.getvalue()) def test_showmigrations_app_name_specified_as_label(self): err = io.StringIO() with self.assertRaises(SystemExit): call_command("showmigrations", "django.contrib.auth", stderr=err) self.assertIn(self.did_you_mean_auth_error, err.getvalue()) def test_sqlmigrate_nonexistent_app_label(self): with self.assertRaisesMessage(CommandError, self.nonexistent_app_error): call_command("sqlmigrate", "nonexistent_app", "0002") def test_sqlmigrate_app_name_specified_as_label(self): with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error): call_command("sqlmigrate", "django.contrib.auth", "0002") def test_squashmigrations_nonexistent_app_label(self): with self.assertRaisesMessage(CommandError, self.nonexistent_app_error): call_command("squashmigrations", "nonexistent_app", "0002") def test_squashmigrations_app_name_specified_as_label(self): with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error): call_command("squashmigrations", "django.contrib.auth", "0002") def test_optimizemigration_nonexistent_app_label(self): with self.assertRaisesMessage(CommandError, self.nonexistent_app_error): call_command("optimizemigration", "nonexistent_app", "0002") def test_optimizemigration_app_name_specified_as_label(self): with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error): call_command("optimizemigration", "django.contrib.auth", "0002") class OptimizeMigrationTests(MigrationTestBase): def test_no_optimization_possible(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "optimizemigration", "migrations", "0002", stdout=out, no_color=True ) migration_file = os.path.join(migration_dir, "0002_second.py") self.assertTrue(os.path.exists(migration_file)) call_command( "optimizemigration", "migrations", "0002", stdout=out, no_color=True, verbosity=0, ) self.assertEqual(out.getvalue(), "No optimizations possible.\n") def test_optimization(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "optimizemigration", "migrations", "0001", stdout=out, no_color=True ) initial_migration_file = os.path.join(migration_dir, "0001_initial.py") self.assertTrue(os.path.exists(initial_migration_file)) with open(initial_migration_file) as fp: content = fp.read() self.assertIn( '("bool", models.BooleanField' if HAS_BLACK else "('bool', models.BooleanField", content, ) self.assertEqual( out.getvalue(), f"Optimizing from 4 operations to 2 operations.\n" f"Optimized migration {initial_migration_file}\n", ) def test_optimization_no_verbosity(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "optimizemigration", "migrations", "0001", stdout=out, no_color=True, verbosity=0, ) initial_migration_file = os.path.join(migration_dir, "0001_initial.py") self.assertTrue(os.path.exists(initial_migration_file)) with open(initial_migration_file) as fp: content = fp.read() self.assertIn( '("bool", models.BooleanField' if HAS_BLACK else "('bool', models.BooleanField", content, ) self.assertEqual(out.getvalue(), "") def test_creates_replace_migration_manual_porting(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_manual_porting" ) as migration_dir: call_command( "optimizemigration", "migrations", "0003", stdout=out, no_color=True ) optimized_migration_file = os.path.join( migration_dir, "0003_third_optimized.py" ) self.assertTrue(os.path.exists(optimized_migration_file)) with open(optimized_migration_file) as fp: content = fp.read() self.assertIn("replaces = [", content) black_warning = "" if HAS_BLACK: black_warning = ( "Optimized migration couldn't be formatted using the " '"black" command. You can call it manually.\n' ) self.assertEqual( out.getvalue(), "Optimizing from 3 operations to 2 operations.\n" "Manual porting required\n" " Your migrations contained functions that must be manually copied over,\n" " as we could not safely copy their implementation.\n" " See the comment at the top of the optimized migration for details.\n" + black_warning + f"Optimized migration {optimized_migration_file}\n", ) def test_fails_squash_migration_manual_porting(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_manual_porting" ) as migration_dir: msg = ( "Migration will require manual porting but is already a squashed " "migration.\nTransition to a normal migration first: " "https://docs.djangoproject.com/en/dev/topics/migrations/" "#squashing-migrations" ) with self.assertRaisesMessage(CommandError, msg): call_command("optimizemigration", "migrations", "0004", stdout=out) optimized_migration_file = os.path.join( migration_dir, "0004_fourth_optimized.py" ) self.assertFalse(os.path.exists(optimized_migration_file)) self.assertEqual( out.getvalue(), "Optimizing from 3 operations to 2 operations.\n" ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_optimizemigration_check(self): with self.assertRaises(SystemExit): call_command( "optimizemigration", "--check", "migrations", "0001", verbosity=0 ) call_command("optimizemigration", "--check", "migrations", "0002", verbosity=0) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app_simple"], ) def test_app_without_migrations(self): msg = "App 'unmigrated_app_simple' does not have migrations." with self.assertRaisesMessage(CommandError, msg): call_command("optimizemigration", "unmigrated_app_simple", "0001") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_clashing_prefix"}, ) def test_ambigious_prefix(self): msg = ( "More than one migration matches 'a' in app 'migrations'. Please " "be more specific." ) with self.assertRaisesMessage(CommandError, msg): call_command("optimizemigration", "migrations", "a") @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_unknown_prefix(self): msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'." with self.assertRaisesMessage(CommandError, msg): call_command("optimizemigration", "migrations", "nonexistent")
a0b6144fc555c26add9ad92f316af2c4262c899fa5cb918e99871e35f6a821e1
import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, migrations, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_lru_cache from .models import FoodManager, FoodQuerySet class DeconstructibleObject: """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return (self.__module__ + "." + self.__class__.__name__, self.args, self.kwargs) class BaseAutodetectorTests(TestCase): def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations_ in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations_: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail( "Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), ) ) def assertMigrationDependencies(self, changes, app_label, position, dependencies): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if set(migration.dependencies) != set(dependencies): self.fail( "Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), ) ) def assertOperationTypes(self, changes, app_label, position, types): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] real_types = [ operation.__class__.__name__ for operation in migration.operations ] if types != real_types: self.fail( "Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), ) ) def assertOperationAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail( "Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(operation, attr, None), self.repr_changes(changes), ) ) def assertOperationFieldAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] if not hasattr(operation, "field"): self.fail( "No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_position, ) ) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail( "Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, " "got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(field, attr, None), self.repr_changes(changes), ) ) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def get_changes(self, before_states, after_states, questioner=None): if not isinstance(before_states, ProjectState): before_states = self.make_project_state(before_states) if not isinstance(after_states, ProjectState): after_states = self.make_project_state(after_states) return MigrationAutodetector( before_states, after_states, questioner, )._detect_changes() class AutodetectorTests(BaseAutodetectorTests): """ Tests the migration autodetector. """ author_empty = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_name = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) author_name_null = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ], ) author_name_longer = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ], ) author_name_renamed = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ], ) author_name_default = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default="Ada Lovelace")), ], ) author_name_check_constraint = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) author_dates_of_birth_auto_now = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now=True)), ("date_time_of_birth", models.DateTimeField(auto_now=True)), ("time_of_birth", models.TimeField(auto_now=True)), ], ) author_dates_of_birth_auto_now_add = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now_add=True)), ("date_time_of_birth", models.DateTimeField(auto_now_add=True)), ("time_of_birth", models.TimeField(auto_now_add=True)), ], ) author_name_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_4 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_list_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 999] ), ), ], ) author_name_deconstructible_tuple_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 999) ), ), ], ) author_name_deconstructible_dict_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 999}, ), ), ], ) author_name_nested_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2-changed"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_extra_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), None, a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c-changed")), ), ), ), ], ) author_name_nested_deconstructible_extra_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), c=None, ), ), ), ], ) author_custom_pk = ModelState( "testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))] ) author_with_biography_non_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ], ) author_with_biography_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ], ) author_with_book = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_book_order_wrt = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}, ) author_renamed_with_book = ModelState( "testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_publisher_string = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ], ) author_with_publisher = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) author_with_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ], ) author_with_custom_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ], ) author_proxy = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_options = ModelState( "testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author",), ) author_proxy_notproxy = ModelState( "testapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_third = ModelState( "thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_third_notproxy = ModelState( "thirdapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_proxy = ModelState( "testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy",) ) author_unmanaged = ModelState( "testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author",) ) author_unmanaged_managed = ModelState( "testapp", "AuthorUnmanaged", [], {}, ("testapp.author",) ) author_unmanaged_default_pk = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_unmanaged_custom_pk = ModelState( "testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ], ) author_with_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ], ) author_with_m2m_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ], ) author_with_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract"), ), ], ) author_with_renamed_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Deal"), ), ], ) author_with_former_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ], ) author_with_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) author_with_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_with_new_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}, ) author_renamed_with_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_renamed_with_new_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}, ) contract = ModelState( "testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) contract_renamed = ModelState( "testapp", "Deal", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) publisher = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) publisher_with_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_aardvark_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_book = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) other_pony = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], ) other_pony_food = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) other_stable = ModelState( "otherapp", "Stable", [("id", models.AutoField(primary_key=True))] ) third_thing = ModelState( "thirdapp", "Thing", [("id", models.AutoField(primary_key=True))] ) book = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.AAuthorProxyProxy", models.CASCADE)), ], ) book_migrations_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_no_author_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.IntegerField()), ("title", models.CharField(max_length=200)), ], ) book_with_no_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ) book_with_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_field_and_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors_through_attribution = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ( "authors", models.ManyToManyField( "testapp.Author", through="otherapp.Attribution" ), ), ("title", models.CharField(max_length=200)), ], ) book_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["author", "title"], name="book_title_author_idx") ], }, ) book_unordered_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["title", "author"], name="book_author_title_idx") ], }, ) book_unique_together = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("author", "title")}, }, ) book_unique_together_2 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "author")}, }, ) book_unique_together_3 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "newfield")}, }, ) book_unique_together_4 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "newfield2")}, }, ) attribution = ModelState( "otherapp", "Attribution", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) edition = ModelState( "thirdapp", "Edition", [ ("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) custom_user = ModelState( "thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], bases=(AbstractBaseUser,), ) custom_user_no_inherit = ModelState( "thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], ) aardvark = ModelState( "thirdapp", "Aardvark", [("id", models.AutoField(primary_key=True))] ) aardvark_testapp = ModelState( "testapp", "Aardvark", [("id", models.AutoField(primary_key=True))] ) aardvark_based_on_author = ModelState( "testapp", "Aardvark", [], bases=("testapp.Author",) ) aardvark_pk_fk_author = ModelState( "testapp", "Aardvark", [ ( "id", models.OneToOneField( "testapp.Author", models.CASCADE, primary_key=True ), ), ], ) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) rabbit = ModelState( "eggs", "Rabbit", [ ("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight", models.CASCADE)), ("parent", models.ForeignKey("eggs.Rabbit", models.CASCADE)), ], { "unique_together": {("parent", "knight")}, "indexes": [ models.Index( fields=["parent", "knight"], name="rabbit_circular_fk_index" ) ], }, ) def test_arrange_for_graph(self): """Tests auto-naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial"), ) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("otherapp", "0001_initial"), ) # Use project state to make a new migration change set before = self.make_project_state([self.publisher, self.other_pony]) after = self.make_project_state( [ self.author_empty, self.publisher, self.other_pony, self.other_stable, ] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph changes = autodetector.arrange_for_graph(changes, graph) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_author") self.assertEqual( changes["testapp"][0].dependencies, [("testapp", "0002_foobar")] ) self.assertEqual(changes["otherapp"][0].name, "0002_stable") self.assertEqual( changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_arrange_for_graph_with_multiple_initial(self): # Make a fake graph. graph = MigrationGraph() # Use project state to make a new migration change set. before = self.make_project_state([]) after = self.make_project_state( [self.author_with_book, self.book, self.attribution] ) autodetector = MigrationAutodetector( before, after, MigrationQuestioner({"ask_initial": True}) ) changes = autodetector._detect_changes() changes = autodetector.arrange_for_graph(changes, graph) self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].dependencies, []) self.assertEqual(changes["otherapp"][1].name, "0002_initial") self.assertCountEqual( changes["otherapp"][1].dependencies, [("testapp", "0001_initial"), ("otherapp", "0001_initial")], ) self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual( changes["testapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_trim_apps(self): """ Trim does not remove dependencies but does remove unwanted apps. """ # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state( [self.author_empty, self.other_pony, self.other_stable, self.third_thing] ) autodetector = MigrationAutodetector( before, after, MigrationQuestioner({"ask_initial": True}) ) changes = autodetector._detect_changes() # Run through arrange_for_graph graph = MigrationGraph() changes = autodetector.arrange_for_graph(changes, graph) changes["testapp"][0].dependencies.append(("otherapp", "0001_initial")) changes = autodetector._trim_to_apps(changes, {"testapp"}) # Make sure there's the right set of migrations self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertNotIn("thirdapp", changes) def test_custom_migration_name(self): """Tests custom naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial"), ) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state( [self.author_empty, self.other_pony, self.other_stable] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph migration_name = "custom_name" changes = autodetector.arrange_for_graph(changes, graph, migration_name) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_%s" % migration_name) self.assertEqual( changes["testapp"][0].dependencies, [("testapp", "0002_foobar")] ) self.assertEqual(changes["otherapp"][0].name, "0002_%s" % migration_name) self.assertEqual( changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_new_model(self): """Tests autodetection of new models.""" changes = self.get_changes([], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Pony") self.assertEqual( [name for name, mgr in changes["otherapp"][0].operations[0].managers], ["food_qs", "food_mgr", "food_mgr_kwargs"], ) def test_old_model(self): """Tests deletion of old models.""" changes = self.get_changes([self.author_empty], []) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") def test_add_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_empty], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_date_fields_with_auto_now_not_asking_for_default( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now=True) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_date_fields_with_auto_now_add_not_asking_for_null_addition( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now_add] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_auto_now_add_addition" ) def test_add_date_fields_with_auto_now_add_asking_for_default( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now_add] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) self.assertEqual(mocked_ask_method.call_count, 3) def test_remove_field(self): """Tests autodetection of removed fields.""" changes = self.get_changes([self.author_name], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_alter_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_name], [self.author_name_longer]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) def test_supports_functools_partial(self): def _content_file_name(instance, filename, key, **kwargs): return "{}/{}".format(instance, filename) def content_file_name(key, **kwargs): return functools.partial(_content_file_name, key, **kwargs) # An unchanged partial reference. before = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file") ), ), ], ) ] after = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file") ), ), ], ) ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, "testapp", 0) # A changed partial reference. args_changed = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("other-file") ), ), ], ) ] changes = self.get_changes(before, args_changed) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) # Can't use assertOperationFieldAttributes because we need the # deconstructed version, i.e., the exploded func/args/keywords rather # than the partial: we don't care if it's not the same instance of the # partial, only if it's the same source function, args, and keywords. value = changes["testapp"][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ("other-file",), {}), (value.func, value.args, value.keywords), ) kwargs_changed = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file", spam="eggs"), ), ), ], ) ] changes = self.get_changes(before, kwargs_changed) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) value = changes["testapp"][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ("file",), {"spam": "eggs"}), (value.func, value.args, value.keywords), ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_alter_field_to_not_null_with_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default="Ada Lovelace" ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", return_value=models.NOT_PROVIDED, ) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default=models.NOT_PROVIDED ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", return_value="Some Name", ) def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=False ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default="Some Name" ) def test_rename_field(self): """Tests autodetection of renamed fields.""" changes = self.get_changes( [self.author_name], [self.author_name_renamed], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="name", new_name="names" ) def test_rename_field_foreign_key_to_field(self): before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "foo", models.ForeignKey("app.Foo", models.CASCADE, to_field="field"), ), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("renamed_field", models.IntegerField(unique=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "foo", models.ForeignKey( "app.Foo", models.CASCADE, to_field="renamed_field" ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, old_name="field", new_name="renamed_field" ) def test_rename_foreign_object_fields(self): fields = ("first", "second") renamed_fields = ("first_renamed", "second_renamed") before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ], options={"unique_together": {fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=fields, to_fields=fields, ), ), ], ), ] # Case 1: to_fields renames. after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first_renamed", models.IntegerField()), ("second_renamed", models.IntegerField()), ], options={"unique_together": {renamed_fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=fields, to_fields=renamed_fields, ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes( changes, "app", 0, ["RenameField", "RenameField", "AlterUniqueTogether"] ) self.assertOperationAttributes( changes, "app", 0, 0, model_name="foo", old_name="first", new_name="first_renamed", ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="foo", old_name="second", new_name="second_renamed", ) # Case 2: from_fields renames. after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ], options={"unique_together": {fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first_renamed", models.IntegerField()), ("second_renamed", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=renamed_fields, to_fields=fields, ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="bar", old_name="first", new_name="first_renamed", ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="bar", old_name="second", new_name="second_renamed", ) def test_rename_referenced_primary_key(self): before = [ ModelState( "app", "Foo", [ ("id", models.CharField(primary_key=True, serialize=False)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] after = [ ModelState( "app", "Foo", [("renamed_id", models.CharField(primary_key=True, serialize=False))], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, old_name="id", new_name="renamed_id" ) def test_rename_field_preserved_db_column(self): """ RenameField is used if a field is renamed and db_column equal to the old field's column is added. """ before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("renamed_field", models.IntegerField(db_column="field")), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="foo", name="field", ) self.assertEqual( changes["app"][0].operations[0].field.deconstruct(), ( "field", "django.db.models.IntegerField", [], {"db_column": "field"}, ), ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="foo", old_name="field", new_name="renamed_field", ) def test_rename_related_field_preserved_db_column(self): before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "renamed_foo", models.ForeignKey( "app.Foo", models.CASCADE, db_column="foo_id" ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="bar", name="foo", ) self.assertEqual( changes["app"][0].operations[0].field.deconstruct(), ( "foo", "django.db.models.ForeignKey", [], {"to": "app.foo", "on_delete": models.CASCADE, "db_column": "foo_id"}, ), ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="bar", old_name="foo", new_name="renamed_foo", ) def test_rename_field_with_renamed_model(self): changes = self.get_changes( [self.author_name], [ ModelState( "testapp", "RenamedAuthor", [ ("id", models.AutoField(primary_key=True)), ("renamed_name", models.CharField(max_length=200)), ], ), ], MigrationQuestioner({"ask_rename_model": True, "ask_rename": True}), ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel", "RenameField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="RenamedAuthor", ) self.assertOperationAttributes( changes, "testapp", 0, 1, old_name="name", new_name="renamed_name", ) def test_rename_model(self): """Tests autodetection of renamed models.""" changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_author_renamed], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="Writer" ) # Now that RenameModel handles related fields too, there should be # no AlterField for the related field. self.assertNumberMigrations(changes, "otherapp", 0) def test_rename_model_case(self): """ Model name is case-insensitive. Changing case doesn't lead to any autodetected operations. """ author_renamed = ModelState( "testapp", "author", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes( [self.author_empty, self.book], [author_renamed, self.book], questioner=MigrationQuestioner({"ask_rename_model": True}), ) self.assertNumberMigrations(changes, "testapp", 0) self.assertNumberMigrations(changes, "otherapp", 0) def test_renamed_referenced_m2m_model_case(self): publisher_renamed = ModelState( "testapp", "publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) changes = self.get_changes( [self.publisher, self.author_with_m2m], [publisher_renamed, self.author_with_m2m], questioner=MigrationQuestioner({"ask_rename_model": True}), ) self.assertNumberMigrations(changes, "testapp", 0) self.assertNumberMigrations(changes, "otherapp", 0) def test_rename_m2m_through_model(self): """ Tests autodetection of renamed models that are used in M2M relations as through models. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [ self.author_with_renamed_m2m_through, self.publisher, self.contract_renamed, ], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Contract", new_name="Deal" ) def test_rename_model_with_renamed_rel_field(self): """ Tests autodetection of renamed models while simultaneously renaming one of the fields that relate to the renamed model. """ changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_field_and_author_renamed], MigrationQuestioner({"ask_rename": True, "ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="Writer" ) # Right number/type of migrations for related field rename? # Alter is already taken care of. self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameField"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, old_name="author", new_name="writer" ) def test_rename_model_with_fks_in_different_position(self): """ #24537 - The order of fields in a model does not influence the RenameModel detection. """ before = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "testapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("some_label", models.CharField(max_length=255)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ], ), ] after = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "testapp", "RenamedEntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ("some_label", models.CharField(max_length=255)), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename_model": True}) ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB" ) def test_rename_model_reverse_relation_dependencies(self): """ The migration to rename a model pointed to by a foreign key in another app must run after the other app's migration that adds the foreign key with model's original name. Therefore, the renaming migration has a dependency on that other migration. """ before = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "otherapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ], ), ] after = [ ModelState( "testapp", "RenamedEntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "otherapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ( "entity_a", models.ForeignKey("testapp.RenamedEntityA", models.CASCADE), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename_model": True}) ) self.assertNumberMigrations(changes, "testapp", 1) self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "__first__")] ) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="EntityA", new_name="RenamedEntityA" ) def test_fk_dependency(self): """Having a ForeignKey automatically adds a dependency.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (author), # thirdapp (edition) depends on otherapp (book) changes = self.get_changes([], [self.author_name, self.book, self.edition]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes(changes, "thirdapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="Edition") self.assertMigrationDependencies( changes, "thirdapp", 0, [("otherapp", "auto_1")] ) def test_proxy_fk_dependency(self): """FK dependencies still work on proxy models.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (authorproxy) changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("thirdapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes(changes, "thirdapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="AuthorProxy") self.assertMigrationDependencies( changes, "thirdapp", 0, [("testapp", "auto_1")] ) def test_same_app_no_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) def test_circular_fk_dependency(self): """ Having a circular ForeignKey dependency automatically resolves the situation into 2 migrations on one side and 1 on the other. """ changes = self.get_changes( [], [self.author_with_book, self.book, self.publisher_with_book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 2) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationTypes(changes, "otherapp", 1, ["AddField"]) self.assertMigrationDependencies(changes, "otherapp", 0, []) self.assertMigrationDependencies( changes, "otherapp", 1, [("otherapp", "auto_1"), ("testapp", "auto_1")] ) # both split migrations should be `initial` self.assertTrue(changes["otherapp"][0].initial) self.assertTrue(changes["otherapp"][1].initial) def test_same_app_circular_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes( [], [self.author_with_publisher, self.publisher_with_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "CreateModel", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, "testapp", 0, []) def test_same_app_circular_fk_dependency_with_unique_together_and_indexes(self): """ #22275 - A migration with circular FK dependency does not try to create unique together constraint and indexes before creating all required fields first. """ changes = self.get_changes([], [self.knight, self.rabbit]) # Right number/type of migrations? self.assertNumberMigrations(changes, "eggs", 1) self.assertOperationTypes( changes, "eggs", 0, ["CreateModel", "CreateModel", "AddIndex", "AlterUniqueTogether"], ) self.assertNotIn("unique_together", changes["eggs"][0].operations[0].options) self.assertNotIn("unique_together", changes["eggs"][0].operations[1].options) self.assertMigrationDependencies(changes, "eggs", 0, []) def test_alter_db_table_add(self): """Tests detection for adding db_table in model's options.""" changes = self.get_changes( [self.author_empty], [self.author_with_db_table_options] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table="author_one" ) def test_alter_db_table_change(self): """Tests detection for changing db_table in model's options'.""" changes = self.get_changes( [self.author_with_db_table_options], [self.author_with_new_db_table_options] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table="author_two" ) def test_alter_db_table_remove(self): """Tests detection for removing db_table in model's options.""" changes = self.get_changes( [self.author_with_db_table_options], [self.author_empty] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table=None ) def test_alter_db_table_no_changes(self): """ Alter_db_table doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_with_db_table_options] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_keep_db_table_with_model_change(self): """ Tests when model changes but db_table stays as-is, autodetector must not create more than one operation. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor" ) def test_alter_db_table_with_model_change(self): """ Tests when model and db_table changes, autodetector must create two operations. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_new_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RenameModel", "AlterModelTable"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="newauthor", table="author_three" ) def test_identical_regex_doesnt_alter(self): from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[ RegexValidator( re.compile("^[-a-zA-Z0-9_]+\\Z"), "Enter a valid “slug” consisting of letters, numbers, " "underscores or hyphens.", "invalid", ) ], ), ) ], ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))], ) changes = self.get_changes([from_state], [to_state]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 0) def test_different_regex_does_alter(self): from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[ RegexValidator( re.compile("^[a-z]+\\Z", 32), "Enter a valid “slug” consisting of letters, numbers, " "underscores or hyphens.", "invalid", ) ], ), ) ], ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))], ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_alter_regex_string_to_compiled_regex(self): regex_string = "^[a-z]+$" from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[RegexValidator(regex_string)] ), ) ], ) to_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[RegexValidator(re.compile(regex_string))], ), ) ], ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_empty_unique_together(self): """Empty unique_together shouldn't generate a migration.""" # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))] ) # Explicitly testing for None, since this was the issue in #23452 after # an AlterUniqueTogether operation with e.g. () as value model_state_none = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "unique_together": None, }, ) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "unique_together": set(), }, ) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ", ".join( o.__class__.__name__ for o in changes["a"][0].operations ) self.fail("Created operation(s) %s from %s" % (ops, msg)) tests = ( ( model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"', ), (model_state_not_specified, model_state_none, '"not specified" to "None"'), ( model_state_not_specified, model_state_empty, '"not specified" to "empty"', ), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), ( model_state_empty, model_state_not_specified, '"empty" to "not specified"', ), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_create_model_with_indexes(self): """Test creation of new model with indexes already defined.""" author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["name"], name="create_model_with_indexes_idx") ] }, ) changes = self.get_changes([], [author]) added_index = models.Index( fields=["name"], name="create_model_with_indexes_idx" ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel", "AddIndex"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Author") self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="author", index=added_index ) def test_add_indexes(self): """Test change detection of new indexes.""" changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_indexes] ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AddIndex"]) added_index = models.Index( fields=["author", "title"], name="book_title_author_idx" ) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", index=added_index ) def test_remove_indexes(self): """Test change detection of removed indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", name="book_title_author_idx" ) def test_rename_indexes(self): book_renamed_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index( fields=["author", "title"], name="renamed_book_title_author_idx" ) ], }, ) changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, book_renamed_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", new_name="renamed_book_title_author_idx", old_name="book_title_author_idx", ) def test_order_fields_indexes(self): """Test change detection of reordering of fields in indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book_unordered_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveIndex", "AddIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", name="book_title_author_idx" ) added_index = models.Index( fields=["title", "author"], name="book_author_title_idx" ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", index=added_index ) def test_create_model_with_check_constraint(self): """Test creation of new model with constraints already defined.""" author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) changes = self.get_changes([], [author]) added_constraint = models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddConstraint"] ) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Author") self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="author", constraint=added_constraint ) def test_add_constraints(self): """Test change detection of new constraints.""" changes = self.get_changes( [self.author_name], [self.author_name_check_constraint] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddConstraint"]) added_constraint = models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", constraint=added_constraint ) def test_remove_constraints(self): """Test change detection of removed constraints.""" changes = self.get_changes( [self.author_name_check_constraint], [self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveConstraint"]) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="name_contains_bob" ) def test_add_unique_together(self): """Tests unique_together detection.""" changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_unique_together], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}, ) def test_remove_unique_together(self): """Tests unique_together detection.""" changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) def test_unique_together_remove_fk(self): """Tests unique_together and field removal detection & ordering""" changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book_with_no_author], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="author" ) def test_unique_together_no_changes(self): """ unique_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book_unique_together], ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_unique_together_ordering(self): """ unique_together also triggers on ordering changes. """ changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book_unique_together_2], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("title", "author")}, ) def test_add_field_and_unique_together(self): """ Added fields will be created before using them in unique_together. """ changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_unique_together_3], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AddField", "AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield")}, ) def test_create_model_and_unique_together(self): author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) book_with_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "author")}, }, ) changes = self.get_changes( [self.book_with_no_author], [author, book_with_author] ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 3) # Right actions order? self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AlterUniqueTogether"], ) def test_remove_field_and_unique_together(self): """ Removed fields will be removed after updating unique_together. """ changes = self.get_changes( [self.author_empty, self.book_unique_together_3], [self.author_empty, self.book_unique_together], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="newfield", ) def test_alter_field_and_unique_together(self): """Fields are altered after deleting some unique_together.""" initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField(db_index=True)), ], { "unique_together": {("name",)}, }, ) author_reversed_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, unique=True)), ("age", models.IntegerField()), ], { "unique_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterUniqueTogether", "AlterField", "AlterField", "AlterUniqueTogether", ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together=set(), ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="age", ) self.assertOperationAttributes( changes, "testapp", 0, 2, model_name="author", name="name", ) self.assertOperationAttributes( changes, "testapp", 0, 3, name="author", unique_together={("age",)}, ) def test_partly_alter_unique_together_increase(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",), ("age",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together={("name",), ("age",)}, ) def test_partly_alter_unique_together_decrease(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",), ("age",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together={("name",)}, ) def test_rename_field_and_unique_together(self): """Fields are renamed before updating unique_together.""" changes = self.get_changes( [self.author_empty, self.book_unique_together_3], [self.author_empty, self.book_unique_together_4], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RenameField", "AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield2")}, ) def test_proxy(self): """The autodetector correctly deals with proxy models.""" # First, we test adding a proxy model changes = self.get_changes( [self.author_empty], [self.author_empty, self.author_proxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []}, ) # Now, we test turning a proxy model into a non-proxy model # It should delete the proxy then make the real one changes = self.get_changes( [self.author_empty, self.author_proxy], [self.author_empty, self.author_proxy_notproxy], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy") self.assertOperationAttributes( changes, "testapp", 0, 1, name="AuthorProxy", options={} ) def test_proxy_non_model_parent(self): class Mixin: pass author_proxy_non_model_parent = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, (Mixin, "testapp.author"), ) changes = self.get_changes( [self.author_empty], [self.author_empty, author_proxy_non_model_parent], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []}, bases=(Mixin, "testapp.author"), ) def test_proxy_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on proxy models. """ # First, we test the default pk field name changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk] ) # The model the FK is pointing from and to. self.assertEqual( changes["otherapp"][0].operations[0].fields[2][1].remote_field.model, "thirdapp.AuthorProxy", ) # Now, we test the custom pk field name changes = self.get_changes( [], [self.author_custom_pk, self.author_proxy_third, self.book_proxy_fk] ) # The model the FK is pointing from and to. self.assertEqual( changes["otherapp"][0].operations[0].fields[2][1].remote_field.model, "thirdapp.AuthorProxy", ) def test_proxy_to_mti_with_fk_to_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [self.author_empty, self.author_proxy_third, self.book_proxy_fk], ) changes = self.get_changes([], to_state) fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "author"), ) self.assertEqual(fk_field.remote_field.model, "thirdapp.AuthorProxy") # Change AuthorProxy to use MTI. from_state = to_state.clone() to_state = self.make_project_state( [self.author_empty, self.author_proxy_third_notproxy, self.book_proxy_fk], ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["DeleteModel", "CreateModel"] ) # Right number/type of migrations for the Book model with a FK to # AuthorProxy? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) # otherapp should depend on thirdapp. self.assertMigrationDependencies( changes, "otherapp", 0, [("thirdapp", "auto_1")] ) # Now, test the pk table and field name. fk_field = changes["otherapp"][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("thirdapp", "authorproxy"), ) self.assertEqual(fk_field.remote_field.model, "thirdapp.AuthorProxy") def test_proxy_to_mti_with_fk_to_proxy_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [ self.author_empty, self.author_proxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ] ) changes = self.get_changes([], to_state) fk_field = changes["otherapp"][0].operations[0].fields[1][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "author"), ) self.assertEqual(fk_field.remote_field.model, "testapp.AAuthorProxyProxy") # Change AuthorProxy to use MTI. FK still points to AAuthorProxyProxy, # a proxy of AuthorProxy. from_state = to_state.clone() to_state = self.make_project_state( [ self.author_empty, self.author_proxy_notproxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ] ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) # Right number/type of migrations for the Book model with a FK to # AAuthorProxyProxy? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) # otherapp should depend on testapp. self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "auto_1")] ) # Now, test the pk table and field name. fk_field = changes["otherapp"][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "authorproxy"), ) self.assertEqual(fk_field.remote_field.model, "testapp.AAuthorProxyProxy") def test_unmanaged_create(self): """The autodetector correctly deals with managed models.""" # First, we test adding an unmanaged model changes = self.get_changes( [self.author_empty], [self.author_empty, self.author_unmanaged] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorUnmanaged", options={"managed": False} ) def test_unmanaged_delete(self): changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel"]) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty, self.author_unmanaged_managed], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorunmanaged", options={} ) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. changes = self.get_changes( [self.author_empty, self.author_unmanaged_managed], [self.author_empty, self.author_unmanaged], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False} ) def test_unmanaged_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on unmanaged models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_unmanaged_default_pk, self.book]) # The model the FK on the book model points to. fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, "testapp.Author") # Now, we test the custom pk field name changes = self.get_changes([], [self.author_unmanaged_custom_pk, self.book]) # The model the FK on the book model points to. fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, "testapp.Author") @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable(self): with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes( [self.custom_user], [self.custom_user, self.author_with_custom_user] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies( changes, "testapp", 0, [("__setting__", "AUTH_USER_MODEL")] ) def test_swappable_lowercase(self): model_state = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ( "owner", models.ForeignKey( settings.AUTH_USER_MODEL.lower(), models.CASCADE, ), ), ], ) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Document") self.assertMigrationDependencies( changes, "testapp", 0, [("__setting__", "AUTH_USER_MODEL")], ) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_many_to_many_model_case(self): document_lowercase = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL.lower())), ], ) document = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL)), ], ) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes( [self.custom_user, document_lowercase], [self.custom_user, document], ) self.assertEqual(len(changes), 0) def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user]) with override_settings(AUTH_USER_MODEL="thirdapp.CustomUser"): after = self.make_project_state( [self.custom_user, self.author_with_custom_user] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="user" ) fk_field = changes["testapp"][0].operations[0].field self.assertEqual(fk_field.remote_field.model, "thirdapp.CustomUser") def test_add_field_with_default(self): """#22030 - Adding a field with a default should work.""" changes = self.get_changes([self.author_empty], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_custom_deconstructible(self): """ Two instances which deconstruct to the same value aren't considered a change. """ changes = self.get_changes( [self.author_name_deconstructible_1], [self.author_name_deconstructible_2] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_deconstruct_field_kwarg(self): """Field instances are handled correctly by nested deconstruction.""" changes = self.get_changes( [self.author_name_deconstructible_3], [self.author_name_deconstructible_4] ) self.assertEqual(changes, {}) def test_deconstructible_list(self): """Nested deconstruction descends into lists.""" # When lists contain items that deconstruct to identical values, those lists # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed lists should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_3], ) self.assertEqual(len(changes), 1) def test_deconstructible_tuple(self): """Nested deconstruction descends into tuples.""" # When tuples contain items that deconstruct to identical values, those tuples # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed tuples should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_3], ) self.assertEqual(len(changes), 1) def test_deconstructible_dict(self): """Nested deconstruction descends into dict values.""" # When dicts contain items whose values deconstruct to identical values, # those dicts should be considered equal for the purpose of detecting # state changes (even if the original values are unequal). changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed dicts should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_3], ) self.assertEqual(len(changes), 1) def test_nested_deconstructible_objects(self): """ Nested deconstruction is applied recursively to the args/kwargs of deconstructed objects. """ # If the items within a deconstructed object's args/kwargs have the same # deconstructed values - whether or not the items themselves are different # instances - then the object as a whole is regarded as unchanged. changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_2], ) self.assertEqual(changes, {}) # Differences that exist solely within the args list of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_arg], ) self.assertEqual(len(changes), 1) # Additional args should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_arg], ) self.assertEqual(len(changes), 1) # Differences that exist solely within the kwargs dict of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_kwarg], ) self.assertEqual(len(changes), 1) # Additional kwargs should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_kwarg], ) self.assertEqual(len(changes), 1) def test_deconstruct_type(self): """ #22951 -- Uninstantiated classes with deconstruct are correctly returned by deep_deconstruct during serialization. """ author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, # IntegerField intentionally not instantiated. default=models.IntegerField, ), ), ], ) changes = self.get_changes([], [author]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) def test_replace_string_with_foreignkey(self): """ #22300 - Adding an FK in the same "spot" as a deleted CharField should work. """ changes = self.get_changes( [self.author_with_publisher_string], [self.author_with_publisher, self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="publisher_name") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") def test_foreign_key_removed_before_target_model(self): """ Removing an FK and the model it targets in the same change must remove the FK field before the model to maintain consistency. """ changes = self.get_changes( [self.author_with_publisher, self.publisher], [self.author_name] ) # removes both the model and FK # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_many_to_many(self, mocked_ask_method): """#22435 - Adding a ManyToManyField should not prompt for a default.""" changes = self.get_changes( [self.author_empty, self.publisher], [self.author_with_m2m, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers") def test_alter_many_to_many(self): changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_m2m_blank, self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers") def test_create_with_through_model(self): """ Adding a m2m with a through model and the models that use it should be ordered correctly. """ changes = self.get_changes( [], [self.author_with_m2m_through, self.publisher, self.contract] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "CreateModel", "CreateModel", "CreateModel", "AddField", ], ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Contract") self.assertOperationAttributes( changes, "testapp", 0, 3, model_name="author", name="publishers" ) def test_many_to_many_removed_before_through_model(self): """ Removing a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution, ], [self.book_with_no_author, self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RemoveField", "DeleteModel"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="authors", model_name="book" ) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="Attribution") def test_many_to_many_removed_before_through_model_2(self): """ Removing a model that contains a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution, ], [self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="authors", model_name="book" ) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="Attribution") self.assertOperationAttributes(changes, "otherapp", 0, 2, name="Book") def test_m2m_w_through_multistep_remove(self): """ A model with a m2m field that specifies a "through" model cannot be removed in the same migration as that through model as the schema will pass through an inconsistent state. The autodetector should produce two migrations to avoid this issue. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "RemoveField", "DeleteModel", "DeleteModel"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", model_name="contract" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="publisher", model_name="contract" ) self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 3, name="Contract") def test_concrete_field_changed_to_many_to_many(self): """ #23938 - Changing a concrete field into a ManyToManyField first removes the concrete field and then adds the m2m field. """ changes = self.get_changes( [self.author_with_former_m2m], [self.author_with_m2m, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes( changes, "testapp", 0, 1, name="publishers", model_name="author" ) self.assertOperationAttributes( changes, "testapp", 0, 2, name="publishers", model_name="author" ) def test_many_to_many_changed_to_concrete_field(self): """ #23938 - Changing a ManyToManyField into a concrete field first removes the m2m field and then adds the concrete field. """ changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_former_m2m] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "DeleteModel", "AddField"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="publishers", model_name="author" ) self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes( changes, "testapp", 0, 2, name="publishers", model_name="author" ) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ If two models with a ForeignKey from one to the other are removed at the same time, the autodetector should remove them in the correct order. """ changes = self.get_changes( [self.author_with_publisher, self.publisher_with_author], [] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", model_name="publisher" ) self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Publisher") def test_alter_model_options(self): """Changing a model's options should make a change.""" changes = self.get_changes([self.author_empty], [self.author_with_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, options={ "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) # Changing them back to empty should also make a change changes = self.get_changes([self.author_with_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", options={} ) def test_alter_model_options_proxy(self): """Changing a proxy model's options should also make a change.""" changes = self.get_changes( [self.author_proxy, self.author_empty], [self.author_proxy_options, self.author_empty], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorproxy", options={"verbose_name": "Super Author"}, ) def test_set_alter_order_with_respect_to(self): """Setting order_with_respect_to adds a field.""" changes = self.get_changes( [self.book, self.author_with_book], [self.book, self.author_with_book_order_wrt], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterOrderWithRespectTo"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", order_with_respect_to="book" ) def test_add_alter_order_with_respect_to(self): """ Setting order_with_respect_to when adding the FK too does things in the right order. """ changes = self.get_changes( [self.author_name], [self.book, self.author_with_book_order_wrt] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AlterOrderWithRespectTo"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="book" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="author", order_with_respect_to="book" ) def test_remove_alter_order_with_respect_to(self): """ Removing order_with_respect_to when removing the FK too does things in the right order. """ changes = self.get_changes( [self.book, self.author_with_book_order_wrt], [self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterOrderWithRespectTo", "RemoveField"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", order_with_respect_to=None ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="book" ) def test_add_model_order_with_respect_to(self): """ Setting order_with_respect_to when adding the whole model does things in the right order. """ changes = self.get_changes([], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={"order_with_respect_to": "book"}, ) self.assertNotIn( "_order", [name for name, field in changes["testapp"][0].operations[0].fields], ) def test_add_model_order_with_respect_to_unique_together(self): changes = self.get_changes( [], [ self.book, ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "unique_together": {("id", "_order")}, }, ), ], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={ "order_with_respect_to": "book", "unique_together": {("id", "_order")}, }, ) def test_add_model_order_with_respect_to_index_constraint(self): tests = [ ( "AddIndex", { "indexes": [ models.Index(fields=["_order"], name="book_order_idx"), ] }, ), ( "AddConstraint", { "constraints": [ models.CheckConstraint( check=models.Q(_order__gt=1), name="book_order_gt_1", ), ] }, ), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", **extra_option, }, ) changes = self.get_changes([], [self.book, after]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "CreateModel", operation, ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={"order_with_respect_to": "book"}, ) def test_set_alter_order_with_respect_to_index_constraint_unique_together(self): tests = [ ( "AddIndex", { "indexes": [ models.Index(fields=["_order"], name="book_order_idx"), ] }, ), ( "AddConstraint", { "constraints": [ models.CheckConstraint( check=models.Q(_order__gt=1), name="book_order_gt_1", ), ] }, ), ("AlterUniqueTogether", {"unique_together": {("id", "_order")}}), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", **extra_option, }, ) changes = self.get_changes( [self.book, self.author_with_book], [self.book, after], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterOrderWithRespectTo", operation, ], ) def test_alter_model_managers(self): """ Changing the model managers adds a new operation. """ changes = self.get_changes([self.other_pony], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterModelManagers"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="pony") self.assertEqual( [name for name, mgr in changes["otherapp"][0].operations[0].managers], ["food_qs", "food_mgr", "food_mgr_kwargs"], ) self.assertEqual( changes["otherapp"][0].operations[0].managers[1][1].args, ("a", "b", 1, 2) ) self.assertEqual( changes["otherapp"][0].operations[0].managers[2][1].args, ("x", "y", 3, 4) ) def test_swappable_first_inheritance(self): """Swappable models get their CreateModel first.""" changes = self.get_changes([], [self.custom_user, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="CustomUser") self.assertOperationAttributes(changes, "thirdapp", 0, 1, name="Aardvark") def test_default_related_name_option(self): model_state = ModelState( "app", "model", [ ("id", models.AutoField(primary_key=True)), ], options={"default_related_name": "related_name"}, ) changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "app", 0, 0, name="model", options={"default_related_name": "related_name"}, ) altered_model_state = ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes([model_state], [altered_model_state]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "app", 0, 0, name="model", options={}) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_first_setting(self): """Swappable models get their CreateModel first.""" with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [self.custom_user_no_inherit, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="CustomUser") self.assertOperationAttributes(changes, "thirdapp", 0, 1, name="Aardvark") def test_bases_first(self): """Bases of other models come first.""" changes = self.get_changes( [], [self.aardvark_based_on_author, self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Aardvark") def test_bases_first_mixed_case_app_label(self): app_label = "MiXedCaseApp" changes = self.get_changes( [], [ ModelState( app_label, "owner", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( app_label, "place", [ ("id", models.AutoField(primary_key=True)), ( "owner", models.ForeignKey("MiXedCaseApp.owner", models.CASCADE), ), ], ), ModelState(app_label, "restaurant", [], bases=("MiXedCaseApp.place",)), ], ) self.assertNumberMigrations(changes, app_label, 1) self.assertOperationTypes( changes, app_label, 0, [ "CreateModel", "CreateModel", "CreateModel", ], ) self.assertOperationAttributes(changes, app_label, 0, 0, name="owner") self.assertOperationAttributes(changes, app_label, 0, 1, name="place") self.assertOperationAttributes(changes, app_label, 0, 2, name="restaurant") def test_multiple_bases(self): """ Inheriting models doesn't move *_ptr fields into AddField operations. """ A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))]) B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))]) C = ModelState("app", "C", [], bases=("app.A", "app.B")) D = ModelState("app", "D", [], bases=("app.A", "app.B")) E = ModelState("app", "E", [], bases=("app.A", "app.B")) changes = self.get_changes([], [A, B, C, D, E]) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes( changes, "app", 0, ["CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel"], ) self.assertOperationAttributes(changes, "app", 0, 0, name="A") self.assertOperationAttributes(changes, "app", 0, 1, name="B") self.assertOperationAttributes(changes, "app", 0, 2, name="C") self.assertOperationAttributes(changes, "app", 0, 3, name="D") self.assertOperationAttributes(changes, "app", 0, 4, name="E") def test_proxy_bases_first(self): """Bases of proxies come first.""" changes = self.get_changes( [], [self.author_empty, self.author_proxy, self.author_proxy_proxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="AuthorProxy") self.assertOperationAttributes( changes, "testapp", 0, 2, name="AAuthorProxyProxy" ) def test_pk_fk_included(self): """ A relation used as the primary key is kept as part of CreateModel. """ changes = self.get_changes([], [self.aardvark_pk_fk_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Aardvark") def test_first_dependency(self): """ A dependency to an app with no migrations uses __first__. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {"migrations"} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("migrations", "__first__")] ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_last_dependency(self): """ A dependency to an app with existing migrations uses the last migration of that app. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {"migrations"} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("migrations", "0002_second")] ) def test_alter_fk_before_model_deletion(self): """ ForeignKeys are altered _before_ the model they used to refer to are deleted. """ changes = self.get_changes( [self.author_name, self.publisher_with_author], [self.aardvark_testapp, self.publisher_with_aardvark_author], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "AlterField", "DeleteModel"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Aardvark") self.assertOperationAttributes(changes, "testapp", 0, 1, name="author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") def test_fk_dependency_other_app(self): """ #23100 - ForeignKeys correctly depend on other apps' models. """ changes = self.get_changes( [self.author_name, self.book], [self.author_with_book, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="book") self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "__first__")] ) def test_alter_unique_together_fk_to_m2m(self): changes = self.get_changes( [self.author_name, self.book_unique_together], [ self.author_name, ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ], ), ], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField", "AddField"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="author" ) self.assertOperationAttributes( changes, "otherapp", 0, 2, model_name="book", name="author" ) def test_alter_field_to_fk_dependency_other_app(self): changes = self.get_changes( [self.author_empty, self.book_with_no_author_fk], [self.author_empty, self.book], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "__first__")] ) def test_circular_dependency_mixed_addcreate(self): """ #23315 - The dependency resolver knows to put all CreateModel before AddField and not become unsolvable. """ address = ModelState( "a", "Address", [ ("id", models.AutoField(primary_key=True)), ("country", models.ForeignKey("b.DeliveryCountry", models.CASCADE)), ], ) person = ModelState( "a", "Person", [ ("id", models.AutoField(primary_key=True)), ], ) apackage = ModelState( "b", "APackage", [ ("id", models.AutoField(primary_key=True)), ("person", models.ForeignKey("a.Person", models.CASCADE)), ], ) country = ModelState( "b", "DeliveryCountry", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes([], [address, person, apackage, country]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "a", 0, ["CreateModel", "CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertOperationTypes(changes, "b", 0, ["CreateModel", "CreateModel"]) @override_settings(AUTH_USER_MODEL="a.Tenant") def test_circular_dependency_swappable(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): tenant = ModelState( "a", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("b.Address", models.CASCADE)), ], bases=(AbstractBaseUser,), ) address = ModelState( "b", "Address", [ ("id", models.AutoField(primary_key=True)), ( "tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE), ), ], ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertMigrationDependencies(changes, "a", 0, []) self.assertMigrationDependencies( changes, "a", 1, [("a", "auto_1"), ("b", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "b", 0, ["CreateModel"]) self.assertMigrationDependencies( changes, "b", 0, [("__setting__", "AUTH_USER_MODEL")] ) @override_settings(AUTH_USER_MODEL="b.Tenant") def test_circular_dependency_swappable2(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models but with the swappable not being the first migrated model. """ with isolate_lru_cache(apps.get_swappable_settings_name): address = ModelState( "a", "Address", [ ("id", models.AutoField(primary_key=True)), ( "tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE), ), ], ) tenant = ModelState( "b", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("a.Address", models.CASCADE)), ], bases=(AbstractBaseUser,), ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertMigrationDependencies(changes, "a", 0, []) self.assertMigrationDependencies( changes, "a", 1, [("__setting__", "AUTH_USER_MODEL"), ("a", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "b", 0, ["CreateModel"]) self.assertMigrationDependencies(changes, "b", 0, [("a", "auto_1")]) @override_settings(AUTH_USER_MODEL="a.Person") def test_circular_dependency_swappable_self(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): person = ModelState( "a", "Person", [ ("id", models.AutoField(primary_key=True)), ( "parent1", models.ForeignKey( settings.AUTH_USER_MODEL, models.CASCADE, related_name="children", ), ), ], ) changes = self.get_changes([], [person]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 1) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertMigrationDependencies(changes, "a", 0, []) @override_settings(AUTH_USER_MODEL="a.User") def test_swappable_circular_multi_mti(self): with isolate_lru_cache(apps.get_swappable_settings_name): parent = ModelState( "a", "Parent", [("user", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE))], ) child = ModelState("a", "Child", [], bases=("a.Parent",)) user = ModelState("a", "User", [], bases=(AbstractBaseUser, "a.Child")) changes = self.get_changes([], [parent, child, user]) self.assertNumberMigrations(changes, "a", 1) self.assertOperationTypes( changes, "a", 0, ["CreateModel", "CreateModel", "CreateModel", "AddField"] ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and blank `CharField` or `TextField` without default should not prompt for a default. """ changes = self.get_changes( [self.author_empty], [self.author_with_biography_blank] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition" ) def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField` without default should prompt for a default. """ changes = self.get_changes( [self.author_empty], [self.author_with_biography_non_blank] ) self.assertEqual(mocked_ask_method.call_count, 2) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0) def test_mti_inheritance_model_removal(self): Animal = ModelState( "app", "Animal", [ ("id", models.AutoField(primary_key=True)), ], ) Dog = ModelState("app", "Dog", [], bases=("app.Animal",)) changes = self.get_changes([Animal, Dog], [Animal]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "app", 0, 0, name="Dog") def test_add_model_with_field_removed_from_base_model(self): """ Removing a base field takes place before adding a new inherited model that has a field with the same name. """ before = [ ModelState( "app", "readable", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ), ] after = [ ModelState( "app", "readable", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "book", [ ("title", models.CharField(max_length=200)), ], bases=("app.readable",), ), ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RemoveField", "CreateModel"]) self.assertOperationAttributes( changes, "app", 0, 0, name="title", model_name="readable" ) self.assertOperationAttributes(changes, "app", 0, 1, name="book") def test_parse_number(self): tests = [ ("no_number", None), ("0001_initial", 1), ("0002_model3", 2), ("0002_auto_20380101_1112", 2), ("0002_squashed_0003", 3), ("0002_model2_squashed_0003_other4", 3), ("0002_squashed_0003_squashed_0004", 4), ("0002_model2_squashed_0003_other4_squashed_0005_other6", 5), ("0002_custom_name_20380101_1112_squashed_0003_model", 3), ("2_squashed_4", 4), ] for migration_name, expected_number in tests: with self.subTest(migration_name=migration_name): self.assertEqual( MigrationAutodetector.parse_number(migration_name), expected_number, ) def test_add_custom_fk_with_hardcoded_to(self): class HardcodedForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs["to"] = "testapp.Author" super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["to"] return name, path, args, kwargs book_hardcoded_fk_to = ModelState( "testapp", "Book", [ ("author", HardcodedForeignKey(on_delete=models.CASCADE)), ], ) changes = self.get_changes( [self.author_empty], [self.author_empty, book_hardcoded_fk_to], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Book") class AutodetectorIndexTogetherTests(BaseAutodetectorTests): book_index_together = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("author", "title")}, }, ) book_index_together_2 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, }, ) book_index_together_3 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield")}, }, ) book_index_together_4 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield2")}, }, ) def test_empty_index_together(self): """Empty index_together shouldn't generate a migration.""" # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))] ) # Explicitly testing for None, since this was the issue in #23452 after # an AlterIndexTogether operation with e.g. () as value model_state_none = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "index_together": None, }, ) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "index_together": set(), }, ) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ", ".join( o.__class__.__name__ for o in changes["a"][0].operations ) self.fail("Created operation(s) %s from %s" % (ops, msg)) tests = ( ( model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"', ), (model_state_not_specified, model_state_none, '"not specified" to "None"'), ( model_state_not_specified, model_state_empty, '"not specified" to "empty"', ), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), ( model_state_empty, model_state_not_specified, '"empty" to "not specified"', ), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_rename_index_together_to_index(self): changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", new_name="book_title_author_idx", old_fields=("author", "title"), ) def test_rename_index_together_to_index_extra_options(self): # Indexes with extra options don't match indexes in index_together. book_partial_index = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index( fields=["author", "title"], condition=models.Q(title__startswith="The"), name="book_title_author_idx", ) ], }, ) changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, book_partial_index], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "AddIndex"], ) def test_rename_index_together_to_index_order_fields(self): # Indexes with reordered fields don't match indexes in index_together. changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book_unordered_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "AddIndex"], ) def test_add_index_together(self): changes = self.get_changes( [AutodetectorTests.author_empty, AutodetectorTests.book], [AutodetectorTests.author_empty, self.book_index_together], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterIndexTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together={("author", "title")} ) def test_remove_index_together(self): changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterIndexTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together=set() ) def test_index_together_remove_fk(self): changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book_with_no_author], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="author" ) def test_index_together_no_changes(self): """ index_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, self.book_index_together], ) self.assertEqual(len(changes), 0) def test_index_together_ordering(self): """index_together triggers on ordering changes.""" changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, self.book_index_together_2], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together={("title", "author")}, ) def test_add_field_and_index_together(self): """ Added fields will be created before using them in index_together. """ changes = self.get_changes( [AutodetectorTests.author_empty, AutodetectorTests.book], [AutodetectorTests.author_empty, self.book_index_together_3], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AddField", "AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("title", "newfield")}, ) def test_create_model_and_index_together(self): author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) book_with_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, }, ) changes = self.get_changes( [AutodetectorTests.book_with_no_author], [author, book_with_author] ) self.assertEqual(len(changes["otherapp"]), 1) migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 3) self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AlterIndexTogether"], ) def test_remove_field_and_index_together(self): """ Removed fields will be removed after updating index_together. """ changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together_3], [AutodetectorTests.author_empty, self.book_index_together], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="newfield", ) def test_alter_field_and_index_together(self): """Fields are altered after deleting some index_together.""" initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField(db_index=True)), ], { "index_together": {("name",)}, }, ) author_reversed_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, unique=True)), ("age", models.IntegerField()), ], { "index_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterIndexTogether", "AlterField", "AlterField", "AlterIndexTogether", ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", index_together=set(), ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="age", ) self.assertOperationAttributes( changes, "testapp", 0, 2, model_name="author", name="name", ) self.assertOperationAttributes( changes, "testapp", 0, 3, name="author", index_together={("age",)}, ) def test_partly_alter_index_together_increase(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("name",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("name",), ("age",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterIndexTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", index_together={("name",), ("age",)}, ) def test_partly_alter_index_together_decrease(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("name",), ("age",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterIndexTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", index_together={("age",)}, ) def test_rename_field_and_index_together(self): """Fields are renamed before updating index_together.""" changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together_3], [AutodetectorTests.author_empty, self.book_index_together_4], MigrationQuestioner({"ask_rename": True}), ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RenameField", "AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("title", "newfield2")}, ) def test_add_model_order_with_respect_to_index_together(self): changes = self.get_changes( [], [ AutodetectorTests.book, ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, }, ), ], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, }, ) def test_set_alter_order_with_respect_to_index_together(self): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, }, ) changes = self.get_changes( [AutodetectorTests.book, AutodetectorTests.author_with_book], [AutodetectorTests.book, after], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterOrderWithRespectTo", "AlterIndexTogether"], ) class MigrationSuggestNameTests(SimpleTestCase): def test_no_operations(self): class Migration(migrations.Migration): operations = [] migration = Migration("some_migration", "test_app") self.assertIs(migration.suggest_name().startswith("auto_"), True) def test_no_operations_initial(self): class Migration(migrations.Migration): initial = True operations = [] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_single_operation(self): class Migration(migrations.Migration): operations = [migrations.CreateModel("Person", fields=[])] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "person") class Migration(migrations.Migration): operations = [migrations.DeleteModel("Person")] migration = Migration("0002_initial", "test_app") self.assertEqual(migration.suggest_name(), "delete_person") def test_single_operation_long_name(self): class Migration(migrations.Migration): operations = [migrations.CreateModel("A" * 53, fields=[])] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "a" * 53) def test_two_operations(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.DeleteModel("Animal"), ] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "person_delete_animal") def test_two_create_models(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.CreateModel("Animal", fields=[]), ] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "person_animal") def test_two_create_models_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel("Person", fields=[]), migrations.CreateModel("Animal", fields=[]), ] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_many_operations_suffix(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person1", fields=[]), migrations.CreateModel("Person2", fields=[]), migrations.CreateModel("Person3", fields=[]), migrations.DeleteModel("Person4"), migrations.DeleteModel("Person5"), ] migration = Migration("some_migration", "test_app") self.assertEqual( migration.suggest_name(), "person1_person2_person3_delete_person4_and_more", ) def test_operation_with_no_suggested_name(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.RunSQL("SELECT 1 FROM person;"), ] migration = Migration("some_migration", "test_app") self.assertIs(migration.suggest_name().startswith("auto_"), True) def test_none_name(self): class Migration(migrations.Migration): operations = [migrations.RunSQL("SELECT 1 FROM person;")] migration = Migration("0001_initial", "test_app") suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith("auto_"), True) def test_none_name_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [migrations.RunSQL("SELECT 1 FROM person;")] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_auto(self): migration = migrations.Migration("0001_initial", "test_app") suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith("auto_"), True)
333a8d3012e1e0fc3ee42b1f3ef8bcd88e19e788b574d9eade45c0f6b1a0cdd5
from unittest import mock from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.hashers import get_hasher from django.contrib.auth.models import ( AnonymousUser, Group, Permission, User, UserManager, ) from django.contrib.contenttypes.models import ContentType from django.core import mail from django.db import connection, migrations from django.db.migrations.state import ModelState, ProjectState from django.db.models.signals import post_save from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings from django.test.utils import ignore_warnings from django.utils.deprecation import RemovedInDjango51Warning from .models import CustomEmailField, IntegerUsernameUser class NaturalKeysTestCase(TestCase): def test_user_natural_key(self): staff_user = User.objects.create_user(username="staff") self.assertEqual(User.objects.get_by_natural_key("staff"), staff_user) self.assertEqual(staff_user.natural_key(), ("staff",)) def test_group_natural_key(self): users_group = Group.objects.create(name="users") self.assertEqual(Group.objects.get_by_natural_key("users"), users_group) class LoadDataWithoutNaturalKeysTestCase(TestCase): fixtures = ["regular.json"] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username="my_username") group = Group.objects.get(name="my_group") self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysTestCase(TestCase): fixtures = ["natural.json"] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username="my_username") group = Group.objects.get(name="my_group") self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase): databases = {"default", "other"} def test_load_data_with_user_permissions(self): # Create test contenttypes for both databases default_objects = [ ContentType.objects.db_manager("default").create( model="examplemodela", app_label="app_a", ), ContentType.objects.db_manager("default").create( model="examplemodelb", app_label="app_b", ), ] other_objects = [ ContentType.objects.db_manager("other").create( model="examplemodelb", app_label="app_b", ), ContentType.objects.db_manager("other").create( model="examplemodela", app_label="app_a", ), ] # Now we create the test UserPermission Permission.objects.db_manager("default").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=default_objects[1], ) Permission.objects.db_manager("other").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=other_objects[0], ) perm_default = Permission.objects.get_by_natural_key( "delete_examplemodelb", "app_b", "examplemodelb", ) perm_other = Permission.objects.db_manager("other").get_by_natural_key( "delete_examplemodelb", "app_b", "examplemodelb", ) self.assertEqual(perm_default.content_type_id, default_objects[1].id) self.assertEqual(perm_other.content_type_id, other_objects[0].id) class UserManagerTestCase(TransactionTestCase): available_apps = [ "auth_tests", "django.contrib.auth", "django.contrib.contenttypes", ] def test_create_user(self): email_lowercase = "[email protected]" user = User.objects.create_user("user", email_lowercase) self.assertEqual(user.email, email_lowercase) self.assertEqual(user.username, "user") self.assertFalse(user.has_usable_password()) def test_create_user_email_domain_normalize_rfc3696(self): # According to https://tools.ietf.org/html/rfc3696#section-3 # the "@" symbol can be part of the local part of an email address returned = UserManager.normalize_email(r"Abc\@[email protected]") self.assertEqual(returned, r"Abc\@[email protected]") def test_create_user_email_domain_normalize(self): returned = UserManager.normalize_email("[email protected]") self.assertEqual(returned, "[email protected]") def test_create_user_email_domain_normalize_with_whitespace(self): returned = UserManager.normalize_email(r"email\ [email protected]") self.assertEqual(returned, r"email\ [email protected]") def test_empty_username(self): with self.assertRaisesMessage(ValueError, "The given username must be set"): User.objects.create_user(username="") def test_create_user_is_staff(self): email = "[email protected]" user = User.objects.create_user("user", email, is_staff=True) self.assertEqual(user.email, email) self.assertEqual(user.username, "user") self.assertTrue(user.is_staff) def test_create_super_user_raises_error_on_false_is_superuser(self): with self.assertRaisesMessage( ValueError, "Superuser must have is_superuser=True." ): User.objects.create_superuser( username="test", email="[email protected]", password="test", is_superuser=False, ) def test_create_superuser_raises_error_on_false_is_staff(self): with self.assertRaisesMessage(ValueError, "Superuser must have is_staff=True."): User.objects.create_superuser( username="test", email="[email protected]", password="test", is_staff=False, ) @ignore_warnings(category=RemovedInDjango51Warning) def test_make_random_password(self): allowed_chars = "abcdefg" password = UserManager().make_random_password(5, allowed_chars) self.assertEqual(len(password), 5) for char in password: self.assertIn(char, allowed_chars) def test_make_random_password_warning(self): msg = "BaseUserManager.make_random_password() is deprecated." with self.assertWarnsMessage(RemovedInDjango51Warning, msg): UserManager().make_random_password() def test_runpython_manager_methods(self): def forwards(apps, schema_editor): UserModel = apps.get_model("auth", "User") user = UserModel.objects.create_user("user1", password="secure") self.assertIsInstance(user, UserModel) operation = migrations.RunPython(forwards, migrations.RunPython.noop) project_state = ProjectState() project_state.add_model(ModelState.from_model(User)) project_state.add_model(ModelState.from_model(Group)) project_state.add_model(ModelState.from_model(Permission)) project_state.add_model(ModelState.from_model(ContentType)) new_state = project_state.clone() with connection.schema_editor() as editor: operation.state_forwards("test_manager_methods", new_state) operation.database_forwards( "test_manager_methods", editor, project_state, new_state, ) user = User.objects.get(username="user1") self.assertTrue(user.check_password("secure")) class AbstractBaseUserTests(SimpleTestCase): def test_has_usable_password(self): """ Passwords are usable even if they don't correspond to a hasher in settings.PASSWORD_HASHERS. """ self.assertIs(User(password="some-gibbberish").has_usable_password(), True) def test_normalize_username(self): self.assertEqual(IntegerUsernameUser().normalize_username(123), 123) def test_clean_normalize_username(self): # The normalization happens in AbstractBaseUser.clean() ohm_username = "iamtheΩ" # U+2126 OHM SIGN for model in ("auth.User", "auth_tests.CustomUser"): with self.subTest(model=model), self.settings(AUTH_USER_MODEL=model): User = get_user_model() user = User(**{User.USERNAME_FIELD: ohm_username, "password": "foo"}) user.clean() username = user.get_username() self.assertNotEqual(username, ohm_username) self.assertEqual( username, "iamtheΩ" ) # U+03A9 GREEK CAPITAL LETTER OMEGA def test_default_email(self): self.assertEqual(AbstractBaseUser.get_email_field_name(), "email") def test_custom_email(self): user = CustomEmailField() self.assertEqual(user.get_email_field_name(), "email_address") class AbstractUserTestCase(TestCase): def test_email_user(self): # valid send_mail parameters kwargs = { "fail_silently": False, "auth_user": None, "auth_password": None, "connection": None, "html_message": None, } user = User(email="[email protected]") user.email_user( subject="Subject here", message="This is a message", from_email="[email protected]", **kwargs, ) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertEqual(message.subject, "Subject here") self.assertEqual(message.body, "This is a message") self.assertEqual(message.from_email, "[email protected]") self.assertEqual(message.to, [user.email]) def test_last_login_default(self): user1 = User.objects.create(username="user1") self.assertIsNone(user1.last_login) user2 = User.objects.create_user(username="user2") self.assertIsNone(user2.last_login) def test_user_clean_normalize_email(self): user = User(username="user", password="foo", email="[email protected]") user.clean() self.assertEqual(user.email, "[email protected]") def test_user_double_save(self): """ Calling user.save() twice should trigger password_changed() once. """ user = User.objects.create_user(username="user", password="foo") user.set_password("bar") with mock.patch( "django.contrib.auth.password_validation.password_changed" ) as pw_changed: user.save() self.assertEqual(pw_changed.call_count, 1) user.save() self.assertEqual(pw_changed.call_count, 1) @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) def test_check_password_upgrade(self): """ password_changed() shouldn't be called if User.check_password() triggers a hash iteration upgrade. """ user = User.objects.create_user(username="user", password="foo") initial_password = user.password self.assertTrue(user.check_password("foo")) hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) old_iterations = hasher.iterations try: # Upgrade the password iterations hasher.iterations = old_iterations + 1 with mock.patch( "django.contrib.auth.password_validation.password_changed" ) as pw_changed: user.check_password("foo") self.assertEqual(pw_changed.call_count, 0) self.assertNotEqual(initial_password, user.password) finally: hasher.iterations = old_iterations class CustomModelBackend(ModelBackend): def with_perm( self, perm, is_active=True, include_superusers=True, backend=None, obj=None ): if obj is not None and obj.username == "charliebrown": return User.objects.filter(pk=obj.pk) return User.objects.filter(username__startswith="charlie") class UserWithPermTestCase(TestCase): @classmethod def setUpTestData(cls): content_type = ContentType.objects.get_for_model(Group) cls.permission = Permission.objects.create( name="test", content_type=content_type, codename="test", ) # User with permission. cls.user1 = User.objects.create_user("user 1", "[email protected]") cls.user1.user_permissions.add(cls.permission) # User with group permission. group1 = Group.objects.create(name="group 1") group1.permissions.add(cls.permission) group2 = Group.objects.create(name="group 2") group2.permissions.add(cls.permission) cls.user2 = User.objects.create_user("user 2", "[email protected]") cls.user2.groups.add(group1, group2) # Users without permissions. cls.user_charlie = User.objects.create_user("charlie", "[email protected]") cls.user_charlie_b = User.objects.create_user( "charliebrown", "[email protected]" ) # Superuser. cls.superuser = User.objects.create_superuser( "superuser", "[email protected]", "superpassword", ) # Inactive user with permission. cls.inactive_user = User.objects.create_user( "inactive_user", "[email protected]", is_active=False, ) cls.inactive_user.user_permissions.add(cls.permission) def test_invalid_permission_name(self): msg = "Permission name should be in the form app_label.permission_codename." for perm in ("nodots", "too.many.dots", "...", ""): with self.subTest(perm), self.assertRaisesMessage(ValueError, msg): User.objects.with_perm(perm) def test_invalid_permission_type(self): msg = "The `perm` argument must be a string or a permission instance." for perm in (b"auth.test", object(), None): with self.subTest(perm), self.assertRaisesMessage(TypeError, msg): User.objects.with_perm(perm) def test_invalid_backend_type(self): msg = "backend must be a dotted import path string (got %r)." for backend in (b"auth_tests.CustomModelBackend", object()): with self.subTest(backend): with self.assertRaisesMessage(TypeError, msg % backend): User.objects.with_perm("auth.test", backend=backend) def test_basic(self): active_users = [self.user1, self.user2] tests = [ ({}, [*active_users, self.superuser]), ({"obj": self.user1}, []), # Only inactive users. ({"is_active": False}, [self.inactive_user]), # All users. ({"is_active": None}, [*active_users, self.superuser, self.inactive_user]), # Exclude superusers. ({"include_superusers": False}, active_users), ( {"include_superusers": False, "is_active": False}, [self.inactive_user], ), ( {"include_superusers": False, "is_active": None}, [*active_users, self.inactive_user], ), ] for kwargs, expected_users in tests: for perm in ("auth.test", self.permission): with self.subTest(perm=perm, **kwargs): self.assertCountEqual( User.objects.with_perm(perm, **kwargs), expected_users, ) @override_settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.BaseBackend"] ) def test_backend_without_with_perm(self): self.assertSequenceEqual(User.objects.with_perm("auth.test"), []) def test_nonexistent_permission(self): self.assertSequenceEqual(User.objects.with_perm("auth.perm"), [self.superuser]) def test_nonexistent_backend(self): with self.assertRaises(ImportError): User.objects.with_perm( "auth.test", backend="invalid.backend.CustomModelBackend", ) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_models.CustomModelBackend"] ) def test_custom_backend(self): for perm in ("auth.test", self.permission): with self.subTest(perm): self.assertCountEqual( User.objects.with_perm(perm), [self.user_charlie, self.user_charlie_b], ) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_models.CustomModelBackend"] ) def test_custom_backend_pass_obj(self): for perm in ("auth.test", self.permission): with self.subTest(perm): self.assertSequenceEqual( User.objects.with_perm(perm, obj=self.user_charlie_b), [self.user_charlie_b], ) @override_settings( AUTHENTICATION_BACKENDS=[ "auth_tests.test_models.CustomModelBackend", "django.contrib.auth.backends.ModelBackend", ] ) def test_multiple_backends(self): msg = ( "You have multiple authentication backends configured and " "therefore must provide the `backend` argument." ) with self.assertRaisesMessage(ValueError, msg): User.objects.with_perm("auth.test") backend = "auth_tests.test_models.CustomModelBackend" self.assertCountEqual( User.objects.with_perm("auth.test", backend=backend), [self.user_charlie, self.user_charlie_b], ) class IsActiveTestCase(TestCase): """ Tests the behavior of the guaranteed is_active attribute """ def test_builtin_user_isactive(self): user = User.objects.create(username="foo", email="[email protected]") # is_active is true by default self.assertIs(user.is_active, True) user.is_active = False user.save() user_fetched = User.objects.get(pk=user.pk) # the is_active flag is saved self.assertFalse(user_fetched.is_active) @override_settings(AUTH_USER_MODEL="auth_tests.IsActiveTestUser1") def test_is_active_field_default(self): """ tests that the default value for is_active is provided """ UserModel = get_user_model() user = UserModel(username="foo") self.assertIs(user.is_active, True) # you can set the attribute - but it will not save user.is_active = False # there should be no problem saving - but the attribute is not saved user.save() user_fetched = UserModel._default_manager.get(pk=user.pk) # the attribute is always true for newly retrieved instance self.assertIs(user_fetched.is_active, True) class TestCreateSuperUserSignals(TestCase): """ Simple test case for ticket #20541 """ def post_save_listener(self, *args, **kwargs): self.signals_count += 1 def setUp(self): self.signals_count = 0 post_save.connect(self.post_save_listener, sender=User) def tearDown(self): post_save.disconnect(self.post_save_listener, sender=User) def test_create_user(self): User.objects.create_user("JohnDoe") self.assertEqual(self.signals_count, 1) def test_create_superuser(self): User.objects.create_superuser("JohnDoe", "[email protected]", "1") self.assertEqual(self.signals_count, 1) class AnonymousUserTests(SimpleTestCase): no_repr_msg = "Django doesn't provide a DB representation for AnonymousUser." def setUp(self): self.user = AnonymousUser() def test_properties(self): self.assertIsNone(self.user.pk) self.assertEqual(self.user.username, "") self.assertEqual(self.user.get_username(), "") self.assertIs(self.user.is_anonymous, True) self.assertIs(self.user.is_authenticated, False) self.assertIs(self.user.is_staff, False) self.assertIs(self.user.is_active, False) self.assertIs(self.user.is_superuser, False) self.assertEqual(self.user.groups.count(), 0) self.assertEqual(self.user.user_permissions.count(), 0) self.assertEqual(self.user.get_user_permissions(), set()) self.assertEqual(self.user.get_group_permissions(), set()) def test_str(self): self.assertEqual(str(self.user), "AnonymousUser") def test_eq(self): self.assertEqual(self.user, AnonymousUser()) self.assertNotEqual(self.user, User("super", "[email protected]", "super")) def test_hash(self): self.assertEqual(hash(self.user), 1) def test_int(self): msg = ( "Cannot cast AnonymousUser to int. Are you trying to use it in " "place of User?" ) with self.assertRaisesMessage(TypeError, msg): int(self.user) def test_delete(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.delete() def test_save(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.save() def test_set_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.set_password("password") def test_check_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.check_password("password") class GroupTests(SimpleTestCase): def test_str(self): g = Group(name="Users") self.assertEqual(str(g), "Users") class PermissionTests(TestCase): def test_str(self): p = Permission.objects.get(codename="view_customemailfield") self.assertEqual( str(p), "auth_tests | custom email field | Can view custom email field" )
33db1bac85ae0597288112c3247b9aae0c604d13d6177189d200a20107d297aa
import os from argparse import ArgumentDefaultsHelpFormatter from io import StringIO from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.apps import apps from django.core import management from django.core.checks import Tags from django.core.management import BaseCommand, CommandError, find_commands from django.core.management.utils import ( find_command, get_random_secret_key, is_ignored_path, normalize_path_patterns, popen_wrapper, ) from django.db import connection from django.test import SimpleTestCase, override_settings from django.test.utils import captured_stderr, extend_sys_path from django.utils import translation from .management.commands import dance # A minimal set of apps to avoid system checks running on all apps. @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "user_commands", ], ) class CommandTests(SimpleTestCase): def test_command(self): out = StringIO() management.call_command("dance", stdout=out) self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue()) def test_command_style(self): out = StringIO() management.call_command("dance", style="Jive", stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) # Passing options as arguments also works (thanks argparse) management.call_command("dance", "--style", "Jive", stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) def test_language_preserved(self): with translation.override("fr"): management.call_command("dance", verbosity=0) self.assertEqual(translation.get_language(), "fr") def test_explode(self): """An unknown command raises CommandError""" with self.assertRaisesMessage(CommandError, "Unknown command: 'explode'"): management.call_command(("explode",)) def test_system_exit(self): """Exception raised in a command should raise CommandError with call_command, but SystemExit when run from command line """ with self.assertRaises(CommandError) as cm: management.call_command("dance", example="raise") self.assertEqual(cm.exception.returncode, 3) dance.Command.requires_system_checks = [] try: with captured_stderr() as stderr, self.assertRaises(SystemExit) as cm: management.ManagementUtility( ["manage.py", "dance", "--example=raise"] ).execute() self.assertEqual(cm.exception.code, 3) finally: dance.Command.requires_system_checks = "__all__" self.assertIn("CommandError", stderr.getvalue()) def test_no_translations_deactivate_translations(self): """ When the Command handle method is decorated with @no_translations, translations are deactivated inside the command. """ current_locale = translation.get_language() with translation.override("pl"): result = management.call_command("no_translations") self.assertIsNone(result) self.assertEqual(translation.get_language(), current_locale) def test_find_command_without_PATH(self): """ find_command should still work when the PATH environment variable doesn't exist (#22256). """ current_path = os.environ.pop("PATH", None) try: self.assertIsNone(find_command("_missing_")) finally: if current_path is not None: os.environ["PATH"] = current_path def test_discover_commands_in_eggs(self): """ Management commands can also be loaded from Python eggs. """ egg_dir = "%s/eggs" % os.path.dirname(__file__) egg_name = "%s/basic.egg" % egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=["commandegg"]): cmds = find_commands( os.path.join(apps.get_app_config("commandegg").path, "management") ) self.assertEqual(cmds, ["eggcommand"]) def test_call_command_option_parsing(self): """ When passing the long option name to call_command, the available option key is the option dest name (#22985). """ out = StringIO() management.call_command("dance", stdout=out, opt_3=True) self.assertIn("option3", out.getvalue()) self.assertNotIn("opt_3", out.getvalue()) self.assertNotIn("opt-3", out.getvalue()) def test_call_command_option_parsing_non_string_arg(self): """ It should be possible to pass non-string arguments to call_command. """ out = StringIO() management.call_command("dance", 1, verbosity=0, stdout=out) self.assertIn("You passed 1 as a positional argument.", out.getvalue()) def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self): out = StringIO() management.call_command("hal", "--empty", stdout=out) self.assertEqual(out.getvalue(), "\nDave, I can't do that.\n") def test_calling_command_with_app_labels_and_parameters_should_be_ok(self): out = StringIO() management.call_command("hal", "myapp", "--verbosity", "3", stdout=out) self.assertIn( "Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue() ) def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok( self, ): out = StringIO() management.call_command("hal", "--verbosity", "3", "myapp", stdout=out) self.assertIn( "Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue() ) def test_calling_a_command_with_no_app_labels_and_parameters_raise_command_error( self, ): with self.assertRaises(CommandError): management.call_command("hal") def test_output_transaction(self): output = management.call_command( "transaction", stdout=StringIO(), no_color=True ) self.assertTrue( output.strip().startswith(connection.ops.start_transaction_sql()) ) self.assertTrue(output.strip().endswith(connection.ops.end_transaction_sql())) def test_call_command_no_checks(self): """ By default, call_command should not trigger the check framework, unless specifically asked. """ self.counter = 0 def patched_check(self_, **kwargs): self.counter += 1 self.kwargs = kwargs saved_check = BaseCommand.check BaseCommand.check = patched_check try: management.call_command("dance", verbosity=0) self.assertEqual(self.counter, 0) management.call_command("dance", verbosity=0, skip_checks=False) self.assertEqual(self.counter, 1) self.assertEqual(self.kwargs, {}) finally: BaseCommand.check = saved_check def test_requires_system_checks_empty(self): with mock.patch( "django.core.management.base.BaseCommand.check" ) as mocked_check: management.call_command("no_system_checks") self.assertIs(mocked_check.called, False) def test_requires_system_checks_specific(self): with mock.patch( "django.core.management.base.BaseCommand.check" ) as mocked_check: management.call_command("specific_system_checks") mocked_check.called_once_with(tags=[Tags.staticfiles, Tags.models]) def test_requires_system_checks_invalid(self): class Command(BaseCommand): requires_system_checks = "x" msg = "requires_system_checks must be a list or tuple." with self.assertRaisesMessage(TypeError, msg): Command() def test_check_migrations(self): requires_migrations_checks = dance.Command.requires_migrations_checks self.assertIs(requires_migrations_checks, False) try: with mock.patch.object(BaseCommand, "check_migrations") as check_migrations: management.call_command("dance", verbosity=0) self.assertFalse(check_migrations.called) dance.Command.requires_migrations_checks = True management.call_command("dance", verbosity=0) self.assertTrue(check_migrations.called) finally: dance.Command.requires_migrations_checks = requires_migrations_checks def test_call_command_unrecognized_option(self): msg = ( "Unknown option(s) for dance command: unrecognized. Valid options " "are: example, force_color, help, integer, no_color, opt_3, " "option3, pythonpath, settings, skip_checks, stderr, stdout, " "style, traceback, verbosity, version." ) with self.assertRaisesMessage(TypeError, msg): management.call_command("dance", unrecognized=1) msg = ( "Unknown option(s) for dance command: unrecognized, unrecognized2. " "Valid options are: example, force_color, help, integer, no_color, " "opt_3, option3, pythonpath, settings, skip_checks, stderr, " "stdout, style, traceback, verbosity, version." ) with self.assertRaisesMessage(TypeError, msg): management.call_command("dance", unrecognized=1, unrecognized2=1) def test_call_command_with_required_parameters_in_options(self): out = StringIO() management.call_command( "required_option", need_me="foo", needme2="bar", stdout=out ) self.assertIn("need_me", out.getvalue()) self.assertIn("needme2", out.getvalue()) def test_call_command_with_required_parameters_in_mixed_options(self): out = StringIO() management.call_command( "required_option", "--need-me=foo", needme2="bar", stdout=out ) self.assertIn("need_me", out.getvalue()) self.assertIn("needme2", out.getvalue()) def test_command_add_arguments_after_common_arguments(self): out = StringIO() management.call_command("common_args", stdout=out) self.assertIn("Detected that --version already exists", out.getvalue()) def test_mutually_exclusive_group_required_options(self): out = StringIO() management.call_command("mutually_exclusive_required", foo_id=1, stdout=out) self.assertIn("foo_id", out.getvalue()) management.call_command( "mutually_exclusive_required", foo_name="foo", stdout=out ) self.assertIn("foo_name", out.getvalue()) msg = ( "Error: one of the arguments --foo-id --foo-name --foo-list " "--append_const --const --count --flag_false --flag_true is " "required" ) with self.assertRaisesMessage(CommandError, msg): management.call_command("mutually_exclusive_required", stdout=out) def test_mutually_exclusive_group_required_const_options(self): tests = [ ("append_const", [42]), ("const", 31), ("count", 1), ("flag_false", False), ("flag_true", True), ] for arg, value in tests: out = StringIO() expected_output = "%s=%s" % (arg, value) with self.subTest(arg=arg): management.call_command( "mutually_exclusive_required", "--%s" % arg, stdout=out, ) self.assertIn(expected_output, out.getvalue()) out.truncate(0) management.call_command( "mutually_exclusive_required", **{arg: value, "stdout": out}, ) self.assertIn(expected_output, out.getvalue()) def test_mutually_exclusive_group_required_with_same_dest_options(self): tests = [ {"until": "2"}, {"for": "1", "until": "2"}, ] msg = ( "Cannot pass the dest 'until' that matches multiple arguments via " "**options." ) for options in tests: with self.subTest(options=options): with self.assertRaisesMessage(TypeError, msg): management.call_command( "mutually_exclusive_required_with_same_dest", **options, ) def test_mutually_exclusive_group_required_with_same_dest_args(self): tests = [ ("--until=1",), ("--until", 1), ("--for=1",), ("--for", 1), ] for args in tests: out = StringIO() with self.subTest(options=args): management.call_command( "mutually_exclusive_required_with_same_dest", *args, stdout=out, ) output = out.getvalue() self.assertIn("until=1", output) def test_required_list_option(self): tests = [ (("--foo-list", [1, 2]), {}), ((), {"foo_list": [1, 2]}), ] for command in ["mutually_exclusive_required", "required_list_option"]: for args, kwargs in tests: with self.subTest(command=command, args=args, kwargs=kwargs): out = StringIO() management.call_command( command, *args, **{**kwargs, "stdout": out}, ) self.assertIn("foo_list=[1, 2]", out.getvalue()) def test_required_const_options(self): args = { "append_const": [42], "const": 31, "count": 1, "flag_false": False, "flag_true": True, } expected_output = "\n".join( "%s=%s" % (arg, value) for arg, value in args.items() ) out = StringIO() management.call_command( "required_constant_option", "--append_const", "--const", "--count", "--flag_false", "--flag_true", stdout=out, ) self.assertIn(expected_output, out.getvalue()) out.truncate(0) management.call_command("required_constant_option", **{**args, "stdout": out}) self.assertIn(expected_output, out.getvalue()) def test_subparser(self): out = StringIO() management.call_command("subparser", "foo", 12, stdout=out) self.assertIn("bar", out.getvalue()) def test_subparser_dest_args(self): out = StringIO() management.call_command("subparser_dest", "foo", bar=12, stdout=out) self.assertIn("bar", out.getvalue()) def test_subparser_dest_required_args(self): out = StringIO() management.call_command( "subparser_required", "foo_1", "foo_2", bar=12, stdout=out ) self.assertIn("bar", out.getvalue()) def test_subparser_invalid_option(self): msg = "invalid choice: 'test' (choose from 'foo')" with self.assertRaisesMessage(CommandError, msg): management.call_command("subparser", "test", 12) msg = "Error: the following arguments are required: subcommand" with self.assertRaisesMessage(CommandError, msg): management.call_command("subparser_dest", subcommand="foo", bar=12) def test_create_parser_kwargs(self): """BaseCommand.create_parser() passes kwargs to CommandParser.""" epilog = "some epilog text" parser = BaseCommand().create_parser( "prog_name", "subcommand", epilog=epilog, formatter_class=ArgumentDefaultsHelpFormatter, ) self.assertEqual(parser.epilog, epilog) self.assertEqual(parser.formatter_class, ArgumentDefaultsHelpFormatter) def test_outputwrapper_flush(self): out = StringIO() with mock.patch.object(out, "flush") as mocked_flush: management.call_command("outputwrapper", stdout=out) self.assertIn("Working...", out.getvalue()) self.assertIs(mocked_flush.called, True) class CommandRunTests(AdminScriptTestCase): """ Tests that need to run by simulating the command line, not by call_command. """ def test_script_prefix_set_in_commands(self): self.write_settings( "settings.py", apps=["user_commands"], sdict={ "ROOT_URLCONF": '"user_commands.urls"', "FORCE_SCRIPT_NAME": '"/PREFIX/"', }, ) out, err = self.run_manage(["reverse_url"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "/PREFIX/some/url/") def test_disallowed_abbreviated_options(self): """ To avoid conflicts with custom options, commands don't allow abbreviated forms of the --setting and --pythonpath options. """ self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["set_option", "--set", "foo"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "Set foo") def test_skip_checks(self): self.write_settings( "settings.py", apps=["django.contrib.staticfiles", "user_commands"], sdict={ # (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or # list. "STATICFILES_DIRS": '"foo"', }, ) out, err = self.run_manage(["set_option", "--skip-checks", "--set", "foo"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "Set foo") class UtilsTests(SimpleTestCase): def test_no_existent_external_program(self): msg = "Error executing a_42_command_that_doesnt_exist_42" with self.assertRaisesMessage(CommandError, msg): popen_wrapper(["a_42_command_that_doesnt_exist_42"]) def test_get_random_secret_key(self): key = get_random_secret_key() self.assertEqual(len(key), 50) for char in key: self.assertIn(char, "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") def test_is_ignored_path_true(self): patterns = ( ["foo/bar/baz"], ["baz"], ["foo/bar/baz"], ["*/baz"], ["*"], ["b?z"], ["[abc]az"], ["*/ba[!z]/baz"], ) for ignore_patterns in patterns: with self.subTest(ignore_patterns=ignore_patterns): self.assertIs( is_ignored_path("foo/bar/baz", ignore_patterns=ignore_patterns), True, ) def test_is_ignored_path_false(self): self.assertIs( is_ignored_path( "foo/bar/baz", ignore_patterns=["foo/bar/bat", "bar", "flub/blub"] ), False, ) def test_normalize_path_patterns_truncates_wildcard_base(self): expected = [os.path.normcase(p) for p in ["foo/bar", "bar/*/"]] self.assertEqual(normalize_path_patterns(["foo/bar/*", "bar/*/"]), expected)
4d12e8b5223515bce4aeafae7413cbc5024e6942e29f6283e12beb16531def9a
from django.test import modify_settings from . import PostgreSQLTestCase from .models import CharFieldModel, TextFieldModel try: from django.contrib.postgres.search import ( TrigramDistance, TrigramSimilarity, TrigramStrictWordDistance, TrigramStrictWordSimilarity, TrigramWordDistance, TrigramWordSimilarity, ) except ImportError: pass @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class TrigramTest(PostgreSQLTestCase): Model = CharFieldModel @classmethod def setUpTestData(cls): cls.Model.objects.bulk_create( [ cls.Model(field="Matthew"), cls.Model(field="Cat sat on mat."), cls.Model(field="Dog sat on rug."), ] ) def test_trigram_search(self): self.assertQuerysetEqual( self.Model.objects.filter(field__trigram_similar="Mathew"), ["Matthew"], transform=lambda instance: instance.field, ) def test_trigram_word_search(self): obj = self.Model.objects.create( field="Gumby rides on the path of Middlesbrough", ) self.assertSequenceEqual( self.Model.objects.filter(field__trigram_word_similar="Middlesborough"), [obj], ) self.assertSequenceEqual( self.Model.objects.filter(field__trigram_word_similar="Middle"), [obj], ) def test_trigram_strict_word_search_matched(self): obj = self.Model.objects.create( field="Gumby rides on the path of Middlesbrough", ) self.assertSequenceEqual( self.Model.objects.filter( field__trigram_strict_word_similar="Middlesborough" ), [obj], ) self.assertSequenceEqual( self.Model.objects.filter(field__trigram_strict_word_similar="Middle"), [], ) def test_trigram_similarity(self): search = "Bat sat on cat." # Round result of similarity because PostgreSQL uses greater precision. self.assertQuerysetEqual( self.Model.objects.filter( field__trigram_similar=search, ) .annotate(similarity=TrigramSimilarity("field", search)) .order_by("-similarity"), [("Cat sat on mat.", 0.625), ("Dog sat on rug.", 0.333333)], transform=lambda instance: (instance.field, round(instance.similarity, 6)), ordered=True, ) def test_trigram_word_similarity(self): search = "mat" self.assertSequenceEqual( self.Model.objects.filter( field__trigram_word_similar=search, ) .annotate( word_similarity=TrigramWordSimilarity(search, "field"), ) .values("field", "word_similarity") .order_by("-word_similarity"), [ {"field": "Cat sat on mat.", "word_similarity": 1.0}, {"field": "Matthew", "word_similarity": 0.75}, ], ) def test_trigram_strict_word_similarity(self): search = "matt" self.assertSequenceEqual( self.Model.objects.filter(field__trigram_word_similar=search) .annotate(word_similarity=TrigramStrictWordSimilarity(search, "field")) .values("field", "word_similarity") .order_by("-word_similarity"), [ {"field": "Cat sat on mat.", "word_similarity": 0.5}, {"field": "Matthew", "word_similarity": 0.44444445}, ], ) def test_trigram_similarity_alternate(self): # Round result of distance because PostgreSQL uses greater precision. self.assertQuerysetEqual( self.Model.objects.annotate( distance=TrigramDistance("field", "Bat sat on cat."), ) .filter(distance__lte=0.7) .order_by("distance"), [("Cat sat on mat.", 0.375), ("Dog sat on rug.", 0.666667)], transform=lambda instance: (instance.field, round(instance.distance, 6)), ordered=True, ) def test_trigram_word_similarity_alternate(self): self.assertSequenceEqual( self.Model.objects.annotate( word_distance=TrigramWordDistance("mat", "field"), ) .filter( word_distance__lte=0.7, ) .values("field", "word_distance") .order_by("word_distance"), [ {"field": "Cat sat on mat.", "word_distance": 0}, {"field": "Matthew", "word_distance": 0.25}, ], ) def test_trigram_strict_word_distance(self): self.assertSequenceEqual( self.Model.objects.annotate( word_distance=TrigramStrictWordDistance("matt", "field"), ) .filter(word_distance__lte=0.7) .values("field", "word_distance") .order_by("word_distance"), [ {"field": "Cat sat on mat.", "word_distance": 0.5}, {"field": "Matthew", "word_distance": 0.5555556}, ], ) class TrigramTextFieldTest(TrigramTest): """ TextField has the same behavior as CharField regarding trigram lookups. """ Model = TextFieldModel
ec4982a244510950114315c3f4f602e97ee9ec8113df764a6f32016ea48ccae1
import os import re from io import StringIO from unittest import mock, skipUnless from django.core.management import call_command from django.db import connection from django.db.backends.base.introspection import TableInfo from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import PeopleMoreData, test_collation def inspectdb_tables_only(table_name): """ Limit introspection to tables created for models of this app. Some databases such as Oracle are extremely slow at introspection. """ return table_name.startswith("inspectdb_") def inspectdb_views_only(table_name): return table_name.startswith("inspectdb_") and table_name.endswith( ("_materialized", "_view") ) def special_table_only(table_name): return table_name.startswith("inspectdb_special") class InspectDBTestCase(TestCase): unique_re = re.compile(r".*unique_together = \((.+),\).*") def test_stealth_table_name_filter_option(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) error_message = ( "inspectdb has examined a table that should have been filtered out." ) # contrib.contenttypes is one of the apps always installed when running # the Django test suite, check that one of its tables hasn't been # inspected self.assertNotIn( "class DjangoContentType(models.Model):", out.getvalue(), msg=error_message ) def test_table_option(self): """ inspectdb can inspect a subset of tables by passing the table names as arguments. """ out = StringIO() call_command("inspectdb", "inspectdb_people", stdout=out) output = out.getvalue() self.assertIn("class InspectdbPeople(models.Model):", output) self.assertNotIn("InspectdbPeopledata", output) def make_field_type_asserter(self): """ Call inspectdb and return a function to validate a field type in its output. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() def assertFieldType(name, definition): out_def = re.search(r"^\s*%s = (models.*)$" % name, output, re.MULTILINE)[1] self.assertEqual(definition, out_def) return assertFieldType def test_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types char_field_type = introspected_field_types["CharField"] # Inspecting Oracle DB doesn't produce correct results (#19884): # - it reports fields as blank=True when they aren't. if ( not connection.features.interprets_empty_strings_as_nulls and char_field_type == "CharField" ): assertFieldType("char_field", "models.CharField(max_length=10)") assertFieldType( "null_char_field", "models.CharField(max_length=10, blank=True, null=True)", ) assertFieldType("email_field", "models.CharField(max_length=254)") assertFieldType("file_field", "models.CharField(max_length=100)") assertFieldType("file_path_field", "models.CharField(max_length=100)") assertFieldType("slug_field", "models.CharField(max_length=50)") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.CharField(max_length=200)") if char_field_type == "TextField": assertFieldType("char_field", "models.TextField()") assertFieldType( "null_char_field", "models.TextField(blank=True, null=True)" ) assertFieldType("email_field", "models.TextField()") assertFieldType("file_field", "models.TextField()") assertFieldType("file_path_field", "models.TextField()") assertFieldType("slug_field", "models.TextField()") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.TextField()") assertFieldType("date_field", "models.DateField()") assertFieldType("date_time_field", "models.DateTimeField()") if introspected_field_types["GenericIPAddressField"] == "GenericIPAddressField": assertFieldType("gen_ip_address_field", "models.GenericIPAddressField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("gen_ip_address_field", "models.CharField(max_length=39)") assertFieldType( "time_field", "models.%s()" % introspected_field_types["TimeField"] ) if connection.features.has_native_uuid_field: assertFieldType("uuid_field", "models.UUIDField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("uuid_field", "models.CharField(max_length=32)") @skipUnlessDBFeature("can_introspect_json_field", "supports_json_field") def test_json_field(self): out = StringIO() call_command("inspectdb", "inspectdb_jsonfieldcolumntype", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn("json_field = models.JSONField()", output) self.assertIn( "null_json_field = models.JSONField(blank=True, null=True)", output ) @skipUnlessDBFeature("supports_collation_on_charfield") @skipUnless(test_collation, "Language collations are not supported.") def test_char_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_charfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s')" % test_collation, output, ) else: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s', blank=True, null=True)" % test_collation, output, ) @skipUnlessDBFeature("supports_collation_on_textfield") @skipUnless(test_collation, "Language collations are not supported.") def test_text_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_textfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "text_field = models.TextField(db_collation='%s')" % test_collation, output, ) else: self.assertIn( "text_field = models.TextField(db_collation='%s, blank=True, " "null=True)" % test_collation, output, ) def test_number_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types auto_field_type = connection.features.introspected_field_types["AutoField"] if auto_field_type != "AutoField": assertFieldType( "id", "models.%s(primary_key=True) # AutoField?" % auto_field_type ) assertFieldType( "big_int_field", "models.%s()" % introspected_field_types["BigIntegerField"] ) bool_field_type = introspected_field_types["BooleanField"] assertFieldType("bool_field", "models.{}()".format(bool_field_type)) assertFieldType( "null_bool_field", "models.{}(blank=True, null=True)".format(bool_field_type), ) if connection.vendor != "sqlite": assertFieldType( "decimal_field", "models.DecimalField(max_digits=6, decimal_places=1)" ) else: # Guessed arguments on SQLite, see #5014 assertFieldType( "decimal_field", "models.DecimalField(max_digits=10, decimal_places=5) " "# max_digits and decimal_places have been guessed, " "as this database handles decimal fields as float", ) assertFieldType("float_field", "models.FloatField()") assertFieldType( "int_field", "models.%s()" % introspected_field_types["IntegerField"] ) assertFieldType( "pos_int_field", "models.%s()" % introspected_field_types["PositiveIntegerField"], ) assertFieldType( "pos_big_int_field", "models.%s()" % introspected_field_types["PositiveBigIntegerField"], ) assertFieldType( "pos_small_int_field", "models.%s()" % introspected_field_types["PositiveSmallIntegerField"], ) assertFieldType( "small_int_field", "models.%s()" % introspected_field_types["SmallIntegerField"], ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_attribute_name_not_python_keyword(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) output = out.getvalue() error_message = ( "inspectdb generated an attribute name which is a Python keyword" ) # Recursive foreign keys should be set to 'self' self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output) self.assertNotIn( "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)", output, msg=error_message, ) # As InspectdbPeople model is defined after InspectdbMessage, it should # be quoted. self.assertIn( "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " "db_column='from_id')", output, ) self.assertIn( "people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, " "primary_key=True)", output, ) self.assertIn( "people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)", output, ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_foreign_key_to_field(self): out = StringIO() call_command("inspectdb", "inspectdb_foreignkeytofield", stdout=out) self.assertIn( "to_field_fk = models.ForeignKey('InspectdbPeoplemoredata', " "models.DO_NOTHING, to_field='people_unique_id')", out.getvalue(), ) def test_digits_column_name_introspection(self): """Introspection of column names consist/start with digits (#16536/#17676)""" char_field_type = connection.features.introspected_field_types["CharField"] out = StringIO() call_command("inspectdb", "inspectdb_digitsincolumnname", stdout=out) output = out.getvalue() error_message = "inspectdb generated a model field name which is a number" self.assertNotIn( " 123 = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_123 = models.%s" % char_field_type, output) error_message = ( "inspectdb generated a model field name which starts with a digit" ) self.assertNotIn( " 4extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_4extra = models.%s" % char_field_type, output) self.assertNotIn( " 45extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_45extra = models.%s" % char_field_type, output) def test_special_column_name_introspection(self): """ Introspection of column names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() base_name = connection.introspection.identifier_converter("Field") integer_field_type = connection.features.introspected_field_types[ "IntegerField" ] self.assertIn("field = models.%s()" % integer_field_type, output) self.assertIn( "field_field = models.%s(db_column='%s_')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_0 = models.%s(db_column='%s__')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_1 = models.%s(db_column='__field')" % integer_field_type, output, ) self.assertIn( "prc_x = models.{}(db_column='prc(%) x')".format(integer_field_type), output ) self.assertIn("tamaño = models.%s()" % integer_field_type, output) def test_table_name_introspection(self): """ Introspection of table names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() self.assertIn("class InspectdbSpecialTableName(models.Model):", output) @skipUnlessDBFeature("supports_expression_indexes") def test_table_with_func_unique_constraint(self): out = StringIO() call_command("inspectdb", "inspectdb_funcuniqueconstraint", stdout=out) output = out.getvalue() self.assertIn("class InspectdbFuncuniqueconstraint(models.Model):", output) def test_managed_models(self): """ By default the command generates models with `Meta.managed = False`. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.longMessage = False self.assertIn( " managed = False", output, msg="inspectdb should generate unmanaged models.", ) def test_unique_together_meta(self): out = StringIO() call_command("inspectdb", "inspectdb_uniquetogether", stdout=out) output = out.getvalue() self.assertIn(" unique_together = (('", output) unique_together_match = self.unique_re.findall(output) # There should be one unique_together tuple. self.assertEqual(len(unique_together_match), 1) fields = unique_together_match[0] # Fields with db_column = field name. self.assertIn("('field1', 'field2')", fields) # Fields from columns whose names are Python keywords. self.assertIn("('field1', 'field2')", fields) # Fields whose names normalize to the same Python field name and hence # are given an integer suffix. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_unsupported_unique_together(self): """Unsupported index types (COALESCE here) are skipped.""" with connection.cursor() as c: c.execute( "CREATE UNIQUE INDEX Findex ON %s " "(id, people_unique_id, COALESCE(message_id, -1))" % PeopleMoreData._meta.db_table ) try: out = StringIO() call_command( "inspectdb", table_name_filter=lambda tn: tn.startswith( PeopleMoreData._meta.db_table ), stdout=out, ) output = out.getvalue() self.assertIn("# A unique constraint could not be introspected.", output) self.assertEqual( self.unique_re.findall(output), ["('id', 'people_unique')"] ) finally: with connection.cursor() as c: c.execute("DROP INDEX Findex") @skipUnless( connection.vendor == "sqlite", "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test", ) def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) """ out = StringIO() with mock.patch( "django.db.connection.introspection.data_types_reverse." "base_data_types_reverse", { "text": "myfields.TextField", "bigint": "BigIntegerField", }, ): call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.assertIn("text_field = myfields.TextField()", output) self.assertIn("big_int_field = models.BigIntegerField()", output) def test_introspection_errors(self): """ Introspection errors should not crash the command, and the error should be visible in the output. """ out = StringIO() with mock.patch( "django.db.connection.introspection.get_table_list", return_value=[TableInfo(name="nonexistent", type="t")], ): call_command("inspectdb", stdout=out) output = out.getvalue() self.assertIn("# Unable to inspect table 'nonexistent'", output) # The error message depends on the backend self.assertIn("# The error was:", output) class InspectDBTransactionalTests(TransactionTestCase): available_apps = ["inspectdb"] def test_include_views(self): """inspectdb --include-views creates models for database views.""" with connection.cursor() as cursor: cursor.execute( "CREATE VIEW inspectdb_people_view AS " "SELECT id, name FROM inspectdb_people" ) out = StringIO() view_model = "class InspectdbPeopleView(models.Model):" view_managed = "managed = False # Created from a view." try: call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute("DROP VIEW inspectdb_people_view") @skipUnlessDBFeature("can_introspect_materialized_views") def test_include_materialized_views(self): """inspectdb --include-views creates models for materialized views.""" with connection.cursor() as cursor: cursor.execute( "CREATE MATERIALIZED VIEW inspectdb_people_materialized AS " "SELECT id, name FROM inspectdb_people" ) out = StringIO() view_model = "class InspectdbPeopleMaterialized(models.Model):" view_managed = "managed = False # Created from a view." try: call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute("DROP MATERIALIZED VIEW inspectdb_people_materialized") @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_include_partitions(self): """inspectdb --include-partitions creates models for partitions.""" with connection.cursor() as cursor: cursor.execute( """\ CREATE TABLE inspectdb_partition_parent (name text not null) PARTITION BY LIST (left(upper(name), 1)) """ ) cursor.execute( """\ CREATE TABLE inspectdb_partition_child PARTITION OF inspectdb_partition_parent FOR VALUES IN ('A', 'B', 'C') """ ) out = StringIO() partition_model_parent = "class InspectdbPartitionParent(models.Model):" partition_model_child = "class InspectdbPartitionChild(models.Model):" partition_managed = "managed = False # Created from a partition." try: call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out ) no_partitions_output = out.getvalue() self.assertIn(partition_model_parent, no_partitions_output) self.assertNotIn(partition_model_child, no_partitions_output) self.assertNotIn(partition_managed, no_partitions_output) call_command( "inspectdb", table_name_filter=inspectdb_tables_only, include_partitions=True, stdout=out, ) with_partitions_output = out.getvalue() self.assertIn(partition_model_parent, with_partitions_output) self.assertIn(partition_model_child, with_partitions_output) self.assertIn(partition_managed, with_partitions_output) finally: with connection.cursor() as cursor: cursor.execute("DROP TABLE IF EXISTS inspectdb_partition_child") cursor.execute("DROP TABLE IF EXISTS inspectdb_partition_parent") @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_foreign_data_wrapper(self): with connection.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS file_fdw") cursor.execute( "CREATE SERVER inspectdb_server FOREIGN DATA WRAPPER file_fdw" ) cursor.execute( """\ CREATE FOREIGN TABLE inspectdb_iris_foreign_table ( petal_length real, petal_width real, sepal_length real, sepal_width real ) SERVER inspectdb_server OPTIONS ( filename %s ) """, [os.devnull], ) out = StringIO() foreign_table_model = "class InspectdbIrisForeignTable(models.Model):" foreign_table_managed = "managed = False" try: call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out, ) output = out.getvalue() self.assertIn(foreign_table_model, output) self.assertIn(foreign_table_managed, output) finally: with connection.cursor() as cursor: cursor.execute( "DROP FOREIGN TABLE IF EXISTS inspectdb_iris_foreign_table" ) cursor.execute("DROP SERVER IF EXISTS inspectdb_server") cursor.execute("DROP EXTENSION IF EXISTS file_fdw") @skipUnlessDBFeature("create_test_table_with_composite_primary_key") def test_composite_primary_key(self): table_name = "test_table_composite_pk" with connection.cursor() as cursor: cursor.execute( connection.features.create_test_table_with_composite_primary_key ) out = StringIO() if connection.vendor == "sqlite": field_type = connection.features.introspected_field_types["AutoField"] else: field_type = connection.features.introspected_field_types["IntegerField"] try: call_command("inspectdb", table_name, stdout=out) output = out.getvalue() self.assertIn( f"column_1 = models.{field_type}(primary_key=True) # The composite " f"primary key (column_1, column_2) found, that is not supported. The " f"first column is selected.", output, ) self.assertIn( "column_2 = models.%s()" % connection.features.introspected_field_types["IntegerField"], output, ) finally: with connection.cursor() as cursor: cursor.execute("DROP TABLE %s" % table_name)
0cd814ffc1f3e4d809f03e54daee861057475b1a3be532b067526617270c536b
import gzip import random import re import struct from io import BytesIO from urllib.parse import quote from django.conf import settings from django.core import mail from django.core.exceptions import PermissionDenied from django.http import ( FileResponse, HttpRequest, HttpResponse, HttpResponseNotFound, HttpResponsePermanentRedirect, HttpResponseRedirect, StreamingHttpResponse, ) from django.middleware.clickjacking import XFrameOptionsMiddleware from django.middleware.common import BrokenLinkEmailsMiddleware, CommonMiddleware from django.middleware.gzip import GZipMiddleware from django.middleware.http import ConditionalGetMiddleware from django.test import RequestFactory, SimpleTestCase, override_settings int2byte = struct.Struct(">B").pack def get_response_empty(request): return HttpResponse() def get_response_404(request): return HttpResponseNotFound() @override_settings(ROOT_URLCONF="middleware.urls") class CommonMiddlewareTest(SimpleTestCase): rf = RequestFactory() @override_settings(APPEND_SLASH=True) def test_append_slash_have_slash(self): """ URLs with slashes should go unmolested. """ request = self.rf.get("/slash/") self.assertIsNone(CommonMiddleware(get_response_404).process_request(request)) self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_slashless_resource(self): """ Matches to explicit slashless URLs should go unmolested. """ def get_response(req): return HttpResponse("Here's the text of the web page.") request = self.rf.get("/noslash") self.assertIsNone(CommonMiddleware(get_response).process_request(request)) self.assertEqual( CommonMiddleware(get_response)(request).content, b"Here's the text of the web page.", ) @override_settings(APPEND_SLASH=True) def test_append_slash_slashless_unknown(self): """ APPEND_SLASH should not redirect to unknown resources. """ request = self.rf.get("/unknown") response = CommonMiddleware(get_response_404)(request) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_redirect(self): """ APPEND_SLASH should redirect slashless URLs to a valid pattern. """ request = self.rf.get("/slash") r = CommonMiddleware(get_response_empty).process_request(request) self.assertIsNone(r) response = HttpResponseNotFound() r = CommonMiddleware(get_response_empty).process_response(request, response) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/slash/") @override_settings(APPEND_SLASH=True) def test_append_slash_redirect_querystring(self): """ APPEND_SLASH should preserve querystrings when redirecting. """ request = self.rf.get("/slash?test=1") resp = CommonMiddleware(get_response_404)(request) self.assertEqual(resp.url, "/slash/?test=1") @override_settings(APPEND_SLASH=True) def test_append_slash_redirect_querystring_have_slash(self): """ APPEND_SLASH should append slash to path when redirecting a request with a querystring ending with slash. """ request = self.rf.get("/slash?test=slash/") resp = CommonMiddleware(get_response_404)(request) self.assertIsInstance(resp, HttpResponsePermanentRedirect) self.assertEqual(resp.url, "/slash/?test=slash/") @override_settings(APPEND_SLASH=True, DEBUG=True) def test_append_slash_no_redirect_on_POST_in_DEBUG(self): """ While in debug mode, an exception is raised with a warning when a failed attempt is made to POST, PUT, or PATCH to an URL which would normally be redirected to a slashed version. """ msg = "maintaining %s data. Change your form to point to testserver/slash/" request = self.rf.get("/slash") request.method = "POST" with self.assertRaisesMessage(RuntimeError, msg % request.method): CommonMiddleware(get_response_404)(request) request = self.rf.get("/slash") request.method = "PUT" with self.assertRaisesMessage(RuntimeError, msg % request.method): CommonMiddleware(get_response_404)(request) request = self.rf.get("/slash") request.method = "PATCH" with self.assertRaisesMessage(RuntimeError, msg % request.method): CommonMiddleware(get_response_404)(request) @override_settings(APPEND_SLASH=False) def test_append_slash_disabled(self): """ Disabling append slash functionality should leave slashless URLs alone. """ request = self.rf.get("/slash") self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_opt_out(self): """ Views marked with @no_append_slash should be left alone. """ request = self.rf.get("/sensitive_fbv") self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) request = self.rf.get("/sensitive_cbv") self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_quoted(self): """ URLs which require quoting should be redirected to their slash version. """ request = self.rf.get(quote("/needsquoting#")) r = CommonMiddleware(get_response_404)(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/needsquoting%23/") @override_settings(APPEND_SLASH=True) def test_append_slash_leading_slashes(self): """ Paths starting with two slashes are escaped to prevent open redirects. If there's a URL pattern that allows paths to start with two slashes, a request with path //evil.com must not redirect to //evil.com/ (appended slash) which is a schemaless absolute URL. The browser would navigate to evil.com/. """ # Use 4 slashes because of RequestFactory behavior. request = self.rf.get("////evil.com/security") r = CommonMiddleware(get_response_404).process_request(request) self.assertIsNone(r) response = HttpResponseNotFound() r = CommonMiddleware(get_response_404).process_response(request, response) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/%2Fevil.com/security/") r = CommonMiddleware(get_response_404)(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/%2Fevil.com/security/") @override_settings(APPEND_SLASH=False, PREPEND_WWW=True) def test_prepend_www(self): request = self.rf.get("/path/") r = CommonMiddleware(get_response_empty).process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "http://www.testserver/path/") @override_settings(APPEND_SLASH=True, PREPEND_WWW=True) def test_prepend_www_append_slash_have_slash(self): request = self.rf.get("/slash/") r = CommonMiddleware(get_response_empty).process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "http://www.testserver/slash/") @override_settings(APPEND_SLASH=True, PREPEND_WWW=True) def test_prepend_www_append_slash_slashless(self): request = self.rf.get("/slash") r = CommonMiddleware(get_response_empty).process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "http://www.testserver/slash/") # The following tests examine expected behavior given a custom URLconf that # overrides the default one through the request object. @override_settings(APPEND_SLASH=True) def test_append_slash_have_slash_custom_urlconf(self): """ URLs with slashes should go unmolested. """ request = self.rf.get("/customurlconf/slash/") request.urlconf = "middleware.extra_urls" self.assertIsNone(CommonMiddleware(get_response_404).process_request(request)) self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_slashless_resource_custom_urlconf(self): """ Matches to explicit slashless URLs should go unmolested. """ def get_response(req): return HttpResponse("web content") request = self.rf.get("/customurlconf/noslash") request.urlconf = "middleware.extra_urls" self.assertIsNone(CommonMiddleware(get_response).process_request(request)) self.assertEqual( CommonMiddleware(get_response)(request).content, b"web content" ) @override_settings(APPEND_SLASH=True) def test_append_slash_slashless_unknown_custom_urlconf(self): """ APPEND_SLASH should not redirect to unknown resources. """ request = self.rf.get("/customurlconf/unknown") request.urlconf = "middleware.extra_urls" self.assertIsNone(CommonMiddleware(get_response_404).process_request(request)) self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_redirect_custom_urlconf(self): """ APPEND_SLASH should redirect slashless URLs to a valid pattern. """ request = self.rf.get("/customurlconf/slash") request.urlconf = "middleware.extra_urls" r = CommonMiddleware(get_response_404)(request) self.assertIsNotNone( r, "CommonMiddleware failed to return APPEND_SLASH redirect using " "request.urlconf", ) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/customurlconf/slash/") @override_settings(APPEND_SLASH=True, DEBUG=True) def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self): """ While in debug mode, an exception is raised with a warning when a failed attempt is made to POST to an URL which would normally be redirected to a slashed version. """ request = self.rf.get("/customurlconf/slash") request.urlconf = "middleware.extra_urls" request.method = "POST" with self.assertRaisesMessage(RuntimeError, "end in a slash"): CommonMiddleware(get_response_404)(request) @override_settings(APPEND_SLASH=False) def test_append_slash_disabled_custom_urlconf(self): """ Disabling append slash functionality should leave slashless URLs alone. """ request = self.rf.get("/customurlconf/slash") request.urlconf = "middleware.extra_urls" self.assertIsNone(CommonMiddleware(get_response_404).process_request(request)) self.assertEqual(CommonMiddleware(get_response_404)(request).status_code, 404) @override_settings(APPEND_SLASH=True) def test_append_slash_quoted_custom_urlconf(self): """ URLs which require quoting should be redirected to their slash version. """ request = self.rf.get(quote("/customurlconf/needsquoting#")) request.urlconf = "middleware.extra_urls" r = CommonMiddleware(get_response_404)(request) self.assertIsNotNone( r, "CommonMiddleware failed to return APPEND_SLASH redirect using " "request.urlconf", ) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/customurlconf/needsquoting%23/") @override_settings(APPEND_SLASH=False, PREPEND_WWW=True) def test_prepend_www_custom_urlconf(self): request = self.rf.get("/customurlconf/path/") request.urlconf = "middleware.extra_urls" r = CommonMiddleware(get_response_empty).process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "http://www.testserver/customurlconf/path/") @override_settings(APPEND_SLASH=True, PREPEND_WWW=True) def test_prepend_www_append_slash_have_slash_custom_urlconf(self): request = self.rf.get("/customurlconf/slash/") request.urlconf = "middleware.extra_urls" r = CommonMiddleware(get_response_empty).process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "http://www.testserver/customurlconf/slash/") @override_settings(APPEND_SLASH=True, PREPEND_WWW=True) def test_prepend_www_append_slash_slashless_custom_urlconf(self): request = self.rf.get("/customurlconf/slash") request.urlconf = "middleware.extra_urls" r = CommonMiddleware(get_response_empty).process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "http://www.testserver/customurlconf/slash/") # Tests for the Content-Length header def test_content_length_header_added(self): def get_response(req): response = HttpResponse("content") self.assertNotIn("Content-Length", response) return response response = CommonMiddleware(get_response)(self.rf.get("/")) self.assertEqual(int(response.headers["Content-Length"]), len(response.content)) def test_content_length_header_not_added_for_streaming_response(self): def get_response(req): response = StreamingHttpResponse("content") self.assertNotIn("Content-Length", response) return response response = CommonMiddleware(get_response)(self.rf.get("/")) self.assertNotIn("Content-Length", response) def test_content_length_header_not_changed(self): bad_content_length = 500 def get_response(req): response = HttpResponse() response.headers["Content-Length"] = bad_content_length return response response = CommonMiddleware(get_response)(self.rf.get("/")) self.assertEqual(int(response.headers["Content-Length"]), bad_content_length) # Other tests @override_settings(DISALLOWED_USER_AGENTS=[re.compile(r"foo")]) def test_disallowed_user_agents(self): request = self.rf.get("/slash") request.META["HTTP_USER_AGENT"] = "foo" with self.assertRaisesMessage(PermissionDenied, "Forbidden user agent"): CommonMiddleware(get_response_empty).process_request(request) def test_non_ascii_query_string_does_not_crash(self): """Regression test for #15152""" request = self.rf.get("/slash") request.META["QUERY_STRING"] = "drink=café" r = CommonMiddleware(get_response_empty).process_request(request) self.assertIsNone(r) response = HttpResponseNotFound() r = CommonMiddleware(get_response_empty).process_response(request, response) self.assertEqual(r.status_code, 301) def test_response_redirect_class(self): request = self.rf.get("/slash") r = CommonMiddleware(get_response_404)(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, "/slash/") self.assertIsInstance(r, HttpResponsePermanentRedirect) def test_response_redirect_class_subclass(self): class MyCommonMiddleware(CommonMiddleware): response_redirect_class = HttpResponseRedirect request = self.rf.get("/slash") r = MyCommonMiddleware(get_response_404)(request) self.assertEqual(r.status_code, 302) self.assertEqual(r.url, "/slash/") self.assertIsInstance(r, HttpResponseRedirect) @override_settings( IGNORABLE_404_URLS=[re.compile(r"foo")], MANAGERS=[("PHD", "[email protected]")], ) class BrokenLinkEmailsMiddlewareTest(SimpleTestCase): rf = RequestFactory() def setUp(self): self.req = self.rf.get("/regular_url/that/does/not/exist") def get_response(self, req): return self.client.get(req.path) def test_404_error_reporting(self): self.req.META["HTTP_REFERER"] = "/another/url/" BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 1) self.assertIn("Broken", mail.outbox[0].subject) def test_404_error_reporting_no_referer(self): BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) def test_404_error_reporting_ignored_url(self): self.req.path = self.req.path_info = "foo_url/that/does/not/exist" BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) def test_custom_request_checker(self): class SubclassedMiddleware(BrokenLinkEmailsMiddleware): ignored_user_agent_patterns = ( re.compile(r"Spider.*"), re.compile(r"Robot.*"), ) def is_ignorable_request(self, request, uri, domain, referer): """Check user-agent in addition to normal checks.""" if super().is_ignorable_request(request, uri, domain, referer): return True user_agent = request.META["HTTP_USER_AGENT"] return any( pattern.search(user_agent) for pattern in self.ignored_user_agent_patterns ) self.req.META["HTTP_REFERER"] = "/another/url/" self.req.META["HTTP_USER_AGENT"] = "Spider machine 3.4" SubclassedMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) self.req.META["HTTP_USER_AGENT"] = "My user agent" SubclassedMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 1) def test_referer_equal_to_requested_url(self): """ Some bots set the referer to the current URL to avoid being blocked by an referer check (#25302). """ self.req.META["HTTP_REFERER"] = self.req.path BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) # URL with scheme and domain should also be ignored self.req.META["HTTP_REFERER"] = "http://testserver%s" % self.req.path BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) # URL with a different scheme should be ignored as well because bots # tend to use http:// in referers even when browsing HTTPS websites. self.req.META["HTTP_X_PROTO"] = "https" self.req.META["SERVER_PORT"] = 443 with self.settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_PROTO", "https")): BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) def test_referer_equal_to_requested_url_on_another_domain(self): self.req.META["HTTP_REFERER"] = "http://anotherserver%s" % self.req.path BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 1) @override_settings(APPEND_SLASH=True) def test_referer_equal_to_requested_url_without_trailing_slash_with_append_slash( self, ): self.req.path = self.req.path_info = "/regular_url/that/does/not/exist/" self.req.META["HTTP_REFERER"] = self.req.path_info[:-1] BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 0) @override_settings(APPEND_SLASH=False) def test_referer_equal_to_requested_url_without_trailing_slash_with_no_append_slash( self, ): self.req.path = self.req.path_info = "/regular_url/that/does/not/exist/" self.req.META["HTTP_REFERER"] = self.req.path_info[:-1] BrokenLinkEmailsMiddleware(self.get_response)(self.req) self.assertEqual(len(mail.outbox), 1) @override_settings(ROOT_URLCONF="middleware.cond_get_urls") class ConditionalGetMiddlewareTest(SimpleTestCase): request_factory = RequestFactory() def setUp(self): self.req = self.request_factory.get("/") self.resp_headers = {} def get_response(self, req): resp = self.client.get(req.path_info) for key, value in self.resp_headers.items(): resp[key] = value return resp # Tests for the ETag header def test_middleware_calculates_etag(self): resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) self.assertNotEqual("", resp["ETag"]) def test_middleware_wont_overwrite_etag(self): self.resp_headers["ETag"] = "eggs" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) self.assertEqual("eggs", resp["ETag"]) def test_no_etag_streaming_response(self): def get_response(req): return StreamingHttpResponse(["content"]) self.assertFalse( ConditionalGetMiddleware(get_response)(self.req).has_header("ETag") ) def test_no_etag_response_empty_content(self): def get_response(req): return HttpResponse() self.assertFalse( ConditionalGetMiddleware(get_response)(self.req).has_header("ETag") ) def test_no_etag_no_store_cache(self): self.resp_headers["Cache-Control"] = "No-Cache, No-Store, Max-age=0" self.assertFalse( ConditionalGetMiddleware(self.get_response)(self.req).has_header("ETag") ) def test_etag_extended_cache_control(self): self.resp_headers["Cache-Control"] = 'my-directive="my-no-store"' self.assertTrue( ConditionalGetMiddleware(self.get_response)(self.req).has_header("ETag") ) def test_if_none_match_and_no_etag(self): self.req.META["HTTP_IF_NONE_MATCH"] = "spam" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) def test_no_if_none_match_and_etag(self): self.resp_headers["ETag"] = "eggs" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) def test_if_none_match_and_same_etag(self): self.req.META["HTTP_IF_NONE_MATCH"] = '"spam"' self.resp_headers["ETag"] = '"spam"' resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 304) def test_if_none_match_and_different_etag(self): self.req.META["HTTP_IF_NONE_MATCH"] = "spam" self.resp_headers["ETag"] = "eggs" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) def test_if_none_match_and_redirect(self): def get_response(req): resp = self.client.get(req.path_info) resp["ETag"] = "spam" resp["Location"] = "/" resp.status_code = 301 return resp self.req.META["HTTP_IF_NONE_MATCH"] = "spam" resp = ConditionalGetMiddleware(get_response)(self.req) self.assertEqual(resp.status_code, 301) def test_if_none_match_and_client_error(self): def get_response(req): resp = self.client.get(req.path_info) resp["ETag"] = "spam" resp.status_code = 400 return resp self.req.META["HTTP_IF_NONE_MATCH"] = "spam" resp = ConditionalGetMiddleware(get_response)(self.req) self.assertEqual(resp.status_code, 400) # Tests for the Last-Modified header def test_if_modified_since_and_no_last_modified(self): self.req.META["HTTP_IF_MODIFIED_SINCE"] = "Sat, 12 Feb 2011 17:38:44 GMT" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) def test_no_if_modified_since_and_last_modified(self): self.resp_headers["Last-Modified"] = "Sat, 12 Feb 2011 17:38:44 GMT" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 200) def test_if_modified_since_and_same_last_modified(self): self.req.META["HTTP_IF_MODIFIED_SINCE"] = "Sat, 12 Feb 2011 17:38:44 GMT" self.resp_headers["Last-Modified"] = "Sat, 12 Feb 2011 17:38:44 GMT" self.resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(self.resp.status_code, 304) def test_if_modified_since_and_last_modified_in_the_past(self): self.req.META["HTTP_IF_MODIFIED_SINCE"] = "Sat, 12 Feb 2011 17:38:44 GMT" self.resp_headers["Last-Modified"] = "Sat, 12 Feb 2011 17:35:44 GMT" resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(resp.status_code, 304) def test_if_modified_since_and_last_modified_in_the_future(self): self.req.META["HTTP_IF_MODIFIED_SINCE"] = "Sat, 12 Feb 2011 17:38:44 GMT" self.resp_headers["Last-Modified"] = "Sat, 12 Feb 2011 17:41:44 GMT" self.resp = ConditionalGetMiddleware(self.get_response)(self.req) self.assertEqual(self.resp.status_code, 200) def test_if_modified_since_and_redirect(self): def get_response(req): resp = self.client.get(req.path_info) resp["Last-Modified"] = "Sat, 12 Feb 2011 17:35:44 GMT" resp["Location"] = "/" resp.status_code = 301 return resp self.req.META["HTTP_IF_MODIFIED_SINCE"] = "Sat, 12 Feb 2011 17:38:44 GMT" resp = ConditionalGetMiddleware(get_response)(self.req) self.assertEqual(resp.status_code, 301) def test_if_modified_since_and_client_error(self): def get_response(req): resp = self.client.get(req.path_info) resp["Last-Modified"] = "Sat, 12 Feb 2011 17:35:44 GMT" resp.status_code = 400 return resp self.req.META["HTTP_IF_MODIFIED_SINCE"] = "Sat, 12 Feb 2011 17:38:44 GMT" resp = ConditionalGetMiddleware(get_response)(self.req) self.assertEqual(resp.status_code, 400) def test_not_modified_headers(self): """ The 304 Not Modified response should include only the headers required by section 4.1 of RFC 7232, Last-Modified, and the cookies. """ def get_response(req): resp = self.client.get(req.path_info) resp["Date"] = "Sat, 12 Feb 2011 17:35:44 GMT" resp["Last-Modified"] = "Sat, 12 Feb 2011 17:35:44 GMT" resp["Expires"] = "Sun, 13 Feb 2011 17:35:44 GMT" resp["Vary"] = "Cookie" resp["Cache-Control"] = "public" resp["Content-Location"] = "/alt" resp["Content-Language"] = "en" # shouldn't be preserved resp["ETag"] = '"spam"' resp.set_cookie("key", "value") return resp self.req.META["HTTP_IF_NONE_MATCH"] = '"spam"' new_response = ConditionalGetMiddleware(get_response)(self.req) self.assertEqual(new_response.status_code, 304) base_response = get_response(self.req) for header in ( "Cache-Control", "Content-Location", "Date", "ETag", "Expires", "Last-Modified", "Vary", ): self.assertEqual( new_response.headers[header], base_response.headers[header] ) self.assertEqual(new_response.cookies, base_response.cookies) self.assertNotIn("Content-Language", new_response) def test_no_unsafe(self): """ ConditionalGetMiddleware shouldn't return a conditional response on an unsafe request. A response has already been generated by the time ConditionalGetMiddleware is called, so it's too late to return a 412 Precondition Failed. """ def get_200_response(req): return HttpResponse(status=200) response = ConditionalGetMiddleware(self.get_response)(self.req) etag = response.headers["ETag"] put_request = self.request_factory.put("/", HTTP_IF_MATCH=etag) conditional_get_response = ConditionalGetMiddleware(get_200_response)( put_request ) self.assertEqual( conditional_get_response.status_code, 200 ) # should never be a 412 def test_no_head(self): """ ConditionalGetMiddleware shouldn't compute and return an ETag on a HEAD request since it can't do so accurately without access to the response body of the corresponding GET. """ def get_200_response(req): return HttpResponse(status=200) request = self.request_factory.head("/") conditional_get_response = ConditionalGetMiddleware(get_200_response)(request) self.assertNotIn("ETag", conditional_get_response) class XFrameOptionsMiddlewareTest(SimpleTestCase): """ Tests for the X-Frame-Options clickjacking prevention middleware. """ def test_same_origin(self): """ The X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the middleware use that value for the HTTP header. """ with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"): r = XFrameOptionsMiddleware(get_response_empty)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") with override_settings(X_FRAME_OPTIONS="sameorigin"): r = XFrameOptionsMiddleware(get_response_empty)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") def test_deny(self): """ The X_FRAME_OPTIONS setting can be set to DENY to have the middleware use that value for the HTTP header. """ with override_settings(X_FRAME_OPTIONS="DENY"): r = XFrameOptionsMiddleware(get_response_empty)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") with override_settings(X_FRAME_OPTIONS="deny"): r = XFrameOptionsMiddleware(get_response_empty)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") def test_defaults_sameorigin(self): """ If the X_FRAME_OPTIONS setting is not set then it defaults to DENY. """ with override_settings(X_FRAME_OPTIONS=None): del settings.X_FRAME_OPTIONS # restored by override_settings r = XFrameOptionsMiddleware(get_response_empty)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") def test_dont_set_if_set(self): """ If the X-Frame-Options header is already set then the middleware does not attempt to override it. """ def same_origin_response(request): response = HttpResponse() response.headers["X-Frame-Options"] = "SAMEORIGIN" return response def deny_response(request): response = HttpResponse() response.headers["X-Frame-Options"] = "DENY" return response with override_settings(X_FRAME_OPTIONS="DENY"): r = XFrameOptionsMiddleware(same_origin_response)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"): r = XFrameOptionsMiddleware(deny_response)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") def test_response_exempt(self): """ If the response has an xframe_options_exempt attribute set to False then it still sets the header, but if it's set to True then it doesn't. """ def xframe_exempt_response(request): response = HttpResponse() response.xframe_options_exempt = True return response def xframe_not_exempt_response(request): response = HttpResponse() response.xframe_options_exempt = False return response with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"): r = XFrameOptionsMiddleware(xframe_not_exempt_response)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") r = XFrameOptionsMiddleware(xframe_exempt_response)(HttpRequest()) self.assertIsNone(r.headers.get("X-Frame-Options")) def test_is_extendable(self): """ The XFrameOptionsMiddleware method that determines the X-Frame-Options header value can be overridden based on something in the request or response. """ class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware): # This is just an example for testing purposes... def get_xframe_options_value(self, request, response): if getattr(request, "sameorigin", False): return "SAMEORIGIN" if getattr(response, "sameorigin", False): return "SAMEORIGIN" return "DENY" def same_origin_response(request): response = HttpResponse() response.sameorigin = True return response with override_settings(X_FRAME_OPTIONS="DENY"): r = OtherXFrameOptionsMiddleware(same_origin_response)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") request = HttpRequest() request.sameorigin = True r = OtherXFrameOptionsMiddleware(get_response_empty)(request) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"): r = OtherXFrameOptionsMiddleware(get_response_empty)(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") class GZipMiddlewareTest(SimpleTestCase): """ Tests the GZipMiddleware. """ short_string = b"This string is too short to be worth compressing." compressible_string = b"a" * 500 incompressible_string = b"".join( int2byte(random.randint(0, 255)) for _ in range(500) ) sequence = [b"a" * 500, b"b" * 200, b"a" * 300] sequence_unicode = ["a" * 500, "é" * 200, "a" * 300] request_factory = RequestFactory() def setUp(self): self.req = self.request_factory.get("/") self.req.META["HTTP_ACCEPT_ENCODING"] = "gzip, deflate" self.req.META[ "HTTP_USER_AGENT" ] = "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" self.resp = HttpResponse() self.resp.status_code = 200 self.resp.content = self.compressible_string self.resp["Content-Type"] = "text/html; charset=UTF-8" def get_response(self, request): return self.resp @staticmethod def decompress(gzipped_string): with gzip.GzipFile(mode="rb", fileobj=BytesIO(gzipped_string)) as f: return f.read() @staticmethod def get_mtime(gzipped_string): with gzip.GzipFile(mode="rb", fileobj=BytesIO(gzipped_string)) as f: f.read() # must read the data before accessing the header return f.mtime def test_compress_response(self): """ Compression is performed on responses with compressible content. """ r = GZipMiddleware(self.get_response)(self.req) self.assertEqual(self.decompress(r.content), self.compressible_string) self.assertEqual(r.get("Content-Encoding"), "gzip") self.assertEqual(r.get("Content-Length"), str(len(r.content))) def test_compress_streaming_response(self): """ Compression is performed on responses with streaming content. """ def get_stream_response(request): resp = StreamingHttpResponse(self.sequence) resp["Content-Type"] = "text/html; charset=UTF-8" return resp r = GZipMiddleware(get_stream_response)(self.req) self.assertEqual(self.decompress(b"".join(r)), b"".join(self.sequence)) self.assertEqual(r.get("Content-Encoding"), "gzip") self.assertFalse(r.has_header("Content-Length")) def test_compress_streaming_response_unicode(self): """ Compression is performed on responses with streaming Unicode content. """ def get_stream_response_unicode(request): resp = StreamingHttpResponse(self.sequence_unicode) resp["Content-Type"] = "text/html; charset=UTF-8" return resp r = GZipMiddleware(get_stream_response_unicode)(self.req) self.assertEqual( self.decompress(b"".join(r)), b"".join(x.encode() for x in self.sequence_unicode), ) self.assertEqual(r.get("Content-Encoding"), "gzip") self.assertFalse(r.has_header("Content-Length")) def test_compress_file_response(self): """ Compression is performed on FileResponse. """ with open(__file__, "rb") as file1: def get_response(req): file_resp = FileResponse(file1) file_resp["Content-Type"] = "text/html; charset=UTF-8" return file_resp r = GZipMiddleware(get_response)(self.req) with open(__file__, "rb") as file2: self.assertEqual(self.decompress(b"".join(r)), file2.read()) self.assertEqual(r.get("Content-Encoding"), "gzip") self.assertIsNot(r.file_to_stream, file1) def test_compress_non_200_response(self): """ Compression is performed on responses with a status other than 200 (#10762). """ self.resp.status_code = 404 r = GZipMiddleware(self.get_response)(self.req) self.assertEqual(self.decompress(r.content), self.compressible_string) self.assertEqual(r.get("Content-Encoding"), "gzip") def test_no_compress_short_response(self): """ Compression isn't performed on responses with short content. """ self.resp.content = self.short_string r = GZipMiddleware(self.get_response)(self.req) self.assertEqual(r.content, self.short_string) self.assertIsNone(r.get("Content-Encoding")) def test_no_compress_compressed_response(self): """ Compression isn't performed on responses that are already compressed. """ self.resp["Content-Encoding"] = "deflate" r = GZipMiddleware(self.get_response)(self.req) self.assertEqual(r.content, self.compressible_string) self.assertEqual(r.get("Content-Encoding"), "deflate") def test_no_compress_incompressible_response(self): """ Compression isn't performed on responses with incompressible content. """ self.resp.content = self.incompressible_string r = GZipMiddleware(self.get_response)(self.req) self.assertEqual(r.content, self.incompressible_string) self.assertIsNone(r.get("Content-Encoding")) def test_compress_deterministic(self): """ Compression results are the same for the same content and don't include a modification time (since that would make the results of compression non-deterministic and prevent ConditionalGetMiddleware from recognizing conditional matches on gzipped content). """ r1 = GZipMiddleware(self.get_response)(self.req) r2 = GZipMiddleware(self.get_response)(self.req) self.assertEqual(r1.content, r2.content) self.assertEqual(self.get_mtime(r1.content), 0) self.assertEqual(self.get_mtime(r2.content), 0) class ETagGZipMiddlewareTest(SimpleTestCase): """ ETags are handled properly by GZipMiddleware. """ rf = RequestFactory() compressible_string = b"a" * 500 def test_strong_etag_modified(self): """ GZipMiddleware makes a strong ETag weak. """ def get_response(req): response = HttpResponse(self.compressible_string) response.headers["ETag"] = '"eggs"' return response request = self.rf.get("/", HTTP_ACCEPT_ENCODING="gzip, deflate") gzip_response = GZipMiddleware(get_response)(request) self.assertEqual(gzip_response.headers["ETag"], 'W/"eggs"') def test_weak_etag_not_modified(self): """ GZipMiddleware doesn't modify a weak ETag. """ def get_response(req): response = HttpResponse(self.compressible_string) response.headers["ETag"] = 'W/"eggs"' return response request = self.rf.get("/", HTTP_ACCEPT_ENCODING="gzip, deflate") gzip_response = GZipMiddleware(get_response)(request) self.assertEqual(gzip_response.headers["ETag"], 'W/"eggs"') def test_etag_match(self): """ GZipMiddleware allows 304 Not Modified responses. """ def get_response(req): response = HttpResponse(self.compressible_string) return response def get_cond_response(req): return ConditionalGetMiddleware(get_response)(req) request = self.rf.get("/", HTTP_ACCEPT_ENCODING="gzip, deflate") response = GZipMiddleware(get_cond_response)(request) gzip_etag = response.headers["ETag"] next_request = self.rf.get( "/", HTTP_ACCEPT_ENCODING="gzip, deflate", HTTP_IF_NONE_MATCH=gzip_etag ) next_response = ConditionalGetMiddleware(get_response)(next_request) self.assertEqual(next_response.status_code, 304)
68e0245357f387c2f66bb02c3e0263f2816dc9a69ec28931a642b2e1fe6cc172
import asyncio import sys import threading from pathlib import Path from asgiref.testing import ApplicationCommunicator from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.asgi import get_asgi_application from django.core.signals import request_finished, request_started from django.db import close_old_connections from django.test import ( AsyncRequestFactory, SimpleTestCase, modify_settings, override_settings, ) from django.utils.http import http_date from .urls import sync_waiter, test_filename TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static" @override_settings(ROOT_URLCONF="asgi.urls") class ASGITest(SimpleTestCase): async_request_factory = AsyncRequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) async def test_get_asgi_application(self): """ get_asgi_application() returns a functioning ASGI callable. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"12"), (b"Content-Type", b"text/html; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") async def test_file_response(self): """ Makes sure that FileResponse works over ASGI. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/file/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. with open(test_filename, "rb") as test_file: test_file_contents = test_file.read() # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) headers = response_start["headers"] self.assertEqual(len(headers), 3) expected_headers = { b"Content-Length": str(len(test_file_contents)).encode("ascii"), b"Content-Type": b"text/x-python", b"Content-Disposition": b'inline; filename="urls.py"', } for key, value in headers: try: self.assertEqual(value, expected_headers[key]) except AssertionError: # Windows registry may not be configured with correct # mimetypes. if sys.platform == "win32" and key == b"Content-Type": self.assertEqual(value, b"text/plain") else: raise response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() @modify_settings(INSTALLED_APPS={"append": "django.contrib.staticfiles"}) @override_settings( STATIC_URL="static/", STATIC_ROOT=TEST_STATIC_ROOT, STATICFILES_DIRS=[TEST_STATIC_ROOT], STATICFILES_FINDERS=[ "django.contrib.staticfiles.finders.FileSystemFinder", ], ) async def test_static_file_response(self): application = ASGIStaticFilesHandler(get_asgi_application()) # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/static/file.txt") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. file_path = TEST_STATIC_ROOT / "file.txt" with open(file_path, "rb") as test_file: test_file_contents = test_file.read() # Read the response. stat = file_path.stat() response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", str(len(test_file_contents)).encode("ascii")), (b"Content-Type", b"text/plain"), (b"Content-Disposition", b'inline; filename="file.txt"'), (b"Last-Modified", http_date(stat.st_mtime).encode("ascii")), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() async def test_headers(self): application = get_asgi_application() communicator = ApplicationCommunicator( application, self.async_request_factory._base_scope( path="/meta/", headers=[ [b"content-type", b"text/plain; charset=utf-8"], [b"content-length", b"77"], [b"referer", b"Scotland"], [b"referer", b"Wales"], ], ), ) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"19"), (b"Content-Type", b"text/plain; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"From Scotland,Wales") async def test_post_body(self): application = get_asgi_application() scope = self.async_request_factory._base_scope( method="POST", path="/post/", query_string="echo=1", ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request", "body": b"Echo!"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Echo!") async def test_untouched_request_body_gets_closed(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(method="POST", path="/post/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 204) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") async def test_get_query_string(self): application = get_asgi_application() for query_string in (b"name=Andrew", "name=Andrew"): with self.subTest(query_string=query_string): scope = self.async_request_factory._base_scope( path="/", query_string=query_string, ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello Andrew!") async def test_disconnect(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.disconnect"}) with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() async def test_wrong_connection_type(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", type="other") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) msg = "Django can only handle ASGI/HTTP connections, not other." with self.assertRaisesMessage(ValueError, msg): await communicator.receive_output() async def test_non_unicode_query_string(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", query_string=b"\xff") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 400) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") async def test_request_lifecycle_signals_dispatched_with_thread_sensitive(self): class SignalHandler: """Track threads handler is dispatched on.""" threads = [] def __call__(self, **kwargs): self.threads.append(threading.current_thread()) signal_handler = SignalHandler() request_started.connect(signal_handler) request_finished.connect(signal_handler) # Perform a basic request. application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # AsyncToSync should have executed the signals in the same thread. request_started_thread, request_finished_thread = signal_handler.threads self.assertEqual(request_started_thread, request_finished_thread) request_started.disconnect(signal_handler) request_finished.disconnect(signal_handler) async def test_concurrent_async_uses_multiple_thread_pools(self): sync_waiter.active_threads.clear() # Send 2 requests concurrently application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/wait/") communicators = [] for _ in range(2): communicators.append(ApplicationCommunicator(application, scope)) await communicators[-1].send_input({"type": "http.request"}) # Each request must complete with a status code of 200 # If requests aren't scheduled concurrently, the barrier in the # sync_wait view will time out, resulting in a 500 status code. for communicator in communicators: response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # The requests should have scheduled on different threads. Note # active_threads is a set (a thread can only appear once), therefore # length is a sufficient check. self.assertEqual(len(sync_waiter.active_threads), 2) sync_waiter.active_threads.clear()
c719d9b91936c908ab98639b9a86b960b3ba2a2019027161006809dd0b8d330c
import threading from django.http import FileResponse, HttpResponse from django.urls import path from django.views.decorators.csrf import csrf_exempt def hello(request): name = request.GET.get("name") or "World" return HttpResponse("Hello %s!" % name) def hello_meta(request): return HttpResponse( "From %s" % request.META.get("HTTP_REFERER") or "", content_type=request.META.get("CONTENT_TYPE"), ) def sync_waiter(request): with sync_waiter.lock: sync_waiter.active_threads.add(threading.current_thread()) sync_waiter.barrier.wait(timeout=0.5) return hello(request) @csrf_exempt def post_echo(request): if request.GET.get("echo"): return HttpResponse(request.body) else: return HttpResponse(status=204) sync_waiter.active_threads = set() sync_waiter.lock = threading.Lock() sync_waiter.barrier = threading.Barrier(2) test_filename = __file__ urlpatterns = [ path("", hello), path("file/", lambda x: FileResponse(open(test_filename, "rb"))), path("meta/", hello_meta), path("post/", post_echo), path("wait/", sync_waiter), ]
9ca458158ef9749ae73badcb87ac18b46f07f163c57bb3eb0ae6f5ffeac03598
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue()) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.ExtraPatternsStorage") class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage", ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") self.patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) self.patched_settings.enable() self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): self.patched_settings.disable() if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.NoneHashStorage") class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STATICFILES_STORAGE="staticfiles_tests.storage.NoPostProcessReplacedPathStorage" ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings(STATICFILES_STORAGE="staticfiles_tests.storage.SimpleStorage") class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): self.manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=self.manifest_path, ) self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) super().setUp() def tearDown(self): os.umask(self.old_umask) super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STATICFILES_STORAGE="staticfiles_tests.test_storage.CustomStaticFilesStorage", ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage", ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
9bcd9ff3a2144f0bc4c34904d1d9fb005b67545be6f53f9a5b590cb27180d13e
import unittest from django.core.exceptions import FieldError from django.db import IntegrityError, connection, transaction from django.db.models import CharField, Count, F, IntegerField, Max from django.db.models.functions import Abs, Concat, Lower from django.test import TestCase from django.test.utils import register_lookup from .models import ( A, B, Bar, D, DataPoint, Foo, RelatedPoint, UniqueNumber, UniqueNumberChild, ) class SimpleTest(TestCase): @classmethod def setUpTestData(cls): cls.a1 = A.objects.create() cls.a2 = A.objects.create() for x in range(20): B.objects.create(a=cls.a1) D.objects.create(a=cls.a1) def test_nonempty_update(self): """ Update changes the right number of rows for a nonempty queryset """ num_updated = self.a1.b_set.update(y=100) self.assertEqual(num_updated, 20) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update(self): """ Update changes the right number of rows for an empty queryset """ num_updated = self.a2.b_set.update(y=100) self.assertEqual(num_updated, 0) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_nonempty_update_with_inheritance(self): """ Update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a1.d_set.update(y=100) self.assertEqual(num_updated, 20) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update_with_inheritance(self): """ Update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a2.d_set.update(y=100) self.assertEqual(num_updated, 0) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_foreign_key_update_with_id(self): """ Update works using <field>_id for foreign keys """ num_updated = self.a1.d_set.update(a_id=self.a2) self.assertEqual(num_updated, 20) self.assertEqual(self.a2.d_set.count(), 20) class AdvancedTests(TestCase): @classmethod def setUpTestData(cls): cls.d0 = DataPoint.objects.create(name="d0", value="apple") cls.d2 = DataPoint.objects.create(name="d2", value="banana") cls.d3 = DataPoint.objects.create(name="d3", value="banana") cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3) def test_update(self): """ Objects are updated by first filtering the candidates into a queryset and then calling the update() method. It executes immediately and returns nothing. """ resp = DataPoint.objects.filter(value="apple").update(name="d1") self.assertEqual(resp, 1) resp = DataPoint.objects.filter(value="apple") self.assertEqual(list(resp), [self.d0]) def test_update_multiple_objects(self): """ We can update multiple objects at once. """ resp = DataPoint.objects.filter(value="banana").update(value="pineapple") self.assertEqual(resp, 2) self.assertEqual(DataPoint.objects.get(name="d2").value, "pineapple") def test_update_fk(self): """ Foreign key fields can also be updated, although you can only update the object referred to, not anything inside the related object. """ resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0) self.assertEqual(resp, 1) resp = RelatedPoint.objects.filter(data__name="d0") self.assertEqual(list(resp), [self.r1]) def test_update_multiple_fields(self): """ Multiple fields can be updated at once """ resp = DataPoint.objects.filter(value="apple").update( value="fruit", another_value="peach" ) self.assertEqual(resp, 1) d = DataPoint.objects.get(name="d0") self.assertEqual(d.value, "fruit") self.assertEqual(d.another_value, "peach") def test_update_all(self): """ In the rare case you want to update every instance of a model, update() is also a manager method. """ self.assertEqual(DataPoint.objects.update(value="thing"), 3) resp = DataPoint.objects.values("value").distinct() self.assertEqual(list(resp), [{"value": "thing"}]) def test_update_slice_fail(self): """ We do not support update on already sliced query sets. """ method = DataPoint.objects.all()[:2].update msg = "Cannot update a query once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): method(another_value="another thing") def test_update_respects_to_field(self): """ Update of an FK field which specifies a to_field works. """ a_foo = Foo.objects.create(target="aaa") b_foo = Foo.objects.create(target="bbb") bar = Bar.objects.create(foo=a_foo) self.assertEqual(bar.foo_id, a_foo.target) bar_qs = Bar.objects.filter(pk=bar.pk) self.assertEqual(bar_qs[0].foo_id, a_foo.target) bar_qs.update(foo=b_foo) self.assertEqual(bar_qs[0].foo_id, b_foo.target) def test_update_m2m_field(self): msg = ( "Cannot update model field " "<django.db.models.fields.related.ManyToManyField: m2m_foo> " "(only non-relations and foreign keys permitted)." ) with self.assertRaisesMessage(FieldError, msg): Bar.objects.update(m2m_foo="whatever") def test_update_transformed_field(self): A.objects.create(x=5) A.objects.create(x=-6) with register_lookup(IntegerField, Abs): A.objects.update(x=F("x__abs")) self.assertCountEqual(A.objects.values_list("x", flat=True), [5, 6]) def test_update_annotated_queryset(self): """ Update of a queryset that's been annotated. """ # Trivial annotated update qs = DataPoint.objects.annotate(alias=F("value")) self.assertEqual(qs.update(another_value="foo"), 3) # Update where annotation is used for filtering qs = DataPoint.objects.annotate(alias=F("value")).filter(alias="apple") self.assertEqual(qs.update(another_value="foo"), 1) # Update where annotation is used in update parameters qs = DataPoint.objects.annotate(alias=F("value")) self.assertEqual(qs.update(another_value=F("alias")), 3) # Update where aggregation annotation is used in update parameters qs = DataPoint.objects.annotate(max=Max("value")) msg = ( "Aggregate functions are not allowed in this query " "(another_value=Max(Col(update_datapoint, update.DataPoint.value)))." ) with self.assertRaisesMessage(FieldError, msg): qs.update(another_value=F("max")) def test_update_annotated_multi_table_queryset(self): """ Update of a queryset that's been annotated and involves multiple tables. """ # Trivial annotated update qs = DataPoint.objects.annotate(related_count=Count("relatedpoint")) self.assertEqual(qs.update(value="Foo"), 3) # Update where annotation is used for filtering qs = DataPoint.objects.annotate(related_count=Count("relatedpoint")) self.assertEqual(qs.filter(related_count=1).update(value="Foo"), 1) # Update where aggregation annotation is used in update parameters qs = RelatedPoint.objects.annotate(max=Max("data__value")) msg = "Joined field references are not permitted in this query" with self.assertRaisesMessage(FieldError, msg): qs.update(name=F("max")) def test_update_with_joined_field_annotation(self): msg = "Joined field references are not permitted in this query" with register_lookup(CharField, Lower): for annotation in ( F("data__name"), F("data__name__lower"), Lower("data__name"), Concat("data__name", "data__value"), ): with self.subTest(annotation=annotation): with self.assertRaisesMessage(FieldError, msg): RelatedPoint.objects.annotate( new_name=annotation, ).update(name=F("new_name")) def test_update_ordered_by_m2m_aggregation_annotation(self): msg = ( "Cannot update when ordering by an aggregate: " "Count(Col(update_bar_m2m_foo, update.Bar_m2m_foo.foo))" ) with self.assertRaisesMessage(FieldError, msg): Bar.objects.annotate(m2m_count=Count("m2m_foo")).order_by( "m2m_count" ).update(x=2) def test_update_ordered_by_inline_m2m_annotation(self): foo = Foo.objects.create(target="test") Bar.objects.create(foo=foo) Bar.objects.order_by(Abs("m2m_foo")).update(x=2) self.assertEqual(Bar.objects.get().x, 2) def test_update_ordered_by_m2m_annotation(self): foo = Foo.objects.create(target="test") Bar.objects.create(foo=foo) Bar.objects.annotate(abs_id=Abs("m2m_foo")).order_by("abs_id").update(x=3) self.assertEqual(Bar.objects.get().x, 3) @unittest.skipUnless( connection.vendor == "mysql", "UPDATE...ORDER BY syntax is supported on MySQL/MariaDB", ) class MySQLUpdateOrderByTest(TestCase): """Update field with a unique constraint using an ordered queryset.""" @classmethod def setUpTestData(cls): UniqueNumber.objects.create(number=1) UniqueNumber.objects.create(number=2) def test_order_by_update_on_unique_constraint(self): tests = [ ("-number", "id"), (F("number").desc(), "id"), (F("number") * -1, "id"), ] for ordering in tests: with self.subTest(ordering=ordering), transaction.atomic(): updated = UniqueNumber.objects.order_by(*ordering).update( number=F("number") + 1, ) self.assertEqual(updated, 2) def test_order_by_update_on_unique_constraint_annotation(self): updated = ( UniqueNumber.objects.annotate(number_inverse=F("number").desc()) .order_by("number_inverse") .update(number=F("number") + 1) ) self.assertEqual(updated, 2) def test_order_by_update_on_parent_unique_constraint(self): # Ordering by inherited fields is omitted because joined fields cannot # be used in the ORDER BY clause. UniqueNumberChild.objects.create(number=3) UniqueNumberChild.objects.create(number=4) with self.assertRaises(IntegrityError): UniqueNumberChild.objects.order_by("number").update( number=F("number") + 1, ) def test_order_by_update_on_related_field(self): # Ordering by related fields is omitted because joined fields cannot be # used in the ORDER BY clause. data = DataPoint.objects.create(name="d0", value="apple") related = RelatedPoint.objects.create(name="r0", data=data) with self.assertNumQueries(1) as ctx: updated = RelatedPoint.objects.order_by("data__name").update(name="new") sql = ctx.captured_queries[0]["sql"] self.assertNotIn("ORDER BY", sql) self.assertEqual(updated, 1) related.refresh_from_db() self.assertEqual(related.name, "new")
3be3a6ea8d0855fec0d818f6a10c678ee0ea654d13e688885168e0f6aa5dbd69
""" Tests for the update() queryset method that allows in-place, multi-object updates. """ from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=20) value = models.CharField(max_length=20) another_value = models.CharField(max_length=20, blank=True) class RelatedPoint(models.Model): name = models.CharField(max_length=20) data = models.ForeignKey(DataPoint, models.CASCADE) class A(models.Model): x = models.IntegerField(default=10) class B(models.Model): a = models.ForeignKey(A, models.CASCADE) y = models.IntegerField(default=10) class C(models.Model): y = models.IntegerField(default=10) class D(C): a = models.ForeignKey(A, models.CASCADE) class Foo(models.Model): target = models.CharField(max_length=10, unique=True) class Bar(models.Model): foo = models.ForeignKey(Foo, models.CASCADE, to_field="target") m2m_foo = models.ManyToManyField(Foo, related_name="m2m_foo") x = models.IntegerField(default=0) class UniqueNumber(models.Model): number = models.IntegerField(unique=True) class UniqueNumberChild(UniqueNumber): pass
ad9d43f31e62fed1ef65090490aaf9f8dd5b415172e91024898f4fd202e0afb3
import os from datetime import datetime from django.core.serializers.json import DjangoJSONEncoder from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, json_script, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe class TestUtilsHtml(SimpleTestCase): def check_output(self, function, value, output=None): """ function(value) equals output. If output is None, function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output) def test_escape(self): items = ( ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ('"', "&quot;"), ("'", "&#x27;"), ) # Substitution patterns for testing the above items. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb") for value, output in items: with self.subTest(value=value, output=output): for pattern in patterns: with self.subTest(value=value, output=output, pattern=pattern): self.check_output(escape, pattern % value, pattern % output) self.check_output( escape, lazystr(pattern % value), pattern % output ) # Check repeated values. self.check_output(escape, value * 2, output * 2) # Verify it doesn't double replace &. self.check_output(escape, "<&", "&lt;&amp;") def test_format_html(self): self.assertEqual( format_html( "{} {} {third} {fourth}", "< Dangerous >", mark_safe("<b>safe</b>"), third="< dangerous again", fourth=mark_safe("<i>safe again</i>"), ), "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>", ) def test_linebreaks(self): items = ( ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"), ( "para1\nsub1\rsub2\n\npara2", "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>", ), ( "para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>", ), ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(linebreaks, value, output) self.check_output(linebreaks, lazystr(value), output) def test_strip_tags(self): items = ( ( "<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>", "See: &#39;&eacute; is an apostrophe followed by e acute", ), ( "<p>See: &#x27;&eacute; is an apostrophe followed by e acute</p>", "See: &#x27;&eacute; is an apostrophe followed by e acute", ), ("<adf>a", "a"), ("</adf>a", "a"), ("<asdf><asdf>e", "e"), ("hi, <f x", "hi, <f x"), ("234<235, right?", "234<235, right?"), ("a4<a5 right?", "a4<a5 right?"), ("b7>b2!", "b7>b2!"), ("</fe", "</fe"), ("<x>b<y>", "b"), ("a<p onclick=\"alert('<test>')\">b</p>c", "abc"), ("a<p a >b</p>c", "abc"), ("d<a:b c:d>e</p>f", "def"), ('<strong>foo</strong><a href="http://example.com">bar</a>', "foobar"), # caused infinite loop on Pythons not patched with # https://bugs.python.org/issue20288 ("&gotcha&#;<>", "&gotcha&#;<>"), ("<sc<!-- -->ript>test<<!-- -->/script>", "ript>test"), ("<script>alert()</script>&h", "alert()h"), ("><!" + ("&" * 16000) + "D", "><!" + ("&" * 16000) + "D"), ("X<<<<br>br>br>br>X", "XX"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_tags, value, output) self.check_output(strip_tags, lazystr(value), output) def test_strip_tags_files(self): # Test with more lengthy content (also catching performance regressions) for filename in ("strip_tags1.html", "strip_tags2.txt"): with self.subTest(filename=filename): path = os.path.join(os.path.dirname(__file__), "files", filename) with open(path) as fp: content = fp.read() start = datetime.now() stripped = strip_tags(content) elapsed = datetime.now() - start self.assertEqual(elapsed.seconds, 0) self.assertIn("Test string that has not been stripped.", stripped) self.assertNotIn("<", stripped) def test_strip_spaces_between_tags(self): # Strings that should come out untouched. items = (" <adf>", "<adf> ", " </adf> ", " <f> x</f>") for value in items: with self.subTest(value=value): self.check_output(strip_spaces_between_tags, value) self.check_output(strip_spaces_between_tags, lazystr(value)) # Strings that have spaces to strip. items = ( ("<d> </d>", "<d></d>"), ("<p>hello </p>\n<p> world</p>", "<p>hello </p><p> world</p>"), ("\n<p>\t</p>\n<p> </p>\n", "\n<p></p><p></p>\n"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_spaces_between_tags, value, output) self.check_output(strip_spaces_between_tags, lazystr(value), output) def test_escapejs(self): items = ( ( "\"double quotes\" and 'single quotes'", "\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027", ), (r"\ : backslashes, too", "\\u005C : backslashes, too"), ( "and lots of whitespace: \r\n\t\v\f\b", "and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008", ), ( r"<script>and this</script>", "\\u003Cscript\\u003Eand this\\u003C/script\\u003E", ), ( "paragraph separator:\u2029and line separator:\u2028", "paragraph separator:\\u2029and line separator:\\u2028", ), ("`", "\\u0060"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(escapejs, value, output) self.check_output(escapejs, lazystr(value), output) def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings ( ( "&<>", '<script id="test_id" type="application/json">' '"\\u0026\\u003C\\u003E"</script>', ) ), # "<", ">" and "&" are quoted inside JSON objects ( {"a": "<script>test&ing</script>"}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), # Lazy strings are quoted ( lazystr("&<>"), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"' "</script>", ), ( {"a": lazystr("<script>test&ing</script>")}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, "test_id"), expected) def test_json_script_custom_encoder(self): class CustomDjangoJSONEncoder(DjangoJSONEncoder): def encode(self, o): return '{"hello": "world"}' self.assertHTMLEqual( json_script({}, encoder=CustomDjangoJSONEncoder), '<script type="application/json">{"hello": "world"}</script>', ) def test_json_script_without_id(self): self.assertHTMLEqual( json_script({"key": "value"}), '<script type="application/json">{"key": "value"}</script>', ) def test_smart_urlquote(self): items = ( ("http://öäü.com/", "http://xn--4ca9at.com/"), ("http://öäü.com/öäü/", "http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/"), # Everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered # safe as per RFC. ( "http://example.com/path/öäü/", "http://example.com/path/%C3%B6%C3%A4%C3%BC/", ), ("http://example.com/%C3%B6/ä/", "http://example.com/%C3%B6/%C3%A4/"), ("http://example.com/?x=1&y=2+3&z=", "http://example.com/?x=1&y=2+3&z="), ("http://example.com/?x=<>\"'", "http://example.com/?x=%3C%3E%22%27"), ( "http://example.com/?q=http://example.com/?x=1%26q=django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ( "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ("http://.www.f oo.bar/", "http://.www.f%20oo.bar/"), ) # IDNs are properly quoted for value, output in items: with self.subTest(value=value, output=output): self.assertEqual(smart_urlquote(value), output) def test_conditional_escape(self): s = "<h1>interop</h1>" self.assertEqual(conditional_escape(s), "&lt;h1&gt;interop&lt;/h1&gt;") self.assertEqual(conditional_escape(mark_safe(s)), s) self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s) def test_html_safe(self): @html_safe class HtmlClass: def __str__(self): return "<h1>I'm a html class!</h1>" html_obj = HtmlClass() self.assertTrue(hasattr(HtmlClass, "__html__")) self.assertTrue(hasattr(html_obj, "__html__")) self.assertEqual(str(html_obj), html_obj.__html__()) def test_html_safe_subclass(self): class BaseClass: def __html__(self): # defines __html__ on its own return "some html content" def __str__(self): return "some non html content" @html_safe class Subclass(BaseClass): def __str__(self): # overrides __str__ and is marked as html_safe return "some html safe content" subclass_obj = Subclass() self.assertEqual(str(subclass_obj), subclass_obj.__html__()) def test_html_safe_defines_html_error(self): msg = "can't apply @html_safe to HtmlClass because it defines __html__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: def __html__(self): return "<h1>I'm a html class!</h1>" def test_html_safe_doesnt_define_str(self): msg = "can't apply @html_safe to HtmlClass because it doesn't define __str__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: pass def test_urlize(self): tests = ( ( "Search for google.com/?q=! and see.", 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and ' "see.", ), ( "Search for google.com/?q=1&lt! and see.", 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt' "</a>! and see.", ), ( lazystr("Search for google.com/?q=!"), 'Search for <a href="http://google.com/?q=">google.com/?q=</a>!', ), ("[email protected]", '<a href="mailto:[email protected]">[email protected]</a>'), ) for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output) def test_urlize_unchanged_inputs(self): tests = ( ("a" + "@a" * 50000) + "a", # simple_email_re catastrophic test ("a" + "." * 1000000) + "a", # trailing_punctuation catastrophic test "foo@", "@foo.com", "[email protected]", "foo@localhost", "foo@localhost.", ) for value in tests: with self.subTest(value=value): self.assertEqual(urlize(value), value)
6423f18d356b5f5899817d5a6326aa19c908590c40b9a1e43ddf1146ae6d4525
import platform import unittest from datetime import datetime, timezone from unittest import mock from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.http import ( base36_to_int, escape_leading_slashes, http_date, int_to_base36, is_same_domain, parse_etags, parse_header_parameters, parse_http_date, quote_etag, url_has_allowed_host_and_scheme, urlencode, urlsafe_base64_decode, urlsafe_base64_encode, ) class URLEncodeTests(SimpleTestCase): cannot_encode_none_msg = ( "Cannot encode None for key 'a' in a query string. Did you mean to " "pass an empty string or omit the value?" ) def test_tuples(self): self.assertEqual(urlencode((("a", 1), ("b", 2), ("c", 3))), "a=1&b=2&c=3") def test_dict(self): result = urlencode({"a": 1, "b": 2, "c": 3}) # Dictionaries are treated as unordered. self.assertIn( result, [ "a=1&b=2&c=3", "a=1&c=3&b=2", "b=2&a=1&c=3", "b=2&c=3&a=1", "c=3&a=1&b=2", "c=3&b=2&a=1", ], ) def test_dict_containing_sequence_not_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=False), "a=%5B1%2C+2%5D") def test_dict_containing_tuple_not_doseq(self): self.assertEqual(urlencode({"a": (1, 2)}, doseq=False), "a=%281%2C+2%29") def test_custom_iterable_not_doseq(self): class IterableWithStr: def __str__(self): return "custom" def __iter__(self): yield from range(0, 3) self.assertEqual(urlencode({"a": IterableWithStr()}, doseq=False), "a=custom") def test_dict_containing_sequence_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=True), "a=1&a=2") def test_dict_containing_empty_sequence_doseq(self): self.assertEqual(urlencode({"a": []}, doseq=True), "") def test_multivaluedict(self): result = urlencode( MultiValueDict( { "name": ["Adrian", "Simon"], "position": ["Developer"], } ), doseq=True, ) # MultiValueDicts are similarly unordered. self.assertIn( result, [ "name=Adrian&name=Simon&position=Developer", "position=Developer&name=Adrian&name=Simon", ], ) def test_dict_with_bytes_values(self): self.assertEqual(urlencode({"a": b"abc"}, doseq=True), "a=abc") def test_dict_with_sequence_of_bytes(self): self.assertEqual( urlencode({"a": [b"spam", b"eggs", b"bacon"]}, doseq=True), "a=spam&a=eggs&a=bacon", ) def test_dict_with_bytearray(self): self.assertEqual(urlencode({"a": bytearray(range(2))}, doseq=True), "a=0&a=1") def test_generator(self): self.assertEqual(urlencode({"a": range(2)}, doseq=True), "a=0&a=1") self.assertEqual(urlencode({"a": range(2)}, doseq=False), "a=range%280%2C+2%29") def test_none(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": None}) def test_none_in_sequence(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": [None]}, doseq=True) def test_none_in_generator(self): def gen(): yield None with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": gen()}, doseq=True) class Base36IntTests(SimpleTestCase): def test_roundtrip(self): for n in [0, 1, 1000, 1000000]: self.assertEqual(n, base36_to_int(int_to_base36(n))) def test_negative_input(self): with self.assertRaisesMessage(ValueError, "Negative base36 conversion input."): int_to_base36(-1) def test_to_base36_errors(self): for n in ["1", "foo", {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): int_to_base36(n) def test_invalid_literal(self): for n in ["#", " "]: with self.assertRaisesMessage( ValueError, "invalid literal for int() with base 36: '%s'" % n ): base36_to_int(n) def test_input_too_large(self): with self.assertRaisesMessage(ValueError, "Base36 input too large"): base36_to_int("1" * 14) def test_to_int_errors(self): for n in [123, {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): base36_to_int(n) def test_values(self): for n, b36 in [(0, "0"), (1, "1"), (42, "16"), (818469960, "django")]: self.assertEqual(int_to_base36(n), b36) self.assertEqual(base36_to_int(b36), n) class URLHasAllowedHostAndSchemeTests(unittest.TestCase): def test_bad_urls(self): bad_urls = ( "http://example.com", "http:///example.com", "https://example.com", "ftp://example.com", r"\\example.com", r"\\\example.com", r"/\\/example.com", r"\\\example.com", r"\\example.com", r"\\//example.com", r"/\/example.com", r"\/example.com", r"/\example.com", "http:///example.com", r"http:/\//example.com", r"http:\/example.com", r"http:/\example.com", 'javascript:alert("XSS")', "\njavascript:alert(x)", "java\nscript:alert(x)", "\x08//example.com", r"http://otherserver\@example.com", r"http:\\testserver\@example.com", r"http://testserver\me:[email protected]", r"http://testserver\@example.com", r"http:\\testserver\confirm\[email protected]", "http:999999999", "ftp:9999999999", "\n", "http://[2001:cdba:0000:0000:0000:0000:3257:9652/", "http://2001:cdba:0000:0000:0000:0000:3257:9652]/", ) for bad_url in bad_urls: with self.subTest(url=bad_url): self.assertIs( url_has_allowed_host_and_scheme( bad_url, allowed_hosts={"testserver", "testserver2"} ), False, ) def test_good_urls(self): good_urls = ( "/view/?param=http://example.com", "/view/?param=https://example.com", "/view?param=ftp://example.com", "view/?param=//example.com", "https://testserver/", "HTTPS://testserver/", "//testserver/", "http://testserver/[email protected]", "/url%20with%20spaces/", "path/http:2222222222", ) for good_url in good_urls: with self.subTest(url=good_url): self.assertIs( url_has_allowed_host_and_scheme( good_url, allowed_hosts={"otherserver", "testserver"} ), True, ) def test_basic_auth(self): # Valid basic auth credentials are allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://user:pass@testserver/", allowed_hosts={"user:pass@testserver"} ), True, ) def test_no_allowed_hosts(self): # A path without host is allowed. self.assertIs( url_has_allowed_host_and_scheme( "/confirm/[email protected]", allowed_hosts=None ), True, ) # Basic auth without host is not allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://testserver\@example.com", allowed_hosts=None ), False, ) def test_allowed_hosts_str(self): self.assertIs( url_has_allowed_host_and_scheme( "http://good.com/good", allowed_hosts="good.com" ), True, ) self.assertIs( url_has_allowed_host_and_scheme( "http://good.co/evil", allowed_hosts="good.com" ), False, ) def test_secure_param_https_urls(self): secure_urls = ( "https://example.com/p", "HTTPS://example.com/p", "/view/?param=http://example.com", ) for url in secure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), True, ) def test_secure_param_non_https_urls(self): insecure_urls = ( "http://example.com/p", "ftp://example.com/p", "//example.com/p", ) for url in insecure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), False, ) class URLSafeBase64Tests(unittest.TestCase): def test_roundtrip(self): bytestring = b"foo" encoded = urlsafe_base64_encode(bytestring) decoded = urlsafe_base64_decode(encoded) self.assertEqual(bytestring, decoded) class IsSameDomainTests(unittest.TestCase): def test_good(self): for pair in ( ("example.com", "example.com"), ("example.com", ".example.com"), ("foo.example.com", ".example.com"), ("example.com:8888", "example.com:8888"), ("example.com:8888", ".example.com:8888"), ("foo.example.com:8888", ".example.com:8888"), ): self.assertIs(is_same_domain(*pair), True) def test_bad(self): for pair in ( ("example2.com", "example.com"), ("foo.example.com", "example.com"), ("example.com:9999", "example.com:8888"), ("foo.example.com:8888", ""), ): self.assertIs(is_same_domain(*pair), False) class ETagProcessingTests(unittest.TestCase): def test_parsing(self): self.assertEqual( parse_etags(r'"" , "etag", "e\\tag", W/"weak"'), ['""', '"etag"', r'"e\\tag"', 'W/"weak"'], ) self.assertEqual(parse_etags("*"), ["*"]) # Ignore RFC 2616 ETags that are invalid according to RFC 7232. self.assertEqual(parse_etags(r'"etag", "e\"t\"ag"'), ['"etag"']) def test_quoting(self): self.assertEqual(quote_etag("etag"), '"etag"') # unquoted self.assertEqual(quote_etag('"etag"'), '"etag"') # quoted self.assertEqual(quote_etag('W/"etag"'), 'W/"etag"') # quoted, weak class HttpDateProcessingTests(unittest.TestCase): def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), "Mon, 01 Jan 2007 01:54:21 GMT") def test_parsing_rfc1123(self): parsed = parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) @unittest.skipIf(platform.architecture()[0] == "32bit", "The Year 2038 problem.") @mock.patch("django.utils.http.datetime.datetime") def test_parsing_rfc850(self, mocked_datetime): mocked_datetime.side_effect = datetime mocked_datetime.now = mock.Mock() now_1 = datetime(2019, 11, 6, 8, 49, 37, tzinfo=timezone.utc) now_2 = datetime(2020, 11, 6, 8, 49, 37, tzinfo=timezone.utc) now_3 = datetime(2048, 11, 6, 8, 49, 37, tzinfo=timezone.utc) tests = ( ( now_1, "Tuesday, 31-Dec-69 08:49:37 GMT", datetime(2069, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_1, "Tuesday, 10-Nov-70 08:49:37 GMT", datetime(1970, 11, 10, 8, 49, 37, tzinfo=timezone.utc), ), ( now_1, "Sunday, 06-Nov-94 08:49:37 GMT", datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ), ( now_2, "Wednesday, 31-Dec-70 08:49:37 GMT", datetime(2070, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_2, "Friday, 31-Dec-71 08:49:37 GMT", datetime(1971, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_3, "Sunday, 31-Dec-00 08:49:37 GMT", datetime(2000, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_3, "Friday, 31-Dec-99 08:49:37 GMT", datetime(1999, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ) for now, rfc850str, expected_date in tests: with self.subTest(rfc850str=rfc850str): mocked_datetime.now.return_value = now parsed = parse_http_date(rfc850str) mocked_datetime.now.assert_called_once_with(tz=timezone.utc) self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), expected_date, ) mocked_datetime.reset_mock() def test_parsing_asctime(self): parsed = parse_http_date("Sun Nov 6 08:49:37 1994") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) def test_parsing_asctime_nonascii_digits(self): """Non-ASCII unicode decimals raise an error.""" with self.assertRaises(ValueError): parse_http_date("Sun Nov 6 08:49:37 1994") with self.assertRaises(ValueError): parse_http_date("Sun Nov 12 08:49:37 1994") def test_parsing_year_less_than_70(self): parsed = parse_http_date("Sun Nov 6 08:49:37 0037") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(2037, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) class EscapeLeadingSlashesTests(unittest.TestCase): def test(self): tests = ( ("//example.com", "/%2Fexample.com"), ("//", "/%2F"), ) for url, expected in tests: with self.subTest(url=url): self.assertEqual(escape_leading_slashes(url), expected) class ParseHeaderParameterTests(unittest.TestCase): def test_basic(self): tests = [ ("text/plain", ("text/plain", {})), ("text/vnd.just.made.this.up ; ", ("text/vnd.just.made.this.up", {})), ("text/plain;charset=us-ascii", ("text/plain", {"charset": "us-ascii"})), ( 'text/plain ; charset="us-ascii"', ("text/plain", {"charset": "us-ascii"}), ), ( 'text/plain ; charset="us-ascii"; another=opt', ("text/plain", {"charset": "us-ascii", "another": "opt"}), ), ( 'attachment; filename="silly.txt"', ("attachment", {"filename": "silly.txt"}), ), ( 'attachment; filename="strange;name"', ("attachment", {"filename": "strange;name"}), ), ( 'attachment; filename="strange;name";size=123;', ("attachment", {"filename": "strange;name", "size": "123"}), ), ( 'form-data; name="files"; filename="fo\\"o;bar"', ("form-data", {"name": "files", "filename": 'fo"o;bar'}), ), ] for header, expected in tests: with self.subTest(header=header): self.assertEqual(parse_header_parameters(header), expected) def test_rfc2231_parsing(self): test_data = ( ( "Content-Type: application/x-stuff; " "title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***", ), ( "Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html", ), ( "Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html", ), ) for raw_line, expected_title in test_data: parsed = parse_header_parameters(raw_line) self.assertEqual(parsed[1]["title"], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( ( "Content-Type: application/x-stuff; " "title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", "'This%20is%20%2A%2A%2Afun%2A%2A%2A", ), ("Content-Type: application/x-stuff; title*='foo.html", "'foo.html"), ("Content-Type: application/x-stuff; title*=bar.html", "bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header_parameters(raw_line) self.assertEqual(parsed[1]["title"], expected_title)
e90fe0c9f2187ed743e70c67b58ae2a860f83725a45a46e08aed8886f77667f1
from unittest import mock from django.conf import settings from django.db import connection, models from django.db.models.functions import Lower, Upper from django.test import SimpleTestCase, TestCase, override_settings, skipUnlessDBFeature from django.test.utils import isolate_apps from .models import Book, ChildModel1, ChildModel2 class SimpleIndexesTests(SimpleTestCase): def test_suffix(self): self.assertEqual(models.Index.suffix, "idx") def test_repr(self): index = models.Index(fields=["title"]) named_index = models.Index(fields=["title"], name="title_idx") multi_col_index = models.Index(fields=["title", "author"]) partial_index = models.Index( fields=["title"], name="long_books_idx", condition=models.Q(pages__gt=400) ) covering_index = models.Index( fields=["title"], name="include_idx", include=["author", "pages"], ) opclasses_index = models.Index( fields=["headline", "body"], name="opclasses_idx", opclasses=["varchar_pattern_ops", "text_pattern_ops"], ) func_index = models.Index(Lower("title"), "subtitle", name="book_func_idx") tablespace_index = models.Index( fields=["title"], db_tablespace="idx_tbls", name="book_tablespace_idx", ) self.assertEqual(repr(index), "<Index: fields=['title']>") self.assertEqual( repr(named_index), "<Index: fields=['title'] name='title_idx'>", ) self.assertEqual(repr(multi_col_index), "<Index: fields=['title', 'author']>") self.assertEqual( repr(partial_index), "<Index: fields=['title'] name='long_books_idx' " "condition=(AND: ('pages__gt', 400))>", ) self.assertEqual( repr(covering_index), "<Index: fields=['title'] name='include_idx' " "include=('author', 'pages')>", ) self.assertEqual( repr(opclasses_index), "<Index: fields=['headline', 'body'] name='opclasses_idx' " "opclasses=['varchar_pattern_ops', 'text_pattern_ops']>", ) self.assertEqual( repr(func_index), "<Index: expressions=(Lower(F(title)), F(subtitle)) " "name='book_func_idx'>", ) self.assertEqual( repr(tablespace_index), "<Index: fields=['title'] name='book_tablespace_idx' " "db_tablespace='idx_tbls'>", ) def test_eq(self): index = models.Index(fields=["title"]) same_index = models.Index(fields=["title"]) another_index = models.Index(fields=["title", "author"]) index.model = Book same_index.model = Book another_index.model = Book self.assertEqual(index, same_index) self.assertEqual(index, mock.ANY) self.assertNotEqual(index, another_index) def test_eq_func(self): index = models.Index(Lower("title"), models.F("author"), name="book_func_idx") same_index = models.Index(Lower("title"), "author", name="book_func_idx") another_index = models.Index(Lower("title"), name="book_func_idx") self.assertEqual(index, same_index) self.assertEqual(index, mock.ANY) self.assertNotEqual(index, another_index) def test_index_fields_type(self): with self.assertRaisesMessage( ValueError, "Index.fields must be a list or tuple." ): models.Index(fields="title") def test_index_fields_strings(self): msg = "Index.fields must contain only strings with field names." with self.assertRaisesMessage(ValueError, msg): models.Index(fields=[models.F("title")]) def test_fields_tuple(self): self.assertEqual(models.Index(fields=("title",)).fields, ["title"]) def test_requires_field_or_expression(self): msg = "At least one field or expression is required to define an index." with self.assertRaisesMessage(ValueError, msg): models.Index() def test_expressions_and_fields_mutually_exclusive(self): msg = "Index.fields and expressions are mutually exclusive." with self.assertRaisesMessage(ValueError, msg): models.Index(Upper("foo"), fields=["field"]) def test_opclasses_requires_index_name(self): with self.assertRaisesMessage( ValueError, "An index must be named to use opclasses." ): models.Index(opclasses=["jsonb_path_ops"]) def test_opclasses_requires_list_or_tuple(self): with self.assertRaisesMessage( ValueError, "Index.opclasses must be a list or tuple." ): models.Index( name="test_opclass", fields=["field"], opclasses="jsonb_path_ops" ) def test_opclasses_and_fields_same_length(self): msg = "Index.fields and Index.opclasses must have the same number of elements." with self.assertRaisesMessage(ValueError, msg): models.Index( name="test_opclass", fields=["field", "other"], opclasses=["jsonb_path_ops"], ) def test_condition_requires_index_name(self): with self.assertRaisesMessage( ValueError, "An index must be named to use condition." ): models.Index(condition=models.Q(pages__gt=400)) def test_expressions_requires_index_name(self): msg = "An index must be named to use expressions." with self.assertRaisesMessage(ValueError, msg): models.Index(Lower("field")) def test_expressions_with_opclasses(self): msg = ( "Index.opclasses cannot be used with expressions. Use " "django.contrib.postgres.indexes.OpClass() instead." ) with self.assertRaisesMessage(ValueError, msg): models.Index( Lower("field"), name="test_func_opclass", opclasses=["jsonb_path_ops"], ) def test_condition_must_be_q(self): with self.assertRaisesMessage( ValueError, "Index.condition must be a Q instance." ): models.Index(condition="invalid", name="long_book_idx") def test_include_requires_list_or_tuple(self): msg = "Index.include must be a list or tuple." with self.assertRaisesMessage(ValueError, msg): models.Index(name="test_include", fields=["field"], include="other") def test_include_requires_index_name(self): msg = "A covering index must be named." with self.assertRaisesMessage(ValueError, msg): models.Index(fields=["field"], include=["other"]) def test_name_auto_generation(self): index = models.Index(fields=["author"]) index.set_name_with_model(Book) self.assertEqual(index.name, "model_index_author_0f5565_idx") # '-' for DESC columns should be accounted for in the index name. index = models.Index(fields=["-author"]) index.set_name_with_model(Book) self.assertEqual(index.name, "model_index_author_708765_idx") # fields may be truncated in the name. db_column is used for naming. long_field_index = models.Index(fields=["pages"]) long_field_index.set_name_with_model(Book) self.assertEqual(long_field_index.name, "model_index_page_co_69235a_idx") # suffix can't be longer than 3 characters. long_field_index.suffix = "suff" msg = ( "Index too long for multiple database support. Is self.suffix " "longer than 3 characters?" ) with self.assertRaisesMessage(ValueError, msg): long_field_index.set_name_with_model(Book) @isolate_apps("model_indexes") def test_name_auto_generation_with_quoted_db_table(self): class QuotedDbTable(models.Model): name = models.CharField(max_length=50) class Meta: db_table = '"t_quoted"' index = models.Index(fields=["name"]) index.set_name_with_model(QuotedDbTable) self.assertEqual(index.name, "t_quoted_name_e4ed1b_idx") def test_deconstruction(self): index = models.Index(fields=["title"], db_tablespace="idx_tbls") index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "model_index_title_196f42_idx", "db_tablespace": "idx_tbls", }, ) def test_deconstruct_with_condition(self): index = models.Index( name="big_book_index", fields=["title"], condition=models.Q(pages__gt=400), ) index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "model_index_title_196f42_idx", "condition": models.Q(pages__gt=400), }, ) def test_deconstruct_with_include(self): index = models.Index( name="book_include_idx", fields=["title"], include=["author"], ) index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "model_index_title_196f42_idx", "include": ("author",), }, ) def test_deconstruct_with_expressions(self): index = models.Index(Upper("title"), name="book_func_idx") path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, (Upper("title"),)) self.assertEqual(kwargs, {"name": "book_func_idx"}) def test_clone(self): index = models.Index(fields=["title"]) new_index = index.clone() self.assertIsNot(index, new_index) self.assertEqual(index.fields, new_index.fields) def test_clone_with_expressions(self): index = models.Index(Upper("title"), name="book_func_idx") new_index = index.clone() self.assertIsNot(index, new_index) self.assertEqual(index.expressions, new_index.expressions) def test_name_set(self): index_names = [index.name for index in Book._meta.indexes] self.assertCountEqual( index_names, [ "model_index_title_196f42_idx", "model_index_isbn_34f975_idx", "model_indexes_book_barcode_idx", ], ) def test_abstract_children(self): index_names = [index.name for index in ChildModel1._meta.indexes] self.assertEqual( index_names, ["model_index_name_440998_idx", "model_indexes_childmodel1_idx"], ) index_names = [index.name for index in ChildModel2._meta.indexes] self.assertEqual( index_names, ["model_index_name_b6c374_idx", "model_indexes_childmodel2_idx"], ) @override_settings(DEFAULT_TABLESPACE=None) class IndexesTests(TestCase): @skipUnlessDBFeature("supports_tablespaces") def test_db_tablespace(self): editor = connection.schema_editor() # Index with db_tablespace attribute. for fields in [ # Field with db_tablespace specified on model. ["shortcut"], # Field without db_tablespace specified on model. ["author"], # Multi-column with db_tablespaces specified on model. ["shortcut", "isbn"], # Multi-column without db_tablespace specified on model. ["title", "author"], ]: with self.subTest(fields=fields): index = models.Index(fields=fields, db_tablespace="idx_tbls2") self.assertIn( '"idx_tbls2"', str(index.create_sql(Book, editor)).lower() ) # Indexes without db_tablespace attribute. for fields in [["author"], ["shortcut", "isbn"], ["title", "author"]]: with self.subTest(fields=fields): index = models.Index(fields=fields) # The DEFAULT_INDEX_TABLESPACE setting can't be tested because # it's evaluated when the model class is defined. As a # consequence, @override_settings doesn't work. if settings.DEFAULT_INDEX_TABLESPACE: self.assertIn( '"%s"' % settings.DEFAULT_INDEX_TABLESPACE, str(index.create_sql(Book, editor)).lower(), ) else: self.assertNotIn("TABLESPACE", str(index.create_sql(Book, editor))) # Field with db_tablespace specified on the model and an index without # db_tablespace. index = models.Index(fields=["shortcut"]) self.assertIn('"idx_tbls"', str(index.create_sql(Book, editor)).lower()) @skipUnlessDBFeature("supports_tablespaces") def test_func_with_tablespace(self): # Functional index with db_tablespace attribute. index = models.Index( Lower("shortcut").desc(), name="functional_tbls", db_tablespace="idx_tbls2", ) with connection.schema_editor() as editor: sql = str(index.create_sql(Book, editor)) self.assertIn(editor.quote_name("idx_tbls2"), sql) # Functional index without db_tablespace attribute. index = models.Index(Lower("shortcut").desc(), name="functional_no_tbls") with connection.schema_editor() as editor: sql = str(index.create_sql(Book, editor)) # The DEFAULT_INDEX_TABLESPACE setting can't be tested because it's # evaluated when the model class is defined. As a consequence, # @override_settings doesn't work. if settings.DEFAULT_INDEX_TABLESPACE: self.assertIn( editor.quote_name(settings.DEFAULT_INDEX_TABLESPACE), sql, ) else: self.assertNotIn("TABLESPACE", sql)
e612c8790ddd812b5b13ed8f4abae60b4da457cacb5f1c8287301bd4c0fb91bc
import inspect import threading from datetime import datetime, timedelta from unittest import mock from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections, models from django.db.models.manager import BaseManager from django.db.models.query import MAX_GET_RESULTS, EmptyQuerySet from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature, ) from django.utils.translation import gettext_lazy from .models import ( Article, ArticleSelectOnSave, ChildPrimaryKeyWithDefault, FeaturedArticle, PrimaryKeyWithDefault, SelfRef, ) class ModelInstanceCreationTests(TestCase): def test_object_is_not_written_to_database_until_save_was_called(self): a = Article( id=None, headline="Parrot programs in Python", pub_date=datetime(2005, 7, 28), ) self.assertIsNone(a.id) self.assertEqual(Article.objects.count(), 0) # Save it into the database. You have to call save() explicitly. a.save() self.assertIsNotNone(a.id) self.assertEqual(Article.objects.count(), 1) def test_can_initialize_model_instance_using_positional_arguments(self): """ You can initialize a model instance using positional arguments, which should match the field order as defined in the model. """ a = Article(None, "Second article", datetime(2005, 7, 29)) a.save() self.assertEqual(a.headline, "Second article") self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0)) def test_can_create_instance_using_kwargs(self): a = Article( id=None, headline="Third article", pub_date=datetime(2005, 7, 30), ) a.save() self.assertEqual(a.headline, "Third article") self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0)) def test_autofields_generate_different_values_for_each_instance(self): a1 = Article.objects.create( headline="First", pub_date=datetime(2005, 7, 30, 0, 0) ) a2 = Article.objects.create( headline="First", pub_date=datetime(2005, 7, 30, 0, 0) ) a3 = Article.objects.create( headline="First", pub_date=datetime(2005, 7, 30, 0, 0) ) self.assertNotEqual(a3.id, a1.id) self.assertNotEqual(a3.id, a2.id) def test_can_mix_and_match_position_and_kwargs(self): # You can also mix and match position and keyword arguments, but # be sure not to duplicate field information. a = Article(None, "Fourth article", pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, "Fourth article") def test_positional_and_keyword_args_for_the_same_field(self): msg = "Article() got both positional and keyword arguments for field '%s'." with self.assertRaisesMessage(TypeError, msg % "headline"): Article(None, "Fifth article", headline="Other headline.") with self.assertRaisesMessage(TypeError, msg % "headline"): Article(None, "Sixth article", headline="") with self.assertRaisesMessage(TypeError, msg % "pub_date"): Article(None, "Seventh article", datetime(2021, 3, 1), pub_date=None) def test_cannot_create_instance_with_invalid_kwargs(self): msg = "Article() got unexpected keyword arguments: 'foo'" with self.assertRaisesMessage(TypeError, msg): Article( id=None, headline="Some headline", pub_date=datetime(2005, 7, 31), foo="bar", ) msg = "Article() got unexpected keyword arguments: 'foo', 'bar'" with self.assertRaisesMessage(TypeError, msg): Article( id=None, headline="Some headline", pub_date=datetime(2005, 7, 31), foo="bar", bar="baz", ) def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self): """ You can leave off the value for an AutoField when creating an object, because it'll get filled in automatically when you save(). """ a = Article(headline="Article 5", pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, "Article 5") self.assertIsNotNone(a.id) def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self): a = Article(pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, "Default headline") def test_for_datetimefields_saves_as_much_precision_as_was_given(self): """as much precision in *seconds*""" a1 = Article( headline="Article 7", pub_date=datetime(2005, 7, 31, 12, 30), ) a1.save() self.assertEqual( Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30) ) a2 = Article( headline="Article 8", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a2.save() self.assertEqual( Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45), ) def test_saving_an_object_again_does_not_create_a_new_object(self): a = Article(headline="original", pub_date=datetime(2014, 5, 16)) a.save() current_id = a.id a.save() self.assertEqual(a.id, current_id) a.headline = "Updated headline" a.save() self.assertEqual(a.id, current_id) def test_querysets_checking_for_membership(self): headlines = ["Parrot programs in Python", "Second article", "Third article"] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() a = Article(headline="Some headline", pub_date=some_pub_date) a.save() # You can use 'in' to test for membership... self.assertIn(a, Article.objects.all()) # ... but there will often be more efficient ways if that is all you need: self.assertTrue(Article.objects.filter(id=a.id).exists()) def test_save_primary_with_default(self): # An UPDATE attempt is skipped when a primary key has default. with self.assertNumQueries(1): PrimaryKeyWithDefault().save() def test_save_parent_primary_with_default(self): # An UPDATE attempt is skipped when an inherited primary key has # default. with self.assertNumQueries(2): ChildPrimaryKeyWithDefault().save() class ModelTest(TestCase): def test_objects_attribute_is_only_available_on_the_class_itself(self): with self.assertRaisesMessage( AttributeError, "Manager isn't accessible via Article instances" ): getattr( Article(), "objects", ) self.assertFalse(hasattr(Article(), "objects")) self.assertTrue(hasattr(Article, "objects")) def test_queryset_delete_removes_all_items_in_that_queryset(self): headlines = ["An article", "Article One", "Amazing article", "Boring article"] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() self.assertQuerysetEqual( Article.objects.order_by("headline"), sorted(headlines), transform=lambda a: a.headline, ) Article.objects.filter(headline__startswith="A").delete() self.assertEqual(Article.objects.get().headline, "Boring article") def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self): some_pub_date = datetime(2014, 5, 16, 12, 1) a1 = Article.objects.create(headline="First", pub_date=some_pub_date) a2 = Article.objects.create(headline="Second", pub_date=some_pub_date) self.assertNotEqual(a1, a2) self.assertEqual(a1, Article.objects.get(id__exact=a1.id)) self.assertNotEqual( Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id) ) def test_microsecond_precision(self): a9 = Article( headline="Article 9", pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() self.assertEqual( Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180), ) def test_manually_specify_primary_key(self): # You can manually specify the primary key when creating a new object. a101 = Article( id=101, headline="Article 101", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a101.save() a101 = Article.objects.get(pk=101) self.assertEqual(a101.headline, "Article 101") def test_create_method(self): # You can create saved objects in a single step a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) self.assertEqual(Article.objects.get(headline="Article 10"), a10) def test_year_lookup_edge_case(self): # Edge-case test: A year lookup should retrieve all objects in # the given year, including Jan. 1 and Dec. 31. a11 = Article.objects.create( headline="Article 11", pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline="Article 12", pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) self.assertSequenceEqual( Article.objects.filter(pub_date__year=2008), [a11, a12], ) def test_unicode_data(self): # Unicode data works, too. a = Article( headline="\u6797\u539f \u3081\u3050\u307f", pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual( Article.objects.get(pk=a.id).headline, "\u6797\u539f \u3081\u3050\u307f" ) def test_hash_function(self): # Model instances have a hash function, so they can be used in sets # or as dictionary keys. Two models compare as equal if their primary # keys are equal. a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a11 = Article.objects.create( headline="Article 11", pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline="Article 12", pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) s = {a10, a11, a12} self.assertIn(Article.objects.get(headline="Article 11"), s) def test_extra_method_select_argument_with_dashes_and_values(self): # The 'select' argument to extra() supports names with dashes in # them, as long as you use values(). Article.objects.bulk_create( [ Article( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45) ), Article(headline="Article 11", pub_date=datetime(2008, 1, 1)), Article( headline="Article 12", pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ), ] ) dicts = ( Article.objects.filter(pub_date__year=2008) .extra(select={"dashed-value": "1"}) .values("headline", "dashed-value") ) self.assertEqual( [sorted(d.items()) for d in dicts], [ [("dashed-value", 1), ("headline", "Article 11")], [("dashed-value", 1), ("headline", "Article 12")], ], ) def test_extra_method_select_argument_with_dashes(self): # If you use 'select' with extra() and names containing dashes on a # query that's *not* a values() query, those extra 'select' values # will silently be ignored. Article.objects.bulk_create( [ Article( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45) ), Article(headline="Article 11", pub_date=datetime(2008, 1, 1)), Article( headline="Article 12", pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ), ] ) articles = Article.objects.filter(pub_date__year=2008).extra( select={"dashed-value": "1", "undashedvalue": "2"} ) self.assertEqual(articles[0].undashedvalue, 2) def test_create_relation_with_gettext_lazy(self): """ gettext_lazy objects work when saving model instances through various methods. Refs #10498. """ notlazy = "test" lazy = gettext_lazy(notlazy) Article.objects.create(headline=lazy, pub_date=datetime.now()) article = Article.objects.get() self.assertEqual(article.headline, notlazy) # test that assign + save works with Promise objects article.headline = lazy article.save() self.assertEqual(article.headline, notlazy) # test .update() Article.objects.update(headline=lazy) article = Article.objects.get() self.assertEqual(article.headline, notlazy) # still test bulk_create() Article.objects.all().delete() Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())]) article = Article.objects.get() self.assertEqual(article.headline, notlazy) def test_emptyqs(self): msg = "EmptyQuerySet can't be instantiated" with self.assertRaisesMessage(TypeError, msg): EmptyQuerySet() self.assertIsInstance(Article.objects.none(), EmptyQuerySet) self.assertNotIsInstance("", EmptyQuerySet) def test_emptyqs_values(self): # test for #15959 Article.objects.create(headline="foo", pub_date=datetime.now()) with self.assertNumQueries(0): qs = Article.objects.none().values_list("pk") self.assertIsInstance(qs, EmptyQuerySet) self.assertEqual(len(qs), 0) def test_emptyqs_customqs(self): # A hacky test for custom QuerySet subclass - refs #17271 Article.objects.create(headline="foo", pub_date=datetime.now()) class CustomQuerySet(models.QuerySet): def do_something(self): return "did something" qs = Article.objects.all() qs.__class__ = CustomQuerySet qs = qs.none() with self.assertNumQueries(0): self.assertEqual(len(qs), 0) self.assertIsInstance(qs, EmptyQuerySet) self.assertEqual(qs.do_something(), "did something") def test_emptyqs_values_order(self): # Tests for ticket #17712 Article.objects.create(headline="foo", pub_date=datetime.now()) with self.assertNumQueries(0): self.assertEqual( len(Article.objects.none().values_list("id").order_by("id")), 0 ) with self.assertNumQueries(0): self.assertEqual( len( Article.objects.none().filter( id__in=Article.objects.values_list("id", flat=True) ) ), 0, ) @skipUnlessDBFeature("can_distinct_on_fields") def test_emptyqs_distinct(self): # Tests for #19426 Article.objects.create(headline="foo", pub_date=datetime.now()) with self.assertNumQueries(0): self.assertEqual( len(Article.objects.none().distinct("headline", "pub_date")), 0 ) def test_ticket_20278(self): sr = SelfRef.objects.create() with self.assertRaises(ObjectDoesNotExist): SelfRef.objects.get(selfref=sr) def test_eq(self): self.assertEqual(Article(id=1), Article(id=1)) self.assertNotEqual(Article(id=1), object()) self.assertNotEqual(object(), Article(id=1)) a = Article() self.assertEqual(a, a) self.assertEqual(a, mock.ANY) self.assertNotEqual(Article(), a) def test_hash(self): # Value based on PK self.assertEqual(hash(Article(id=1)), hash(1)) msg = "Model instances without primary key value are unhashable" with self.assertRaisesMessage(TypeError, msg): # No PK value -> unhashable (because save() would then change # hash) hash(Article()) def test_missing_hash_not_inherited(self): class NoHash(models.Model): def __eq__(self, other): return super.__eq__(other) with self.assertRaisesMessage(TypeError, "unhashable type: 'NoHash'"): hash(NoHash(id=1)) def test_specified_parent_hash_inherited(self): class ParentHash(models.Model): def __eq__(self, other): return super.__eq__(other) __hash__ = models.Model.__hash__ self.assertEqual(hash(ParentHash(id=1)), 1) def test_delete_and_access_field(self): # Accessing a field after it's deleted from a model reloads its value. pub_date = datetime.now() article = Article.objects.create(headline="foo", pub_date=pub_date) new_pub_date = article.pub_date + timedelta(days=10) article.headline = "bar" article.pub_date = new_pub_date del article.headline with self.assertNumQueries(1): self.assertEqual(article.headline, "foo") # Fields that weren't deleted aren't reloaded. self.assertEqual(article.pub_date, new_pub_date) def test_multiple_objects_max_num_fetched(self): max_results = MAX_GET_RESULTS - 1 Article.objects.bulk_create( Article(headline="Area %s" % i, pub_date=datetime(2005, 7, 28)) for i in range(max_results) ) self.assertRaisesMessage( MultipleObjectsReturned, "get() returned more than one Article -- it returned %d!" % max_results, Article.objects.get, headline__startswith="Area", ) Article.objects.create( headline="Area %s" % max_results, pub_date=datetime(2005, 7, 28) ) self.assertRaisesMessage( MultipleObjectsReturned, "get() returned more than one Article -- it returned more than %d!" % max_results, Article.objects.get, headline__startswith="Area", ) class ModelLookupTest(TestCase): @classmethod def setUpTestData(cls): # Create an Article. cls.a = Article( id=None, headline="Swallow programs in Python", pub_date=datetime(2005, 7, 28), ) # Save it into the database. You have to call save() explicitly. cls.a.save() def test_all_lookup(self): # Change values by changing the attributes, then calling save(). self.a.headline = "Parrot programs in Python" self.a.save() # Article.objects.all() returns all the articles in the database. self.assertSequenceEqual(Article.objects.all(), [self.a]) def test_rich_lookup(self): # Django provides a rich database lookup API. self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a) self.assertEqual(Article.objects.get(headline__startswith="Swallow"), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005), self.a) self.assertEqual( Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a ) self.assertEqual( Article.objects.get( pub_date__year=2005, pub_date__month=7, pub_date__day=28 ), self.a, ) self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a) def test_equal_lookup(self): # The "__exact" lookup type can be omitted, as a shortcut. self.assertEqual(Article.objects.get(id=self.a.id), self.a) self.assertEqual( Article.objects.get(headline="Swallow programs in Python"), self.a ) self.assertSequenceEqual( Article.objects.filter(pub_date__year=2005), [self.a], ) self.assertSequenceEqual( Article.objects.filter(pub_date__year=2004), [], ) self.assertSequenceEqual( Article.objects.filter(pub_date__year=2005, pub_date__month=7), [self.a], ) self.assertSequenceEqual( Article.objects.filter(pub_date__week_day=5), [self.a], ) self.assertSequenceEqual( Article.objects.filter(pub_date__week_day=6), [], ) def test_does_not_exist(self): # Django raises an Article.DoesNotExist exception for get() if the # parameters don't match any object. with self.assertRaisesMessage( ObjectDoesNotExist, "Article matching query does not exist." ): Article.objects.get( id__exact=2000, ) # To avoid dict-ordering related errors check only one lookup # in single assert. with self.assertRaises(ObjectDoesNotExist): Article.objects.get(pub_date__year=2005, pub_date__month=8) with self.assertRaisesMessage( ObjectDoesNotExist, "Article matching query does not exist." ): Article.objects.get( pub_date__week_day=6, ) def test_lookup_by_primary_key(self): # Lookup by a primary key is the most common case, so Django # provides a shortcut for primary-key exact lookups. # The following is identical to articles.get(id=a.id). self.assertEqual(Article.objects.get(pk=self.a.id), self.a) # pk can be used as a shortcut for the primary key name in any query. self.assertSequenceEqual(Article.objects.filter(pk__in=[self.a.id]), [self.a]) # Model instances of the same type and same ID are considered equal. a = Article.objects.get(pk=self.a.id) b = Article.objects.get(pk=self.a.id) self.assertEqual(a, b) def test_too_many(self): # Create a very similar object a = Article( id=None, headline="Swallow bites Python", pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual(Article.objects.count(), 2) # Django raises an Article.MultipleObjectsReturned exception if the # lookup matches more than one object msg = "get() returned more than one Article -- it returned 2!" with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get( headline__startswith="Swallow", ) with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get( pub_date__year=2005, ) with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(pub_date__year=2005, pub_date__month=7) class ConcurrentSaveTests(TransactionTestCase): available_apps = ["basic"] @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_concurrent_delete_with_save(self): """ Test fetching, deleting and finally saving an object - we should get an insert in this case. """ a = Article.objects.create(headline="foo", pub_date=datetime.now()) exceptions = [] def deleter(): try: # Do not delete a directly - doing so alters its state. Article.objects.filter(pk=a.pk).delete() except Exception as e: exceptions.append(e) finally: connections[DEFAULT_DB_ALIAS].close() self.assertEqual(len(exceptions), 0) t = threading.Thread(target=deleter) t.start() t.join() a.save() self.assertEqual(Article.objects.get(pk=a.pk).headline, "foo") class ManagerTest(SimpleTestCase): QUERYSET_PROXY_METHODS = [ "none", "count", "dates", "datetimes", "distinct", "extra", "get", "get_or_create", "update_or_create", "create", "bulk_create", "bulk_update", "filter", "aggregate", "annotate", "alias", "complex_filter", "exclude", "in_bulk", "iterator", "earliest", "latest", "first", "last", "order_by", "select_for_update", "select_related", "prefetch_related", "values", "values_list", "update", "reverse", "defer", "only", "using", "exists", "contains", "explain", "_insert", "_update", "raw", "union", "intersection", "difference", "aaggregate", "abulk_create", "abulk_update", "acontains", "acount", "acreate", "aearliest", "aexists", "aexplain", "afirst", "aget", "aget_or_create", "ain_bulk", "aiterator", "alast", "alatest", "aupdate", "aupdate_or_create", ] def test_manager_methods(self): """ This test ensures that the correct set of methods from `QuerySet` are copied onto `Manager`. It's particularly useful to prevent accidentally leaking new methods into `Manager`. New `QuerySet` methods that should also be copied onto `Manager` will need to be added to `ManagerTest.QUERYSET_PROXY_METHODS`. """ self.assertEqual( sorted(BaseManager._get_queryset_methods(models.QuerySet)), sorted(self.QUERYSET_PROXY_METHODS), ) def test_manager_method_attributes(self): self.assertEqual(Article.objects.get.__doc__, models.QuerySet.get.__doc__) self.assertEqual(Article.objects.count.__name__, models.QuerySet.count.__name__) def test_manager_method_signature(self): self.assertEqual( str(inspect.signature(Article.objects.bulk_create)), "(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, " "update_fields=None, unique_fields=None)", ) class SelectOnSaveTests(TestCase): def test_select_on_save(self): a1 = Article.objects.create(pub_date=datetime.now()) with self.assertNumQueries(1): a1.save() asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now()) with self.assertNumQueries(2): asos.save() with self.assertNumQueries(1): asos.save(force_update=True) Article.objects.all().delete() with self.assertRaisesMessage( DatabaseError, "Forced update did not affect any rows." ): with self.assertNumQueries(1): asos.save(force_update=True) def test_select_on_save_lying_update(self): """ select_on_save works correctly if the database doesn't return correct information about matched rows from UPDATE. """ # Change the manager to not return "row matched" for update(). # We are going to change the Article's _base_manager class # dynamically. This is a bit of a hack, but it seems hard to # test this properly otherwise. Article's manager, because # proxy models use their parent model's _base_manager. orig_class = Article._base_manager._queryset_class class FakeQuerySet(models.QuerySet): # Make sure the _update method below is in fact called. called = False def _update(self, *args, **kwargs): FakeQuerySet.called = True super()._update(*args, **kwargs) return 0 try: Article._base_manager._queryset_class = FakeQuerySet asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now()) with self.assertNumQueries(3): asos.save() self.assertTrue(FakeQuerySet.called) # This is not wanted behavior, but this is how Django has always # behaved for databases that do not return correct information # about matched rows for UPDATE. with self.assertRaisesMessage( DatabaseError, "Forced update did not affect any rows." ): asos.save(force_update=True) msg = ( "An error occurred in the current transaction. You can't " "execute queries until the end of the 'atomic' block." ) with self.assertRaisesMessage(DatabaseError, msg): asos.save(update_fields=["pub_date"]) finally: Article._base_manager._queryset_class = orig_class class ModelRefreshTests(TestCase): def test_refresh(self): a = Article.objects.create(pub_date=datetime.now()) Article.objects.create(pub_date=datetime.now()) Article.objects.filter(pk=a.pk).update(headline="new headline") with self.assertNumQueries(1): a.refresh_from_db() self.assertEqual(a.headline, "new headline") orig_pub_date = a.pub_date new_pub_date = a.pub_date + timedelta(10) Article.objects.update(headline="new headline 2", pub_date=new_pub_date) with self.assertNumQueries(1): a.refresh_from_db(fields=["headline"]) self.assertEqual(a.headline, "new headline 2") self.assertEqual(a.pub_date, orig_pub_date) with self.assertNumQueries(1): a.refresh_from_db() self.assertEqual(a.pub_date, new_pub_date) def test_unknown_kwarg(self): s = SelfRef.objects.create() msg = "refresh_from_db() got an unexpected keyword argument 'unknown_kwarg'" with self.assertRaisesMessage(TypeError, msg): s.refresh_from_db(unknown_kwarg=10) def test_lookup_in_fields(self): s = SelfRef.objects.create() msg = ( 'Found "__" in fields argument. Relations and transforms are not allowed ' "in fields." ) with self.assertRaisesMessage(ValueError, msg): s.refresh_from_db(fields=["foo__bar"]) def test_refresh_fk(self): s1 = SelfRef.objects.create() s2 = SelfRef.objects.create() s3 = SelfRef.objects.create(selfref=s1) s3_copy = SelfRef.objects.get(pk=s3.pk) s3_copy.selfref.touched = True s3.selfref = s2 s3.save() with self.assertNumQueries(1): s3_copy.refresh_from_db() with self.assertNumQueries(1): # The old related instance was thrown away (the selfref_id has # changed). It needs to be reloaded on access, so one query # executed. self.assertFalse(hasattr(s3_copy.selfref, "touched")) self.assertEqual(s3_copy.selfref, s2) def test_refresh_null_fk(self): s1 = SelfRef.objects.create() s2 = SelfRef.objects.create(selfref=s1) s2.selfref = None s2.refresh_from_db() self.assertEqual(s2.selfref, s1) def test_refresh_unsaved(self): pub_date = datetime.now() a = Article.objects.create(pub_date=pub_date) a2 = Article(id=a.pk) with self.assertNumQueries(1): a2.refresh_from_db() self.assertEqual(a2.pub_date, pub_date) self.assertEqual(a2._state.db, "default") def test_refresh_fk_on_delete_set_null(self): a = Article.objects.create( headline="Parrot programs in Python", pub_date=datetime(2005, 7, 28), ) s1 = SelfRef.objects.create(article=a) a.delete() s1.refresh_from_db() self.assertIsNone(s1.article_id) self.assertIsNone(s1.article) def test_refresh_no_fields(self): a = Article.objects.create(pub_date=datetime.now()) with self.assertNumQueries(0): a.refresh_from_db(fields=[]) def test_refresh_clears_reverse_related(self): """refresh_from_db() clear cached reverse relations.""" article = Article.objects.create( headline="Parrot programs in Python", pub_date=datetime(2005, 7, 28), ) self.assertFalse(hasattr(article, "featured")) FeaturedArticle.objects.create(article_id=article.pk) article.refresh_from_db() self.assertTrue(hasattr(article, "featured")) def test_refresh_clears_one_to_one_field(self): article = Article.objects.create( headline="Parrot programs in Python", pub_date=datetime(2005, 7, 28), ) featured = FeaturedArticle.objects.create(article_id=article.pk) self.assertEqual(featured.article.headline, "Parrot programs in Python") article.headline = "Parrot programs in Python 2.0" article.save() featured.refresh_from_db() self.assertEqual(featured.article.headline, "Parrot programs in Python 2.0") def test_prefetched_cache_cleared(self): a = Article.objects.create(pub_date=datetime(2005, 7, 28)) s = SelfRef.objects.create(article=a) # refresh_from_db() without fields=[...] a1_prefetched = Article.objects.prefetch_related("selfref_set").first() self.assertCountEqual(a1_prefetched.selfref_set.all(), [s]) s.article = None s.save() # Relation is cleared and prefetch cache is stale. self.assertCountEqual(a1_prefetched.selfref_set.all(), [s]) a1_prefetched.refresh_from_db() # Cache was cleared and new results are available. self.assertCountEqual(a1_prefetched.selfref_set.all(), []) # refresh_from_db() with fields=[...] a2_prefetched = Article.objects.prefetch_related("selfref_set").first() self.assertCountEqual(a2_prefetched.selfref_set.all(), []) s.article = a s.save() # Relation is added and prefetch cache is stale. self.assertCountEqual(a2_prefetched.selfref_set.all(), []) a2_prefetched.refresh_from_db(fields=["selfref_set"]) # Cache was cleared and new results are available. self.assertCountEqual(a2_prefetched.selfref_set.all(), [s])
efc039638e7e3ec0589c7dd7c6e441dfbdd9c501343e850dc1edcc35f7f048b0
import operator from django.db import DatabaseError, NotSupportedError, connection from django.db.models import Exists, F, IntegerField, OuterRef, Subquery, Value from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import Author, Celebrity, ExtraInfo, Number, ReservedName @skipUnlessDBFeature("supports_select_union") class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i, other_num=10 - i) for i in range(10)) def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerysetEqual( queryset, expected_numbers, operator.attrgetter("num"), ordered ) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.intersection(qs1).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.intersection(qs1).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) @skipUnlessDBFeature("supports_select_difference") def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) def test_union_none(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = qs1.union(qs2) self.assertSequenceEqual(qs3.none(), []) self.assertNumbersEqual(qs3, [0, 1, 8, 9], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.intersection(qs2)), 0) self.assertEqual(len(qs1.intersection(qs3)), 0) self.assertEqual(len(qs2.intersection(qs1)), 0) self.assertEqual(len(qs3.intersection(qs1)), 0) self.assertEqual(len(qs2.intersection(qs2)), 0) self.assertEqual(len(qs3.intersection(qs3)), 0) @skipUnlessDBFeature("supports_select_difference") def test_difference_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.difference(qs2)), 10) self.assertEqual(len(qs1.difference(qs3)), 10) self.assertEqual(len(qs2.difference(qs1)), 0) self.assertEqual(len(qs3.difference(qs1)), 0) self.assertEqual(len(qs2.difference(qs2)), 0) self.assertEqual(len(qs3.difference(qs3)), 0) @skipUnlessDBFeature("supports_select_difference") def test_difference_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() qs2 = ReservedName.objects.none() reserved_name = qs1.difference(qs2).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.difference(qs2).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) def test_union_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.union(qs2)), 10) self.assertEqual(len(qs2.union(qs1)), 10) self.assertEqual(len(qs1.union(qs3)), 10) self.assertEqual(len(qs3.union(qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, all=True)), 20) self.assertEqual(len(qs2.union(qs2)), 0) self.assertEqual(len(qs3.union(qs3)), 0) def test_empty_qs_union_with_ordered_qs(self): qs1 = Number.objects.order_by("num") qs2 = Number.objects.none().union(qs1).order_by("num") self.assertEqual(list(qs1), list(qs2)) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by("-num"), [3, 2, 1, 0]) def test_ordering_by_alias(self): qs1 = Number.objects.filter(num__lte=1).values(alias=F("num")) qs2 = Number.objects.filter(num__gte=2, num__lte=3).values(alias=F("num")) self.assertQuerysetEqual( qs1.union(qs2).order_by("-alias"), [3, 2, 1, 0], operator.itemgetter("alias"), ) def test_ordering_by_f_expression(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by(F("num").desc()), [3, 2, 1, 0]) def test_ordering_by_f_expression_and_alias(self): qs1 = Number.objects.filter(num__lte=1).values(alias=F("other_num")) qs2 = Number.objects.filter(num__gte=2, num__lte=3).values(alias=F("other_num")) self.assertQuerysetEqual( qs1.union(qs2).order_by(F("alias").desc()), [10, 9, 8, 7], operator.itemgetter("alias"), ) Number.objects.create(num=-1) self.assertQuerysetEqual( qs1.union(qs2).order_by(F("alias").desc(nulls_last=True)), [10, 9, 8, 7, None], operator.itemgetter("alias"), ) def test_union_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.union(qs1).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.union(qs1).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) # List of columns can be changed. reserved_name = qs1.union(qs1).values_list("order").get() self.assertEqual(reserved_name, (2,)) def test_union_with_two_annotated_values_list(self): qs1 = ( Number.objects.filter(num=1) .annotate( count=Value(0, IntegerField()), ) .values_list("num", "count") ) qs2 = ( Number.objects.filter(num=2) .values("pk") .annotate( count=F("num"), ) .annotate( num=Value(1, IntegerField()), ) .values_list("num", "count") ) self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_extra_and_values_list(self): qs1 = ( Number.objects.filter(num=1) .extra( select={"count": 0}, ) .values_list("num", "count") ) qs2 = Number.objects.filter(num=2).extra(select={"count": 1}) self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_values_list_on_annotated_and_unannotated(self): ReservedName.objects.create(name="rn1", order=1) qs1 = Number.objects.annotate( has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef("num"))) ).filter(has_reserved_name=True) qs2 = Number.objects.filter(num=9) self.assertCountEqual(qs1.union(qs2).values_list("num", flat=True), [1, 9]) def test_union_with_values_list_and_order(self): ReservedName.objects.bulk_create( [ ReservedName(name="rn1", order=7), ReservedName(name="rn2", order=5), ReservedName(name="rn0", order=6), ReservedName(name="rn9", order=-1), ] ) qs1 = ReservedName.objects.filter(order__gte=6) qs2 = ReservedName.objects.filter(order__lte=5) union_qs = qs1.union(qs2) for qs, expected_result in ( # Order by a single column. (union_qs.order_by("-pk").values_list("order", flat=True), [-1, 6, 5, 7]), (union_qs.order_by("pk").values_list("order", flat=True), [7, 5, 6, -1]), (union_qs.values_list("order", flat=True).order_by("-pk"), [-1, 6, 5, 7]), (union_qs.values_list("order", flat=True).order_by("pk"), [7, 5, 6, -1]), # Order by multiple columns. ( union_qs.order_by("-name", "pk").values_list("order", flat=True), [-1, 5, 7, 6], ), ( union_qs.values_list("order", flat=True).order_by("-name", "pk"), [-1, 5, 7, 6], ), ): with self.subTest(qs=qs): self.assertEqual(list(qs), expected_result) def test_union_with_values_list_and_order_on_annotation(self): qs1 = Number.objects.annotate( annotation=Value(-1), multiplier=F("annotation"), ).filter(num__gte=6) qs2 = Number.objects.annotate( annotation=Value(2), multiplier=F("annotation"), ).filter(num__lte=5) self.assertSequenceEqual( qs1.union(qs2).order_by("annotation", "num").values_list("num", flat=True), [6, 7, 8, 9, 0, 1, 2, 3, 4, 5], ) self.assertQuerysetEqual( qs1.union(qs2) .order_by( F("annotation") * F("multiplier"), "num", ) .values("num"), [6, 7, 8, 9, 0, 1, 2, 3, 4, 5], operator.itemgetter("num"), ) def test_union_multiple_models_with_values_list_and_order(self): reserved_name = ReservedName.objects.create(name="rn1", order=0) qs1 = Celebrity.objects.all() qs2 = ReservedName.objects.all() self.assertSequenceEqual( qs1.union(qs2).order_by("name").values_list("pk", flat=True), [reserved_name.pk], ) def test_union_multiple_models_with_values_list_and_order_by_extra_select(self): reserved_name = ReservedName.objects.create(name="rn1", order=0) qs1 = Celebrity.objects.extra(select={"extra_name": "name"}) qs2 = ReservedName.objects.extra(select={"extra_name": "name"}) self.assertSequenceEqual( qs1.union(qs2).order_by("extra_name").values_list("pk", flat=True), [reserved_name.pk], ) def test_union_in_subquery(self): ReservedName.objects.bulk_create( [ ReservedName(name="rn1", order=8), ReservedName(name="rn2", order=1), ReservedName(name="rn3", order=5), ] ) qs1 = Number.objects.filter(num__gt=7, num=OuterRef("order")) qs2 = Number.objects.filter(num__lt=2, num=OuterRef("order")) self.assertCountEqual( ReservedName.objects.annotate( number=Subquery(qs1.union(qs2).values("num")), ) .filter(number__isnull=False) .values_list("order", flat=True), [8, 1], ) def test_union_in_subquery_related_outerref(self): e1 = ExtraInfo.objects.create(value=7, info="e3") e2 = ExtraInfo.objects.create(value=5, info="e2") e3 = ExtraInfo.objects.create(value=1, info="e1") Author.objects.bulk_create( [ Author(name="a1", num=1, extra=e1), Author(name="a2", num=3, extra=e2), Author(name="a3", num=2, extra=e3), ] ) qs1 = ExtraInfo.objects.order_by().filter(value=OuterRef("num")) qs2 = ExtraInfo.objects.order_by().filter(value__lt=OuterRef("extra__value")) qs = ( Author.objects.annotate( info=Subquery(qs1.union(qs2).values("info")[:1]), ) .filter(info__isnull=False) .values_list("name", flat=True) ) self.assertCountEqual(qs, ["a1", "a2"]) # Combined queries don't mutate. self.assertCountEqual(qs, ["a1", "a2"]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_in_with_ordering(self): qs1 = Number.objects.filter(num__gt=7).order_by("num") qs2 = Number.objects.filter(num__lt=2).order_by("num") self.assertNumbersEqual( Number.objects.exclude(id__in=qs1.union(qs2).values("id")), [2, 3, 4, 5, 6, 7], ordered=False, ) @skipUnlessDBFeature( "supports_slicing_ordering_in_compound", "allow_sliced_subqueries_with_in" ) def test_union_in_with_ordering_and_slice(self): qs1 = Number.objects.filter(num__gt=7).order_by("num")[:1] qs2 = Number.objects.filter(num__lt=2).order_by("-num")[:1] self.assertNumbersEqual( Number.objects.exclude(id__in=qs1.union(qs2).values("id")), [0, 2, 3, 4, 5, 6, 7, 9], ordered=False, ) def test_count_union(self): qs1 = Number.objects.filter(num__lte=1).values("num") qs2 = Number.objects.filter(num__gte=2, num__lte=3).values("num") self.assertEqual(qs1.union(qs2).count(), 4) def test_count_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertEqual(qs.union(qs).count(), 0) @skipUnlessDBFeature("supports_select_difference") def test_count_difference(self): qs1 = Number.objects.filter(num__lt=10) qs2 = Number.objects.filter(num__lt=9) self.assertEqual(qs1.difference(qs2).count(), 1) @skipUnlessDBFeature("supports_select_intersection") def test_count_intersection(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) self.assertEqual(qs1.intersection(qs2).count(), 1) def test_exists_union(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) with CaptureQueriesContext(connection) as context: self.assertIs(qs1.union(qs2).exists(), True) captured_queries = context.captured_queries self.assertEqual(len(captured_queries), 1) captured_sql = captured_queries[0]["sql"] self.assertNotIn( connection.ops.quote_name(Number._meta.pk.column), captured_sql, ) self.assertEqual( captured_sql.count(connection.ops.limit_offset_sql(None, 1)), 3 if connection.features.supports_slicing_ordering_in_compound else 1, ) def test_exists_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertIs(qs.union(qs).exists(), False) @skipUnlessDBFeature("supports_select_intersection") def test_exists_intersection(self): qs1 = Number.objects.filter(num__gt=5) qs2 = Number.objects.filter(num__lt=5) self.assertIs(qs1.intersection(qs1).exists(), True) self.assertIs(qs1.intersection(qs2).exists(), False) @skipUnlessDBFeature("supports_select_difference") def test_exists_difference(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__gte=3) self.assertIs(qs1.difference(qs2).exists(), False) self.assertIs(qs2.difference(qs1).exists(), True) def test_get_union(self): qs = Number.objects.filter(num=2) self.assertEqual(qs.union(qs).get().num, 2) @skipUnlessDBFeature("supports_select_difference") def test_get_difference(self): qs1 = Number.objects.all() qs2 = Number.objects.exclude(num=2) self.assertEqual(qs1.difference(qs2).get().num, 2) @skipUnlessDBFeature("supports_select_intersection") def test_get_intersection(self): qs1 = Number.objects.all() qs2 = Number.objects.filter(num=2) self.assertEqual(qs1.intersection(qs2).get().num, 2) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_ordering_subqueries(self): qs1 = Number.objects.order_by("num")[:2] qs2 = Number.objects.order_by("-num")[:2] self.assertNumbersEqual(qs1.union(qs2).order_by("-num")[:4], [9, 8, 1, 0]) @skipIfDBFeature("supports_slicing_ordering_in_compound") def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() qs3 = Number.objects.all() msg = "LIMIT/OFFSET not allowed in subqueries of compound statements" with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = "ORDER BY not allowed in subqueries of compound statements" with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by("id").union(qs2)) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("id").union(qs3)) @skipIfDBFeature("supports_select_intersection") def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = "intersection is not supported on this database backend" with self.assertRaisesMessage(NotSupportedError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name="99 little bugs", order=99) qs1 = Number.objects.filter(num=1).values_list("num", flat=True) qs2 = ReservedName.objects.values_list("order") self.assertEqual(list(qs1.union(qs2).order_by("num")), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = ( Number.objects.filter() .annotate( annotation=Value(1, IntegerField()), ) .values("annotation", num2=F("num")) ) qs2 = Number.objects.filter().values("id", "num") # Should not raise list(qs1.union(qs2).order_by("annotation")) list(qs1.union(qs2).order_by("num2")) msg = "ORDER BY term does not match any column in the result set" # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("id")) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("num")) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by(F("num"))) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by(F("num").desc())) # switched order, now 'exists' again: list(qs2.union(qs1).order_by("num")) @skipUnlessDBFeature("supports_select_difference", "supports_select_intersection") def test_qs_with_subcompound_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.intersection(Number.objects.filter(num__gt=1)) self.assertEqual(qs1.difference(qs2).count(), 2) def test_order_by_same_type(self): qs = Number.objects.all() union = qs.union(qs) numbers = list(range(10)) self.assertNumbersEqual(union.order_by("num"), numbers) self.assertNumbersEqual(union.order_by("other_num"), reversed(numbers)) def test_unsupported_operations_on_combined_qs(self): qs = Number.objects.all() msg = "Calling QuerySet.%s() after %s() is not supported." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") for combinator in combinators: for operation in ( "alias", "annotate", "defer", "delete", "distinct", "exclude", "extra", "filter", "only", "prefetch_related", "select_related", "update", ): with self.subTest(combinator=combinator, operation=operation): with self.assertRaisesMessage( NotSupportedError, msg % (operation, combinator), ): getattr(getattr(qs, combinator)(qs), operation)() with self.assertRaisesMessage( NotSupportedError, msg % ("contains", combinator), ): obj = Number.objects.first() getattr(qs, combinator)(qs).contains(obj) def test_get_with_filters_unsupported_on_combined_qs(self): qs = Number.objects.all() msg = "Calling QuerySet.get(...) with filters after %s() is not supported." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") for combinator in combinators: with self.subTest(combinator=combinator): with self.assertRaisesMessage(NotSupportedError, msg % combinator): getattr(qs, combinator)(qs).get(num=2) def test_operator_on_combined_qs_error(self): qs = Number.objects.all() msg = "Cannot use %s operator with combined queryset." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") operators = [ ("|", operator.or_), ("&", operator.and_), ("^", operator.xor), ] for combinator in combinators: combined_qs = getattr(qs, combinator)(qs) for operator_, operator_func in operators: with self.subTest(combinator=combinator): with self.assertRaisesMessage(TypeError, msg % operator_): operator_func(qs, combined_qs) with self.assertRaisesMessage(TypeError, msg % operator_): operator_func(combined_qs, qs)
aeda80884680c15e4d3999eb00a8ba254c93058ffd23ee328cc27e7ac16c67fe
import datetime from django.core.exceptions import FieldDoesNotExist from django.db.models import F from django.db.models.functions import Lower from django.db.utils import IntegrityError from django.test import TestCase, override_settings, skipUnlessDBFeature from .models import ( Article, CustomDbColumn, CustomPk, Detail, Food, Individual, JSONFieldNullable, Member, Note, Number, Order, Paragraph, RelatedObject, SingleObject, SpecialCategory, Tag, Valid, ) class WriteToOtherRouter: def db_for_write(self, model, **hints): return "other" class BulkUpdateNoteTests(TestCase): @classmethod def setUpTestData(cls): cls.notes = [Note.objects.create(note=str(i), misc=str(i)) for i in range(10)] def create_tags(self): self.tags = [Tag.objects.create(name=str(i)) for i in range(10)] def test_simple(self): for note in self.notes: note.note = "test-%s" % note.id with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ["note"]) self.assertCountEqual( Note.objects.values_list("note", flat=True), [cat.note for cat in self.notes], ) def test_multiple_fields(self): for note in self.notes: note.note = "test-%s" % note.id note.misc = "misc-%s" % note.id with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ["note", "misc"]) self.assertCountEqual( Note.objects.values_list("note", flat=True), [cat.note for cat in self.notes], ) self.assertCountEqual( Note.objects.values_list("misc", flat=True), [cat.misc for cat in self.notes], ) def test_batch_size(self): with self.assertNumQueries(len(self.notes)): Note.objects.bulk_update(self.notes, fields=["note"], batch_size=1) def test_unsaved_models(self): objs = self.notes + [Note(note="test", misc="test")] msg = "All bulk_update() objects must have a primary key set." with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update(objs, fields=["note"]) def test_foreign_keys_do_not_lookup(self): self.create_tags() for note, tag in zip(self.notes, self.tags): note.tag = tag with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ["tag"]) self.assertSequenceEqual(Note.objects.filter(tag__isnull=False), self.notes) def test_set_field_to_null(self): self.create_tags() Note.objects.update(tag=self.tags[0]) for note in self.notes: note.tag = None Note.objects.bulk_update(self.notes, ["tag"]) self.assertCountEqual(Note.objects.filter(tag__isnull=True), self.notes) def test_set_mixed_fields_to_null(self): self.create_tags() midpoint = len(self.notes) // 2 top, bottom = self.notes[:midpoint], self.notes[midpoint:] for note in top: note.tag = None for note in bottom: note.tag = self.tags[0] Note.objects.bulk_update(self.notes, ["tag"]) self.assertCountEqual(Note.objects.filter(tag__isnull=True), top) self.assertCountEqual(Note.objects.filter(tag__isnull=False), bottom) def test_functions(self): Note.objects.update(note="TEST") for note in self.notes: note.note = Lower("note") Note.objects.bulk_update(self.notes, ["note"]) self.assertEqual(set(Note.objects.values_list("note", flat=True)), {"test"}) # Tests that use self.notes go here, otherwise put them in another class. class BulkUpdateTests(TestCase): databases = {"default", "other"} def test_no_fields(self): msg = "Field names must be given to bulk_update()." with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=[]) def test_invalid_batch_size(self): msg = "Batch size must be a positive integer." with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=["note"], batch_size=-1) with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=["note"], batch_size=0) def test_nonexistent_field(self): with self.assertRaisesMessage( FieldDoesNotExist, "Note has no field named 'nonexistent'" ): Note.objects.bulk_update([], ["nonexistent"]) pk_fields_error = "bulk_update() cannot be used with primary key fields." def test_update_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): Note.objects.bulk_update([], ["id"]) def test_update_custom_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): CustomPk.objects.bulk_update([], ["name"]) def test_empty_objects(self): with self.assertNumQueries(0): rows_updated = Note.objects.bulk_update([], ["note"]) self.assertEqual(rows_updated, 0) def test_large_batch(self): Note.objects.bulk_create( [Note(note=str(i), misc=str(i)) for i in range(0, 2000)] ) notes = list(Note.objects.all()) rows_updated = Note.objects.bulk_update(notes, ["note"]) self.assertEqual(rows_updated, 2000) def test_updated_rows_when_passing_duplicates(self): note = Note.objects.create(note="test-note", misc="test") rows_updated = Note.objects.bulk_update([note, note], ["note"]) self.assertEqual(rows_updated, 1) # Duplicates in different batches. rows_updated = Note.objects.bulk_update([note, note], ["note"], batch_size=1) self.assertEqual(rows_updated, 2) def test_only_concrete_fields_allowed(self): obj = Valid.objects.create(valid="test") detail = Detail.objects.create(data="test") paragraph = Paragraph.objects.create(text="test") Member.objects.create(name="test", details=detail) msg = "bulk_update() can only be used with concrete fields." with self.assertRaisesMessage(ValueError, msg): Detail.objects.bulk_update([detail], fields=["member"]) with self.assertRaisesMessage(ValueError, msg): Paragraph.objects.bulk_update([paragraph], fields=["page"]) with self.assertRaisesMessage(ValueError, msg): Valid.objects.bulk_update([obj], fields=["parent"]) def test_custom_db_columns(self): model = CustomDbColumn.objects.create(custom_column=1) model.custom_column = 2 CustomDbColumn.objects.bulk_update([model], fields=["custom_column"]) model.refresh_from_db() self.assertEqual(model.custom_column, 2) def test_custom_pk(self): custom_pks = [ CustomPk.objects.create(name="pk-%s" % i, extra="") for i in range(10) ] for model in custom_pks: model.extra = "extra-%s" % model.pk CustomPk.objects.bulk_update(custom_pks, ["extra"]) self.assertCountEqual( CustomPk.objects.values_list("extra", flat=True), [cat.extra for cat in custom_pks], ) def test_falsey_pk_value(self): order = Order.objects.create(pk=0, name="test") order.name = "updated" Order.objects.bulk_update([order], ["name"]) order.refresh_from_db() self.assertEqual(order.name, "updated") def test_inherited_fields(self): special_categories = [ SpecialCategory.objects.create(name=str(i), special_name=str(i)) for i in range(10) ] for category in special_categories: category.name = "test-%s" % category.id category.special_name = "special-test-%s" % category.special_name SpecialCategory.objects.bulk_update( special_categories, ["name", "special_name"] ) self.assertCountEqual( SpecialCategory.objects.values_list("name", flat=True), [cat.name for cat in special_categories], ) self.assertCountEqual( SpecialCategory.objects.values_list("special_name", flat=True), [cat.special_name for cat in special_categories], ) def test_field_references(self): numbers = [Number.objects.create(num=0) for _ in range(10)] for number in numbers: number.num = F("num") + 1 Number.objects.bulk_update(numbers, ["num"]) self.assertCountEqual(Number.objects.filter(num=1), numbers) def test_f_expression(self): notes = [ Note.objects.create(note="test_note", misc="test_misc") for _ in range(10) ] for note in notes: note.misc = F("note") Note.objects.bulk_update(notes, ["misc"]) self.assertCountEqual(Note.objects.filter(misc="test_note"), notes) def test_booleanfield(self): individuals = [Individual.objects.create(alive=False) for _ in range(10)] for individual in individuals: individual.alive = True Individual.objects.bulk_update(individuals, ["alive"]) self.assertCountEqual(Individual.objects.filter(alive=True), individuals) def test_ipaddressfield(self): for ip in ("2001::1", "1.2.3.4"): with self.subTest(ip=ip): models = [ CustomDbColumn.objects.create(ip_address="0.0.0.0") for _ in range(10) ] for model in models: model.ip_address = ip CustomDbColumn.objects.bulk_update(models, ["ip_address"]) self.assertCountEqual( CustomDbColumn.objects.filter(ip_address=ip), models ) def test_datetime_field(self): articles = [ Article.objects.create(name=str(i), created=datetime.datetime.today()) for i in range(10) ] point_in_time = datetime.datetime(1991, 10, 31) for article in articles: article.created = point_in_time Article.objects.bulk_update(articles, ["created"]) self.assertCountEqual(Article.objects.filter(created=point_in_time), articles) @skipUnlessDBFeature("supports_json_field") def test_json_field(self): JSONFieldNullable.objects.bulk_create( [JSONFieldNullable(json_field={"a": i}) for i in range(10)] ) objs = JSONFieldNullable.objects.all() for obj in objs: obj.json_field = {"c": obj.json_field["a"] + 1} JSONFieldNullable.objects.bulk_update(objs, ["json_field"]) self.assertCountEqual( JSONFieldNullable.objects.filter(json_field__has_key="c"), objs ) def test_nullable_fk_after_related_save(self): parent = RelatedObject.objects.create() child = SingleObject() parent.single = child parent.single.save() RelatedObject.objects.bulk_update([parent], fields=["single"]) self.assertEqual(parent.single_id, parent.single.pk) parent.refresh_from_db() self.assertEqual(parent.single, child) def test_unsaved_parent(self): parent = RelatedObject.objects.create() parent.single = SingleObject() msg = ( "bulk_update() prohibited to prevent data loss due to unsaved " "related object 'single'." ) with self.assertRaisesMessage(ValueError, msg): RelatedObject.objects.bulk_update([parent], fields=["single"]) def test_unspecified_unsaved_parent(self): parent = RelatedObject.objects.create() parent.single = SingleObject() parent.f = 42 RelatedObject.objects.bulk_update([parent], fields=["f"]) parent.refresh_from_db() self.assertEqual(parent.f, 42) self.assertIsNone(parent.single) @override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()]) def test_database_routing(self): note = Note.objects.create(note="create") note.note = "bulk_update" with self.assertNumQueries(1, using="other"): Note.objects.bulk_update([note], fields=["note"]) @override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()]) def test_database_routing_batch_atomicity(self): f1 = Food.objects.create(name="Banana") f2 = Food.objects.create(name="Apple") f1.name = "Kiwi" f2.name = "Kiwi" with self.assertRaises(IntegrityError): Food.objects.bulk_update([f1, f2], fields=["name"], batch_size=1) self.assertIs(Food.objects.filter(name="Kiwi").exists(), False)
ae0eadfbef4aa3f9a8a72295caff72e946fb31333f09725ffdcc271562870ce9
import datetime from unittest import skipUnless from django.conf import settings from django.db import connection from django.db.models import ( CASCADE, CharField, DateTimeField, ForeignKey, Index, Model, Q, ) from django.db.models.functions import Lower from django.test import ( TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import isolate_apps, override_settings from django.utils import timezone from .models import Article, ArticleTranslation, IndexedArticle2 class SchemaIndexesTests(TestCase): """ Test index handling by the db.backends.schema infrastructure. """ def test_index_name_hash(self): """ Index names should be deterministic. """ editor = connection.schema_editor() index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=("c1",), suffix="123", ) self.assertEqual(index_name, "indexes_article_c1_a52bd80b123") def test_index_name(self): """ Index names on the built-in database backends:: * Are truncated as needed. * Include all the column names. * Include a deterministic hash. """ long_name = "l%sng" % ("o" * 100) editor = connection.schema_editor() index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=("c1", "c2", long_name), suffix="ix", ) expected = { "mysql": "indexes_article_c1_c2_looooooooooooooooooo_255179b2ix", "oracle": "indexes_a_c1_c2_loo_255179b2ix", "postgresql": "indexes_article_c1_c2_loooooooooooooooooo_255179b2ix", "sqlite": "indexes_article_c1_c2_l%sng_255179b2ix" % ("o" * 100), } if connection.vendor not in expected: self.skipTest( "This test is only supported on the built-in database backends." ) self.assertEqual(index_name, expected[connection.vendor]) def test_index_together(self): editor = connection.schema_editor() index_sql = [str(statement) for statement in editor._model_indexes_sql(Article)] self.assertEqual(len(index_sql), 1) # Ensure the index name is properly quoted self.assertIn( connection.ops.quote_name( editor._create_index_name( Article._meta.db_table, ["headline", "pub_date"], suffix="_idx" ) ), index_sql[0], ) @isolate_apps("indexes") def test_index_together_single_list(self): class IndexTogetherSingleList(Model): headline = CharField(max_length=100) pub_date = DateTimeField() class Meta: index_together = ["headline", "pub_date"] index_sql = connection.schema_editor()._model_indexes_sql( IndexTogetherSingleList ) self.assertEqual(len(index_sql), 1) def test_columns_list_sql(self): index = Index(fields=["headline"], name="whitespace_idx") editor = connection.schema_editor() self.assertIn( "(%s)" % editor.quote_name("headline"), str(index.create_sql(Article, editor)), ) @skipUnlessDBFeature("supports_index_column_ordering") def test_descending_columns_list_sql(self): index = Index(fields=["-headline"], name="whitespace_idx") editor = connection.schema_editor() self.assertIn( "(%s DESC)" % editor.quote_name("headline"), str(index.create_sql(Article, editor)), ) class SchemaIndexesNotPostgreSQLTests(TransactionTestCase): available_apps = ["indexes"] def test_create_index_ignores_opclasses(self): index = Index( name="test_ops_class", fields=["headline"], opclasses=["varchar_pattern_ops"], ) with connection.schema_editor() as editor: # This would error if opclasses weren't ignored. editor.add_index(IndexedArticle2, index) # The `condition` parameter is ignored by databases that don't support partial # indexes. @skipIfDBFeature("supports_partial_indexes") class PartialIndexConditionIgnoredTests(TransactionTestCase): available_apps = ["indexes"] def test_condition_ignored(self): index = Index( name="test_condition_ignored", fields=["published"], condition=Q(published=True), ) with connection.schema_editor() as editor: # This would error if condition weren't ignored. editor.add_index(Article, index) self.assertNotIn( "WHERE %s" % editor.quote_name("published"), str(index.create_sql(Article, editor)), ) @skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class SchemaIndexesPostgreSQLTests(TransactionTestCase): available_apps = ["indexes"] get_opclass_query = """ SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = '%s' """ def test_text_indexes(self): """Test creation of PostgreSQL-specific text indexes (#12234)""" from .models import IndexedArticle index_sql = [ str(statement) for statement in connection.schema_editor()._model_indexes_sql( IndexedArticle ) ] self.assertEqual(len(index_sql), 5) self.assertIn('("headline" varchar_pattern_ops)', index_sql[1]) self.assertIn('("body" text_pattern_ops)', index_sql[3]) # unique=True and db_index=True should only create the varchar-specific # index (#19441). self.assertIn('("slug" varchar_pattern_ops)', index_sql[4]) def test_virtual_relation_indexes(self): """Test indexes are not created for related objects""" index_sql = connection.schema_editor()._model_indexes_sql(Article) self.assertEqual(len(index_sql), 1) def test_ops_class(self): index = Index( name="test_ops_class", fields=["headline"], opclasses=["varchar_pattern_ops"], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % "test_ops_class") self.assertEqual( cursor.fetchall(), [("varchar_pattern_ops", "test_ops_class")] ) def test_ops_class_multiple_columns(self): index = Index( name="test_ops_class_multiple", fields=["headline", "body"], opclasses=["varchar_pattern_ops", "text_pattern_ops"], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % "test_ops_class_multiple") expected_ops_classes = ( ("varchar_pattern_ops", "test_ops_class_multiple"), ("text_pattern_ops", "test_ops_class_multiple"), ) self.assertCountEqual(cursor.fetchall(), expected_ops_classes) def test_ops_class_partial(self): index = Index( name="test_ops_class_partial", fields=["body"], opclasses=["text_pattern_ops"], condition=Q(headline__contains="China"), ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % "test_ops_class_partial") self.assertCountEqual( cursor.fetchall(), [("text_pattern_ops", "test_ops_class_partial")] ) def test_ops_class_partial_tablespace(self): indexname = "test_ops_class_tblspace" index = Index( name=indexname, fields=["body"], opclasses=["text_pattern_ops"], condition=Q(headline__contains="China"), db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) self.assertIn( 'TABLESPACE "pg_default" ', str(index.create_sql(IndexedArticle2, editor)), ) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % indexname) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", indexname)]) def test_ops_class_descending(self): indexname = "test_ops_class_ordered" index = Index( name=indexname, fields=["-body"], opclasses=["text_pattern_ops"], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % indexname) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", indexname)]) def test_ops_class_descending_partial(self): indexname = "test_ops_class_ordered_partial" index = Index( name=indexname, fields=["-body"], opclasses=["text_pattern_ops"], condition=Q(headline__contains="China"), ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % indexname) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", indexname)]) @skipUnlessDBFeature("supports_covering_indexes") def test_ops_class_include(self): index_name = "test_ops_class_include" index = Index( name=index_name, fields=["body"], opclasses=["text_pattern_ops"], include=["headline"], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % index_name) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) @skipUnlessDBFeature("supports_covering_indexes") def test_ops_class_include_tablespace(self): index_name = "test_ops_class_include_tblspace" index = Index( name=index_name, fields=["body"], opclasses=["text_pattern_ops"], include=["headline"], db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) self.assertIn( 'TABLESPACE "pg_default"', str(index.create_sql(IndexedArticle2, editor)), ) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % index_name) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) def test_ops_class_columns_lists_sql(self): index = Index( fields=["headline"], name="whitespace_idx", opclasses=["text_pattern_ops"], ) with connection.schema_editor() as editor: self.assertIn( "(%s text_pattern_ops)" % editor.quote_name("headline"), str(index.create_sql(Article, editor)), ) def test_ops_class_descending_columns_list_sql(self): index = Index( fields=["-headline"], name="whitespace_idx", opclasses=["text_pattern_ops"], ) with connection.schema_editor() as editor: self.assertIn( "(%s text_pattern_ops DESC)" % editor.quote_name("headline"), str(index.create_sql(Article, editor)), ) @skipUnless(connection.vendor == "mysql", "MySQL tests") class SchemaIndexesMySQLTests(TransactionTestCase): available_apps = ["indexes"] def test_no_index_for_foreignkey(self): """ MySQL on InnoDB already creates indexes automatically for foreign keys. (#14180). An index should be created if db_constraint=False (#26171). """ with connection.cursor() as cursor: storage = connection.introspection.get_storage_engine( cursor, ArticleTranslation._meta.db_table, ) if storage != "InnoDB": self.skipTest("This test only applies to the InnoDB storage engine") index_sql = [ str(statement) for statement in connection.schema_editor()._model_indexes_sql( ArticleTranslation ) ] self.assertEqual( index_sql, [ "CREATE INDEX " "`indexes_articletranslation_article_no_constraint_id_d6c0806b` " "ON `indexes_articletranslation` (`article_no_constraint_id`)" ], ) # The index also shouldn't be created if the ForeignKey is added after # the model was created. field_created = False try: with connection.schema_editor() as editor: new_field = ForeignKey(Article, CASCADE) new_field.set_attributes_from_name("new_foreign_key") editor.add_field(ArticleTranslation, new_field) field_created = True # No deferred SQL. The FK constraint is included in the # statement to add the field. self.assertFalse(editor.deferred_sql) finally: if field_created: with connection.schema_editor() as editor: editor.remove_field(ArticleTranslation, new_field) @skipUnlessDBFeature("supports_partial_indexes") # SQLite doesn't support timezone-aware datetimes when USE_TZ is False. @override_settings(USE_TZ=True) class PartialIndexTests(TransactionTestCase): # Schema editor is used to create the index to test that it works. available_apps = ["indexes"] def test_partial_index(self): with connection.schema_editor() as editor: index = Index( name="recent_article_idx", fields=["pub_date"], condition=Q( pub_date__gt=datetime.datetime( year=2015, month=1, day=1, # PostgreSQL would otherwise complain about the lookup # being converted to a mutable function (by removing # the timezone in the cast) which is forbidden. tzinfo=timezone.get_current_timezone(), ), ), ) self.assertIn( "WHERE %s" % editor.quote_name("pub_date"), str(index.create_sql(Article, schema_editor=editor)), ) editor.add_index(index=index, model=Article) with connection.cursor() as cursor: self.assertIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) editor.remove_index(index=index, model=Article) def test_integer_restriction_partial(self): with connection.schema_editor() as editor: index = Index( name="recent_article_idx", fields=["id"], condition=Q(pk__gt=1), ) self.assertIn( "WHERE %s" % editor.quote_name("id"), str(index.create_sql(Article, schema_editor=editor)), ) editor.add_index(index=index, model=Article) with connection.cursor() as cursor: self.assertIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) editor.remove_index(index=index, model=Article) def test_boolean_restriction_partial(self): with connection.schema_editor() as editor: index = Index( name="published_index", fields=["published"], condition=Q(published=True), ) self.assertIn( "WHERE %s" % editor.quote_name("published"), str(index.create_sql(Article, schema_editor=editor)), ) editor.add_index(index=index, model=Article) with connection.cursor() as cursor: self.assertIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) editor.remove_index(index=index, model=Article) @skipUnlessDBFeature("supports_functions_in_partial_indexes") def test_multiple_conditions(self): with connection.schema_editor() as editor: index = Index( name="recent_article_idx", fields=["pub_date", "headline"], condition=( Q( pub_date__gt=datetime.datetime( year=2015, month=1, day=1, tzinfo=timezone.get_current_timezone(), ) ) & Q(headline__contains="China") ), ) sql = str(index.create_sql(Article, schema_editor=editor)) where = sql.find("WHERE") self.assertIn("WHERE (%s" % editor.quote_name("pub_date"), sql) # Because each backend has different syntax for the operators, # check ONLY the occurrence of headline in the SQL. self.assertGreater(sql.rfind("headline"), where) editor.add_index(index=index, model=Article) with connection.cursor() as cursor: self.assertIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) editor.remove_index(index=index, model=Article) def test_is_null_condition(self): with connection.schema_editor() as editor: index = Index( name="recent_article_idx", fields=["pub_date"], condition=Q(pub_date__isnull=False), ) self.assertIn( "WHERE %s IS NOT NULL" % editor.quote_name("pub_date"), str(index.create_sql(Article, schema_editor=editor)), ) editor.add_index(index=index, model=Article) with connection.cursor() as cursor: self.assertIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) editor.remove_index(index=index, model=Article) @skipUnlessDBFeature("supports_expression_indexes") def test_partial_func_index(self): index_name = "partial_func_idx" index = Index( Lower("headline").desc(), name=index_name, condition=Q(pub_date__isnull=False), ) with connection.schema_editor() as editor: editor.add_index(index=index, model=Article) sql = index.create_sql(Article, schema_editor=editor) table = Article._meta.db_table self.assertIs(sql.references_column(table, "headline"), True) sql = str(sql) self.assertIn("LOWER(%s)" % editor.quote_name("headline"), sql) self.assertIn( "WHERE %s IS NOT NULL" % editor.quote_name("pub_date"), sql, ) self.assertGreater(sql.find("WHERE"), sql.find("LOWER")) with connection.cursor() as cursor: constraints = connection.introspection.get_constraints( cursor=cursor, table_name=table, ) self.assertIn(index_name, constraints) if connection.features.supports_index_column_ordering: self.assertEqual(constraints[index_name]["orders"], ["DESC"]) with connection.schema_editor() as editor: editor.remove_index(Article, index) with connection.cursor() as cursor: self.assertNotIn( index_name, connection.introspection.get_constraints( cursor=cursor, table_name=table, ), ) @skipUnlessDBFeature("supports_covering_indexes") class CoveringIndexTests(TransactionTestCase): available_apps = ["indexes"] def test_covering_index(self): index = Index( name="covering_headline_idx", fields=["headline"], include=["pub_date", "published"], ) with connection.schema_editor() as editor: self.assertIn( "(%s) INCLUDE (%s, %s)" % ( editor.quote_name("headline"), editor.quote_name("pub_date"), editor.quote_name("published"), ), str(index.create_sql(Article, editor)), ) editor.add_index(Article, index) with connection.cursor() as cursor: constraints = connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ) self.assertIn(index.name, constraints) self.assertEqual( constraints[index.name]["columns"], ["headline", "pub_date", "published"], ) editor.remove_index(Article, index) with connection.cursor() as cursor: self.assertNotIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) def test_covering_partial_index(self): index = Index( name="covering_partial_headline_idx", fields=["headline"], include=["pub_date"], condition=Q(pub_date__isnull=False), ) with connection.schema_editor() as editor: extra_sql = "" if settings.DEFAULT_INDEX_TABLESPACE: extra_sql = "TABLESPACE %s " % editor.quote_name( settings.DEFAULT_INDEX_TABLESPACE ) self.assertIn( "(%s) INCLUDE (%s) %sWHERE %s " % ( editor.quote_name("headline"), editor.quote_name("pub_date"), extra_sql, editor.quote_name("pub_date"), ), str(index.create_sql(Article, editor)), ) editor.add_index(Article, index) with connection.cursor() as cursor: constraints = connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ) self.assertIn(index.name, constraints) self.assertEqual( constraints[index.name]["columns"], ["headline", "pub_date"], ) editor.remove_index(Article, index) with connection.cursor() as cursor: self.assertNotIn( index.name, connection.introspection.get_constraints( cursor=cursor, table_name=Article._meta.db_table, ), ) @skipUnlessDBFeature("supports_expression_indexes") def test_covering_func_index(self): index_name = "covering_func_headline_idx" index = Index(Lower("headline"), name=index_name, include=["pub_date"]) with connection.schema_editor() as editor: editor.add_index(index=index, model=Article) sql = index.create_sql(Article, schema_editor=editor) table = Article._meta.db_table self.assertIs(sql.references_column(table, "headline"), True) sql = str(sql) self.assertIn("LOWER(%s)" % editor.quote_name("headline"), sql) self.assertIn("INCLUDE (%s)" % editor.quote_name("pub_date"), sql) self.assertGreater(sql.find("INCLUDE"), sql.find("LOWER")) with connection.cursor() as cursor: constraints = connection.introspection.get_constraints( cursor=cursor, table_name=table, ) self.assertIn(index_name, constraints) self.assertIn("pub_date", constraints[index_name]["columns"]) with connection.schema_editor() as editor: editor.remove_index(Article, index) with connection.cursor() as cursor: self.assertNotIn( index_name, connection.introspection.get_constraints( cursor=cursor, table_name=table, ), ) @skipIfDBFeature("supports_covering_indexes") class CoveringIndexIgnoredTests(TransactionTestCase): available_apps = ["indexes"] def test_covering_ignored(self): index = Index( name="test_covering_ignored", fields=["headline"], include=["pub_date"], ) with connection.schema_editor() as editor: editor.add_index(Article, index) self.assertNotIn( "INCLUDE (%s)" % editor.quote_name("headline"), str(index.create_sql(Article, editor)), )
27a05e0fabc24a2959e50de94842e90d9f3d9612491cee5e2f467f479f098b15
from django.db import models class CurrentTranslation(models.ForeignObject): """ Creates virtual relation to the translation with model cache enabled. """ # Avoid validation requires_unique_target = False def __init__(self, to, on_delete, from_fields, to_fields, **kwargs): # Disable reverse relation kwargs["related_name"] = "+" # Set unique to enable model cache. kwargs["unique"] = True super().__init__(to, on_delete, from_fields, to_fields, **kwargs) class ArticleTranslation(models.Model): article = models.ForeignKey("indexes.Article", models.CASCADE) article_no_constraint = models.ForeignKey( "indexes.Article", models.CASCADE, db_constraint=False, related_name="+" ) language = models.CharField(max_length=10, unique=True) content = models.TextField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() published = models.BooleanField(default=False) # Add virtual relation to the ArticleTranslation model. translation = CurrentTranslation( ArticleTranslation, models.CASCADE, ["id"], ["article"] ) class Meta: index_together = [ ["headline", "pub_date"], ] class IndexedArticle(models.Model): headline = models.CharField(max_length=100, db_index=True) body = models.TextField(db_index=True) slug = models.CharField(max_length=40, unique=True) class Meta: required_db_features = {"supports_index_on_text_field"} class IndexedArticle2(models.Model): headline = models.CharField(max_length=100) body = models.TextField()
1778c42d9df66d6a97387b0bec8f55a49c27c88b608bea7e9cf9cd288c245c45
""" Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. ``Client`` objects are stateful - they will retain cookie (and thus session) details for the lifetime of the ``Client`` instance. This is not intended as a replacement for Twill, Selenium, or other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ import itertools import pickle import tempfile from unittest import mock from django.contrib.auth.models import User from django.core import mail from django.http import HttpResponse, HttpResponseNotAllowed from django.test import ( AsyncRequestFactory, Client, RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.urls import reverse_lazy from django.utils.decorators import async_only_middleware from django.views.generic import RedirectView from .views import TwoArgException, get_view, post_view, trace_view def middleware_urlconf(get_response): def middleware(request): request.urlconf = "test_client.urls_middleware_urlconf" return get_response(request) return middleware @async_only_middleware def async_middleware_urlconf(get_response): async def middleware(request): request.urlconf = "test_client.urls_middleware_urlconf" return await get_response(request) return middleware @override_settings(ROOT_URLCONF="test_client.urls") class ClientTest(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username="testclient", password="password") cls.u2 = User.objects.create_user( username="inactive", password="password", is_active=False ) def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {"var": "\xf2"} response = self.client.get("/get_view/", data) # Check some response details self.assertContains(response, "This is a test") self.assertEqual(response.context["var"], "\xf2") self.assertEqual(response.templates[0].name, "GET Template") def test_pickling_response(self): tests = ["/cbv_view/", "/get_view/"] for url in tests: with self.subTest(url=url): response = self.client.get(url) dump = pickle.dumps(response) response_from_pickle = pickle.loads(dump) self.assertEqual(repr(response), repr(response_from_pickle)) async def test_pickling_response_async(self): response = await self.async_client.get("/async_get_view/") dump = pickle.dumps(response) response_from_pickle = pickle.loads(dump) self.assertEqual(repr(response), repr(response_from_pickle)) def test_query_string_encoding(self): # WSGI requires latin-1 encoded strings. response = self.client.get("/get_view/?var=1\ufffd") self.assertEqual(response.context["var"], "1\ufffd") def test_get_data_none(self): msg = ( "Cannot encode None for key 'value' in a query string. Did you " "mean to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.get("/get_view/", {"value": None}) def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get("/post_view/", {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Empty GET Template") self.assertTemplateUsed(response, "Empty GET Template") self.assertTemplateNotUsed(response, "Empty POST Template") def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post("/post_view/", {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Empty POST Template") self.assertTemplateNotUsed(response, "Empty GET Template") self.assertTemplateUsed(response, "Empty POST Template") def test_post(self): "POST some data to a view" post_data = {"value": 37} response = self.client.post("/post_view/", post_data) # Check some response details self.assertContains(response, "Data received") self.assertEqual(response.context["data"], "37") self.assertEqual(response.templates[0].name, "POST Template") def test_post_data_none(self): msg = ( "Cannot encode None for key 'value' as POST data. Did you mean " "to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.post("/post_view/", {"value": None}) def test_json_serialization(self): """The test client serializes JSON data.""" methods = ("post", "put", "patch", "delete") tests = ( ({"value": 37}, {"value": 37}), ([37, True], [37, True]), ((37, False), [37, False]), ) for method in methods: with self.subTest(method=method): for data, expected in tests: with self.subTest(data): client_method = getattr(self.client, method) method_name = method.upper() response = client_method( "/json_view/", data, content_type="application/json" ) self.assertContains(response, "Viewing %s page." % method_name) self.assertEqual(response.context["data"], expected) def test_json_encoder_argument(self): """The test Client accepts a json_encoder.""" mock_encoder = mock.MagicMock() mock_encoding = mock.MagicMock() mock_encoder.return_value = mock_encoding mock_encoding.encode.return_value = '{"value": 37}' client = self.client_class(json_encoder=mock_encoder) # Vendored tree JSON content types are accepted. client.post( "/json_view/", {"value": 37}, content_type="application/vnd.api+json" ) self.assertTrue(mock_encoder.called) self.assertTrue(mock_encoding.encode.called) def test_put(self): response = self.client.put("/put_view/", {"foo": "bar"}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "PUT Template") self.assertEqual(response.context["data"], "{'foo': 'bar'}") self.assertEqual(response.context["Content-Length"], "14") def test_trace(self): """TRACE a view""" response = self.client.trace("/trace_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["method"], "TRACE") self.assertEqual(response.templates[0].name, "TRACE Template") def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/header_view/") self.assertEqual(response.headers["X-DJANGO-TEST"], "Slartibartfast") def test_response_attached_request(self): """ The returned response has a ``request`` attribute with the originating environ dict and a ``wsgi_request`` with the originating WSGIRequest. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, "request")) self.assertTrue(hasattr(response, "wsgi_request")) for key, value in response.request.items(): self.assertIn(key, response.wsgi_request.environ) self.assertEqual(response.wsgi_request.environ[key], value) def test_response_resolver_match(self): """ The response contains a ResolverMatch instance. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, "resolver_match")) def test_response_resolver_match_redirect_follow(self): """ The response ResolverMatch instance contains the correct information when following redirects. """ response = self.client.get("/redirect_view/", follow=True) self.assertEqual(response.resolver_match.url_name, "get_view") def test_response_resolver_match_regular_view(self): """ The response ResolverMatch instance contains the correct information when accessing a regular view. """ response = self.client.get("/get_view/") self.assertEqual(response.resolver_match.url_name, "get_view") def test_response_resolver_match_class_based_view(self): """ The response ResolverMatch instance can be used to access the CBV view class. """ response = self.client.get("/accounts/") self.assertIs(response.resolver_match.func.view_class, RedirectView) @modify_settings(MIDDLEWARE={"prepend": "test_client.tests.middleware_urlconf"}) def test_response_resolver_match_middleware_urlconf(self): response = self.client.get("/middleware_urlconf_view/") self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?> <library><book><title>Blink</title><author>Malcolm Gladwell</author></book> </library> """ response = self.client.post( "/raw_post_view/", test_doc, content_type="text/xml" ) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, b"Blink - Malcolm Gladwell") def test_insecure(self): "GET a URL through http" response = self.client.get("/secure_view/", secure=False) self.assertFalse(response.test_was_secure_request) self.assertEqual(response.test_server_port, "80") def test_secure(self): "GET a URL through https" response = self.client.get("/secure_view/", secure=True) self.assertTrue(response.test_was_secure_request) self.assertEqual(response.test_server_port, "443") def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get("/redirect_view/") self.assertRedirects(response, "/get_view/") def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get("/redirect_view/", {"var": "value"}) self.assertRedirects(response, "/get_view/?var=value") def test_redirect_with_query_ordering(self): """assertRedirects() ignores the order of query string parameters.""" response = self.client.get("/redirect_view/", {"var": "value", "foo": "bar"}) self.assertRedirects(response, "/get_view/?var=value&foo=bar") self.assertRedirects(response, "/get_view/?foo=bar&var=value") def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get("/permanent_redirect_view/") self.assertRedirects(response, "/get_view/", status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get("/temporary_redirect_view/") self.assertRedirects(response, "/get_view/", status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get("/double_redirect_view/") # The response was a 302, and that the attempt to get the redirection # location returned 301 when retrieved self.assertRedirects( response, "/permanent_redirect_view/", target_status_code=301 ) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get("/double_redirect_view/", follow=True) self.assertRedirects( response, "/get_view/", status_code=302, target_status_code=200 ) self.assertEqual(len(response.redirect_chain), 2) def test_follow_relative_redirect(self): "A URL with a relative redirect can be followed." response = self.client.get("/accounts/", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") def test_follow_relative_redirect_no_trailing_slash(self): "A URL with a relative redirect with no trailing slash can be followed." response = self.client.get("/accounts/no_trailing_slash", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") def test_redirect_to_querystring_only(self): """A URL that consists of a querystring only can be followed""" response = self.client.post("/post_then_get_view/", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/post_then_get_view/") self.assertEqual(response.content, b"The value of success is true.") def test_follow_307_and_308_redirect(self): """ A 307 or 308 redirect preserves the request method after the redirect. """ methods = ("get", "post", "head", "options", "put", "patch", "delete", "trace") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s/" % code, data={"value": "test"}, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/post_view/") self.assertEqual(response.request["REQUEST_METHOD"], method.upper()) def test_follow_307_and_308_preserves_query_string(self): methods = ("post", "options", "put", "patch", "delete", "trace") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s_query_string/" % code, data={"value": "test"}, follow=True, ) self.assertRedirects( response, "/post_view/?hello=world", status_code=code ) self.assertEqual(response.request["QUERY_STRING"], "hello=world") def test_follow_307_and_308_get_head_query_string(self): methods = ("get", "head") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s_query_string/" % code, data={"value": "test"}, follow=True, ) self.assertRedirects( response, "/post_view/?hello=world", status_code=code ) self.assertEqual(response.request["QUERY_STRING"], "value=test") def test_follow_307_and_308_preserves_post_data(self): for code in (307, 308): with self.subTest(code=code): response = self.client.post( "/redirect_view_%s/" % code, data={"value": "test"}, follow=True ) self.assertContains(response, "test is the value") def test_follow_307_and_308_preserves_put_body(self): for code in (307, 308): with self.subTest(code=code): response = self.client.put( "/redirect_view_%s/?to=/put_view/" % code, data="a=b", follow=True ) self.assertContains(response, "a=b is the body") def test_follow_307_and_308_preserves_get_params(self): data = {"var": 30, "to": "/get_view/"} for code in (307, 308): with self.subTest(code=code): response = self.client.get( "/redirect_view_%s/" % code, data=data, follow=True ) self.assertContains(response, "30 is the value") def test_redirect_http(self): """GET a URL that redirects to an HTTP URI.""" response = self.client.get("/http_redirect_view/", follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): """GET a URL that redirects to an HTTPS URI.""" response = self.client.get("/https_redirect_view/", follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get("/bad_view/") self.assertContains(response, "MAGIC", status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = {"text": "Hello World", "multi": ("b", "c", "e")} response = self.client.get("/form_view/", data=hints) # The multi-value data has been rolled out ok self.assertContains(response, "Select a valid choice.", 0) self.assertTemplateUsed(response, "Form GET Template") def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = {"text": "Hello World", "value": 37} response = self.client.post("/form_view/", post_data) self.assertContains(response, "This field is required.", 3) self.assertTemplateUsed(response, "Invalid POST Template") form = response.context["form"] self.assertFormError(form, "email", "This field is required.") self.assertFormError(form, "single", "This field is required.") self.assertFormError(form, "multi", "This field is required.") def test_form_error(self): "POST erroneous data to a form" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError( response.context["form"], "email", "Enter a valid email address." ) def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data OK") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = {"text": "Hello World", "value": 37} response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data has errors") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Invalid POST Template") form = response.context["form"] self.assertFormError(form, "email", "This field is required.") self.assertFormError(form, "single", "This field is required.") self.assertFormError(form, "multi", "This field is required.") def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data has errors") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError( response.context["form"], "email", "Enter a valid email address." ) def test_unknown_page(self): "GET an invalid URL" response = self.client.get("/unknown_view/") # The response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get("/unknown_view/;some-parameter") # The path in the response includes it (ignore that it's a 404) self.assertEqual(response.request["PATH_INFO"], "/unknown_view/;some-parameter") def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( INSTALLED_APPS=["django.contrib.auth"], SESSION_ENGINE="django.contrib.sessions.backends.file", ) def test_view_with_login_when_sessions_app_is_not_installed(self): self.test_view_with_login() def test_view_with_force_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/login_protected_method_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_method_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_method_force_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/login_protected_method_view/" ) # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_method_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view_custom_redirect/") self.assertRedirects( response, "/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_view_custom_redirect/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_force_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view_custom_redirect/") self.assertRedirects( response, "/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", ) # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view_custom_redirect/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username="otheruser", password="nopassword") self.assertFalse(login) def test_view_with_inactive_login(self): """ An inactive user may login if the authenticate backend allows it. """ credentials = {"username": "inactive", "password": "password"} self.assertFalse(self.client.login(**credentials)) with self.settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.AllowAllUsersModelBackend" ] ): self.assertTrue(self.client.login(**credentials)) @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "django.contrib.auth.backends.AllowAllUsersModelBackend", ] ) def test_view_with_inactive_force_login(self): "Request a page that is protected with @login, but use an inactive login" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login( self.u2, backend="django.contrib.auth.backends.AllowAllUsersModelBackend" ) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "inactive") def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username="testclient", password="password") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") # Log out self.client.logout() # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") def test_logout_with_force_login(self): "Request a logout after logging in" # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") # Log out self.client.logout() # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "test_client.auth_backends.TestClientBackend", ], ) def test_force_login_with_backend(self): """ Request a page that is protected with @login_required when using force_login() and passing a backend. """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login( self.u1, backend="test_client.auth_backends.TestClientBackend" ) self.assertEqual(self.u1.backend, "test_client.auth_backends.TestClientBackend") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "test_client.auth_backends.TestClientBackend", ], ) def test_force_login_without_backend(self): """ force_login() without passing a backend and with multiple backends configured should automatically use the first backend. """ self.client.force_login(self.u1) response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") @override_settings( AUTHENTICATION_BACKENDS=[ "test_client.auth_backends.BackendWithoutGetUserMethod", "django.contrib.auth.backends.ModelBackend", ] ) def test_force_login_with_backend_missing_get_user(self): """ force_login() skips auth backends without a get_user() method. """ self.client.force_login(self.u1) self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") def test_logout_cookie_sessions(self): self.test_logout() def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get("/permission_protected_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 302. response = self.client.get("/permission_protected_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_view/" ) # TODO: Log in with right permissions and request the page again def test_view_with_permissions_exception(self): """ Request a page that is protected with @permission_required but raises an exception. """ # Get the page without logging in. Should result in 403. response = self.client.get("/permission_protected_view_exception/") self.assertEqual(response.status_code, 403) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 403. response = self.client.get("/permission_protected_view_exception/") self.assertEqual(response.status_code, 403) def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/permission_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_method_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 302. response = self.client.get("/permission_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_method_view/" ) # TODO: Log in with right permissions and request the page again def test_external_redirect(self): response = self.client.get("/django_project_redirect/") self.assertRedirects( response, "https://www.djangoproject.com/", fetch_redirect_response=False ) def test_external_redirect_without_trailing_slash(self): """ Client._handle_redirects() with an empty path. """ response = self.client.get("/no_trailing_slash_external_redirect/", follow=True) self.assertRedirects(response, "https://testserver") def test_external_redirect_with_fetch_error_msg(self): """ assertRedirects without fetch_redirect_response=False raises a relevant ValueError rather than a non-descript AssertionError. """ response = self.client.get("/django_project_redirect/") msg = ( "The test client is unable to fetch remote URLs (got " "https://www.djangoproject.com/). If the host is served by Django, " "add 'www.djangoproject.com' to ALLOWED_HOSTS. " "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." ) with self.assertRaisesMessage(ValueError, msg): self.assertRedirects(response, "https://www.djangoproject.com/") def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially with self.assertRaises(KeyError): self.client.session["tobacconist"] self.client.post("/session_view/") # The session was modified self.assertEqual(self.client.session["tobacconist"], "hovercraft") @override_settings( INSTALLED_APPS=[], SESSION_ENGINE="django.contrib.sessions.backends.file", ) def test_sessions_app_is_not_installed(self): self.test_session_modifying_view() @override_settings( INSTALLED_APPS=[], SESSION_ENGINE="django.contrib.sessions.backends.nonexistent", ) def test_session_engine_is_invalid(self): with self.assertRaisesMessage(ImportError, "nonexistent"): self.test_session_modifying_view() def test_view_with_exception(self): "Request a page that is known to throw an error" with self.assertRaises(KeyError): self.client.get("/broken_view/") def test_exc_info(self): client = Client(raise_request_exception=False) response = client.get("/broken_view/") self.assertEqual(response.status_code, 500) exc_type, exc_value, exc_traceback = response.exc_info self.assertIs(exc_type, KeyError) self.assertIsInstance(exc_value, KeyError) self.assertEqual(str(exc_value), "'Oops! Looks like you wrote some bad code.'") self.assertIsNotNone(exc_traceback) def test_exc_info_none(self): response = self.client.get("/get_view/") self.assertIsNone(response.exc_info) def test_mail_sending(self): "Mail is redirected to a dummy outbox during test setup" response = self.client.get("/mail_sending_view/") self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test message") self.assertEqual(mail.outbox[0].body, "This is a test email") self.assertEqual(mail.outbox[0].from_email, "[email protected]") self.assertEqual(mail.outbox[0].to[0], "[email protected]") self.assertEqual(mail.outbox[0].to[1], "[email protected]") def test_reverse_lazy_decodes(self): "reverse_lazy() works in the test client" data = {"var": "data"} response = self.client.get(reverse_lazy("get_view"), data) # Check some response details self.assertContains(response, "This is a test") def test_relative_redirect(self): response = self.client.get("/accounts/") self.assertRedirects(response, "/accounts/login/") def test_relative_redirect_no_trailing_slash(self): response = self.client.get("/accounts/no_trailing_slash") self.assertRedirects(response, "/accounts/login/") def test_mass_mail_sending(self): "Mass mail is redirected to a dummy outbox during test setup" response = self.client.get("/mass_mail_sending_view/") self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "First Test message") self.assertEqual(mail.outbox[0].body, "This is the first test email") self.assertEqual(mail.outbox[0].from_email, "[email protected]") self.assertEqual(mail.outbox[0].to[0], "[email protected]") self.assertEqual(mail.outbox[0].to[1], "[email protected]") self.assertEqual(mail.outbox[1].subject, "Second Test message") self.assertEqual(mail.outbox[1].body, "This is the second test email") self.assertEqual(mail.outbox[1].from_email, "[email protected]") self.assertEqual(mail.outbox[1].to[0], "[email protected]") self.assertEqual(mail.outbox[1].to[1], "[email protected]") def test_exception_following_nested_client_request(self): """ A nested test client request shouldn't clobber exception signals from the outer client request. """ with self.assertRaisesMessage(Exception, "exception message"): self.client.get("/nesting_exception_view/") def test_response_raises_multi_arg_exception(self): """A request may raise an exception with more than one required arg.""" with self.assertRaises(TwoArgException) as cm: self.client.get("/two_arg_exception/") self.assertEqual(cm.exception.args, ("one", "two")) def test_uploading_temp_file(self): with tempfile.TemporaryFile() as test_file: response = self.client.post("/upload_view/", data={"temp_file": test_file}) self.assertEqual(response.content, b"temp_file") def test_uploading_named_temp_file(self): with tempfile.NamedTemporaryFile() as test_file: response = self.client.post( "/upload_view/", data={"named_temp_file": test_file}, ) self.assertEqual(response.content, b"named_temp_file") @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], ROOT_URLCONF="test_client.urls", ) class CSRFEnabledClientTests(SimpleTestCase): def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post("/post_view/", {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post("/post_view/", {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(SimpleTestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertIs(hasattr(self.client, "i_am_customized"), True) def _generic_view(request): return HttpResponse(status=200) @override_settings(ROOT_URLCONF="test_client.urls") class RequestFactoryTest(SimpleTestCase): """Tests for the request factory.""" # A mapping between names of HTTP/1.1 methods and their test views. http_methods_and_views = ( ("get", get_view), ("post", post_view), ("put", _generic_view), ("patch", _generic_view), ("delete", _generic_view), ("head", _generic_view), ("options", _generic_view), ("trace", trace_view), ) request_factory = RequestFactory() def test_request_factory(self): """The request factory implements all the HTTP/1.1 methods.""" for method_name, view in self.http_methods_and_views: method = getattr(self.request_factory, method_name) request = method("/somewhere/") response = view(request) self.assertEqual(response.status_code, 200) def test_get_request_from_factory(self): """ The request factory returns a templated response for a GET request. """ request = self.request_factory.get("/somewhere/") response = get_view(request) self.assertContains(response, "This is a test") def test_trace_request_from_factory(self): """The request factory returns an echo response for a TRACE request.""" url_path = "/somewhere/" request = self.request_factory.trace(url_path) response = trace_view(request) protocol = request.META["SERVER_PROTOCOL"] echoed_request_line = "TRACE {} {}".format(url_path, protocol) self.assertContains(response, echoed_request_line) @override_settings(ROOT_URLCONF="test_client.urls") class AsyncClientTest(TestCase): async def test_response_resolver_match(self): response = await self.async_client.get("/async_get_view/") self.assertTrue(hasattr(response, "resolver_match")) self.assertEqual(response.resolver_match.url_name, "async_get_view") @modify_settings( MIDDLEWARE={"prepend": "test_client.tests.async_middleware_urlconf"}, ) async def test_response_resolver_match_middleware_urlconf(self): response = await self.async_client.get("/middleware_urlconf_view/") self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") async def test_follow_parameter_not_implemented(self): msg = "AsyncClient request methods do not accept the follow parameter." tests = ( "get", "post", "put", "patch", "delete", "head", "options", "trace", ) for method_name in tests: with self.subTest(method=method_name): method = getattr(self.async_client, method_name) with self.assertRaisesMessage(NotImplementedError, msg): await method("/redirect_view/", follow=True) async def test_get_data(self): response = await self.async_client.get("/get_view/", {"var": "val"}) self.assertContains(response, "This is a test. val is the value.") @override_settings(ROOT_URLCONF="test_client.urls") class AsyncRequestFactoryTest(SimpleTestCase): request_factory = AsyncRequestFactory() async def test_request_factory(self): tests = ( "get", "post", "put", "patch", "delete", "head", "options", "trace", ) for method_name in tests: with self.subTest(method=method_name): async def async_generic_view(request): if request.method.lower() != method_name: return HttpResponseNotAllowed(method_name) return HttpResponse(status=200) method = getattr(self.request_factory, method_name) request = method("/somewhere/") response = await async_generic_view(request) self.assertEqual(response.status_code, 200) async def test_request_factory_data(self): async def async_generic_view(request): return HttpResponse(status=200, content=request.body) request = self.request_factory.post( "/somewhere/", data={"example": "data"}, content_type="application/json", ) self.assertEqual(request.headers["content-length"], "19") self.assertEqual(request.headers["content-type"], "application/json") response = await async_generic_view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'{"example": "data"}') def test_request_factory_sets_headers(self): request = self.request_factory.get( "/somewhere/", AUTHORIZATION="Bearer faketoken", X_ANOTHER_HEADER="some other value", ) self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) def test_request_factory_query_string(self): request = self.request_factory.get("/somewhere/", {"example": "data"}) self.assertNotIn("Query-String", request.headers) self.assertEqual(request.GET["example"], "data")
e41a6f3f32b078b50c8c275609691f7f6b8f9b24802e22683b5f3e79fd46c00d
from django.contrib.auth import views as auth_views from django.urls import path from django.views.generic import RedirectView from . import views urlpatterns = [ path("upload_view/", views.upload_view, name="upload_view"), path("get_view/", views.get_view, name="get_view"), path("cbv_view/", views.CBView.as_view()), path("post_view/", views.post_view), path("post_then_get_view/", views.post_then_get_view), path("put_view/", views.put_view), path("trace_view/", views.trace_view), path("header_view/", views.view_with_header), path("raw_post_view/", views.raw_post_view), path("redirect_view/", views.redirect_view), path("redirect_view_307/", views.method_saving_307_redirect_view), path( "redirect_view_307_query_string/", views.method_saving_307_redirect_query_string_view, ), path("redirect_view_308/", views.method_saving_308_redirect_view), path( "redirect_view_308_query_string/", views.method_saving_308_redirect_query_string_view, ), path("secure_view/", views.view_with_secure), path( "permanent_redirect_view/", RedirectView.as_view(url="/get_view/", permanent=True), ), path( "temporary_redirect_view/", RedirectView.as_view(url="/get_view/", permanent=False), ), path("http_redirect_view/", RedirectView.as_view(url="/secure_view/")), path( "https_redirect_view/", RedirectView.as_view(url="https://testserver/secure_view/"), ), path("double_redirect_view/", views.double_redirect_view), path("bad_view/", views.bad_view), path("form_view/", views.form_view), path("form_view_with_template/", views.form_view_with_template), path("json_view/", views.json_view), path("login_protected_view/", views.login_protected_view), path("login_protected_method_view/", views.login_protected_method_view), path( "login_protected_view_custom_redirect/", views.login_protected_view_changed_redirect, ), path("permission_protected_view/", views.permission_protected_view), path( "permission_protected_view_exception/", views.permission_protected_view_exception, ), path("permission_protected_method_view/", views.permission_protected_method_view), path("session_view/", views.session_view), path("broken_view/", views.broken_view), path("mail_sending_view/", views.mail_sending_view), path("mass_mail_sending_view/", views.mass_mail_sending_view), path("nesting_exception_view/", views.nesting_exception_view), path("django_project_redirect/", views.django_project_redirect), path( "no_trailing_slash_external_redirect/", views.no_trailing_slash_external_redirect, ), path( "", views.index_view, name="index" ), # Target for no_trailing_slash_external_redirect/ with follow=True path("two_arg_exception/", views.two_arg_exception), path("accounts/", RedirectView.as_view(url="login/")), path("accounts/no_trailing_slash", RedirectView.as_view(url="login/")), path("accounts/login/", auth_views.LoginView.as_view(template_name="login.html")), path("accounts/logout/", auth_views.LogoutView.as_view()), # Async views. path("async_get_view/", views.async_get_view, name="async_get_view"), ]
635d8c9a35461477f4da9dc50498417d0d2c93b8093235cab671b0770bba8819
import json from urllib.parse import urlencode from xml.dom.minidom import parseString from django.contrib.auth.decorators import login_required, permission_required from django.core import mail from django.core.exceptions import ValidationError from django.forms import fields from django.forms.forms import Form from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseRedirect, ) from django.shortcuts import render from django.template import Context, Template from django.test import Client from django.utils.decorators import method_decorator from django.views.generic import TemplateView def get_view(request): "A simple view that expects a GET request, and returns a rendered template" t = Template("This is a test. {{ var }} is the value.", name="GET Template") c = Context({"var": request.GET.get("var", 42)}) return HttpResponse(t.render(c)) async def async_get_view(request): return HttpResponse(b"GET content.") def trace_view(request): """ A simple view that expects a TRACE request and echoes its status line. TRACE requests should not have an entity; the view will return a 400 status response if it is present. """ if request.method.upper() != "TRACE": return HttpResponseNotAllowed("TRACE") elif request.body: return HttpResponseBadRequest("TRACE requests MUST NOT include an entity") else: protocol = request.META["SERVER_PROTOCOL"] t = Template( "{{ method }} {{ uri }} {{ version }}", name="TRACE Template", ) c = Context( { "method": request.method, "uri": request.path, "version": protocol, } ) return HttpResponse(t.render(c)) def put_view(request): if request.method == "PUT": t = Template("Data received: {{ data }} is the body.", name="PUT Template") c = Context( { "Content-Length": request.META["CONTENT_LENGTH"], "data": request.body.decode(), } ) else: t = Template("Viewing GET page.", name="Empty GET Template") c = Context() return HttpResponse(t.render(c)) def post_view(request): """A view that expects a POST, and returns a different template depending on whether any POST data is available """ if request.method == "POST": if request.POST: t = Template( "Data received: {{ data }} is the value.", name="POST Template" ) c = Context({"data": request.POST["value"]}) else: t = Template("Viewing POST page.", name="Empty POST Template") c = Context() else: t = Template("Viewing GET page.", name="Empty GET Template") c = Context() return HttpResponse(t.render(c)) def post_then_get_view(request): """ A view that expects a POST request, returns a redirect response to itself providing only a ?success=true querystring, the value of this querystring is then rendered upon GET. """ if request.method == "POST": return HttpResponseRedirect("?success=true") t = Template("The value of success is {{ value }}.", name="GET Template") c = Context({"value": request.GET.get("success", "false")}) return HttpResponse(t.render(c)) def json_view(request): """ A view that expects a request with the header 'application/json' and JSON data, which is deserialized and included in the context. """ if request.META.get("CONTENT_TYPE") != "application/json": return HttpResponse() t = Template("Viewing {} page. With data {{ data }}.".format(request.method)) data = json.loads(request.body.decode("utf-8")) c = Context({"data": data}) return HttpResponse(t.render(c)) def view_with_header(request): "A view that has a custom header" response = HttpResponse() response.headers["X-DJANGO-TEST"] = "Slartibartfast" return response def raw_post_view(request): """A view which expects raw XML to be posted and returns content extracted from the XML""" if request.method == "POST": root = parseString(request.body) first_book = root.firstChild.firstChild title, author = [n.firstChild.nodeValue for n in first_book.childNodes] t = Template("{{ title }} - {{ author }}", name="Book template") c = Context({"title": title, "author": author}) else: t = Template("GET request.", name="Book GET template") c = Context() return HttpResponse(t.render(c)) def redirect_view(request): "A view that redirects all requests to the GET view" if request.GET: query = "?" + urlencode(request.GET, True) else: query = "" return HttpResponseRedirect("/get_view/" + query) def method_saving_307_redirect_query_string_view(request): return HttpResponseRedirect("/post_view/?hello=world", status=307) def method_saving_308_redirect_query_string_view(request): return HttpResponseRedirect("/post_view/?hello=world", status=308) def _post_view_redirect(request, status_code): """Redirect to /post_view/ using the status code.""" redirect_to = request.GET.get("to", "/post_view/") return HttpResponseRedirect(redirect_to, status=status_code) def method_saving_307_redirect_view(request): return _post_view_redirect(request, 307) def method_saving_308_redirect_view(request): return _post_view_redirect(request, 308) def view_with_secure(request): "A view that indicates if the request was secure" response = HttpResponse() response.test_was_secure_request = request.is_secure() response.test_server_port = request.META.get("SERVER_PORT", 80) return response def double_redirect_view(request): "A view that redirects all requests to a redirection view" return HttpResponseRedirect("/permanent_redirect_view/") def bad_view(request): "A view that returns a 404 with some error content" return HttpResponseNotFound("Not found!. This page contains some MAGIC content") TestChoices = ( ("a", "First Choice"), ("b", "Second Choice"), ("c", "Third Choice"), ("d", "Fourth Choice"), ("e", "Fifth Choice"), ) class TestForm(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices) def clean(self): cleaned_data = self.cleaned_data if cleaned_data.get("text") == "Raise non-field error": raise ValidationError("Non-field error.") return cleaned_data def form_view(request): "A view that tests a simple form" if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): t = Template("Valid POST data.", name="Valid POST Template") c = Context() else: t = Template( "Invalid POST data. {{ form.errors }}", name="Invalid POST Template" ) c = Context({"form": form}) else: form = TestForm(request.GET) t = Template("Viewing base form. {{ form }}.", name="Form GET Template") c = Context({"form": form}) return HttpResponse(t.render(c)) def form_view_with_template(request): "A view that tests a simple form" if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): message = "POST data OK" else: message = "POST data has errors" else: form = TestForm() message = "GET form page" return render( request, "form_view.html", { "form": form, "message": message, }, ) @login_required def login_protected_view(request): "A simple view that is login protected." t = Template( "This is a login protected test. Username is {{ user.username }}.", name="Login Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) @login_required(redirect_field_name="redirect_to") def login_protected_view_changed_redirect(request): "A simple view that is login protected with a custom redirect field set" t = Template( "This is a login protected test. Username is {{ user.username }}.", name="Login Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) def _permission_protected_view(request): "A simple view that is permission protected." t = Template( "This is a permission protected test. " "Username is {{ user.username }}. " "Permissions are {{ user.get_all_permissions }}.", name="Permissions Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) permission_protected_view = permission_required("permission_not_granted")( _permission_protected_view ) permission_protected_view_exception = permission_required( "permission_not_granted", raise_exception=True )(_permission_protected_view) class _ViewManager: @method_decorator(login_required) def login_protected_view(self, request): t = Template( "This is a login protected test using a method. " "Username is {{ user.username }}.", name="Login Method Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) @method_decorator(permission_required("permission_not_granted")) def permission_protected_view(self, request): t = Template( "This is a permission protected test using a method. " "Username is {{ user.username }}. " "Permissions are {{ user.get_all_permissions }}.", name="Permissions Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) _view_manager = _ViewManager() login_protected_method_view = _view_manager.login_protected_view permission_protected_method_view = _view_manager.permission_protected_view def session_view(request): "A view that modifies the session" request.session["tobacconist"] = "hovercraft" t = Template( "This is a view that modifies the session.", name="Session Modifying View Template", ) c = Context() return HttpResponse(t.render(c)) def broken_view(request): """A view which just raises an exception, simulating a broken view.""" raise KeyError("Oops! Looks like you wrote some bad code.") def mail_sending_view(request): mail.EmailMessage( "Test message", "This is a test email", "[email protected]", ["[email protected]", "[email protected]"], ).send() return HttpResponse("Mail sent") def mass_mail_sending_view(request): m1 = mail.EmailMessage( "First Test message", "This is the first test email", "[email protected]", ["[email protected]", "[email protected]"], ) m2 = mail.EmailMessage( "Second Test message", "This is the second test email", "[email protected]", ["[email protected]", "[email protected]"], ) c = mail.get_connection() c.send_messages([m1, m2]) return HttpResponse("Mail sent") def nesting_exception_view(request): """ A view that uses a nested client to call another view and then raises an exception. """ client = Client() client.get("/get_view/") raise Exception("exception message") def django_project_redirect(request): return HttpResponseRedirect("https://www.djangoproject.com/") def no_trailing_slash_external_redirect(request): """ RFC 2616 3.2.2: A bare domain without any abs_path element should be treated as having the trailing `/`. Use https://testserver, rather than an external domain, in order to allow use of follow=True, triggering Client._handle_redirects(). """ return HttpResponseRedirect("https://testserver") def index_view(request): """Target for no_trailing_slash_external_redirect with follow=True.""" return HttpResponse("Hello world") def upload_view(request): """Prints keys of request.FILES to the response.""" return HttpResponse(", ".join(request.FILES)) class TwoArgException(Exception): def __init__(self, one, two): pass def two_arg_exception(request): raise TwoArgException("one", "two") class CBView(TemplateView): template_name = "base.html"
a77055ffbbc5bea192a582300bfab242c317fb2c098904b2c1e0e999b2045b4a
import datetime import itertools import unittest from copy import copy from unittest import mock from django.core.exceptions import FieldError from django.core.management.color import no_style from django.db import ( DatabaseError, DataError, IntegrityError, OperationalError, connection, ) from django.db.models import ( CASCADE, PROTECT, AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, CheckConstraint, DateField, DateTimeField, DecimalField, DurationField, F, FloatField, ForeignKey, ForeignObject, Index, IntegerField, JSONField, ManyToManyField, Model, OneToOneField, OrderBy, PositiveIntegerField, Q, SlugField, SmallAutoField, SmallIntegerField, TextField, TimeField, UniqueConstraint, UUIDField, Value, ) from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Abs, Cast, Collate, Lower, Random, Upper from django.db.models.indexes import IndexExpression from django.db.transaction import TransactionManagementError, atomic from django.test import TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup from .fields import CustomManyToManyField, InheritedManyToManyField, MediumBlobField from .models import ( Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, AuthorWithIndexedName, AuthorWithUniqueName, AuthorWithUniqueNameAndBirthday, Book, BookForeignObj, BookWeak, BookWithLongName, BookWithO2O, BookWithoutAuthor, BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag, TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps, ) class SchemaTests(TransactionTestCase): """ Tests for the schema-alteration code. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = [] models = [ Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book, BookWeak, BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Node, Note, Tag, TagM2MTest, TagUniqueRename, Thing, UniqueTest, ] # Utility functions def setUp(self): # local_models should contain test dependent model classes that will be # automatically removed from the app cache on test tear down. self.local_models = [] # isolated_local_models contains models that are in test methods # decorated with @isolate_apps. self.isolated_local_models = [] def tearDown(self): # Delete any tables made for our models self.delete_tables() new_apps.clear_cache() for model in new_apps.get_models(): model._meta._expire_cache() if "schema" in new_apps.all_models: for model in self.local_models: for many_to_many in model._meta.many_to_many: through = many_to_many.remote_field.through if through and through._meta.auto_created: del new_apps.all_models["schema"][through._meta.model_name] del new_apps.all_models["schema"][model._meta.model_name] if self.isolated_local_models: with connection.schema_editor() as editor: for model in self.isolated_local_models: editor.delete_model(model) def delete_tables(self): "Deletes all model tables for our models for a clean test environment" converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: connection.disable_constraint_checking() table_names = connection.introspection.table_names() if connection.features.ignores_table_name_case: table_names = [table_name.lower() for table_name in table_names] for model in itertools.chain(SchemaTests.models, self.local_models): tbl = converter(model._meta.db_table) if connection.features.ignores_table_name_case: tbl = tbl.lower() if tbl in table_names: editor.delete_model(model) table_names.remove(tbl) connection.enable_constraint_checking() def column_classes(self, model): with connection.cursor() as cursor: columns = { d[0]: (connection.introspection.get_field_type(d[1], d), d) for d in connection.introspection.get_table_description( cursor, model._meta.db_table, ) } # SQLite has a different format for field_type for name, (type, desc) in columns.items(): if isinstance(type, tuple): columns[name] = (type[0], desc) return columns def get_primary_key(self, table): with connection.cursor() as cursor: return connection.introspection.get_primary_key_column(cursor, table) def get_indexes(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table ).values() if c["index"] and len(c["columns"]) == 1 ] def get_uniques(self, table): with connection.cursor() as cursor: return [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table ).values() if c["unique"] and len(c["columns"]) == 1 ] def get_constraints(self, table): """ Get the constraints on a table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def get_constraints_for_column(self, model, column_name): constraints = self.get_constraints(model._meta.db_table) constraints_for_column = [] for name, details in constraints.items(): if details["columns"] == [column_name]: constraints_for_column.append(name) return sorted(constraints_for_column) def check_added_field_default( self, schema_editor, model, field, field_name, expected_default, cast_function=None, ): with connection.cursor() as cursor: schema_editor.add_field(model, field) cursor.execute( "SELECT {} FROM {};".format(field_name, model._meta.db_table) ) database_default = cursor.fetchall()[0][0] if cast_function and type(database_default) != type(expected_default): database_default = cast_function(database_default) self.assertEqual(database_default, expected_default) def get_constraints_count(self, table, column, fk_to): """ Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the number of foreign keys, unique constraints, and indexes on `table`.`column`. The `fk_to` argument is a 2-tuple specifying the expected foreign key relationship's (table, column). """ with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) counts = {"fks": 0, "uniques": 0, "indexes": 0} for c in constraints.values(): if c["columns"] == [column]: if c["foreign_key"] == fk_to: counts["fks"] += 1 if c["unique"]: counts["uniques"] += 1 elif c["index"]: counts["indexes"] += 1 return counts def get_column_collation(self, table, column): with connection.cursor() as cursor: return next( f.collation for f in connection.introspection.get_table_description(cursor, table) if f.name == column ) def assertIndexOrder(self, table, index, order): constraints = self.get_constraints(table) self.assertIn(index, constraints) index_orders = constraints[index]["orders"] self.assertTrue( all(val == expected for val, expected in zip(index_orders, order)) ) def assertForeignKeyExists(self, model, column, expected_fk_table, field="id"): """ Fail if the FK constraint on `model.Meta.db_table`.`column` to `expected_fk_table`.id doesn't exist. """ if not connection.features.can_introspect_foreign_keys: return constraints = self.get_constraints(model._meta.db_table) constraint_fk = None for details in constraints.values(): if details["columns"] == [column] and details["foreign_key"]: constraint_fk = details["foreign_key"] break self.assertEqual(constraint_fk, (expected_fk_table, field)) def assertForeignKeyNotExists(self, model, column, expected_fk_table): if not connection.features.can_introspect_foreign_keys: return with self.assertRaises(AssertionError): self.assertForeignKeyExists(model, column, expected_fk_table) # Tests def test_creation_deletion(self): """ Tries creating a model's table, and then deleting it. """ with connection.schema_editor() as editor: # Create the table editor.create_model(Author) # The table is there list(Author.objects.all()) # Clean up that table editor.delete_model(Author) # No deferred SQL should be left over. self.assertEqual(editor.deferred_sql, []) # The table is gone with self.assertRaises(DatabaseError): list(Author.objects.all()) @skipUnlessDBFeature("supports_foreign_keys") def test_fk(self): "Creating tables out of FK order, then repointing, works" # Create the table with connection.schema_editor() as editor: editor.create_model(Book) editor.create_model(Author) editor.create_model(Tag) # Initial tables are there list(Author.objects.all()) list(Book.objects.all()) # Make sure the FK constraint is present with self.assertRaises(IntegrityError): Book.objects.create( author_id=1, title="Much Ado About Foreign Keys", pub_date=datetime.datetime.now(), ) # Repoint the FK constraint old_field = Book._meta.get_field("author") new_field = ForeignKey(Tag, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) self.assertForeignKeyExists(Book, "author_id", "schema_tag") @skipUnlessDBFeature("can_create_inline_fk") def test_inline_fk(self): # Create some tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.create_model(Note) self.assertForeignKeyNotExists(Note, "book_id", "schema_book") # Add a foreign key from one to the other. with connection.schema_editor() as editor: new_field = ForeignKey(Book, CASCADE) new_field.set_attributes_from_name("book") editor.add_field(Note, new_field) self.assertForeignKeyExists(Note, "book_id", "schema_book") # Creating a FK field with a constraint uses a single statement without # a deferred ALTER TABLE. self.assertFalse( [ sql for sql in (str(statement) for statement in editor.deferred_sql) if sql.startswith("ALTER TABLE") and "ADD CONSTRAINT" in sql ] ) @skipUnlessDBFeature("can_create_inline_fk") def test_add_inline_fk_update_data(self): with connection.schema_editor() as editor: editor.create_model(Node) # Add an inline foreign key and update data in the same transaction. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True) new_field.set_attributes_from_name("new_parent_fk") parent = Node.objects.create() with connection.schema_editor() as editor: editor.add_field(Node, new_field) editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk]) assertIndex = ( self.assertIn if connection.features.indexes_foreign_keys else self.assertNotIn ) assertIndex("new_parent_fk_id", self.get_indexes(Node._meta.db_table)) @skipUnlessDBFeature( "can_create_inline_fk", "allows_multiple_constraints_on_same_fields", ) @isolate_apps("schema") def test_add_inline_fk_index_update_data(self): class Node(Model): class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Node) # Add an inline foreign key, update data, and an index in the same # transaction. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True) new_field.set_attributes_from_name("new_parent_fk") parent = Node.objects.create() with connection.schema_editor() as editor: editor.add_field(Node, new_field) Node._meta.add_field(new_field) editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk]) editor.add_index( Node, Index(fields=["new_parent_fk"], name="new_parent_inline_fk_idx") ) self.assertIn("new_parent_fk_id", self.get_indexes(Node._meta.db_table)) @skipUnlessDBFeature("supports_foreign_keys") def test_char_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorCharFieldWithIndex) # Change CharField to FK old_field = AuthorCharFieldWithIndex._meta.get_field("char_field") new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name("char_field") with connection.schema_editor() as editor: editor.alter_field( AuthorCharFieldWithIndex, old_field, new_field, strict=True ) self.assertForeignKeyExists( AuthorCharFieldWithIndex, "char_field_id", "schema_author" ) @skipUnlessDBFeature("supports_foreign_keys") @skipUnlessDBFeature("supports_index_on_text_field") def test_text_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorTextFieldWithIndex) # Change TextField to FK old_field = AuthorTextFieldWithIndex._meta.get_field("text_field") new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name("text_field") with connection.schema_editor() as editor: editor.alter_field( AuthorTextFieldWithIndex, old_field, new_field, strict=True ) self.assertForeignKeyExists( AuthorTextFieldWithIndex, "text_field_id", "schema_author" ) @isolate_apps("schema") def test_char_field_pk_to_auto_field(self): class Foo(Model): id = CharField(max_length=255, primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @skipUnlessDBFeature("supports_foreign_keys") def test_fk_to_proxy(self): "Creating a FK to a proxy model creates database constraints." class AuthorProxy(Author): class Meta: app_label = "schema" apps = new_apps proxy = True class AuthorRef(Model): author = ForeignKey(AuthorProxy, on_delete=CASCADE) class Meta: app_label = "schema" apps = new_apps self.local_models = [AuthorProxy, AuthorRef] # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorRef) self.assertForeignKeyExists(AuthorRef, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") def test_fk_db_constraint(self): "The db_constraint parameter is respected" # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) editor.create_model(BookWeak) # Initial tables are there list(Author.objects.all()) list(Tag.objects.all()) list(BookWeak.objects.all()) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") # Make a db_constraint=False FK new_field = ForeignKey(Tag, CASCADE, db_constraint=False) new_field.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.add_field(Author, new_field) self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag") # Alter to one with a constraint new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) self.assertForeignKeyExists(Author, "tag_id", "schema_tag") # Alter to one without a constraint again new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field2, new_field, strict=True) self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag") @isolate_apps("schema") def test_no_db_constraint_added_during_primary_key_change(self): """ When a primary key that's pointed to by a ForeignKey with db_constraint=False is altered, a foreign key constraint isn't added. """ class Author(Model): class Meta: app_label = "schema" class BookWeak(Model): author = ForeignKey(Author, CASCADE, db_constraint=False) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWeak) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") old_field = Author._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Author new_field.set_attributes_from_name("id") # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") def _test_m2m_db_constraint(self, M2MFieldClass): class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(LocalAuthorWithM2M) # Initial tables are there list(LocalAuthorWithM2M.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False) new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) self.assertForeignKeyNotExists( new_field.remote_field.through, "tag_id", "schema_tag" ) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint(self): self._test_m2m_db_constraint(ManyToManyField) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint_custom(self): self._test_m2m_db_constraint(CustomManyToManyField) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint_inherited(self): self._test_m2m_db_constraint(InheritedManyToManyField) def test_add_field(self): """ Tests adding fields to models """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") with CaptureQueriesContext( connection ) as ctx, connection.schema_editor() as editor: editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { "column": editor.quote_name(new_field.name), } self.assertFalse( any(drop_default_sql in query["sql"] for query in ctx.captured_queries) ) # Table is not rebuilt. self.assertIs( any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False ) columns = self.column_classes(Author) self.assertEqual( columns["age"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertTrue(columns["age"][1][6]) def test_add_field_remove_field(self): """ Adding a field and removing it removes all deferred sql referring to it. """ with connection.schema_editor() as editor: # Create a table with a unique constraint on the slug field. editor.create_model(Tag) # Remove the slug column. editor.remove_field(Tag, Tag._meta.get_field("slug")) self.assertEqual(editor.deferred_sql, []) def test_add_field_temp_default(self): """ Tests adding fields to models with a temporary default """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = CharField(max_length=30, default="Godwin") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["surname"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual( columns["surname"][1][6], connection.features.interprets_empty_strings_as_nulls, ) def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns["awesome"][0] self.assertEqual( field_type, connection.features.introspected_field_types["BooleanField"] ) def test_add_field_default_transform(self): """ Tests adding fields to models with a default that is not directly valid in the database (#22581) """ class TestTransformField(IntegerField): # Weird field that saves the count of items in its value def get_default(self): return self.default def get_prep_value(self, value): if value is None: return 0 return len(value) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add the field with a default it needs to cast (to string in this case) new_field = TestTransformField(default={1: 2}) new_field.set_attributes_from_name("thing") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is there columns = self.column_classes(Author) field_type, field_info = columns["thing"] self.assertEqual( field_type, connection.features.introspected_field_types["IntegerField"] ) # Make sure the values were transformed correctly self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2) def test_add_field_o2o_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Note) new_field = OneToOneField(Note, CASCADE, null=True) new_field.set_attributes_from_name("note") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertIn("note_id", columns) self.assertTrue(columns["note_id"][1][6]) def test_add_field_binary(self): """ Tests binary fields get a sane default (#22851) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field new_field = BinaryField(blank=True) new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # MySQL annoyingly uses the same backend, so it'll come back as one of # these two types. self.assertIn(columns["bits"][0], ("BinaryField", "TextField")) def test_add_field_durationfield_with_default(self): with connection.schema_editor() as editor: editor.create_model(Author) new_field = DurationField(default=datetime.timedelta(minutes=10)) new_field.set_attributes_from_name("duration") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["duration"][0], connection.features.introspected_field_types["DurationField"], ) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_add_binaryfield_mediumblob(self): """ Test adding a custom-sized binary field on MySQL (#24846). """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field with default new_field = MediumBlobField(blank=True, default=b"123") new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # Introspection treats BLOBs as TextFields self.assertEqual(columns["bits"][0], "TextField") def test_remove_field(self): with connection.schema_editor() as editor: editor.create_model(Author) with CaptureQueriesContext(connection) as ctx: editor.remove_field(Author, Author._meta.get_field("name")) columns = self.column_classes(Author) self.assertNotIn("name", columns) if getattr(connection.features, "can_alter_table_drop_column", True): # Table is not rebuilt. self.assertIs( any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False, ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False, ) def test_alter(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual( bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls), ) # Alter the name field to a TextField old_field = Author._meta.get_field("name") new_field = TextField(null=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertTrue(columns["name"][1][6]) # Change nullability again new_field2 = TextField(null=False) new_field2.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertEqual( bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls), ) def test_alter_auto_field_to_integer_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to IntegerField old_field = Author._meta.get_field("id") new_field = IntegerField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Now that ID is an IntegerField, the database raises an error if it # isn't provided. if not connection.features.supports_unspecified_pk: with self.assertRaises(DatabaseError): Author.objects.create() def test_alter_auto_field_to_char_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to CharField old_field = Author._meta.get_field("id") new_field = CharField(primary_key=True, max_length=50) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @isolate_apps("schema") def test_alter_auto_field_quoted_db_column(self): class Foo(Model): id = AutoField(primary_key=True, db_column='"quoted_id"') class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.db_column = '"quoted_id"' new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_not_unique_field_to_primary_key(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Change UUIDField to primary key. old_field = Author._meta.get_field("uuid") new_field = UUIDField(primary_key=True) new_field.set_attributes_from_name("uuid") new_field.model = Author with connection.schema_editor() as editor: editor.remove_field(Author, Author._meta.get_field("id")) editor.alter_field(Author, old_field, new_field, strict=True) # Redundant unique constraint is not added. count = self.get_constraints_count( Author._meta.db_table, Author._meta.get_field("uuid").column, None, ) self.assertLessEqual(count["uniques"], 1) @isolate_apps("schema") def test_alter_primary_key_quoted_db_table(self): class Foo(Model): class Meta: app_label = "schema" db_table = '"foo"' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_text_field(self): # Regression for "BLOB/TEXT column 'info' can't have a default value") # on MySQL. # Create the table with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = TextField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) def test_alter_text_field_to_not_null_with_default_value(self): with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("address") new_field = TextField(blank=True, default="", null=False) new_field.set_attributes_from_name("address") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature("can_defer_constraint_checks", "can_rollback_ddl") def test_alter_fk_checks_deferred_constraints(self): """ #25492 - Altering a foreign key's structure and data in the same transaction. """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field("parent") new_field = ForeignKey(Node, CASCADE) new_field.set_attributes_from_name("parent") parent = Node.objects.create() with connection.schema_editor() as editor: # Update the parent FK to create a deferred constraint check. Node.objects.update(parent=parent) editor.alter_field(Node, old_field, new_field, strict=True) @isolate_apps("schema") def test_alter_null_with_default_value_deferred_constraints(self): class Publisher(Model): class Meta: app_label = "schema" class Article(Model): publisher = ForeignKey(Publisher, CASCADE) title = CharField(max_length=50, null=True) description = CharField(max_length=100, null=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Publisher) editor.create_model(Article) self.isolated_local_models = [Article, Publisher] publisher = Publisher.objects.create() Article.objects.create(publisher=publisher) old_title = Article._meta.get_field("title") new_title = CharField(max_length=50, null=False, default="") new_title.set_attributes_from_name("title") old_description = Article._meta.get_field("description") new_description = CharField(max_length=100, null=False, default="") new_description.set_attributes_from_name("description") with connection.schema_editor() as editor: editor.alter_field(Article, old_title, new_title, strict=True) editor.alter_field(Article, old_description, new_description, strict=True) def test_alter_text_field_to_date_field(self): """ #25002 - Test conversion of text field to date field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="1988-05-05") old_field = Note._meta.get_field("info") new_field = DateField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) def test_alter_text_field_to_datetime_field(self): """ #25002 - Test conversion of text field to datetime field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="1988-05-05 3:16:17.4567") old_field = Note._meta.get_field("info") new_field = DateTimeField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) def test_alter_text_field_to_time_field(self): """ #25002 - Test conversion of text field to time field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="3:16:17.4567") old_field = Note._meta.get_field("info") new_field = TimeField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_alter_textual_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = CharField(max_length=50) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): Note.objects.create(info=None) @skipUnlessDBFeature("interprets_empty_strings_as_nulls") def test_alter_textual_field_not_null_to_null(self): """ Nullability for textual fields is preserved on databases that interpret empty strings as NULLs. """ with connection.schema_editor() as editor: editor.create_model(Author) columns = self.column_classes(Author) # Field is nullable. self.assertTrue(columns["uuid"][1][6]) # Change to NOT NULL. old_field = Author._meta.get_field("uuid") new_field = SlugField(null=False, blank=True) new_field.set_attributes_from_name("uuid") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) # Nullability is preserved. self.assertTrue(columns["uuid"][1][6]) def test_alter_numeric_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(UniqueTest) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug="aaa") old_field = UniqueTest._meta.get_field("year") new_field = BigIntegerField() new_field.set_attributes_from_name("year") with connection.schema_editor() as editor: editor.alter_field(UniqueTest, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug="bbb") def test_alter_null_to_not_null(self): """ #23609 - Tests handling of default values when altering from NULL to NOT NULL. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertTrue(columns["height"][1][6]) # Create some test data Author.objects.create(name="Not null author", height=12) Author.objects.create(name="Null author") # Verify null value self.assertEqual(Author.objects.get(name="Not null author").height, 12) self.assertIsNone(Author.objects.get(name="Null author").height) # Alter the height field to NOT NULL with default old_field = Author._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertFalse(columns["height"][1][6]) # Verify default value self.assertEqual(Author.objects.get(name="Not null author").height, 12) self.assertEqual(Author.objects.get(name="Null author").height, 42) def test_alter_charfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_nulls when changing a CharField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change the CharField to null old_field = Author._meta.get_field("name") new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_char_field_decrease_length(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) Author.objects.create(name="x" * 255) # Change max_length of CharField. old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: msg = "value too long for type character varying(254)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_with_custom_db_type(self): from django.contrib.postgres.fields import ArrayField class Foo(Model): field = ArrayField(CharField(max_length=255)) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("field") new_field = ArrayField(CharField(max_length=16)) new_field.set_attributes_from_name("field") new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_array_field_decrease_base_field_length(self): from django.contrib.postgres.fields import ArrayField class ArrayModel(Model): field = ArrayField(CharField(max_length=16)) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] ArrayModel.objects.create(field=["x" * 16]) old_field = ArrayModel._meta.get_field("field") new_field = ArrayField(CharField(max_length=15)) new_field.set_attributes_from_name("field") new_field.model = ArrayModel with connection.schema_editor() as editor: msg = "value too long for type character varying(15)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(ArrayModel, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_array_field_decrease_nested_base_field_length(self): from django.contrib.postgres.fields import ArrayField class ArrayModel(Model): field = ArrayField(ArrayField(CharField(max_length=16))) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] ArrayModel.objects.create(field=[["x" * 16]]) old_field = ArrayModel._meta.get_field("field") new_field = ArrayField(ArrayField(CharField(max_length=15))) new_field.set_attributes_from_name("field") new_field.model = ArrayModel with connection.schema_editor() as editor: msg = "value too long for type character varying(15)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(ArrayModel, old_field, new_field, strict=True) def test_alter_textfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_nulls when changing a TextField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Note) # Change the TextField to null old_field = Note._meta.get_field("info") new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) def test_alter_null_to_not_null_keeping_default(self): """ #23738 - Can change a nullable field with default to non-nullable with the same default. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) # Ensure the field is right to begin with columns = self.column_classes(AuthorWithDefaultHeight) self.assertTrue(columns["height"][1][6]) # Alter the height field to NOT NULL keeping the previous default old_field = AuthorWithDefaultHeight._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field( AuthorWithDefaultHeight, old_field, new_field, strict=True ) columns = self.column_classes(AuthorWithDefaultHeight) self.assertFalse(columns["height"][1][6]) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_fk(self): """ Tests altering of FKs """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertForeignKeyExists(Book, "author_id", "schema_author") # Alter the FK old_field = Book._meta.get_field("author") new_field = ForeignKey(Author, CASCADE, editable=False) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertForeignKeyExists(Book, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys") def test_alter_to_fk(self): """ #24447 - Tests adding a FK constraint for an existing column """ class LocalBook(Model): author = IntegerField() title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBook] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBook) # Ensure no FK constraint exists constraints = self.get_constraints(LocalBook._meta.db_table) for details in constraints.values(): if details["foreign_key"]: self.fail( "Found an unexpected FK constraint to %s" % details["columns"] ) old_field = LocalBook._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(LocalBook, old_field, new_field, strict=True) self.assertForeignKeyExists(LocalBook, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") def test_alter_o2o_to_fk(self): """ #24163 - Tests altering of OneToOneField to ForeignKey """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) # Ensure the field is right to begin with columns = self.column_classes(BookWithO2O) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is unique author = Author.objects.create(name="Joe") BookWithO2O.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) with self.assertRaises(IntegrityError): BookWithO2O.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) BookWithO2O.objects.all().delete() self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") # Alter the OneToOneField to ForeignKey old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is not unique anymore Book.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) Book.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) self.assertForeignKeyExists(Book, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys") def test_alter_fk_to_o2o(self): """ #24163 - Tests altering of ForeignKey to OneToOneField """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is not unique author = Author.objects.create(name="Joe") Book.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) Book.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) Book.objects.all().delete() self.assertForeignKeyExists(Book, "author_id", "schema_author") # Alter the ForeignKey to OneToOneField old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) columns = self.column_classes(BookWithO2O) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is unique now BookWithO2O.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) with self.assertRaises(IntegrityError): BookWithO2O.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") def test_alter_field_fk_to_o2o(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) expected_indexes = 1 if connection.features.indexes_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The index on ForeignKey is replaced with a unique constraint for # OneToOneField. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) def test_alter_field_fk_keeps_index(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) expected_indexes = 1 if connection.features.indexes_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) old_field = Book._meta.get_field("author") # on_delete changed from CASCADE. new_field = ForeignKey(Author, PROTECT) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The index remains. self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) def test_alter_field_o2o_to_fk(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint on OneToOneField is replaced with an index for # ForeignKey. self.assertEqual(counts, {"fks": expected_fks, "uniques": 0, "indexes": 1}) def test_alter_field_o2o_keeps_unique(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = ( 1 if connection.features.supports_foreign_keys and connection.features.can_introspect_foreign_keys else 0 ) # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) old_field = BookWithO2O._meta.get_field("author") # on_delete changed from CASCADE. new_field = OneToOneField(Author, PROTECT) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint remains. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) @skipUnlessDBFeature("ignores_table_name_case") def test_alter_db_table_case(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Alter the case of the table old_table_name = Author._meta.db_table with connection.schema_editor() as editor: editor.alter_db_table(Author, old_table_name, old_table_name.upper()) def test_alter_implicit_id_to_explicit(self): """ Should be able to convert an implicit "id" field to an explicit "id" primary key field. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # This will fail if DROP DEFAULT is inadvertently executed on this # field which drops the id sequence, at least on PostgreSQL. Author.objects.create(name="Foo") Author.objects.create(name="Bar") def test_alter_autofield_pk_to_bigautofield_pk(self): with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name="Foo", pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql( no_style(), [Author] ) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) self.assertIsNotNone(Author.objects.create(name="Bar")) def test_alter_autofield_pk_to_smallautofield_pk(self): with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = SmallAutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name="Foo", pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql( no_style(), [Author] ) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) self.assertIsNotNone(Author.objects.create(name="Bar")) def test_alter_int_pk_to_autofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to AutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field("i") new_field = AutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # A model representing the updated model. class IntegerPKToAutoField(Model): i = AutoField(primary_key=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = IntegerPK._meta.db_table # An id (i) is generated by the database. obj = IntegerPKToAutoField.objects.create(j=1) self.assertIsNotNone(obj.i) def test_alter_int_pk_to_bigautofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to BigAutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field("i") new_field = BigAutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # A model representing the updated model. class IntegerPKToBigAutoField(Model): i = BigAutoField(primary_key=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = IntegerPK._meta.db_table # An id (i) is generated by the database. obj = IntegerPKToBigAutoField.objects.create(j=1) self.assertIsNotNone(obj.i) @isolate_apps("schema") def test_alter_smallint_pk_to_smallautofield_pk(self): """ Should be able to rename an SmallIntegerField(primary_key=True) to SmallAutoField(primary_key=True). """ class SmallIntegerPK(Model): i = SmallIntegerField(primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(SmallIntegerPK) self.isolated_local_models = [SmallIntegerPK] old_field = SmallIntegerPK._meta.get_field("i") new_field = SmallAutoField(primary_key=True) new_field.model = SmallIntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(SmallIntegerPK, old_field, new_field, strict=True) def test_alter_int_pk_to_int_unique(self): """ Should be able to rename an IntegerField(primary_key=True) to IntegerField(unique=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) # Delete the old PK old_field = IntegerPK._meta.get_field("i") new_field = IntegerField(unique=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # The primary key constraint is gone. Result depends on database: # 'id' for SQLite, None for others (must not be 'i'). self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ("id", None)) # Set up a model class as it currently stands. The original IntegerPK # class is now out of date and some backends make use of the whole # model class when modifying a field (such as sqlite3 when remaking a # table) so an outdated model class leads to incorrect results. class Transitional(Model): i = IntegerField(unique=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = "INTEGERPK" # model requires a new PK old_field = Transitional._meta.get_field("j") new_field = IntegerField(primary_key=True) new_field.model = Transitional new_field.set_attributes_from_name("j") with connection.schema_editor() as editor: editor.alter_field(Transitional, old_field, new_field, strict=True) # Create a model class representing the updated model. class IntegerUnique(Model): i = IntegerField(unique=True) j = IntegerField(primary_key=True) class Meta: app_label = "schema" apps = new_apps db_table = "INTEGERPK" # Ensure unique constraint works. IntegerUnique.objects.create(i=1, j=1) with self.assertRaises(IntegrityError): IntegerUnique.objects.create(i=1, j=2) def test_rename(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) self.assertNotIn("display_name", columns) # Alter the name field's name old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("display_name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertEqual( columns["display_name"][0], connection.features.introspected_field_types["CharField"], ) self.assertNotIn("name", columns) @isolate_apps("schema") def test_rename_referenced_field(self): class Author(Model): name = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE, to_field="name") class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) # Ensure the foreign key reference was updated. self.assertForeignKeyExists(Book, "author_id", "schema_author", "renamed") @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_rename_keep_null_status(self): """ Renaming a field shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = TextField() new_field.set_attributes_from_name("detail_info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns["detail_info"][0], "TextField") self.assertNotIn("info", columns) with self.assertRaises(IntegrityError): NoteRename.objects.create(detail_info=None) def _test_m2m_create(self, M2MFieldClass): """ Tests M2M fields on models during creation """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2M) # Ensure there is now an m2m table there columns = self.column_classes( LocalBookWithM2M._meta.get_field("tags").remote_field.through ) self.assertEqual( columns["tagm2mtest_id"][0], connection.features.introspected_field_types["IntegerField"], ) def test_m2m_create(self): self._test_m2m_create(ManyToManyField) def test_m2m_create_custom(self): self._test_m2m_create(CustomManyToManyField) def test_m2m_create_inherited(self): self._test_m2m_create(InheritedManyToManyField) def _test_m2m_create_through(self, M2MFieldClass): """ Tests M2M fields on models during creation with through models """ class LocalTagThrough(Model): book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalBookWithM2MThrough(Model): tags = M2MFieldClass( "TagM2MTest", related_name="books", through=LocalTagThrough ) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalTagThrough, LocalBookWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalTagThrough) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2MThrough) # Ensure there is now an m2m table there columns = self.column_classes(LocalTagThrough) self.assertEqual( columns["book_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertEqual( columns["tag_id"][0], connection.features.introspected_field_types["IntegerField"], ) def test_m2m_create_through(self): self._test_m2m_create_through(ManyToManyField) def test_m2m_create_through_custom(self): self._test_m2m_create_through(CustomManyToManyField) def test_m2m_create_through_inherited(self): self._test_m2m_create_through(InheritedManyToManyField) def test_m2m_through_remove(self): class LocalAuthorNoteThrough(Model): book = ForeignKey("schema.Author", CASCADE) tag = ForeignKey("self", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalNoteWithM2MThrough(Model): authors = ManyToManyField("schema.Author", through=LocalAuthorNoteThrough) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorNoteThrough, LocalNoteWithM2MThrough] # Create the tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalAuthorNoteThrough) editor.create_model(LocalNoteWithM2MThrough) # Remove the through parameter. old_field = LocalNoteWithM2MThrough._meta.get_field("authors") new_field = ManyToManyField("Author") new_field.set_attributes_from_name("authors") msg = ( f"Cannot alter field {old_field} into {new_field} - they are not " f"compatible types (you cannot alter to or from M2M fields, or add or " f"remove through= on M2M fields)" ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.alter_field(LocalNoteWithM2MThrough, old_field, new_field) def _test_m2m(self, M2MFieldClass): """ Tests adding/removing M2M fields on models """ class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorWithM2M) editor.create_model(TagM2MTest) # Create an M2M field new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors") new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) # Ensure there is now an m2m table there columns = self.column_classes(new_field.remote_field.through) self.assertEqual( columns["tagm2mtest_id"][0], connection.features.introspected_field_types["IntegerField"], ) # "Alter" the field. This should not rename the DB table to itself. with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True) # Remove the M2M table again with connection.schema_editor() as editor: editor.remove_field(LocalAuthorWithM2M, new_field) # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Make sure the model state is coherent with the table one now that # we've removed the tags field. opts = LocalAuthorWithM2M._meta opts.local_many_to_many.remove(new_field) del new_apps.all_models["schema"][ new_field.remote_field.through._meta.model_name ] opts._expire_cache() def test_m2m(self): self._test_m2m(ManyToManyField) def test_m2m_custom(self): self._test_m2m(CustomManyToManyField) def test_m2m_inherited(self): self._test_m2m(InheritedManyToManyField) def _test_m2m_through_alter(self, M2MFieldClass): """ Tests altering M2Ms with explicit through models (should no-op) """ class LocalAuthorTag(Model): author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalAuthorWithM2MThrough(Model): name = CharField(max_length=255) tags = M2MFieldClass( "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag ) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorTag) editor.create_model(LocalAuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags") new_field = M2MFieldClass( "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag ) new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags") with connection.schema_editor() as editor: editor.alter_field( LocalAuthorWithM2MThrough, old_field, new_field, strict=True ) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) def test_m2m_through_alter(self): self._test_m2m_through_alter(ManyToManyField) def test_m2m_through_alter_custom(self): self._test_m2m_through_alter(CustomManyToManyField) def test_m2m_through_alter_inherited(self): self._test_m2m_through_alter(InheritedManyToManyField) def _test_m2m_repoint(self, M2MFieldClass): """ Tests repointing M2M fields """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( LocalBookWithM2M._meta.get_field("tags").remote_field.through, "tagm2mtest_id", "schema_tagm2mtest", ) # Repoint the M2M old_field = LocalBookWithM2M._meta.get_field("tags") new_field = M2MFieldClass(UniqueTest) new_field.contribute_to_class(LocalBookWithM2M, "uniques") with connection.schema_editor() as editor: editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True) # Ensure old M2M is gone with self.assertRaises(DatabaseError): self.column_classes( LocalBookWithM2M._meta.get_field("tags").remote_field.through ) # This model looks like the new model and is used for teardown. opts = LocalBookWithM2M._meta opts.local_many_to_many.remove(old_field) # Ensure the new M2M exists and points to UniqueTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( new_field.remote_field.through, "uniquetest_id", "schema_uniquetest" ) def test_m2m_repoint(self): self._test_m2m_repoint(ManyToManyField) def test_m2m_repoint_custom(self): self._test_m2m_repoint(CustomManyToManyField) def test_m2m_repoint_inherited(self): self._test_m2m_repoint(InheritedManyToManyField) @isolate_apps("schema") def test_m2m_rename_field_in_target_model(self): class LocalTagM2MTest(Model): title = CharField(max_length=255) class Meta: app_label = "schema" class LocalM2M(Model): tags = ManyToManyField(LocalTagM2MTest) class Meta: app_label = "schema" # Create the tables. with connection.schema_editor() as editor: editor.create_model(LocalM2M) editor.create_model(LocalTagM2MTest) self.isolated_local_models = [LocalM2M, LocalTagM2MTest] # Ensure the m2m table is there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) # Alter a field in LocalTagM2MTest. old_field = LocalTagM2MTest._meta.get_field("title") new_field = CharField(max_length=254) new_field.contribute_to_class(LocalTagM2MTest, "title1") # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True) # Ensure the m2m table is still there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_check_constraints(self): """ Tests creating/deleting CHECK constraints """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the constraint exists constraints = self.get_constraints(Author._meta.db_table) if not any( details["columns"] == ["height"] and details["check"] for details in constraints.values() ): self.fail("No check constraint for height found") # Alter the column to remove it old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) for details in constraints.values(): if details["columns"] == ["height"] and details["check"]: self.fail("Check constraint for height found") # Alter the column to re-add it new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) if not any( details["columns"] == ["height"] and details["check"] for details in constraints.values() ): self.fail("No check constraint for height found") @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) @isolate_apps("schema") def test_check_constraint_timedelta_param(self): class DurationModel(Model): duration = DurationField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(DurationModel) self.isolated_local_models = [DurationModel] constraint_name = "duration_gte_5_minutes" constraint = CheckConstraint( check=Q(duration__gt=datetime.timedelta(minutes=5)), name=constraint_name, ) DurationModel._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(DurationModel, constraint) constraints = self.get_constraints(DurationModel._meta.db_table) self.assertIn(constraint_name, constraints) with self.assertRaises(IntegrityError), atomic(): DurationModel.objects.create(duration=datetime.timedelta(minutes=4)) DurationModel.objects.create(duration=datetime.timedelta(minutes=10)) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_remove_field_check_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add the custom check constraint constraint = CheckConstraint( check=Q(height__gte=0), name="author_height_gte_0_check" ) custom_constraint_name = constraint.name Author._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) # Ensure the constraints exist constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field check old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field check new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the check constraint with connection.schema_editor() as editor: Author._meta.constraints = [] editor.remove_constraint(Author, constraint) def test_unique(self): """ Tests removing and adding unique constraints to a single column. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the field is unique to begin with Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be non-unique old_field = Tag._meta.get_field("slug") new_field = SlugField(unique=False) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) # Ensure the field is no longer unique Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be unique new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) # Ensure the field is unique again Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Rename the field new_field3 = SlugField(unique=True) new_field3.set_attributes_from_name("slug2") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field2, new_field3, strict=True) # Ensure the field is still unique TagUniqueRename.objects.create(title="foo", slug2="foo") with self.assertRaises(IntegrityError): TagUniqueRename.objects.create(title="bar", slug2="foo") Tag.objects.all().delete() def test_unique_name_quoting(self): old_table_name = TagUniqueRename._meta.db_table try: with connection.schema_editor() as editor: editor.create_model(TagUniqueRename) editor.alter_db_table(TagUniqueRename, old_table_name, "unique-table") TagUniqueRename._meta.db_table = "unique-table" # This fails if the unique index name isn't quoted. editor.alter_unique_together(TagUniqueRename, [], (("title", "slug2"),)) finally: with connection.schema_editor() as editor: editor.delete_model(TagUniqueRename) TagUniqueRename._meta.db_table = old_table_name @isolate_apps("schema") @skipUnlessDBFeature("supports_foreign_keys") def test_unique_no_unnecessary_fk_drops(self): """ If AlterField isn't selective about dropping foreign key constraints when modifying a field with a unique constraint, the AlterField incorrectly drops and recreates the Book.author foreign key even though it doesn't restrict the field being changed (#29193). """ class Author(Model): name = CharField(max_length=254, unique=True) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.model = Author new_field.set_attributes_from_name("name") with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: with connection.schema_editor() as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) @isolate_apps("schema") def test_unique_and_reverse_m2m(self): """ AlterField can modify a unique field when there's a reverse M2M relation on the model. """ class Tag(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = "schema" class Book(Model): tags = ManyToManyField(Tag, related_name="books") class Meta: app_label = "schema" self.isolated_local_models = [Book._meta.get_field("tags").remote_field.through] with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Book) new_field = SlugField(max_length=75, unique=True) new_field.model = Tag new_field.set_attributes_from_name("slug") with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: with connection.schema_editor() as editor: editor.alter_field(Tag, Tag._meta.get_field("slug"), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) # Ensure that the field is still unique. Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_field_unique_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueName) self.local_models = [AuthorWithUniqueName] # Add the custom unique constraint constraint = UniqueConstraint(fields=["name"], name="author_name_uniq") custom_constraint_name = constraint.name AuthorWithUniqueName._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueName, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field uniqueness old_field = AuthorWithUniqueName._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field uniqueness new_field2 = AuthorWithUniqueName._meta.get_field("name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueName._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueName, constraint) def test_unique_together(self): """ Tests removing and adding unique_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(UniqueTest) # Ensure the fields are unique to begin with UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2011, slug="foo") UniqueTest.objects.create(year=2011, slug="bar") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter the model to its non-unique-together companion with connection.schema_editor() as editor: editor.alter_unique_together( UniqueTest, UniqueTest._meta.unique_together, [] ) # Ensure the fields are no longer unique UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_unique_together( UniqueTest, [], UniqueTest._meta.unique_together ) # Ensure the fields are unique again UniqueTest.objects.create(year=2012, slug="foo") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() def test_unique_together_with_fk(self): """ Tests removing and adding unique_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [["author", "title"]], []) def test_unique_together_with_fk_with_existing_index(self): """ Tests removing and adding unique_together constraints that include a foreign key, where the foreign key is added after the model is created. """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithoutAuthor) new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") editor.add_field(BookWithoutAuthor, new_field) # Ensure the fields aren't unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [["author", "title"]], []) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueNameAndBirthday) self.local_models = [AuthorWithUniqueNameAndBirthday] # Add the custom unique constraint constraint = UniqueConstraint( fields=["name", "birthday"], name="author_name_birthday_uniq" ) custom_constraint_name = constraint.name AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint) # Ensure the constraints exist constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Remove unique together unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together with connection.schema_editor() as editor: editor.alter_unique_together( AuthorWithUniqueNameAndBirthday, unique_together, [] ) constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Re-add unique together with connection.schema_editor() as editor: editor.alter_unique_together( AuthorWithUniqueNameAndBirthday, [], unique_together ) constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueNameAndBirthday._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint) def test_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(fields=["name"], name="name_uq") # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table self.assertIs(sql.references_table(table), True) self.assertIs(sql.references_column(table, "name"), True) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(Upper("name").desc(), name="func_upper_uq") # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC"]) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains a database function. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) constraint = UniqueConstraint( Upper("title"), Lower("slug"), name="func_upper_lower_unq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(BookWithSlug, constraint) sql = constraint.create_sql(BookWithSlug, editor) table = BookWithSlug._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains database functions. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) sql = str(sql) self.assertIn("UPPER(%s)" % editor.quote_name("title"), sql) self.assertIn("LOWER(%s)" % editor.quote_name("slug"), sql) self.assertLess(sql.index("UPPER"), sql.index("LOWER")) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(BookWithSlug, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_unique_constraint_field_and_expression(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( F("height").desc(), "uuid", Lower("name").asc(), name="func_f_lower_field_unq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC", "ASC", "ASC"]) constraints = self.get_constraints(table) self.assertIs(constraints[constraint.name]["unique"], True) self.assertEqual(len(constraints[constraint.name]["columns"]), 3) self.assertEqual(constraints[constraint.name]["columns"][1], "uuid") # SQL contains database functions and columns. self.assertIs(sql.references_column(table, "height"), True) self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "uuid"), True) self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_partial_indexes") def test_func_unique_constraint_partial(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( Upper("name"), name="func_upper_cond_weight_uq", condition=Q(weight__isnull=False), ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) self.assertIs(sql.references_column(table, "name"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) self.assertIn( "WHERE %s IS NOT NULL" % editor.quote_name("weight"), str(sql), ) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_covering_indexes") def test_func_unique_constraint_covering(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( Upper("name"), name="func_upper_covering_uq", include=["weight", "height"], ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) self.assertEqual( constraints[constraint.name]["columns"], [None, "weight", "height"], ) self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) self.assertIs(sql.references_column(table, "height"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) self.assertIn( "INCLUDE (%s, %s)" % ( editor.quote_name("weight"), editor.quote_name("height"), ), str(sql), ) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_lookups(self): with connection.schema_editor() as editor: editor.create_model(Author) with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs): constraint = UniqueConstraint( F("name__lower"), F("weight__abs"), name="func_lower_abs_lookup_uq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains columns. self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_collate(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) constraint = UniqueConstraint( Collate(F("title"), collation=collation).desc(), Collate("slug", collation=collation), name="func_collate_uq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(BookWithSlug, constraint) sql = constraint.create_sql(BookWithSlug, editor) table = BookWithSlug._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC", "ASC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(BookWithSlug, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipIfDBFeature("supports_expression_indexes") def test_func_unique_constraint_unsupported(self): # UniqueConstraint is ignored on databases that don't support indexes on # expressions. with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(F("name"), name="func_name_uq") with connection.schema_editor() as editor, self.assertNumQueries(0): self.assertIsNone(editor.add_constraint(Author, constraint)) self.assertIsNone(editor.remove_constraint(Author, constraint)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_nonexistent_field(self): constraint = UniqueConstraint(Lower("nonexistent"), name="func_nonexistent_uq") msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: " "height, id, name, uuid, weight" ) with self.assertRaisesMessage(FieldError, msg): with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_nondeterministic(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(Random(), name="func_random_uq") with connection.schema_editor() as editor: with self.assertRaises(DatabaseError): editor.add_constraint(Author, constraint) def test_index_together(self): """ Tests removing and adding index_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure there's no index on the year/slug columns first self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), False, ) # Alter the model to add an index with connection.schema_editor() as editor: editor.alter_index_together(Tag, [], [("slug", "title")]) # Ensure there is now an index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), True, ) # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_index_together(Tag, [("slug", "title")], []) # Ensure there's no index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), False, ) def test_index_together_with_fk(self): """ Tests removing and adding index_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.index_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_index_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_index_together(Book, [["author", "title"]], []) @isolate_apps("schema") def test_create_index_together(self): """ Tests creating models with index_together already defined """ class TagIndexed(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = "schema" index_together = [["slug", "title"]] # Create the table with connection.schema_editor() as editor: editor.create_model(TagIndexed) self.isolated_local_models = [TagIndexed] # Ensure there is an index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tagindexed").values() if c["columns"] == ["slug", "title"] ), True, ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") @isolate_apps("schema") def test_remove_index_together_does_not_remove_meta_indexes(self): class AuthorWithIndexedNameAndBirthday(Model): name = CharField(max_length=255) birthday = DateField() class Meta: app_label = "schema" index_together = [["name", "birthday"]] with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedNameAndBirthday) self.isolated_local_models = [AuthorWithIndexedNameAndBirthday] # Add the custom index index = Index(fields=["name", "birthday"], name="author_name_birthday_idx") custom_index_name = index.name AuthorWithIndexedNameAndBirthday._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedNameAndBirthday, index) # Ensure the indexes exist constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Remove index together index_together = AuthorWithIndexedNameAndBirthday._meta.index_together with connection.schema_editor() as editor: editor.alter_index_together( AuthorWithIndexedNameAndBirthday, index_together, [] ) constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 0) # Re-add index together with connection.schema_editor() as editor: editor.alter_index_together( AuthorWithIndexedNameAndBirthday, [], index_together ) constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Drop the index with connection.schema_editor() as editor: AuthorWithIndexedNameAndBirthday._meta.indexes = [] editor.remove_index(AuthorWithIndexedNameAndBirthday, index) @isolate_apps("schema") def test_db_table(self): """ Tests renaming of the table """ class Author(Model): name = CharField(max_length=255) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" # Create the table and one referring it. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) # Alter the table with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_db_table(Author, "schema_author", "schema_otherauthor") Author._meta.db_table = "schema_otherauthor" columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) # Ensure the foreign key reference was updated self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor") # Alter the table again with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_db_table(Author, "schema_otherauthor", "schema_author") # Ensure the table is still there Author._meta.db_table = "schema_author" columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) def test_add_remove_index(self): """ Tests index addition and removal """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the table is there and has no index self.assertNotIn("title", self.get_indexes(Author._meta.db_table)) # Add the index index = Index(fields=["name"], name="author_title_idx") with connection.schema_editor() as editor: editor.add_index(Author, index) self.assertIn("name", self.get_indexes(Author._meta.db_table)) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn("name", self.get_indexes(Author._meta.db_table)) def test_remove_db_index_doesnt_remove_custom_indexes(self): """ Changing db_index to False doesn't remove indexes from Meta.indexes. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedName) self.local_models = [AuthorWithIndexedName] # Ensure the table has its index self.assertIn("name", self.get_indexes(AuthorWithIndexedName._meta.db_table)) # Add the custom index index = Index(fields=["-name"], name="author_name_idx") author_index_name = index.name with connection.schema_editor() as editor: db_index_name = editor._create_index_name( table_name=AuthorWithIndexedName._meta.db_table, column_names=("name",), ) try: AuthorWithIndexedName._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedName, index) old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertIn(author_index_name, old_constraints) self.assertIn(db_index_name, old_constraints) # Change name field to db_index=False old_field = AuthorWithIndexedName._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field( AuthorWithIndexedName, old_field, new_field, strict=True ) new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertNotIn(db_index_name, new_constraints) # The index from Meta.indexes is still in the database. self.assertIn(author_index_name, new_constraints) # Drop the index with connection.schema_editor() as editor: editor.remove_index(AuthorWithIndexedName, index) finally: AuthorWithIndexedName._meta.indexes = [] def test_order_index(self): """ Indexes defined with ordering (ASC/DESC) defined on column """ with connection.schema_editor() as editor: editor.create_model(Author) # The table doesn't have an index self.assertNotIn("title", self.get_indexes(Author._meta.db_table)) index_name = "author_name_idx" # Add the index index = Index(fields=["name", "-weight"], name=index_name) with connection.schema_editor() as editor: editor.add_index(Author, index) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Author._meta.db_table, index_name, ["ASC", "DESC"]) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) def test_indexes(self): """ Tests creation/altering of indexes """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there and has the right index self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to remove the index old_field = Book._meta.get_field("title") new_field = CharField(max_length=100, db_index=False) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the table is there and has no index self.assertNotIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to re-add the index new_field2 = Book._meta.get_field("title") with connection.schema_editor() as editor: editor.alter_field(Book, new_field, new_field2, strict=True) # Ensure the table is there and has the index again self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Add a unique column, verify that creates an implicit index new_field3 = BookWithSlug._meta.get_field("slug") with connection.schema_editor() as editor: editor.add_field(Book, new_field3) self.assertIn( "slug", self.get_uniques(Book._meta.db_table), ) # Remove the unique, check the index goes with it new_field4 = CharField(max_length=20, unique=False) new_field4.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True) self.assertNotIn( "slug", self.get_uniques(Book._meta.db_table), ) def test_text_field_with_db_index(self): with connection.schema_editor() as editor: editor.create_model(AuthorTextFieldWithIndex) # The text_field index is present if the database supports it. assertion = ( self.assertIn if connection.features.supports_index_on_text_field else self.assertNotIn ) assertion( "text_field", self.get_indexes(AuthorTextFieldWithIndex._meta.db_table) ) def _index_expressions_wrappers(self): index_expression = IndexExpression() index_expression.set_wrapper_classes(connection) return ", ".join( [ wrapper_cls.__qualname__ for wrapper_cls in index_expression.wrapper_classes ] ) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_multiple_wrapper_references(self): index = Index(OrderBy(F("name").desc(), descending=True), name="name") msg = ( "Multiple references to %s can't be used in an indexed expression." % self._index_expressions_wrappers() ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_invalid_topmost_expressions(self): index = Index(Upper(F("name").desc()), name="name") msg = ( "%s must be topmost expressions in an indexed expression." % self._index_expressions_wrappers() ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Lower("name").desc(), name="func_lower_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC"]) # SQL contains a database function. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_f(self): with connection.schema_editor() as editor: editor.create_model(Tag) index = Index("slug", F("title").desc(), name="func_f_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Tag, index) sql = index.create_sql(Tag, editor) table = Tag._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Tag._meta.db_table, index.name, ["ASC", "DESC"]) # SQL contains columns. self.assertIs(sql.references_column(table, "slug"), True) self.assertIs(sql.references_column(table, "title"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Tag, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_lookups(self): with connection.schema_editor() as editor: editor.create_model(Author) with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs): index = Index( F("name__lower"), F("weight__abs"), name="func_lower_abs_lookup_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains columns. self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_index(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Lower("name"), Upper("name"), name="func_lower_upper_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains database functions. self.assertIs(sql.references_column(table, "name"), True) sql = str(sql) self.assertIn("LOWER(%s)" % editor.quote_name("name"), sql) self.assertIn("UPPER(%s)" % editor.quote_name("name"), sql) self.assertLess(sql.index("LOWER"), sql.index("UPPER")) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_index_field_and_expression(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) index = Index( F("author").desc(), Lower("title").asc(), "pub_date", name="func_f_lower_field_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Book, index) sql = index.create_sql(Book, editor) table = Book._meta.db_table constraints = self.get_constraints(table) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC", "ASC", "ASC"]) self.assertEqual(len(constraints[index.name]["columns"]), 3) self.assertEqual(constraints[index.name]["columns"][2], "pub_date") # SQL contains database functions and columns. self.assertIs(sql.references_column(table, "author_id"), True) self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "pub_date"), True) self.assertIn("LOWER(%s)" % editor.quote_name("title"), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") @isolate_apps("schema") def test_func_index_f_decimalfield(self): class Node(Model): value = DecimalField(max_digits=5, decimal_places=2) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Node) index = Index(F("value"), name="func_f_decimalfield_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Node, index) sql = index.create_sql(Node, editor) table = Node._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "value"), True) # SQL doesn't contain casting. self.assertNotIn("CAST", str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Node, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_cast(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Cast("weight", FloatField()), name="func_cast_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "weight"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_collate(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) index = Index( Collate(F("title"), collation=collation).desc(), Collate("slug", collation=collation), name="func_collate_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(BookWithSlug, index) sql = index.create_sql(BookWithSlug, editor) table = Book._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC", "ASC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") @skipIfDBFeature("collate_as_index_expression") def test_func_index_collate_f_ordered(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) index = Index( Collate(F("name").desc(), collation=collation), name="func_collate_f_desc_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_calc(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(F("height") / (F("weight") + Value(5)), name="func_calc_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains columns and expressions. self.assertIs(sql.references_column(table, "height"), True) self.assertIs(sql.references_column(table, "weight"), True) sql = str(sql) self.assertIs( sql.index(editor.quote_name("height")) < sql.index("/") < sql.index(editor.quote_name("weight")) < sql.index("+") < sql.index("5"), True, ) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field") @isolate_apps("schema") def test_func_index_json_key_transform(self): class JSONModel(Model): field = JSONField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(JSONModel) self.isolated_local_models = [JSONModel] index = Index("field__some_key", name="func_json_key_idx") with connection.schema_editor() as editor: editor.add_index(JSONModel, index) sql = index.create_sql(JSONModel, editor) table = JSONModel._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "field"), True) with connection.schema_editor() as editor: editor.remove_index(JSONModel, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field") @isolate_apps("schema") def test_func_index_json_key_transform_cast(self): class JSONModel(Model): field = JSONField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(JSONModel) self.isolated_local_models = [JSONModel] index = Index( Cast(KeyTextTransform("some_key", "field"), IntegerField()), name="func_json_key_cast_idx", ) with connection.schema_editor() as editor: editor.add_index(JSONModel, index) sql = index.create_sql(JSONModel, editor) table = JSONModel._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "field"), True) with connection.schema_editor() as editor: editor.remove_index(JSONModel, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipIfDBFeature("supports_expression_indexes") def test_func_index_unsupported(self): # Index is ignored on databases that don't support indexes on # expressions. with connection.schema_editor() as editor: editor.create_model(Author) index = Index(F("name"), name="random_idx") with connection.schema_editor() as editor, self.assertNumQueries(0): self.assertIsNone(editor.add_index(Author, index)) self.assertIsNone(editor.remove_index(Author, index)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_nonexistent_field(self): index = Index(Lower("nonexistent"), name="func_nonexistent_idx") msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: " "height, id, name, uuid, weight" ) with self.assertRaisesMessage(FieldError, msg): with connection.schema_editor() as editor: editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_nondeterministic(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Random(), name="func_random_idx") with connection.schema_editor() as editor: with self.assertRaises(DatabaseError): editor.add_index(Author, index) def test_primary_key(self): """ Tests altering of the primary key """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the table is there and has the right PK self.assertEqual(self.get_primary_key(Tag._meta.db_table), "id") # Alter to change the PK id_field = Tag._meta.get_field("id") old_field = Tag._meta.get_field("slug") new_field = SlugField(primary_key=True) new_field.set_attributes_from_name("slug") new_field.model = Tag with connection.schema_editor() as editor: editor.remove_field(Tag, id_field) editor.alter_field(Tag, old_field, new_field) # Ensure the PK changed self.assertNotIn( "id", self.get_indexes(Tag._meta.db_table), ) self.assertEqual(self.get_primary_key(Tag._meta.db_table), "slug") def test_alter_primary_key_the_same_name(self): with connection.schema_editor() as editor: editor.create_model(Thing) old_field = Thing._meta.get_field("when") new_field = CharField(max_length=2, primary_key=True) new_field.set_attributes_from_name("when") new_field.model = Thing with connection.schema_editor() as editor: editor.alter_field(Thing, old_field, new_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") with connection.schema_editor() as editor: editor.alter_field(Thing, new_field, old_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") def test_context_manager_exit(self): """ Ensures transaction is correctly closed when an error occurs inside a SchemaEditor context. """ class SomeError(Exception): pass try: with connection.schema_editor(): raise SomeError except SomeError: self.assertFalse(connection.in_atomic_block) @skipIfDBFeature("can_rollback_ddl") def test_unsupported_transactional_ddl_disallowed(self): message = ( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) with atomic(), connection.schema_editor() as editor: with self.assertRaisesMessage(TransactionManagementError, message): editor.execute( editor.sql_create_table % {"table": "foo", "definition": ""} ) @skipUnlessDBFeature("supports_foreign_keys", "indexes_foreign_keys") def test_foreign_key_index_long_names_regression(self): """ Regression test for #21497. Only affects databases that supports foreign keys. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Find the properly shortened column name column_name = connection.ops.quote_name( "author_foreign_key_with_really_long_field_name_id" ) column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase # Ensure the table is there and has an index on the column self.assertIn( column_name, self.get_indexes(BookWithLongName._meta.db_table), ) @skipUnlessDBFeature("supports_foreign_keys") def test_add_foreign_key_long_names(self): """ Regression test for #23009. Only affects databases that supports foreign keys. """ # Create the initial tables with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Add a second FK, this would fail due to long ref name before the fix new_field = ForeignKey( AuthorWithEvenLongerName, CASCADE, related_name="something" ) new_field.set_attributes_from_name( "author_other_really_long_named_i_mean_so_long_fk" ) with connection.schema_editor() as editor: editor.add_field(BookWithLongName, new_field) @isolate_apps("schema") @skipUnlessDBFeature("supports_foreign_keys") def test_add_foreign_key_quoted_db_table(self): class Author(Model): class Meta: db_table = '"table_author_double_quoted"' app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) self.isolated_local_models = [Author] if connection.vendor == "mysql": self.assertForeignKeyExists( Book, "author_id", '"table_author_double_quoted"' ) else: self.assertForeignKeyExists(Book, "author_id", "table_author_double_quoted") def test_add_foreign_object(self): with connection.schema_editor() as editor: editor.create_model(BookForeignObj) self.local_models = [BookForeignObj] new_field = ForeignObject( Author, on_delete=CASCADE, from_fields=["author_id"], to_fields=["id"] ) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.add_field(BookForeignObj, new_field) def test_creation_deletion_reserved_names(self): """ Tries creating a model's table, and then deleting it when it has a SQL reserved name. """ # Create the table with connection.schema_editor() as editor: try: editor.create_model(Thing) except OperationalError as e: self.fail( "Errors when applying initial migration for a model " "with a table named after an SQL reserved word: %s" % e ) # The table is there list(Thing.objects.all()) # Clean up that table with connection.schema_editor() as editor: editor.delete_model(Thing) # The table is gone with self.assertRaises(DatabaseError): list(Thing.objects.all()) def test_remove_constraints_capital_letters(self): """ #23065 - Constraint names must be quoted if they contain capital letters. """ def get_field(*args, field_class=IntegerField, **kwargs): kwargs["db_column"] = "CamelCase" field = field_class(*args, **kwargs) field.set_attributes_from_name("CamelCase") return field model = Author field = get_field() table = model._meta.db_table column = field.column identifier_converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: editor.create_model(model) editor.add_field(model, field) constraint_name = "CamelCaseIndex" expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_index % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "using": "", "columns": editor.quote_name(column), "extra": "", "condition": "", "include": "", } ) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field(model, get_field(db_index=True), field, strict=True) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) constraint_name = "CamelCaseUniqConstraint" expected_constraint_name = identifier_converter(constraint_name) editor.execute(editor._create_unique_sql(model, [field], constraint_name)) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field(model, get_field(unique=True), field, strict=True) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) if editor.sql_create_fk and connection.features.can_introspect_foreign_keys: constraint_name = "CamelCaseFKConstraint" expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_fk % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "column": editor.quote_name(column), "to_table": editor.quote_name(table), "to_column": editor.quote_name(model._meta.auto_field.column), "deferrable": connection.ops.deferrable_sql(), } ) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field( model, get_field(Author, CASCADE, field_class=ForeignKey), field, strict=True, ) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) def test_add_field_use_effective_default(self): """ #23987 - effective_default() should be used as the field default when adding a new field. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name="Anonymous1") # Add new CharField to ensure default will be used from effective_default new_field = CharField(max_length=15, blank=True) new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual( item[0], None if connection.features.interprets_empty_strings_as_nulls else "", ) def test_add_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name="Anonymous1") # Add new CharField with a default new_field = CharField(max_length=15, blank=True, default="surname default") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], "surname default") # And that the default is no longer set in the database. field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author" ) if f.name == "surname" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_add_field_default_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add new nullable CharField with a default. new_field = CharField(max_length=15, blank=True, null=True, default="surname") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) Author.objects.create(name="Anonymous1") with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertIsNone(item[0]) field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author", ) if f.name == "surname" ) # Field is still nullable. self.assertTrue(field.null_ok) # The database default is no longer set. if connection.features.can_introspect_default: self.assertIn(field.default, ["NULL", None]) def test_add_textfield_default_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add new nullable TextField with a default. new_field = TextField(blank=True, null=True, default="text") new_field.set_attributes_from_name("description") with connection.schema_editor() as editor: editor.add_field(Author, new_field) Author.objects.create(name="Anonymous1") with connection.cursor() as cursor: cursor.execute("SELECT description FROM schema_author;") item = cursor.fetchall()[0] self.assertIsNone(item[0]) field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author", ) if f.name == "description" ) # Field is still nullable. self.assertTrue(field.null_ok) # The database default is no longer set. if connection.features.can_introspect_default: self.assertIn(field.default, ["NULL", None]) def test_alter_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name="Anonymous1") self.assertIsNone(Author.objects.get().height) old_field = Author._meta.get_field("height") # The default from the new field is used in updating existing rows. new_field = IntegerField(blank=True, default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(Author.objects.get().height, 42) # The database default should be removed. with connection.cursor() as cursor: field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author" ) if f.name == "height" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_alter_field_default_doesnt_perform_queries(self): """ No queries are performed if a field default changes and the field's not changing from null to non-null. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) old_field = AuthorWithDefaultHeight._meta.get_field("height") new_default = old_field.default * 2 new_field = PositiveIntegerField(null=True, blank=True, default=new_default) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field( AuthorWithDefaultHeight, old_field, new_field, strict=True ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_fk_attributes_noop(self): """ No queries are performed when changing field attributes that don't affect the schema. """ with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_field = Book._meta.get_field("author") new_field = ForeignKey( Author, blank=True, editable=False, error_messages={"invalid": "error message"}, help_text="help text", limit_choices_to={"limit": "choice"}, on_delete=PROTECT, related_name="related_name", related_query_name="related_query_name", validators=[lambda x: x], verbose_name="verbose name", ) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Book, old_field, new_field, strict=True) with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Book, new_field, old_field, strict=True) def test_alter_field_choices_noop(self): with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("name") new_field = CharField( choices=(("Jane", "Jane"), ("Joe", "Joe")), max_length=255, ) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Author, old_field, new_field, strict=True) with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Author, new_field, old_field, strict=True) def test_add_textfield_unhashable_default(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name="Anonymous1") # Create a field that has an unhashable default new_field = TextField(default={}) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.add_field(Author, new_field) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_add_indexed_charfield(self): field = CharField(max_length=255, db_index=True) field.set_attributes_from_name("nom_de_plume") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, "nom_de_plume"), [ "schema_author_nom_de_plume_7570a851", "schema_author_nom_de_plume_7570a851_like", ], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_add_unique_charfield(self): field = CharField(max_length=255, unique=True) field.set_attributes_from_name("nom_de_plume") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, "nom_de_plume"), [ "schema_author_nom_de_plume_7570a851_like", "schema_author_nom_de_plume_key", ], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_index_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) # Alter to add db_index=True and create 2 indexes. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_index=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "name"), ["schema_author_name_1fbc5617", "schema_author_name_1fbc5617_like"], ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_unique_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) # Alter to add unique=True and create 2 indexes. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "name"), ["schema_author_name_1fbc5617_like", "schema_author_name_1fbc5617_uniq"], ) # Remove unique=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_index_to_textfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Note) self.assertEqual(self.get_constraints_for_column(Note, "info"), []) # Alter to add db_index=True and create 2 indexes. old_field = Note._meta.get_field("info") new_field = TextField(db_index=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Note, "info"), ["schema_note_info_4b0ea695", "schema_note_info_4b0ea695_like"], ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Note, "info"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_unique_to_charfield_with_db_index(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to remove unique=True (should drop unique index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_remove_unique_and_db_index_from_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to remove both unique=True and db_index=True (should drop all indexes) new_field2 = CharField(max_length=100) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), [] ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_swap_unique_and_db_index_with_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to set unique=True and remove db_index=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to set db_index=True and remove unique=True (should restore index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_db_index_to_charfield_with_unique(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(Tag) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) # Alter to add db_index=True old_field = Tag._meta.get_field("slug") new_field = SlugField(db_index=True, unique=True) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) # Alter to remove db_index=True new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) def test_alter_field_add_index_to_integerfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "weight"), []) # Alter to add db_index=True and create index. old_field = Author._meta.get_field("weight") new_field = IntegerField(null=True, db_index=True) new_field.set_attributes_from_name("weight") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "weight"), ["schema_author_weight_587740f9"], ) # Remove db_index=True to drop index. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "weight"), []) def test_alter_pk_with_self_referential_field(self): """ Changing the primary key field name of a model with a self-referential foreign key (#26384). """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field("node_id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Node, old_field, new_field, strict=True) self.assertForeignKeyExists(Node, "parent_id", Node._meta.db_table) @mock.patch("django.db.backends.base.schema.datetime") @mock.patch("django.db.backends.base.schema.timezone") def test_add_datefield_and_datetimefield_use_effective_default( self, mocked_datetime, mocked_tz ): """ effective_default() should be used for DateField, DateTimeField, and TimeField if auto_now or auto_now_add is set (#25005). """ now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1) now_tz = datetime.datetime( month=1, day=1, year=2000, hour=1, minute=1, tzinfo=datetime.timezone.utc ) mocked_datetime.now = mock.MagicMock(return_value=now) mocked_tz.now = mock.MagicMock(return_value=now_tz) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Check auto_now/auto_now_add attributes are not defined columns = self.column_classes(Author) self.assertNotIn("dob_auto_now", columns) self.assertNotIn("dob_auto_now_add", columns) self.assertNotIn("dtob_auto_now", columns) self.assertNotIn("dtob_auto_now_add", columns) self.assertNotIn("tob_auto_now", columns) self.assertNotIn("tob_auto_now_add", columns) # Create a row Author.objects.create(name="Anonymous1") # Ensure fields were added with the correct defaults dob_auto_now = DateField(auto_now=True) dob_auto_now.set_attributes_from_name("dob_auto_now") self.check_added_field_default( editor, Author, dob_auto_now, "dob_auto_now", now.date(), cast_function=lambda x: x.date(), ) dob_auto_now_add = DateField(auto_now_add=True) dob_auto_now_add.set_attributes_from_name("dob_auto_now_add") self.check_added_field_default( editor, Author, dob_auto_now_add, "dob_auto_now_add", now.date(), cast_function=lambda x: x.date(), ) dtob_auto_now = DateTimeField(auto_now=True) dtob_auto_now.set_attributes_from_name("dtob_auto_now") self.check_added_field_default( editor, Author, dtob_auto_now, "dtob_auto_now", now, ) dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True) dt_tm_of_birth_auto_now_add.set_attributes_from_name("dtob_auto_now_add") self.check_added_field_default( editor, Author, dt_tm_of_birth_auto_now_add, "dtob_auto_now_add", now, ) tob_auto_now = TimeField(auto_now=True) tob_auto_now.set_attributes_from_name("tob_auto_now") self.check_added_field_default( editor, Author, tob_auto_now, "tob_auto_now", now.time(), cast_function=lambda x: x.time(), ) tob_auto_now_add = TimeField(auto_now_add=True) tob_auto_now_add.set_attributes_from_name("tob_auto_now_add") self.check_added_field_default( editor, Author, tob_auto_now_add, "tob_auto_now_add", now.time(), cast_function=lambda x: x.time(), ) def test_namespaced_db_table_create_index_name(self): """ Table names are stripped of their namespace/schema before being used to generate index names. """ with connection.schema_editor() as editor: max_name_length = connection.ops.max_name_length() or 200 namespace = "n" * max_name_length table_name = "t" * max_name_length namespaced_table_name = '"%s"."%s"' % (namespace, table_name) self.assertEqual( editor._create_index_name(table_name, []), editor._create_index_name(namespaced_table_name, []), ) @unittest.skipUnless( connection.vendor == "oracle", "Oracle specific db_table syntax" ) def test_creation_with_db_table_double_quotes(self): oracle_user = connection.creation._test_database_user() class Student(Model): name = CharField(max_length=30) class Meta: app_label = "schema" apps = new_apps db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user class Document(Model): name = CharField(max_length=30) students = ManyToManyField(Student) class Meta: app_label = "schema" apps = new_apps db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user self.isolated_local_models = [Student, Document] with connection.schema_editor() as editor: editor.create_model(Student) editor.create_model(Document) doc = Document.objects.create(name="Test Name") student = Student.objects.create(name="Some man") doc.students.add(student) @isolate_apps("schema") @unittest.skipUnless( connection.vendor == "postgresql", "PostgreSQL specific db_table syntax." ) def test_namespaced_db_table_foreign_key_reference(self): with connection.cursor() as cursor: cursor.execute("CREATE SCHEMA django_schema_tests") def delete_schema(): with connection.cursor() as cursor: cursor.execute("DROP SCHEMA django_schema_tests CASCADE") self.addCleanup(delete_schema) class Author(Model): class Meta: app_label = "schema" class Book(Model): class Meta: app_label = "schema" db_table = '"django_schema_tests"."schema_book"' author = ForeignKey(Author, CASCADE) author.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.add_field(Book, author) def test_rename_table_renames_deferred_sql_references(self): atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: editor.create_model(Author) editor.create_model(Book) editor.alter_db_table(Author, "schema_author", "schema_renamed_author") editor.alter_db_table(Author, "schema_book", "schema_renamed_book") try: self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_table("schema_author"), False) self.assertIs(statement.references_table("schema_book"), False) finally: editor.alter_db_table(Author, "schema_renamed_author", "schema_author") editor.alter_db_table(Author, "schema_renamed_book", "schema_book") def test_rename_column_renames_deferred_sql_references(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_title = Book._meta.get_field("title") new_title = CharField(max_length=100, db_index=True) new_title.set_attributes_from_name("renamed_title") editor.alter_field(Book, old_title, new_title) old_author = Book._meta.get_field("author") new_author = ForeignKey(Author, CASCADE) new_author.set_attributes_from_name("renamed_author") editor.alter_field(Book, old_author, new_author) self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_column("book", "title"), False) self.assertIs(statement.references_column("book", "author_id"), False) @isolate_apps("schema") def test_referenced_field_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the field they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False) class Meta: app_label = "schema" self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor(atomic=True) as editor: editor.alter_field(Foo, Foo._meta.get_field("field"), new_field) @isolate_apps("schema") def test_referenced_table_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the table they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False) class Meta: app_label = "schema" self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Foo, Foo._meta.db_table, "renamed_table") Foo._meta.db_table = "renamed_table" @isolate_apps("schema") @skipUnlessDBFeature("supports_collation_on_charfield") def test_db_collation_charfield(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") class Foo(Model): field = CharField(max_length=255, db_collation=collation) class Meta: app_label = "schema" self.isolated_local_models = [Foo] with connection.schema_editor() as editor: editor.create_model(Foo) self.assertEqual( self.get_column_collation(Foo._meta.db_table, "field"), collation, ) @isolate_apps("schema") @skipUnlessDBFeature("supports_collation_on_textfield") def test_db_collation_textfield(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") class Foo(Model): field = TextField(db_collation=collation) class Meta: app_label = "schema" self.isolated_local_models = [Foo] with connection.schema_editor() as editor: editor.create_model(Foo) self.assertEqual( self.get_column_collation(Foo._meta.db_table, "field"), collation, ) @skipUnlessDBFeature("supports_collation_on_charfield") def test_add_field_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("alias") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["alias"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual(columns["alias"][1][8], collation) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_field_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_collation(Author._meta.db_table, "name"), collation, ) with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertIsNone(self.get_column_collation(Author._meta.db_table, "name")) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_primary_key_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Thing) old_field = Thing._meta.get_field("when") new_field = CharField(max_length=1, db_collation=collation, primary_key=True) new_field.set_attributes_from_name("when") new_field.model = Thing with connection.schema_editor() as editor: editor.alter_field(Thing, old_field, new_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") self.assertEqual( self.get_column_collation(Thing._meta.db_table, "when"), collation, ) with connection.schema_editor() as editor: editor.alter_field(Thing, new_field, old_field, strict=True) self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when") self.assertIsNone(self.get_column_collation(Thing._meta.db_table, "when")) @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_collation_on_textfield" ) def test_alter_field_type_and_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("info") new_field.model = Note with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual( columns["info"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual(columns["info"][1][8], collation) with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns["info"][0], "TextField") self.assertIsNone(columns["info"][1][8]) @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_non_deterministic_collations", ) def test_ci_cs_db_collation(self): cs_collation = connection.features.test_collations.get("cs") ci_collation = connection.features.test_collations.get("ci") try: if connection.vendor == "mysql": cs_collation = "latin1_general_cs" elif connection.vendor == "postgresql": cs_collation = "en-x-icu" with connection.cursor() as cursor: cursor.execute( "CREATE COLLATION IF NOT EXISTS case_insensitive " "(provider = icu, locale = 'und-u-ks-level2', " "deterministic = false)" ) ci_collation = "case_insensitive" # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Case-insensitive collation. old_field = Author._meta.get_field("name") new_field_ci = CharField(max_length=255, db_collation=ci_collation) new_field_ci.set_attributes_from_name("name") new_field_ci.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field_ci, strict=True) Author.objects.create(name="ANDREW") self.assertIs(Author.objects.filter(name="Andrew").exists(), True) # Case-sensitive collation. new_field_cs = CharField(max_length=255, db_collation=cs_collation) new_field_cs.set_attributes_from_name("name") new_field_cs.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, new_field_ci, new_field_cs, strict=True) self.assertIs(Author.objects.filter(name="Andrew").exists(), False) finally: if connection.vendor == "postgresql": with connection.cursor() as cursor: cursor.execute("DROP COLLATION IF EXISTS case_insensitive")
61d5a4ef6ac1635e9b0940764cfe8072e6f87a946a50ee1f34d127a5be636db7
from django.apps.registry import Apps from django.db import models # Because we want to test creation and deletion of these as separate things, # these models are all inserted into a separate Apps so the main test # runner doesn't migrate them. new_apps = Apps() class Author(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) uuid = models.UUIDField(null=True) class Meta: apps = new_apps class AuthorCharFieldWithIndex(models.Model): char_field = models.CharField(max_length=31, db_index=True) class Meta: apps = new_apps class AuthorTextFieldWithIndex(models.Model): text_field = models.TextField(db_index=True) class Meta: apps = new_apps class AuthorWithDefaultHeight(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True, default=42) class Meta: apps = new_apps class AuthorWithEvenLongerName(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True) class Meta: apps = new_apps class AuthorWithIndexedName(models.Model): name = models.CharField(max_length=255, db_index=True) class Meta: apps = new_apps class AuthorWithUniqueName(models.Model): name = models.CharField(max_length=255, unique=True) class Meta: apps = new_apps class AuthorWithUniqueNameAndBirthday(models.Model): name = models.CharField(max_length=255) birthday = models.DateField() class Meta: apps = new_apps unique_together = [["name", "birthday"]] class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() # tags = models.ManyToManyField("Tag", related_name="books") class Meta: apps = new_apps class BookWeak(models.Model): author = models.ForeignKey(Author, models.CASCADE, db_constraint=False) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps class BookWithLongName(models.Model): author_foreign_key_with_really_long_field_name = models.ForeignKey( AuthorWithEvenLongerName, models.CASCADE, ) class Meta: apps = new_apps class BookWithO2O(models.Model): author = models.OneToOneField(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps db_table = "schema_book" class BookWithSlug(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() slug = models.CharField(max_length=20, unique=True) class Meta: apps = new_apps db_table = "schema_book" class BookWithoutAuthor(models.Model): title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps db_table = "schema_book" class BookForeignObj(models.Model): title = models.CharField(max_length=100, db_index=True) author_id = models.IntegerField() class Meta: apps = new_apps class IntegerPK(models.Model): i = models.IntegerField(primary_key=True) j = models.IntegerField(unique=True) class Meta: apps = new_apps db_table = "INTEGERPK" # uppercase to ensure proper quoting class Note(models.Model): info = models.TextField() address = models.TextField(null=True) class Meta: apps = new_apps class NoteRename(models.Model): detail_info = models.TextField() class Meta: apps = new_apps db_table = "schema_note" class Tag(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps class TagM2MTest(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps class TagUniqueRename(models.Model): title = models.CharField(max_length=255) slug2 = models.SlugField(unique=True) class Meta: apps = new_apps db_table = "schema_tag" # Based on tests/reserved_names/models.py class Thing(models.Model): when = models.CharField(max_length=1, primary_key=True) class Meta: apps = new_apps db_table = "drop" def __str__(self): return self.when class UniqueTest(models.Model): year = models.IntegerField() slug = models.SlugField(unique=False) class Meta: apps = new_apps unique_together = ["year", "slug"] class Node(models.Model): node_id = models.AutoField(primary_key=True) parent = models.ForeignKey("self", models.CASCADE, null=True, blank=True) class Meta: apps = new_apps
002a18530cdeb385784616e99d19fa1c684edaef6bb765528bf5e32b3a0a4aa4
from copy import copy, deepcopy from django.core.checks import Error from django.core.checks.templates import ( E001, E002, E003, check_for_template_tags_with_the_same_name, check_setting_app_dirs_loaders, check_string_if_invalid_is_string, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckTemplateSettingsAppDirsTest(SimpleTestCase): TEMPLATES_APP_DIRS_AND_LOADERS = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "loaders": ["django.template.loaders.filesystem.Loader"], }, }, ] @override_settings(TEMPLATES=TEMPLATES_APP_DIRS_AND_LOADERS) def test_app_dirs_and_loaders(self): """ Error if template loaders are specified and APP_DIRS is True. """ self.assertEqual(check_setting_app_dirs_loaders(None), [E001]) def test_app_dirs_removed(self): TEMPLATES = deepcopy(self.TEMPLATES_APP_DIRS_AND_LOADERS) del TEMPLATES[0]["APP_DIRS"] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_setting_app_dirs_loaders(None), []) def test_loaders_removed(self): TEMPLATES = deepcopy(self.TEMPLATES_APP_DIRS_AND_LOADERS) del TEMPLATES[0]["OPTIONS"]["loaders"] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_setting_app_dirs_loaders(None), []) class CheckTemplateStringIfInvalidTest(SimpleTestCase): TEMPLATES_STRING_IF_INVALID = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "string_if_invalid": False, }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "string_if_invalid": 42, }, }, ] @classmethod def setUpClass(cls): super().setUpClass() cls.error1 = copy(E002) cls.error2 = copy(E002) string_if_invalid1 = cls.TEMPLATES_STRING_IF_INVALID[0]["OPTIONS"][ "string_if_invalid" ] string_if_invalid2 = cls.TEMPLATES_STRING_IF_INVALID[1]["OPTIONS"][ "string_if_invalid" ] cls.error1.msg = cls.error1.msg.format( string_if_invalid1, type(string_if_invalid1).__name__ ) cls.error2.msg = cls.error2.msg.format( string_if_invalid2, type(string_if_invalid2).__name__ ) @override_settings(TEMPLATES=TEMPLATES_STRING_IF_INVALID) def test_string_if_invalid_not_string(self): self.assertEqual( check_string_if_invalid_is_string(None), [self.error1, self.error2] ) def test_string_if_invalid_first_is_string(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "test" with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_string_if_invalid_is_string(None), [self.error2]) def test_string_if_invalid_both_are_strings(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "test" TEMPLATES[1]["OPTIONS"]["string_if_invalid"] = "test" with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_string_if_invalid_is_string(None), []) def test_string_if_invalid_not_specified(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) del TEMPLATES[1]["OPTIONS"]["string_if_invalid"] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_string_if_invalid_is_string(None), [self.error1]) class CheckTemplateTagLibrariesWithSameName(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.error_same_tags = Error( E003.msg.format( "'same_tags'", "'check_framework.template_test_apps.same_tags_app_1." "templatetags.same_tags', " "'check_framework.template_test_apps.same_tags_app_2." "templatetags.same_tags'", ), id=E003.id, ) @staticmethod def get_settings(module_name, module_path): return { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "libraries": { module_name: f"check_framework.template_test_apps.{module_path}", }, }, } @override_settings( INSTALLED_APPS=[ "check_framework.template_test_apps.same_tags_app_1", "check_framework.template_test_apps.same_tags_app_2", ] ) def test_template_tags_with_same_name(self): self.assertEqual( check_for_template_tags_with_the_same_name(None), [self.error_same_tags], ) def test_template_tags_with_same_library_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags" ), self.get_settings( "same_tags", "same_tags_app_2.templatetags.same_tags" ), ] ): self.assertEqual( check_for_template_tags_with_the_same_name(None), [self.error_same_tags], ) @override_settings( INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] ) def test_template_tags_same_library_in_installed_apps_libraries(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags" ), ] ): self.assertEqual(check_for_template_tags_with_the_same_name(None), []) @override_settings( INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] ) def test_template_tags_with_same_library_name_and_module_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "different_tags_app.templatetags.different_tags", ), ] ): self.assertEqual( check_for_template_tags_with_the_same_name(None), [ Error( E003.msg.format( "'same_tags'", "'check_framework.template_test_apps.different_tags_app." "templatetags.different_tags', " "'check_framework.template_test_apps.same_tags_app_1." "templatetags.same_tags'", ), id=E003.id, ) ], ) def test_template_tags_with_different_library_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags" ), self.get_settings( "not_same_tags", "same_tags_app_2.templatetags.same_tags" ), ] ): self.assertEqual(check_for_template_tags_with_the_same_name(None), []) @override_settings( INSTALLED_APPS=[ "check_framework.template_test_apps.same_tags_app_1", "check_framework.template_test_apps.different_tags_app", ] ) def test_template_tags_with_different_name(self): self.assertEqual(check_for_template_tags_with_the_same_name(None), [])
5992e4159047f7407cc5de502741ee7d7501dade4ee43976070e42eae6c4dc19
from functools import update_wrapper from django.contrib import admin from django.db import models from django.http import HttpResponseRedirect from django.urls import reverse class Action(models.Model): name = models.CharField(max_length=50, primary_key=True) description = models.CharField(max_length=70) def __str__(self): return self.name class ActionAdmin(admin.ModelAdmin): """ A ModelAdmin for the Action model that changes the URL of the add_view to '<app name>/<model name>/!add/' The Action model has a CharField PK. """ list_display = ("name", "description") def remove_url(self, name): """ Remove all entries named 'name' from the ModelAdmin instance URL patterns list """ return [url for url in super().get_urls() if url.name != name] def get_urls(self): # Add the URL of our custom 'add_view' view to the front of the URLs # list. Remove the existing one(s) first from django.urls import re_path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.opts.app_label, self.opts.model_name view_name = "%s_%s_add" % info return [ re_path("^!add/$", wrap(self.add_view), name=view_name), ] + self.remove_url(view_name) class Person(models.Model): name = models.CharField(max_length=20) class PersonAdmin(admin.ModelAdmin): def response_post_save_add(self, request, obj): return HttpResponseRedirect( reverse("admin:admin_custom_urls_person_history", args=[obj.pk]) ) def response_post_save_change(self, request, obj): return HttpResponseRedirect( reverse("admin:admin_custom_urls_person_delete", args=[obj.pk]) ) class Car(models.Model): name = models.CharField(max_length=20) class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return super().response_add( request, obj, post_url_continue=reverse( "admin:admin_custom_urls_car_history", args=[obj.pk] ), ) site = admin.AdminSite(name="admin_custom_urls") site.register(Action, ActionAdmin) site.register(Person, PersonAdmin) site.register(Car, CarAdmin)
b95825435a1cb1bc61228d7800d6b762d32187efad69c6d1ae141734ae5d060c
import base64 import hashlib import os import shutil import sys import tempfile as sys_tempfile import unittest from io import BytesIO, StringIO from unittest import mock from urllib.parse import quote from django.core.exceptions import SuspiciousFileOperation from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile from django.http.multipartparser import ( FILE, MultiPartParser, MultiPartParserError, Parser, ) from django.test import SimpleTestCase, TestCase, client, override_settings from . import uploadhandler from .models import FileModel UNICODE_FILENAME = "test-0123456789_中文_Orléans.jpg" MEDIA_ROOT = sys_tempfile.mkdtemp() UPLOAD_TO = os.path.join(MEDIA_ROOT, "test_upload") CANDIDATE_TRAVERSAL_FILE_NAMES = [ "/tmp/hax0rd.txt", # Absolute path, *nix-style. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style. "C:/Windows/hax0rd.txt", # Absolute path, broken-style. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing. "subdir/hax0rd.txt", # Descendant path, *nix-style. "subdir\\hax0rd.txt", # Descendant path, win-style. "sub/dir\\hax0rd.txt", # Descendant path, mixed. "../../hax0rd.txt", # Relative path, *nix-style. "..\\..\\hax0rd.txt", # Relative path, win-style. "../..\\hax0rd.txt", # Relative path, mixed. "..&#x2F;hax0rd.txt", # HTML entities. "..&sol;hax0rd.txt", # HTML entities. ] CANDIDATE_INVALID_FILE_NAMES = [ "/tmp/", # Directory, *nix-style. "c:\\tmp\\", # Directory, win-style. "/tmp/.", # Directory dot, *nix-style. "c:\\tmp\\.", # Directory dot, *nix-style. "/tmp/..", # Parent directory, *nix-style. "c:\\tmp\\..", # Parent directory, win-style. "", # Empty filename. ] @override_settings( MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF="file_uploads.urls", MIDDLEWARE=[] ) class FileUploadTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT) def test_upload_name_is_validated(self): candidates = [ "/tmp/", "/tmp/..", "/tmp/.", ] if sys.platform == "win32": candidates.extend( [ "c:\\tmp\\", "c:\\tmp\\..", "c:\\tmp\\.", ] ) for file_name in candidates: with self.subTest(file_name=file_name): self.assertRaises(SuspiciousFileOperation, UploadedFile, name=file_name) def test_simple_upload(self): with open(__file__, "rb") as fp: post_data = { "name": "Ringo", "file_field": fp, } response = self.client.post("/upload/", post_data) self.assertEqual(response.status_code, 200) def test_large_upload(self): file = tempfile.NamedTemporaryFile with file(suffix=".file1") as file1, file(suffix=".file2") as file2: file1.write(b"a" * (2**21)) file1.seek(0) file2.write(b"a" * (10 * 2**20)) file2.seek(0) post_data = { "name": "Ringo", "file_field1": file1, "file_field2": file2, } for key in list(post_data): try: post_data[key + "_hash"] = hashlib.sha1( post_data[key].read() ).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + "_hash"] = hashlib.sha1( post_data[key].encode() ).hexdigest() response = self.client.post("/verify/", post_data) self.assertEqual(response.status_code, 200) def _test_base64_upload(self, content, encode=base64.b64encode): payload = client.FakePayload( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', "Content-Type: application/octet-stream", "Content-Transfer-Encoding: base64", "", ] ) ) payload.write(b"\r\n" + encode(content.encode()) + b"\r\n") payload.write("--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo_content/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.json()["file"], content) def test_base64_upload(self): self._test_base64_upload("This data will be transmitted base64-encoded.") def test_big_base64_upload(self): self._test_base64_upload("Big data" * 68000) # > 512Kb def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', "Content-Type: application/octet-stream", "Content-Transfer-Encoding: base64", "", ] ) ) payload.write(b"\r\n!\r\n") payload.write("--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo_content/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.json()["file"], "") def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accented char in the name. with open(os.path.join(temp_dir, UNICODE_FILENAME), "w+b") as file1: file1.write(b"b" * (2**10)) file1.seek(0) response = self.client.post("/unicode_name/", {"file_unicode": file1}) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; ' "filename*=UTF-8''%s" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, "Content-Disposition: form-data; name*=UTF-8''file_unicode; " "filename*=UTF-8''%s" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231_with_double_quotes(self): payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; ' "filename*=\"UTF-8''%s\"" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231_with_double_quotes(self): payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, "Content-Disposition: form-data; name*=\"UTF-8''file_unicode\"; " "filename*=\"UTF-8''%s\"" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_blank_filenames(self): """ Receiving file upload when filename is blank (before and after sanitization) should be okay. """ filenames = [ "", # Normalized by MultiPartParser.IE_sanitize(). "C:\\Windows\\", # Normalized by os.path.basename(). "/", "ends-with-slash/", ] payload = client.FakePayload() for i, name in enumerate(filenames): payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", ] ) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) # Empty filenames should be ignored received = response.json() for i, name in enumerate(filenames): self.assertIsNone(received.get("file%s" % i)) def test_non_printable_chars_in_file_names(self): file_name = "non-\x00printable\x00\n_chars.txt\x00" payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, f'Content-Disposition: form-data; name="file"; ' f'filename="{file_name}"', "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", ] ) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) # Non-printable chars are sanitized. received = response.json() self.assertEqual(received["file"], "non-printable_chars.txt") def test_dangerous_file_names(self): """Uploaded file names should be sanitized before ever reaching the view.""" # This test simulates possible directory traversal attacks by a # malicious uploader We have to do some monkeybusiness here to construct # a malicious payload with an invalid file name (containing os.sep or # os.pardir). This similar to what an attacker would need to do when # trying such an attack. payload = client.FakePayload() for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES): payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", ] ) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) # The filenames should have been sanitized by the time it got to the view. received = response.json() for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES): got = received["file%s" % i] self.assertEqual(got, "hax0rd.txt") def test_filename_overflow(self): """File names over 256 characters (dangerous on some platforms) get fixed up.""" long_str = "f" * 300 cases = [ # field name, filename, expected ("long_filename", "%s.txt" % long_str, "%s.txt" % long_str[:251]), ("long_extension", "foo.%s" % long_str, ".%s" % long_str[:254]), ("no_extension", long_str, long_str[:255]), ("no_filename", ".%s" % long_str, ".%s" % long_str[:254]), ("long_everything", "%s.%s" % (long_str, long_str), ".%s" % long_str[:254]), ] payload = client.FakePayload() for name, filename, _ in cases: payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="{}"; filename="{}"', "Content-Type: application/octet-stream", "", "Oops.", "", ] ).format(name, filename) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) result = response.json() for name, _, expected in cases: got = result[name] self.assertEqual(expected, got, "Mismatch for {}".format(name)) self.assertLess( len(got), 256, "Got a long file name (%s characters)." % len(got) ) def test_file_content(self): file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file( suffix=".ctype_extra" ) as simple_file: no_content_type.write(b"no content") no_content_type.seek(0) simple_file.write(b"text content") simple_file.seek(0) simple_file.content_type = "text/plain" string_io = StringIO("string content") bytes_io = BytesIO(b"binary content") response = self.client.post( "/echo_content/", { "no_content_type": no_content_type, "simple_file": simple_file, "string": string_io, "binary": bytes_io, }, ) received = response.json() self.assertEqual(received["no_content_type"], "no content") self.assertEqual(received["simple_file"], "text content") self.assertEqual(received["string"], "string content") self.assertEqual(received["binary"], "binary content") def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file( suffix=".ctype_extra" ) as simple_file: no_content_type.write(b"something") no_content_type.seek(0) simple_file.write(b"something") simple_file.seek(0) simple_file.content_type = "text/plain; test-key=test_value" response = self.client.post( "/echo_content_type_extra/", { "no_content_type": no_content_type, "simple_file": simple_file, }, ) received = response.json() self.assertEqual(received["no_content_type"], {}) self.assertEqual(received["simple_file"], {"test-key": "test_value"}) def test_truncated_multipart_handled_gracefully(self): """ If passed an incomplete multipart message, MultiPartParser does not attempt to read beyond the end of the stream, and simply will handle the part that can be parsed gracefully. """ payload_str = "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="foo.txt"', "Content-Type: application/octet-stream", "", "file contents" "--" + client.BOUNDARY + "--", "", ] ) payload = client.FakePayload(payload_str[:-10]) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } self.assertEqual(self.client.request(**r).json(), {}) def test_empty_multipart_handled_gracefully(self): """ If passed an empty multipart message, MultiPartParser will return an empty QueryDict. """ r = { "CONTENT_LENGTH": 0, "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": client.FakePayload(b""), } self.assertEqual(self.client.request(**r).json(), {}) def test_custom_upload_handler(self): file = tempfile.NamedTemporaryFile with file() as smallfile, file() as bigfile: # A small file (under the 5M quota) smallfile.write(b"a" * (2**21)) smallfile.seek(0) # A big file (over the quota) bigfile.write(b"a" * (10 * 2**20)) bigfile.seek(0) # Small file posting should work. self.assertIn("f", self.client.post("/quota/", {"f": smallfile}).json()) # Large files don't go through. self.assertNotIn("f", self.client.post("/quota/", {"f": bigfile}).json()) def test_broken_custom_upload_handler(self): with tempfile.NamedTemporaryFile() as file: file.write(b"a" * (2**21)) file.seek(0) msg = ( "You cannot alter upload handlers after the upload has been processed." ) with self.assertRaisesMessage(AttributeError, msg): self.client.post("/quota/broken/", {"f": file}) def test_stop_upload_temporary_file_handler(self): with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(b"a") temp_file.seek(0) response = self.client.post("/temp_file/stop_upload/", {"file": temp_file}) temp_path = response.json()["temp_path"] self.assertIs(os.path.exists(temp_path), False) def test_upload_interrupted_temporary_file_handler(self): # Simulate an interrupted upload by omitting the closing boundary. class MockedParser(Parser): def __iter__(self): for item in super().__iter__(): item_type, meta_data, field_stream = item yield item_type, meta_data, field_stream if item_type == FILE: return with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(b"a") temp_file.seek(0) with mock.patch( "django.http.multipartparser.Parser", MockedParser, ): response = self.client.post( "/temp_file/upload_interrupted/", {"file": temp_file}, ) temp_path = response.json()["temp_path"] self.assertIs(os.path.exists(temp_path), False) def test_fileupload_getlist(self): file = tempfile.NamedTemporaryFile with file() as file1, file() as file2, file() as file2a: file1.write(b"a" * (2**23)) file1.seek(0) file2.write(b"a" * (2 * 2**18)) file2.seek(0) file2a.write(b"a" * (5 * 2**20)) file2a.seek(0) response = self.client.post( "/getlist_count/", { "file1": file1, "field1": "test", "field2": "test3", "field3": "test5", "field4": "test6", "field5": "test7", "file2": (file2, file2a), }, ) got = response.json() self.assertEqual(got.get("file1"), 1) self.assertEqual(got.get("file2"), 2) def test_fileuploads_closed_at_request_end(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post( "/fd_closing/t/", { "file": f1, "file2": (f2a, f2b), }, ) request = response.wsgi_request # The files were parsed. self.assertTrue(hasattr(request, "_files")) file = request._files["file"] self.assertTrue(file.closed) files = request._files.getlist("file2") self.assertTrue(files[0].closed) self.assertTrue(files[1].closed) def test_no_parsing_triggered_by_fd_closing(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post( "/fd_closing/f/", { "file": f1, "file2": (f2a, f2b), }, ) request = response.wsgi_request # The fd closing logic doesn't trigger parsing of the stream self.assertFalse(hasattr(request, "_files")) def test_file_error_blocking(self): """ The server should not block when there are upload errors (bug #8622). This can happen if something -- i.e. an exception handler -- tries to access POST while handling an error in parsing POST. This shouldn't cause an infinite loop! """ class POSTAccessingHandler(client.ClientHandler): """A handler that'll access POST during an exception.""" def handle_uncaught_exception(self, request, resolver, exc_info): ret = super().handle_uncaught_exception(request, resolver, exc_info) request.POST # evaluate return ret # Maybe this is a little more complicated that it needs to be; but if # the django.test.client.FakePayload.read() implementation changes then # this test would fail. So we need to know exactly what kind of error # it raises when there is an attempt to read more than the available bytes: try: client.FakePayload(b"a").read(2) except Exception as err: reference_error = err # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() with open(__file__, "rb") as fp: post_data = { "name": "Ringo", "file_field": fp, } try: self.client.post("/upload_errors/", post_data) except reference_error.__class__ as err: self.assertNotEqual( str(err), str(reference_error), "Caught a repeated exception that'll cause an infinite loop in " "file uploads.", ) except Exception as err: # CustomUploadError is the error that should have been raised self.assertEqual(err.__class__, uploadhandler.CustomUploadError) def test_filename_case_preservation(self): """ The storage backend shouldn't mess with the case of the filenames uploaded. """ # Synthesize the contents of a file upload with a mixed case filename # so we don't have to carry such a file in the Django tests source code # tree. vars = {"boundary": "oUrBoUnDaRyStRiNg"} post_data = [ "--%(boundary)s", 'Content-Disposition: form-data; name="file_field"; ' 'filename="MiXeD_cAsE.txt"', "Content-Type: application/octet-stream", "", "file contents\n", "--%(boundary)s--\r\n", ] response = self.client.post( "/filename_case/", "\r\n".join(post_data) % vars, "multipart/form-data; boundary=%(boundary)s" % vars, ) self.assertEqual(response.status_code, 200) id = int(response.content) obj = FileModel.objects.get(pk=id) # The name of the file uploaded and the file stored in the server-side # shouldn't differ. self.assertEqual(os.path.basename(obj.testfile.path), "MiXeD_cAsE.txt") def test_filename_traversal_upload(self): os.makedirs(UPLOAD_TO, exist_ok=True) tests = [ "..&#x2F;test.txt", "..&sol;test.txt", ] for file_name in tests: with self.subTest(file_name=file_name): payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="my_file"; ' 'filename="%s";' % file_name, "Content-Type: text/plain", "", "file contents.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ), ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/upload_traversal/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result["file_name"], "test.txt") self.assertIs( os.path.exists(os.path.join(MEDIA_ROOT, "test.txt")), False, ) self.assertIs( os.path.exists(os.path.join(UPLOAD_TO, "test.txt")), True, ) @override_settings(MEDIA_ROOT=MEDIA_ROOT) class DirectoryCreationTests(SimpleTestCase): """ Tests for error handling during directory creation via _save_FIELD_file (ticket #6450) """ @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT) def setUp(self): self.obj = FileModel() @unittest.skipIf( sys.platform == "win32", "Python on Windows doesn't have working os.chmod()." ) def test_readonly_root(self): """Permission errors are not swallowed""" os.chmod(MEDIA_ROOT, 0o500) self.addCleanup(os.chmod, MEDIA_ROOT, 0o700) with self.assertRaises(PermissionError): self.obj.testfile.save( "foo.txt", SimpleUploadedFile("foo.txt", b"x"), save=False ) def test_not_a_directory(self): # Create a file with the upload directory name open(UPLOAD_TO, "wb").close() self.addCleanup(os.remove, UPLOAD_TO) msg = "%s exists and is not a directory." % UPLOAD_TO with self.assertRaisesMessage(FileExistsError, msg): with SimpleUploadedFile("foo.txt", b"x") as file: self.obj.testfile.save("foo.txt", file, save=False) class MultiParserTests(SimpleTestCase): def test_empty_upload_handlers(self): # We're not actually parsing here; just checking if the parser properly # instantiates with empty upload handlers. MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) def test_invalid_content_type(self): with self.assertRaisesMessage( MultiPartParserError, "Invalid Content-Type: text/plain" ): MultiPartParser( { "CONTENT_TYPE": "text/plain", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) def test_negative_content_length(self): with self.assertRaisesMessage( MultiPartParserError, "Invalid content length: -1" ): MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": -1, }, StringIO("x"), [], "utf-8", ) def test_bad_type_content_length(self): multipart_parser = MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "a", }, StringIO("x"), [], "utf-8", ) self.assertEqual(multipart_parser._content_length, 0) def test_sanitize_file_name(self): parser = MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) for file_name in CANDIDATE_TRAVERSAL_FILE_NAMES: with self.subTest(file_name=file_name): self.assertEqual(parser.sanitize_file_name(file_name), "hax0rd.txt") def test_sanitize_invalid_file_name(self): parser = MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) for file_name in CANDIDATE_INVALID_FILE_NAMES: with self.subTest(file_name=file_name): self.assertIsNone(parser.sanitize_file_name(file_name))
77cb57d21f29c6814992d0a91718cae2186adc4824ca9acf91ef3290cc687fe5
import json import os import tempfile import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.files.storage import FileSystemStorage from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.db.models.fields.files import ImageFieldFile from django.utils.translation import gettext_lazy as _ try: from PIL import Image except ImportError: Image = None class Foo(models.Model): a = models.CharField(max_length=10) d = models.DecimalField(max_digits=5, decimal_places=3) def get_foo(): return Foo.objects.get(id=1).pk class Bar(models.Model): b = models.CharField(max_length=10) a = models.ForeignKey(Foo, models.CASCADE, default=get_foo, related_name="bars") class Whiz(models.Model): CHOICES = ( ( "Group 1", ( (1, "First"), (2, "Second"), ), ), ( "Group 2", ( (3, "Third"), (4, "Fourth"), ), ), (0, "Other"), (5, _("translated")), ) c = models.IntegerField(choices=CHOICES, null=True) class WhizDelayed(models.Model): c = models.IntegerField(choices=(), null=True) # Contrived way of adding choices later. WhizDelayed._meta.get_field("c").choices = Whiz.CHOICES class WhizIter(models.Model): c = models.IntegerField(choices=iter(Whiz.CHOICES), null=True) class WhizIterEmpty(models.Model): c = models.CharField(choices=iter(()), blank=True, max_length=1) class Choiceful(models.Model): no_choices = models.IntegerField(null=True) empty_choices = models.IntegerField(choices=(), null=True) with_choices = models.IntegerField(choices=[(1, "A")], null=True) empty_choices_bool = models.BooleanField(choices=()) empty_choices_text = models.TextField(choices=()) class BigD(models.Model): d = models.DecimalField(max_digits=32, decimal_places=30) class FloatModel(models.Model): size = models.FloatField() class BigS(models.Model): s = models.SlugField(max_length=255) class UnicodeSlugField(models.Model): s = models.SlugField(max_length=255, allow_unicode=True) class AutoModel(models.Model): value = models.AutoField(primary_key=True) class BigAutoModel(models.Model): value = models.BigAutoField(primary_key=True) class SmallAutoModel(models.Model): value = models.SmallAutoField(primary_key=True) class SmallIntegerModel(models.Model): value = models.SmallIntegerField() class IntegerModel(models.Model): value = models.IntegerField() class BigIntegerModel(models.Model): value = models.BigIntegerField() null_value = models.BigIntegerField(null=True, blank=True) class PositiveBigIntegerModel(models.Model): value = models.PositiveBigIntegerField() class PositiveSmallIntegerModel(models.Model): value = models.PositiveSmallIntegerField() class PositiveIntegerModel(models.Model): value = models.PositiveIntegerField() class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() class NullBooleanModel(models.Model): nbfield = models.BooleanField(null=True, blank=True) class BooleanModel(models.Model): bfield = models.BooleanField() class DateTimeModel(models.Model): d = models.DateField() dt = models.DateTimeField() t = models.TimeField() class DurationModel(models.Model): field = models.DurationField() class NullDurationModel(models.Model): field = models.DurationField(null=True) class PrimaryKeyCharModel(models.Model): string = models.CharField(max_length=10, primary_key=True) class FksToBooleans(models.Model): """Model with FKs to models with {Null,}BooleanField's, #15040""" bf = models.ForeignKey(BooleanModel, models.CASCADE) nbf = models.ForeignKey(NullBooleanModel, models.CASCADE) class FkToChar(models.Model): """Model with FK to a model with a CharField primary key, #19299""" out = models.ForeignKey(PrimaryKeyCharModel, models.CASCADE) class RenamedField(models.Model): modelname = models.IntegerField(name="fieldname", choices=((1, "One"),)) class VerboseNameField(models.Model): id = models.AutoField("verbose pk", primary_key=True) field1 = models.BigIntegerField("verbose field1") field2 = models.BooleanField("verbose field2", default=False) field3 = models.CharField("verbose field3", max_length=10) field4 = models.DateField("verbose field4") field5 = models.DateTimeField("verbose field5") field6 = models.DecimalField("verbose field6", max_digits=6, decimal_places=1) field7 = models.EmailField("verbose field7") field8 = models.FileField("verbose field8", upload_to="unused") field9 = models.FilePathField("verbose field9") field10 = models.FloatField("verbose field10") # Don't want to depend on Pillow in this test # field_image = models.ImageField("verbose field") field11 = models.IntegerField("verbose field11") field12 = models.GenericIPAddressField("verbose field12", protocol="ipv4") field13 = models.PositiveIntegerField("verbose field13") field14 = models.PositiveSmallIntegerField("verbose field14") field15 = models.SlugField("verbose field15") field16 = models.SmallIntegerField("verbose field16") field17 = models.TextField("verbose field17") field18 = models.TimeField("verbose field18") field19 = models.URLField("verbose field19") field20 = models.UUIDField("verbose field20") field21 = models.DurationField("verbose field21") class GenericIPAddress(models.Model): ip = models.GenericIPAddressField(null=True, protocol="ipv4") ############################################################################### # These models aren't used in any test, just here to ensure they validate # successfully. # See ticket #16570. class DecimalLessThanOne(models.Model): d = models.DecimalField(max_digits=3, decimal_places=3) # See ticket #18389. class FieldClassAttributeModel(models.Model): field_class = models.CharField ############################################################################### class DataModel(models.Model): short_data = models.BinaryField(max_length=10, default=b"\x08") data = models.BinaryField() ############################################################################### # FileField class Document(models.Model): myfile = models.FileField(upload_to="unused", unique=True) ############################################################################### # ImageField # If Pillow available, do these tests. if Image: class TestImageFieldFile(ImageFieldFile): """ Custom Field File class that records whether or not the underlying file was opened. """ def __init__(self, *args, **kwargs): self.was_opened = False super().__init__(*args, **kwargs) def open(self): self.was_opened = True super().open() class TestImageField(models.ImageField): attr_class = TestImageFieldFile # Set up a temp directory for file storage. temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) temp_upload_to_dir = os.path.join(temp_storage.location, "tests") class Person(models.Model): """ Model that defines an ImageField with no dimension fields. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to="tests") class AbstractPersonWithHeight(models.Model): """ Abstract model that defines an ImageField with only one dimension field to make sure the dimension update is correctly run on concrete subclass instance post-initialization. """ mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height" ) mugshot_height = models.PositiveSmallIntegerField() class Meta: abstract = True class PersonWithHeight(AbstractPersonWithHeight): """ Concrete model that subclass an abstract one with only on dimension field. """ name = models.CharField(max_length=50) class PersonWithHeightAndWidth(models.Model): """ Model that defines height and width fields after the ImageField. """ name = models.CharField(max_length=50) mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height", width_field="mugshot_width", ) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() class PersonDimensionsFirst(models.Model): """ Model that defines height and width fields before the ImageField. """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height", width_field="mugshot_width", ) class PersonTwoImages(models.Model): """ Model that: * Defines two ImageFields * Defines the height/width fields before the ImageFields * Has a nullable ImageField """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height", width_field="mugshot_width", ) headshot_height = models.PositiveSmallIntegerField(blank=True, null=True) headshot_width = models.PositiveSmallIntegerField(blank=True, null=True) headshot = TestImageField( blank=True, null=True, storage=temp_storage, upload_to="tests", height_field="headshot_height", width_field="headshot_width", ) class CustomJSONDecoder(json.JSONDecoder): def __init__(self, object_hook=None, *args, **kwargs): return super().__init__(object_hook=self.as_uuid, *args, **kwargs) def as_uuid(self, dct): if "uuid" in dct: dct["uuid"] = uuid.UUID(dct["uuid"]) return dct class JSONModel(models.Model): value = models.JSONField() class Meta: required_db_features = {"supports_json_field"} class NullableJSONModel(models.Model): value = models.JSONField(blank=True, null=True) value_custom = models.JSONField( encoder=DjangoJSONEncoder, decoder=CustomJSONDecoder, null=True, ) class Meta: required_db_features = {"supports_json_field"} class RelatedJSONModel(models.Model): value = models.JSONField() json_model = models.ForeignKey(NullableJSONModel, models.CASCADE) class Meta: required_db_features = {"supports_json_field"} class AllFieldsModel(models.Model): big_integer = models.BigIntegerField() binary = models.BinaryField() boolean = models.BooleanField(default=False) char = models.CharField(max_length=10) date = models.DateField() datetime = models.DateTimeField() decimal = models.DecimalField(decimal_places=2, max_digits=2) duration = models.DurationField() email = models.EmailField() file_path = models.FilePathField() floatf = models.FloatField() integer = models.IntegerField() generic_ip = models.GenericIPAddressField() positive_integer = models.PositiveIntegerField() positive_small_integer = models.PositiveSmallIntegerField() slug = models.SlugField() small_integer = models.SmallIntegerField() text = models.TextField() time = models.TimeField() url = models.URLField() uuid = models.UUIDField() fo = models.ForeignObject( "self", on_delete=models.CASCADE, from_fields=["positive_integer"], to_fields=["id"], related_name="reverse", ) fk = models.ForeignKey("self", models.CASCADE, related_name="reverse2") m2m = models.ManyToManyField("self") oto = models.OneToOneField("self", models.CASCADE) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, models.CASCADE) gfk = GenericForeignKey() gr = GenericRelation(DataModel) class ManyToMany(models.Model): m2m = models.ManyToManyField("self") ############################################################################### class UUIDModel(models.Model): field = models.UUIDField() class NullableUUIDModel(models.Model): field = models.UUIDField(blank=True, null=True) class PrimaryKeyUUIDModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) class RelatedToUUIDModel(models.Model): uuid_fk = models.ForeignKey("PrimaryKeyUUIDModel", models.CASCADE) class UUIDChild(PrimaryKeyUUIDModel): pass class UUIDGrandchild(UUIDChild): pass
1933e321b6151b92dc9e37db963a7ba41b015559fe0af57745a580dda5cded26
from django import forms from django.core.exceptions import ValidationError from django.db import IntegrityError, models, transaction from django.test import SimpleTestCase, TestCase from .models import BooleanModel, FksToBooleans, NullBooleanModel class BooleanFieldTests(TestCase): def _test_get_prep_value(self, f): self.assertIs(f.get_prep_value(True), True) self.assertIs(f.get_prep_value("1"), True) self.assertIs(f.get_prep_value(1), True) self.assertIs(f.get_prep_value(False), False) self.assertIs(f.get_prep_value("0"), False) self.assertIs(f.get_prep_value(0), False) self.assertIsNone(f.get_prep_value(None)) def _test_to_python(self, f): self.assertIs(f.to_python(1), True) self.assertIs(f.to_python(0), False) def test_booleanfield_get_prep_value(self): self._test_get_prep_value(models.BooleanField()) def test_nullbooleanfield_get_prep_value(self): self._test_get_prep_value(models.BooleanField(null=True)) def test_booleanfield_to_python(self): self._test_to_python(models.BooleanField()) def test_nullbooleanfield_to_python(self): self._test_to_python(models.BooleanField(null=True)) def test_booleanfield_choices_blank(self): """ BooleanField with choices and defaults doesn't generate a formfield with the blank option (#9640, #10549). """ choices = [(1, "Si"), (2, "No")] f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices) def test_booleanfield_choices_blank_desired(self): """ BooleanField with choices and no default should generated a formfield with the blank option. """ choices = [(1, "Si"), (2, "No")] f = models.BooleanField(choices=choices) self.assertEqual(f.formfield().choices, [("", "---------")] + choices) def test_nullbooleanfield_formfield(self): f = models.BooleanField(null=True) self.assertIsInstance(f.formfield(), forms.NullBooleanField) def test_return_type(self): b = BooleanModel.objects.create(bfield=True) b.refresh_from_db() self.assertIs(b.bfield, True) b2 = BooleanModel.objects.create(bfield=False) b2.refresh_from_db() self.assertIs(b2.bfield, False) b3 = NullBooleanModel.objects.create(nbfield=True) b3.refresh_from_db() self.assertIs(b3.nbfield, True) b4 = NullBooleanModel.objects.create(nbfield=False) b4.refresh_from_db() self.assertIs(b4.nbfield, False) def test_select_related(self): """ Boolean fields retrieved via select_related() should return booleans. """ bmt = BooleanModel.objects.create(bfield=True) bmf = BooleanModel.objects.create(bfield=False) nbmt = NullBooleanModel.objects.create(nbfield=True) nbmf = NullBooleanModel.objects.create(nbfield=False) m1 = FksToBooleans.objects.create(bf=bmt, nbf=nbmt) m2 = FksToBooleans.objects.create(bf=bmf, nbf=nbmf) # select_related('fk_field_name') ma = FksToBooleans.objects.select_related("bf").get(pk=m1.id) self.assertIs(ma.bf.bfield, True) self.assertIs(ma.nbf.nbfield, True) # select_related() mb = FksToBooleans.objects.select_related().get(pk=m1.id) mc = FksToBooleans.objects.select_related().get(pk=m2.id) self.assertIs(mb.bf.bfield, True) self.assertIs(mb.nbf.nbfield, True) self.assertIs(mc.bf.bfield, False) self.assertIs(mc.nbf.nbfield, False) def test_null_default(self): """ A BooleanField defaults to None, which isn't a valid value (#15124). """ boolean_field = BooleanModel._meta.get_field("bfield") self.assertFalse(boolean_field.has_default()) b = BooleanModel() self.assertIsNone(b.bfield) with transaction.atomic(): with self.assertRaises(IntegrityError): b.save() nb = NullBooleanModel() self.assertIsNone(nb.nbfield) nb.save() # no error class ValidationTest(SimpleTestCase): def test_boolean_field_doesnt_accept_empty_input(self): f = models.BooleanField() with self.assertRaises(ValidationError): f.clean(None, None) def test_nullbooleanfield_blank(self): """ NullBooleanField shouldn't throw a validation error when given a value of None. """ nullboolean = NullBooleanModel(nbfield=None) nullboolean.full_clean()
cfa9aa0eef89801938e68b70ca12639fd491c79547365b08c9e26b621a5f466b
import json import xml.etree.ElementTree from datetime import datetime from asgiref.sync import async_to_sync, sync_to_async from django.db import NotSupportedError, connection from django.db.models import Sum from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import SimpleModel class AsyncQuerySetTest(TestCase): @classmethod def setUpTestData(cls): cls.s1 = SimpleModel.objects.create( field=1, created=datetime(2022, 1, 1, 0, 0, 0), ) cls.s2 = SimpleModel.objects.create( field=2, created=datetime(2022, 1, 1, 0, 0, 1), ) cls.s3 = SimpleModel.objects.create( field=3, created=datetime(2022, 1, 1, 0, 0, 2), ) @staticmethod def _get_db_feature(connection_, feature_name): # Wrapper to avoid accessing connection attributes until inside # coroutine function. Connection access is thread sensitive and cannot # be passed across sync/async boundaries. return getattr(connection_.features, feature_name) async def test_async_iteration(self): results = [] async for m in SimpleModel.objects.order_by("pk"): results.append(m) self.assertEqual(results, [self.s1, self.s2, self.s3]) async def test_aiterator(self): qs = SimpleModel.objects.aiterator() results = [] async for m in qs: results.append(m) self.assertCountEqual(results, [self.s1, self.s2, self.s3]) async def test_aiterator_prefetch_related(self): qs = SimpleModel.objects.prefetch_related("relatedmodels").aiterator() msg = "Using QuerySet.aiterator() after prefetch_related() is not supported." with self.assertRaisesMessage(NotSupportedError, msg): async for m in qs: pass async def test_aiterator_invalid_chunk_size(self): msg = "Chunk size must be strictly positive." for size in [0, -1]: qs = SimpleModel.objects.aiterator(chunk_size=size) with self.subTest(size=size), self.assertRaisesMessage(ValueError, msg): async for m in qs: pass async def test_acount(self): count = await SimpleModel.objects.acount() self.assertEqual(count, 3) async def test_acount_cached_result(self): qs = SimpleModel.objects.all() # Evaluate the queryset to populate the query cache. [x async for x in qs] count = await qs.acount() self.assertEqual(count, 3) await sync_to_async(SimpleModel.objects.create)( field=4, created=datetime(2022, 1, 1, 0, 0, 0), ) # The query cache is used. count = await qs.acount() self.assertEqual(count, 3) async def test_aget(self): instance = await SimpleModel.objects.aget(field=1) self.assertEqual(instance, self.s1) async def test_acreate(self): await SimpleModel.objects.acreate(field=4) self.assertEqual(await SimpleModel.objects.acount(), 4) async def test_aget_or_create(self): instance, created = await SimpleModel.objects.aget_or_create(field=4) self.assertEqual(await SimpleModel.objects.acount(), 4) self.assertIs(created, True) async def test_aupdate_or_create(self): instance, created = await SimpleModel.objects.aupdate_or_create( id=self.s1.id, defaults={"field": 2} ) self.assertEqual(instance, self.s1) self.assertIs(created, False) instance, created = await SimpleModel.objects.aupdate_or_create(field=4) self.assertEqual(await SimpleModel.objects.acount(), 4) self.assertIs(created, True) @skipUnlessDBFeature("has_bulk_insert") @async_to_sync async def test_abulk_create(self): instances = [SimpleModel(field=i) for i in range(10)] qs = await SimpleModel.objects.abulk_create(instances) self.assertEqual(len(qs), 10) @skipUnlessDBFeature("has_bulk_insert", "supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") @async_to_sync async def test_update_conflicts_unique_field_unsupported(self): msg = ( "This database backend does not support updating conflicts with specifying " "unique fields that can trigger the upsert." ) with self.assertRaisesMessage(NotSupportedError, msg): await SimpleModel.objects.abulk_create( [SimpleModel(field=1), SimpleModel(field=2)], update_conflicts=True, update_fields=["field"], unique_fields=["created"], ) async def test_abulk_update(self): instances = SimpleModel.objects.all() async for instance in instances: instance.field = instance.field * 10 await SimpleModel.objects.abulk_update(instances, ["field"]) qs = [(o.pk, o.field) async for o in SimpleModel.objects.all()] self.assertCountEqual( qs, [(self.s1.pk, 10), (self.s2.pk, 20), (self.s3.pk, 30)], ) async def test_ain_bulk(self): res = await SimpleModel.objects.ain_bulk() self.assertEqual( res, {self.s1.pk: self.s1, self.s2.pk: self.s2, self.s3.pk: self.s3}, ) res = await SimpleModel.objects.ain_bulk([self.s2.pk]) self.assertEqual(res, {self.s2.pk: self.s2}) res = await SimpleModel.objects.ain_bulk([self.s2.pk], field_name="id") self.assertEqual(res, {self.s2.pk: self.s2}) async def test_alatest(self): instance = await SimpleModel.objects.alatest("created") self.assertEqual(instance, self.s3) instance = await SimpleModel.objects.alatest("-created") self.assertEqual(instance, self.s1) async def test_aearliest(self): instance = await SimpleModel.objects.aearliest("created") self.assertEqual(instance, self.s1) instance = await SimpleModel.objects.aearliest("-created") self.assertEqual(instance, self.s3) async def test_afirst(self): instance = await SimpleModel.objects.afirst() self.assertEqual(instance, self.s1) instance = await SimpleModel.objects.filter(field=4).afirst() self.assertIsNone(instance) async def test_alast(self): instance = await SimpleModel.objects.alast() self.assertEqual(instance, self.s3) instance = await SimpleModel.objects.filter(field=4).alast() self.assertIsNone(instance) async def test_aaggregate(self): total = await SimpleModel.objects.aaggregate(total=Sum("field")) self.assertEqual(total, {"total": 6}) async def test_aexists(self): check = await SimpleModel.objects.filter(field=1).aexists() self.assertIs(check, True) check = await SimpleModel.objects.filter(field=4).aexists() self.assertIs(check, False) async def test_acontains(self): check = await SimpleModel.objects.acontains(self.s1) self.assertIs(check, True) # Unsaved instances are not allowed, so use an ID known not to exist. check = await SimpleModel.objects.acontains( SimpleModel(id=self.s3.id + 1, field=4) ) self.assertIs(check, False) async def test_aupdate(self): await SimpleModel.objects.aupdate(field=99) qs = [o async for o in SimpleModel.objects.all()] values = [instance.field for instance in qs] self.assertEqual(set(values), {99}) async def test_adelete(self): await SimpleModel.objects.filter(field=2).adelete() qs = [o async for o in SimpleModel.objects.all()] self.assertCountEqual(qs, [self.s1, self.s3]) @skipUnlessDBFeature("supports_explaining_query_execution") @async_to_sync async def test_aexplain(self): supported_formats = await sync_to_async(self._get_db_feature)( connection, "supported_explain_formats" ) all_formats = (None, *supported_formats) for format_ in all_formats: with self.subTest(format=format_): # TODO: Check the captured query when async versions of # self.assertNumQueries/CaptureQueriesContext context # processors are available. result = await SimpleModel.objects.filter(field=1).aexplain( format=format_ ) self.assertIsInstance(result, str) self.assertTrue(result) if not format_: continue if format_.lower() == "xml": try: xml.etree.ElementTree.fromstring(result) except xml.etree.ElementTree.ParseError as e: self.fail(f"QuerySet.aexplain() result is not valid XML: {e}") elif format_.lower() == "json": try: json.loads(result) except json.JSONDecodeError as e: self.fail(f"QuerySet.aexplain() result is not valid JSON: {e}") async def test_raw(self): sql = "SELECT id, field FROM async_queryset_simplemodel WHERE created=%s" qs = SimpleModel.objects.raw(sql, [self.s1.created]) self.assertEqual([o async for o in qs], [self.s1])
3af5210e24622c5ff2709622d4abaf827495375684e0f4052d72b0fcce3b63ba
import os import re import shutil import tempfile import time import warnings from io import StringIO from pathlib import Path from unittest import mock, skipIf, skipUnless from admin_scripts.tests import AdminScriptTestCase from django.core import management from django.core.management import execute_from_command_line from django.core.management.base import CommandError from django.core.management.commands.makemessages import Command as MakeMessagesCommand from django.core.management.commands.makemessages import write_pot_file from django.core.management.utils import find_command from django.test import SimpleTestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.utils._os import symlinks_supported from django.utils.translation import TranslatorCommentWarning from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree LOCALE = "de" has_xgettext = find_command("xgettext") gettext_version = MakeMessagesCommand().gettext_version if has_xgettext else None requires_gettext_019 = skipIf( has_xgettext and gettext_version < (0, 19), "gettext 0.19 required" ) @skipUnless(has_xgettext, "xgettext is mandatory for extraction tests") class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase): work_subdir = "commands" PO_FILE = "locale/%s/LC_MESSAGES/django.po" % LOCALE def _run_makemessages(self, **options): out = StringIO() management.call_command( "makemessages", locale=[LOCALE], verbosity=2, stdout=out, **options ) output = out.getvalue() self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() return output, po_contents def assertMsgIdPlural(self, msgid, haystack, use_quotes=True): return self._assertPoKeyword( "msgid_plural", msgid, haystack, use_quotes=use_quotes ) def assertMsgStr(self, msgstr, haystack, use_quotes=True): return self._assertPoKeyword("msgstr", msgstr, haystack, use_quotes=use_quotes) def assertNotMsgId(self, msgid, s, use_quotes=True): if use_quotes: msgid = '"%s"' % msgid msgid = re.escape(msgid) return self.assertTrue(not re.search("^msgid %s" % msgid, s, re.MULTILINE)) def _assertPoLocComment( self, assert_presence, po_filename, line_number, *comment_parts ): with open(po_filename) as fp: po_contents = fp.read() if os.name == "nt": # #: .\path\to\file.html:123 cwd_prefix = "%s%s" % (os.curdir, os.sep) else: # #: path/to/file.html:123 cwd_prefix = "" path = os.path.join(cwd_prefix, *comment_parts) parts = [path] if isinstance(line_number, str): line_number = self._get_token_line_number(path, line_number) if line_number is not None: parts.append(":%d" % line_number) needle = "".join(parts) pattern = re.compile(r"^\#\:.*" + re.escape(needle), re.MULTILINE) if assert_presence: return self.assertRegex( po_contents, pattern, '"%s" not found in final .po file.' % needle ) else: return self.assertNotRegex( po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle ) def _get_token_line_number(self, path, token): with open(path) as f: for line, content in enumerate(f, 1): if token in content: return line self.fail( "The token '%s' could not be found in %s, please check the test config" % (token, path) ) def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts): r""" self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py') verifies that the django.po file has a gettext-style location comment of the form `#: dirA/dirB/foo.py:42` (or `#: .\dirA\dirB\foo.py:42` on Windows) None can be passed for the line_number argument to skip checking of the :42 suffix part. A string token can also be passed as line_number, in which case it will be searched in the template, and its line number will be used. A msgid is a suitable candidate. """ return self._assertPoLocComment(True, po_filename, line_number, *comment_parts) def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts): """Check the opposite of assertLocationComment()""" return self._assertPoLocComment(False, po_filename, line_number, *comment_parts) def assertRecentlyModified(self, path): """ Assert that file was recently modified (modification time was less than 10 seconds ago). """ delta = time.time() - os.stat(path).st_mtime self.assertLess(delta, 10, "%s was recently modified" % path) def assertNotRecentlyModified(self, path): """ Assert that file was not recently modified (modification time was more than 10 seconds ago). """ delta = time.time() - os.stat(path).st_mtime self.assertGreater(delta, 10, "%s wasn't recently modified" % path) class BasicExtractorTests(ExtractorTests): @override_settings(USE_I18N=False) def test_use_i18n_false(self): """ makemessages also runs successfully when USE_I18N is False. """ management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, encoding="utf-8") as fp: po_contents = fp.read() # Check two random strings self.assertIn("#. Translators: One-line translator comment #1", po_contents) self.assertIn('msgctxt "Special trans context #1"', po_contents) def test_no_option(self): # One of either the --locale, --exclude, or --all options is required. msg = "Type 'manage.py help makemessages' for usage information." with mock.patch( "django.core.management.commands.makemessages.sys.argv", ["manage.py", "makemessages"], ): with self.assertRaisesRegex(CommandError, msg): management.call_command("makemessages") def test_valid_locale(self): out = StringIO() management.call_command("makemessages", locale=["de"], stdout=out, verbosity=1) self.assertNotIn("invalid locale de", out.getvalue()) self.assertIn("processing locale de", out.getvalue()) self.assertIs(Path(self.PO_FILE).exists(), True) def test_valid_locale_with_country(self): out = StringIO() management.call_command( "makemessages", locale=["en_GB"], stdout=out, verbosity=1 ) self.assertNotIn("invalid locale en_GB", out.getvalue()) self.assertIn("processing locale en_GB", out.getvalue()) self.assertIs(Path("locale/en_GB/LC_MESSAGES/django.po").exists(), True) def test_valid_locale_tachelhit_latin_morocco(self): out = StringIO() management.call_command( "makemessages", locale=["shi_Latn_MA"], stdout=out, verbosity=1 ) self.assertNotIn("invalid locale shi_Latn_MA", out.getvalue()) self.assertIn("processing locale shi_Latn_MA", out.getvalue()) self.assertIs(Path("locale/shi_Latn_MA/LC_MESSAGES/django.po").exists(), True) def test_valid_locale_private_subtag(self): out = StringIO() management.call_command( "makemessages", locale=["nl_NL-x-informal"], stdout=out, verbosity=1 ) self.assertNotIn("invalid locale nl_NL-x-informal", out.getvalue()) self.assertIn("processing locale nl_NL-x-informal", out.getvalue()) self.assertIs( Path("locale/nl_NL-x-informal/LC_MESSAGES/django.po").exists(), True ) def test_invalid_locale_uppercase(self): out = StringIO() management.call_command("makemessages", locale=["PL"], stdout=out, verbosity=1) self.assertIn("invalid locale PL, did you mean pl?", out.getvalue()) self.assertNotIn("processing locale pl", out.getvalue()) self.assertIs(Path("locale/pl/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_hyphen(self): out = StringIO() management.call_command( "makemessages", locale=["pl-PL"], stdout=out, verbosity=1 ) self.assertIn("invalid locale pl-PL, did you mean pl_PL?", out.getvalue()) self.assertNotIn("processing locale pl-PL", out.getvalue()) self.assertIs(Path("locale/pl-PL/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_lower_country(self): out = StringIO() management.call_command( "makemessages", locale=["pl_pl"], stdout=out, verbosity=1 ) self.assertIn("invalid locale pl_pl, did you mean pl_PL?", out.getvalue()) self.assertNotIn("processing locale pl_pl", out.getvalue()) self.assertIs(Path("locale/pl_pl/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_private_subtag(self): out = StringIO() management.call_command( "makemessages", locale=["nl-nl-x-informal"], stdout=out, verbosity=1 ) self.assertIn( "invalid locale nl-nl-x-informal, did you mean nl_NL-x-informal?", out.getvalue(), ) self.assertNotIn("processing locale nl-nl-x-informal", out.getvalue()) self.assertIs( Path("locale/nl-nl-x-informal/LC_MESSAGES/django.po").exists(), False ) def test_invalid_locale_plus(self): out = StringIO() management.call_command( "makemessages", locale=["en+GB"], stdout=out, verbosity=1 ) self.assertIn("invalid locale en+GB, did you mean en_GB?", out.getvalue()) self.assertNotIn("processing locale en+GB", out.getvalue()) self.assertIs(Path("locale/en+GB/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_end_with_underscore(self): out = StringIO() management.call_command("makemessages", locale=["en_"], stdout=out, verbosity=1) self.assertIn("invalid locale en_", out.getvalue()) self.assertNotIn("processing locale en_", out.getvalue()) self.assertIs(Path("locale/en_/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_start_with_underscore(self): out = StringIO() management.call_command("makemessages", locale=["_en"], stdout=out, verbosity=1) self.assertIn("invalid locale _en", out.getvalue()) self.assertNotIn("processing locale _en", out.getvalue()) self.assertIs(Path("locale/_en/LC_MESSAGES/django.po").exists(), False) def test_comments_extractor(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, encoding="utf-8") as fp: po_contents = fp.read() self.assertNotIn("This comment should not be extracted", po_contents) # Comments in templates self.assertIn( "#. Translators: This comment should be extracted", po_contents ) self.assertIn( "#. Translators: Django comment block for translators\n#. " "string's meaning unveiled", po_contents, ) self.assertIn("#. Translators: One-line translator comment #1", po_contents) self.assertIn( "#. Translators: Two-line translator comment #1\n#. continued here.", po_contents, ) self.assertIn("#. Translators: One-line translator comment #2", po_contents) self.assertIn( "#. Translators: Two-line translator comment #2\n#. continued here.", po_contents, ) self.assertIn("#. Translators: One-line translator comment #3", po_contents) self.assertIn( "#. Translators: Two-line translator comment #3\n#. continued here.", po_contents, ) self.assertIn("#. Translators: One-line translator comment #4", po_contents) self.assertIn( "#. Translators: Two-line translator comment #4\n#. continued here.", po_contents, ) self.assertIn( "#. Translators: One-line translator comment #5 -- with " "non ASCII characters: áéíóúö", po_contents, ) self.assertIn( "#. Translators: Two-line translator comment #5 -- with " "non ASCII characters: áéíóúö\n#. continued here.", po_contents, ) def test_special_char_extracted(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, encoding="utf-8") as fp: po_contents = fp.read() self.assertMsgId("Non-breaking space\u00a0:", po_contents) def test_blocktranslate_trimmed(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() # should not be trimmed self.assertNotMsgId("Text with a few line breaks.", po_contents) # should be trimmed self.assertMsgId( "Again some text with a few line breaks, this time should be trimmed.", po_contents, ) # #21406 -- Should adjust for eaten line numbers self.assertMsgId("Get my line number", po_contents) self.assertLocationCommentPresent( self.PO_FILE, "Get my line number", "templates", "test.html" ) def test_extraction_error(self): msg = ( "Translation blocks must not include other block tags: blocktranslate " "(file %s, line 3)" % os.path.join("templates", "template_with_error.tpl") ) with self.assertRaisesMessage(SyntaxError, msg): management.call_command( "makemessages", locale=[LOCALE], extensions=["tpl"], verbosity=0 ) # The temporary files were cleaned up. self.assertFalse(os.path.exists("./templates/template_with_error.tpl.py")) self.assertFalse(os.path.exists("./templates/template_0_with_no_error.tpl.py")) def test_unicode_decode_error(self): shutil.copyfile("./not_utf8.sample", "./not_utf8.txt") out = StringIO() management.call_command("makemessages", locale=[LOCALE], stdout=out) self.assertIn( "UnicodeDecodeError: skipped file not_utf8.txt in .", out.getvalue() ) def test_unicode_file_name(self): open(os.path.join(self.test_dir, "vidéo.txt"), "a").close() management.call_command("makemessages", locale=[LOCALE], verbosity=0) def test_extraction_warning(self): """test xgettext warning about multiple bare interpolation placeholders""" shutil.copyfile("./code.sample", "./code_sample.py") out = StringIO() management.call_command("makemessages", locale=[LOCALE], stdout=out) self.assertIn("code_sample.py:4", out.getvalue()) def test_template_message_context_extractor(self): """ Message contexts are correctly extracted for the {% translate %} and {% blocktranslate %} template tags (#14806). """ management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() # {% translate %} self.assertIn('msgctxt "Special trans context #1"', po_contents) self.assertMsgId("Translatable literal #7a", po_contents) self.assertIn('msgctxt "Special trans context #2"', po_contents) self.assertMsgId("Translatable literal #7b", po_contents) self.assertIn('msgctxt "Special trans context #3"', po_contents) self.assertMsgId("Translatable literal #7c", po_contents) # {% translate %} with a filter for ( minor_part ) in "abcdefgh": # Iterate from #7.1a to #7.1h template markers self.assertIn( 'msgctxt "context #7.1{}"'.format(minor_part), po_contents ) self.assertMsgId( "Translatable literal #7.1{}".format(minor_part), po_contents ) # {% blocktranslate %} self.assertIn('msgctxt "Special blocktranslate context #1"', po_contents) self.assertMsgId("Translatable literal #8a", po_contents) self.assertIn('msgctxt "Special blocktranslate context #2"', po_contents) self.assertMsgId("Translatable literal #8b-singular", po_contents) self.assertIn("Translatable literal #8b-plural", po_contents) self.assertIn('msgctxt "Special blocktranslate context #3"', po_contents) self.assertMsgId("Translatable literal #8c-singular", po_contents) self.assertIn("Translatable literal #8c-plural", po_contents) self.assertIn('msgctxt "Special blocktranslate context #4"', po_contents) self.assertMsgId("Translatable literal #8d %(a)s", po_contents) # {% trans %} and {% blocktrans %} self.assertMsgId("trans text", po_contents) self.assertMsgId("blocktrans text", po_contents) def test_context_in_single_quotes(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() # {% translate %} self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents) self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents) # {% blocktranslate %} self.assertIn( 'msgctxt "Special blocktranslate context wrapped in double quotes"', po_contents, ) self.assertIn( 'msgctxt "Special blocktranslate context wrapped in single quotes"', po_contents, ) def test_template_comments(self): """Template comment tags on the same line of other constructs (#19552)""" # Test detection/end user reporting of old, incorrect templates # translator comments syntax with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") management.call_command( "makemessages", locale=[LOCALE], extensions=["thtml"], verbosity=0 ) self.assertEqual(len(ws), 3) for w in ws: self.assertTrue(issubclass(w.category, TranslatorCommentWarning)) self.assertRegex( str(ws[0].message), r"The translator-targeted comment 'Translators: ignored i18n " r"comment #1' \(file templates[/\\]comments.thtml, line 4\) " r"was ignored, because it wasn't the last item on the line\.", ) self.assertRegex( str(ws[1].message), r"The translator-targeted comment 'Translators: ignored i18n " r"comment #3' \(file templates[/\\]comments.thtml, line 6\) " r"was ignored, because it wasn't the last item on the line\.", ) self.assertRegex( str(ws[2].message), r"The translator-targeted comment 'Translators: ignored i18n " r"comment #4' \(file templates[/\\]comments.thtml, line 8\) " r"was ignored, because it wasn't the last item on the line\.", ) # Now test .po file contents self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId("Translatable literal #9a", po_contents) self.assertNotIn("ignored comment #1", po_contents) self.assertNotIn("Translators: ignored i18n comment #1", po_contents) self.assertMsgId("Translatable literal #9b", po_contents) self.assertNotIn("ignored i18n comment #2", po_contents) self.assertNotIn("ignored comment #2", po_contents) self.assertMsgId("Translatable literal #9c", po_contents) self.assertNotIn("ignored comment #3", po_contents) self.assertNotIn("ignored i18n comment #3", po_contents) self.assertMsgId("Translatable literal #9d", po_contents) self.assertNotIn("ignored comment #4", po_contents) self.assertMsgId("Translatable literal #9e", po_contents) self.assertNotIn("ignored comment #5", po_contents) self.assertNotIn("ignored i18n comment #4", po_contents) self.assertMsgId("Translatable literal #9f", po_contents) self.assertIn("#. Translators: valid i18n comment #5", po_contents) self.assertMsgId("Translatable literal #9g", po_contents) self.assertIn("#. Translators: valid i18n comment #6", po_contents) self.assertMsgId("Translatable literal #9h", po_contents) self.assertIn("#. Translators: valid i18n comment #7", po_contents) self.assertMsgId("Translatable literal #9i", po_contents) self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #8") self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #9") self.assertMsgId("Translatable literal #9j", po_contents) def test_makemessages_find_files(self): """ find_files only discover files having the proper extensions. """ cmd = MakeMessagesCommand() cmd.ignore_patterns = ["CVS", ".*", "*~", "*.pyc"] cmd.symlinks = False cmd.domain = "django" cmd.extensions = ["html", "txt", "py"] cmd.verbosity = 0 cmd.locale_paths = [] cmd.default_locale_path = os.path.join(self.test_dir, "locale") found_files = cmd.find_files(self.test_dir) found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files} self.assertEqual(found_exts.difference({".py", ".html", ".txt"}), set()) cmd.extensions = ["js"] cmd.domain = "djangojs" found_files = cmd.find_files(self.test_dir) found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files} self.assertEqual(found_exts.difference({".js"}), set()) @mock.patch("django.core.management.commands.makemessages.popen_wrapper") def test_makemessages_gettext_version(self, mocked_popen_wrapper): # "Normal" output: mocked_popen_wrapper.return_value = ( "xgettext (GNU gettext-tools) 0.18.1\n" "Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n" "License GPLv3+: GNU GPL version 3 or later " "<http://gnu.org/licenses/gpl.html>\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n" "Written by Ulrich Drepper.\n", "", 0, ) cmd = MakeMessagesCommand() self.assertEqual(cmd.gettext_version, (0, 18, 1)) # Version number with only 2 parts (#23788) mocked_popen_wrapper.return_value = ( "xgettext (GNU gettext-tools) 0.17\n", "", 0, ) cmd = MakeMessagesCommand() self.assertEqual(cmd.gettext_version, (0, 17)) # Bad version output mocked_popen_wrapper.return_value = ("any other return value\n", "", 0) cmd = MakeMessagesCommand() with self.assertRaisesMessage( CommandError, "Unable to get gettext version. Is it installed?" ): cmd.gettext_version def test_po_file_encoding_when_updating(self): """ Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows (#23271). """ BR_PO_BASE = "locale/pt_BR/LC_MESSAGES/django" shutil.copyfile(BR_PO_BASE + ".pristine", BR_PO_BASE + ".po") management.call_command("makemessages", locale=["pt_BR"], verbosity=0) self.assertTrue(os.path.exists(BR_PO_BASE + ".po")) with open(BR_PO_BASE + ".po", encoding="utf-8") as fp: po_contents = fp.read() self.assertMsgStr("Größe", po_contents) def test_pot_charset_header_is_utf8(self): """Content-Type: ... charset=CHARSET is replaced with charset=UTF-8""" msgs = ( "# SOME DESCRIPTIVE TITLE.\n" "# (some lines truncated as they are not relevant)\n" '"Content-Type: text/plain; charset=CHARSET\\n"\n' '"Content-Transfer-Encoding: 8bit\\n"\n' "\n" "#: somefile.py:8\n" 'msgid "mañana; charset=CHARSET"\n' 'msgstr ""\n' ) with tempfile.NamedTemporaryFile() as pot_file: pot_filename = pot_file.name write_pot_file(pot_filename, msgs) with open(pot_filename, encoding="utf-8") as fp: pot_contents = fp.read() self.assertIn("Content-Type: text/plain; charset=UTF-8", pot_contents) self.assertIn("mañana; charset=CHARSET", pot_contents) class JavaScriptExtractorTests(ExtractorTests): PO_FILE = "locale/%s/LC_MESSAGES/djangojs.po" % LOCALE def test_javascript_literals(self): _, po_contents = self._run_makemessages(domain="djangojs") self.assertMsgId("This literal should be included.", po_contents) self.assertMsgId("gettext_noop should, too.", po_contents) self.assertMsgId("This one as well.", po_contents) self.assertMsgId(r"He said, \"hello\".", po_contents) self.assertMsgId("okkkk", po_contents) self.assertMsgId("TEXT", po_contents) self.assertMsgId("It's at http://example.com", po_contents) self.assertMsgId("String", po_contents) self.assertMsgId( "/* but this one will be too */ 'cause there is no way of telling...", po_contents, ) self.assertMsgId("foo", po_contents) self.assertMsgId("bar", po_contents) self.assertMsgId("baz", po_contents) self.assertMsgId("quz", po_contents) self.assertMsgId("foobar", po_contents) def test_media_static_dirs_ignored(self): """ Regression test for #23583. """ with override_settings( STATIC_ROOT=os.path.join(self.test_dir, "static/"), MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"), ): _, po_contents = self._run_makemessages(domain="djangojs") self.assertMsgId( "Static content inside app should be included.", po_contents ) self.assertNotMsgId( "Content from STATIC_ROOT should not be included", po_contents ) @override_settings(STATIC_ROOT=None, MEDIA_ROOT="") def test_default_root_settings(self): """ Regression test for #23717. """ _, po_contents = self._run_makemessages(domain="djangojs") self.assertMsgId("Static content inside app should be included.", po_contents) class IgnoredExtractorTests(ExtractorTests): def test_ignore_directory(self): out, po_contents = self._run_makemessages( ignore_patterns=[ os.path.join("ignore_dir", "*"), ] ) self.assertIn("ignoring directory ignore_dir", out) self.assertMsgId("This literal should be included.", po_contents) self.assertNotMsgId("This should be ignored.", po_contents) def test_ignore_subdirectory(self): out, po_contents = self._run_makemessages( ignore_patterns=[ "templates/*/ignore.html", "templates/subdir/*", ] ) self.assertIn("ignoring directory subdir", out) self.assertNotMsgId("This subdir should be ignored too.", po_contents) def test_ignore_file_patterns(self): out, po_contents = self._run_makemessages( ignore_patterns=[ "xxx_*", ] ) self.assertIn("ignoring file xxx_ignored.html", out) self.assertNotMsgId("This should be ignored too.", po_contents) def test_media_static_dirs_ignored(self): with override_settings( STATIC_ROOT=os.path.join(self.test_dir, "static/"), MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"), ): out, _ = self._run_makemessages() self.assertIn("ignoring directory static", out) self.assertIn("ignoring directory media_root", out) class SymlinkExtractorTests(ExtractorTests): def setUp(self): super().setUp() self.symlinked_dir = os.path.join(self.test_dir, "templates_symlinked") def test_symlink(self): if symlinks_supported(): os.symlink(os.path.join(self.test_dir, "templates"), self.symlinked_dir) else: self.skipTest( "os.symlink() not available on this OS + Python version combination." ) management.call_command( "makemessages", locale=[LOCALE], verbosity=0, symlinks=True ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId("This literal should be included.", po_contents) self.assertLocationCommentPresent( self.PO_FILE, None, "templates_symlinked", "test.html" ) class CopyPluralFormsExtractorTests(ExtractorTests): PO_FILE_ES = "locale/es/LC_MESSAGES/django.po" def test_copy_plural_forms(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertIn("Plural-Forms: nplurals=2; plural=(n != 1)", po_contents) def test_override_plural_forms(self): """Ticket #20311.""" management.call_command( "makemessages", locale=["es"], extensions=["djtpl"], verbosity=0 ) self.assertTrue(os.path.exists(self.PO_FILE_ES)) with open(self.PO_FILE_ES, encoding="utf-8") as fp: po_contents = fp.read() found = re.findall( r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL, ) self.assertEqual(1, len(found)) def test_translate_and_plural_blocktranslate_collision(self): """ Ensures a correct workaround for the gettext bug when handling a literal found inside a {% translate %} tag and also in another file inside a {% blocktranslate %} with a plural (#17375). """ management.call_command( "makemessages", locale=[LOCALE], extensions=["html", "djtpl"], verbosity=0 ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertNotIn( "#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents ) self.assertMsgId( "First `translate`, then `blocktranslate` with a plural", po_contents ) self.assertMsgIdPlural( "Plural for a `translate` and `blocktranslate` collision case", po_contents, ) class NoWrapExtractorTests(ExtractorTests): def test_no_wrap_enabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_wrap=True ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId( "This literal should also be included wrapped or not wrapped " "depending on the use of the --no-wrap option.", po_contents, ) def test_no_wrap_disabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_wrap=False ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId( '""\n"This literal should also be included wrapped or not ' 'wrapped depending on the "\n"use of the --no-wrap option."', po_contents, use_quotes=False, ) class LocationCommentsTests(ExtractorTests): def test_no_location_enabled(self): """Behavior is correct if --no-location switch is specified. See #16903.""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_location=True ) self.assertTrue(os.path.exists(self.PO_FILE)) self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html") def test_no_location_disabled(self): """Behavior is correct if --no-location switch isn't specified.""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_location=False ) self.assertTrue(os.path.exists(self.PO_FILE)) # #16903 -- Standard comment with source file relative path should be present self.assertLocationCommentPresent( self.PO_FILE, "Translatable literal #6b", "templates", "test.html" ) def test_location_comments_for_templatized_files(self): """ Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123 Refs #21209/#26341. """ management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId("#: templates/test.html.py", po_contents) self.assertLocationCommentNotPresent(self.PO_FILE, None, ".html.py") self.assertLocationCommentPresent(self.PO_FILE, 5, "templates", "test.html") @requires_gettext_019 def test_add_location_full(self): """makemessages --add-location=full""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="full" ) self.assertTrue(os.path.exists(self.PO_FILE)) # Comment with source file relative path and line number is present. self.assertLocationCommentPresent( self.PO_FILE, "Translatable literal #6b", "templates", "test.html" ) @requires_gettext_019 def test_add_location_file(self): """makemessages --add-location=file""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="file" ) self.assertTrue(os.path.exists(self.PO_FILE)) # Comment with source file relative path is present. self.assertLocationCommentPresent(self.PO_FILE, None, "templates", "test.html") # But it should not contain the line number. self.assertLocationCommentNotPresent( self.PO_FILE, "Translatable literal #6b", "templates", "test.html" ) @requires_gettext_019 def test_add_location_never(self): """makemessages --add-location=never""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="never" ) self.assertTrue(os.path.exists(self.PO_FILE)) self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html") @mock.patch( "django.core.management.commands.makemessages.Command.gettext_version", new=(0, 18, 99), ) def test_add_location_gettext_version_check(self): """ CommandError is raised when using makemessages --add-location with gettext < 0.19. """ msg = ( "The --add-location option requires gettext 0.19 or later. You have " "0.18.99." ) with self.assertRaisesMessage(CommandError, msg): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="full" ) class KeepPotFileExtractorTests(ExtractorTests): POT_FILE = "locale/django.pot" def test_keep_pot_disabled_by_default(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertFalse(os.path.exists(self.POT_FILE)) def test_keep_pot_explicitly_disabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, keep_pot=False ) self.assertFalse(os.path.exists(self.POT_FILE)) def test_keep_pot_enabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, keep_pot=True ) self.assertTrue(os.path.exists(self.POT_FILE)) class MultipleLocaleExtractionTests(ExtractorTests): PO_FILE_PT = "locale/pt/LC_MESSAGES/django.po" PO_FILE_DE = "locale/de/LC_MESSAGES/django.po" PO_FILE_KO = "locale/ko/LC_MESSAGES/django.po" LOCALES = ["pt", "de", "ch"] def test_multiple_locales(self): management.call_command("makemessages", locale=["pt", "de"], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE_PT)) self.assertTrue(os.path.exists(self.PO_FILE_DE)) def test_all_locales(self): """ When the `locale` flag is absent, all dirs from the parent locale dir are considered as language directories, except if the directory doesn't start with two letters (which excludes __pycache__, .gitignore, etc.). """ os.mkdir(os.path.join("locale", "_do_not_pick")) # Excluding locales that do not compile management.call_command("makemessages", exclude=["ja", "es_AR"], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE_KO)) self.assertFalse(os.path.exists("locale/_do_not_pick/LC_MESSAGES/django.po")) class ExcludedLocaleExtractionTests(ExtractorTests): work_subdir = "exclude" LOCALES = ["en", "fr", "it"] PO_FILE = "locale/%s/LC_MESSAGES/django.po" def _set_times_for_all_po_files(self): """ Set access and modification times to the Unix epoch time for all the .po files. """ for locale in self.LOCALES: os.utime(self.PO_FILE % locale, (0, 0)) def setUp(self): super().setUp() copytree("canned_locale", "locale") self._set_times_for_all_po_files() def test_command_help(self): with captured_stdout(), captured_stderr(): # `call_command` bypasses the parser; by calling # `execute_from_command_line` with the help subcommand we # ensure that there are no issues with the parser itself. execute_from_command_line(["django-admin", "help", "makemessages"]) def test_one_locale_excluded(self): management.call_command("makemessages", exclude=["it"], verbosity=0) self.assertRecentlyModified(self.PO_FILE % "en") self.assertRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") def test_multiple_locales_excluded(self): management.call_command("makemessages", exclude=["it", "fr"], verbosity=0) self.assertRecentlyModified(self.PO_FILE % "en") self.assertNotRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") def test_one_locale_excluded_with_locale(self): management.call_command( "makemessages", locale=["en", "fr"], exclude=["fr"], verbosity=0 ) self.assertRecentlyModified(self.PO_FILE % "en") self.assertNotRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") def test_multiple_locales_excluded_with_locale(self): management.call_command( "makemessages", locale=["en", "fr", "it"], exclude=["fr", "it"], verbosity=0 ) self.assertRecentlyModified(self.PO_FILE % "en") self.assertNotRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") class CustomLayoutExtractionTests(ExtractorTests): work_subdir = "project_dir" def test_no_locale_raises(self): msg = ( "Unable to find a locale path to store translations for file " "__init__.py. Make sure the 'locale' directory exists in an app " "or LOCALE_PATHS setting is set." ) with self.assertRaisesMessage(management.CommandError, msg): management.call_command("makemessages", locale=[LOCALE], verbosity=0) # Working files are cleaned up on an error. self.assertFalse(os.path.exists("./app_no_locale/test.html.py")) def test_project_locale_paths(self): self._test_project_locale_paths(os.path.join(self.test_dir, "project_locale")) def test_project_locale_paths_pathlib(self): self._test_project_locale_paths(Path(self.test_dir) / "project_locale") def _test_project_locale_paths(self, locale_path): """ * translations for an app containing a locale folder are stored in that folder * translations outside of that app are in LOCALE_PATHS[0] """ with override_settings(LOCALE_PATHS=[locale_path]): management.call_command("makemessages", locale=[LOCALE], verbosity=0) project_de_locale = os.path.join( self.test_dir, "project_locale", "de", "LC_MESSAGES", "django.po" ) app_de_locale = os.path.join( self.test_dir, "app_with_locale", "locale", "de", "LC_MESSAGES", "django.po", ) self.assertTrue(os.path.exists(project_de_locale)) self.assertTrue(os.path.exists(app_de_locale)) with open(project_de_locale) as fp: po_contents = fp.read() self.assertMsgId("This app has no locale directory", po_contents) self.assertMsgId("This is a project-level string", po_contents) with open(app_de_locale) as fp: po_contents = fp.read() self.assertMsgId("This app has a locale directory", po_contents) @skipUnless(has_xgettext, "xgettext is mandatory for extraction tests") class NoSettingsExtractionTests(AdminScriptTestCase): def test_makemessages_no_settings(self): out, err = self.run_django_admin(["makemessages", "-l", "en", "-v", "0"]) self.assertNoOutput(err) self.assertNoOutput(out) class UnchangedPoExtractionTests(ExtractorTests): work_subdir = "unchanged" def setUp(self): super().setUp() po_file = Path(self.PO_FILE) po_file_tmp = Path(self.PO_FILE + ".tmp") if os.name == "nt": # msgmerge outputs Windows style paths on Windows. po_contents = po_file_tmp.read_text().replace( "#: __init__.py", "#: .\\__init__.py", ) po_file.write_text(po_contents) else: po_file_tmp.rename(po_file) self.original_po_contents = po_file.read_text() def test_po_remains_unchanged(self): """PO files are unchanged unless there are new changes.""" _, po_contents = self._run_makemessages() self.assertEqual(po_contents, self.original_po_contents) def test_po_changed_with_new_strings(self): """PO files are updated when new changes are detected.""" Path("models.py.tmp").rename("models.py") _, po_contents = self._run_makemessages() self.assertNotEqual(po_contents, self.original_po_contents) self.assertMsgId( "This is a hitherto undiscovered translatable string.", po_contents, )
966e985f71f09592eb108e7d97f8451212ab9613c8833f0a6c8b2e55a185a4dc
import datetime import decimal import gettext as gettext_module import os import pickle import re import tempfile from contextlib import contextmanager from importlib import import_module from pathlib import Path from unittest import mock from asgiref.local import Local from django import forms from django.apps import AppConfig from django.conf import settings from django.conf.locale import LANG_INFO from django.conf.urls.i18n import i18n_patterns from django.template import Context, Template from django.test import ( RequestFactory, SimpleTestCase, TestCase, ignore_warnings, override_settings, ) from django.utils import translation from django.utils.deprecation import RemovedInDjango50Warning from django.utils.formats import ( date_format, get_format, iter_format_modules, localize, localize_input, reset_format_cache, sanitize_separators, sanitize_strftime_format, time_format, ) from django.utils.numberformat import format as nformat from django.utils.safestring import SafeString, mark_safe from django.utils.translation import ( activate, check_for_language, deactivate, get_language, get_language_bidi, get_language_from_request, get_language_info, gettext, gettext_lazy, ngettext, ngettext_lazy, npgettext, npgettext_lazy, pgettext, round_away_from_one, to_language, to_locale, trans_null, trans_real, ) from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) from .forms import CompanyForm, I18nForm, SelectDateForm from .models import Company, TestModel here = os.path.dirname(os.path.abspath(__file__)) extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(here, "other", "locale"), ] class AppModuleStub: def __init__(self, **kwargs): self.__dict__.update(kwargs) @contextmanager def patch_formats(lang, **settings): from django.utils.formats import _format_cache # Populate _format_cache with temporary values for key, value in settings.items(): _format_cache[(key, lang)] = value try: yield finally: reset_format_cache() class TranslationTests(SimpleTestCase): @translation.override("fr") def test_plural(self): """ Test plurals with ngettext. French differs from English in that 0 is singular. """ self.assertEqual( ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 année", ) self.assertEqual( ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 années", ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet" ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets" ) def test_plural_null(self): g = trans_null.ngettext self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years") self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year") self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years") @override_settings(LOCALE_PATHS=extended_locale_paths) @translation.override("fr") def test_multiple_plurals_per_language(self): """ Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po has a different plural equation with 3 plurals, this tests if those plural are honored. """ self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1") self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier") self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2") french = trans_real.catalog() # Internal _catalog can query subcatalogs (from different po files). self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier") self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure") def test_override(self): activate("de") try: with translation.override("pl"): self.assertEqual(get_language(), "pl") self.assertEqual(get_language(), "de") with translation.override(None): self.assertIsNone(get_language()) with translation.override("pl"): pass self.assertIsNone(get_language()) self.assertEqual(get_language(), "de") finally: deactivate() def test_override_decorator(self): @translation.override("pl") def func_pl(): self.assertEqual(get_language(), "pl") @translation.override(None) def func_none(): self.assertIsNone(get_language()) try: activate("de") func_pl() self.assertEqual(get_language(), "de") func_none() self.assertEqual(get_language(), "de") finally: deactivate() def test_override_exit(self): """ The language restored is the one used when the function was called, not the one used when the decorator was initialized (#23381). """ activate("fr") @translation.override("pl") def func_pl(): pass deactivate() try: activate("en") func_pl() self.assertEqual(get_language(), "en") finally: deactivate() def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = gettext_lazy("Add %(name)s") d = {"name": "Ringo"} self.assertEqual("Add Ringo", s % d) with translation.override("de", deactivate=True): self.assertEqual("Ringo hinzuf\xfcgen", s % d) with translation.override("pl"): self.assertEqual("Dodaj Ringo", s % d) # It should be possible to compare *_lazy objects. s1 = gettext_lazy("Add %(name)s") self.assertEqual(s, s1) s2 = gettext_lazy("Add %(name)s") s3 = gettext_lazy("Add %(name)s") self.assertEqual(s2, s3) self.assertEqual(s, s2) s4 = gettext_lazy("Some other string") self.assertNotEqual(s, s4) def test_lazy_pickle(self): s1 = gettext_lazy("test") self.assertEqual(str(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(str(s2), "test") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy(self): simple_with_format = ngettext_lazy("%d good result", "%d good results") simple_context_with_format = npgettext_lazy( "Exclamation", "%d good result", "%d good results" ) simple_without_format = ngettext_lazy("good result", "good results") with translation.override("de"): self.assertEqual(simple_with_format % 1, "1 gutes Resultat") self.assertEqual(simple_with_format % 4, "4 guten Resultate") self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!") self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!") self.assertEqual(simple_without_format % 1, "gutes Resultat") self.assertEqual(simple_without_format % 4, "guten Resultate") complex_nonlazy = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4 ) complex_deferred = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy % {"num": 4, "name": "Jim"}, "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 1}, "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 5}, "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred % {"name": "Jim"} self.assertEqual( complex_context_nonlazy % {"num": 4, "name": "Jim"}, "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 1}, "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 5}, "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred % {"name": "Jim"} @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy_format_style(self): simple_with_format = ngettext_lazy("{} good result", "{} good results") simple_context_with_format = npgettext_lazy( "Exclamation", "{} good result", "{} good results" ) with translation.override("de"): self.assertEqual(simple_with_format.format(1), "1 gutes Resultat") self.assertEqual(simple_with_format.format(4), "4 guten Resultate") self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!") self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!") complex_nonlazy = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4 ) complex_deferred = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num" ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy.format(num=4, name="Jim"), "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred.format(name="Jim", num=1), "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred.format(name="Jim", num=5), "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred.format(name="Jim") self.assertEqual( complex_context_nonlazy.format(num=4, name="Jim"), "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=1), "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=5), "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred.format(name="Jim") def test_ngettext_lazy_bool(self): self.assertTrue(ngettext_lazy("%d good result", "%d good results")) self.assertFalse(ngettext_lazy("", "")) def test_ngettext_lazy_pickle(self): s1 = ngettext_lazy("%d good result", "%d good results") self.assertEqual(s1 % 1, "1 good result") self.assertEqual(s1 % 8, "8 good results") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(s2 % 1, "1 good result") self.assertEqual(s2 % 8, "8 good results") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_pgettext(self): trans_real._active = Local() trans_real._translations = {} with translation.override("de"): self.assertEqual(pgettext("unexisting", "May"), "May") self.assertEqual(pgettext("month name", "May"), "Mai") self.assertEqual(pgettext("verb", "May"), "Kann") self.assertEqual( npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate" ) def test_empty_value(self): """Empty value must stay empty after being translated (#23196).""" with translation.override("de"): self.assertEqual("", gettext("")) s = mark_safe("") self.assertEqual(s, gettext(s)) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_safe_status(self): """ Translating a string requiring no auto-escaping with gettext or pgettext shouldn't change the "safe" status. """ trans_real._active = Local() trans_real._translations = {} s1 = mark_safe("Password") s2 = mark_safe("May") with translation.override("de", deactivate=True): self.assertIs(type(gettext(s1)), SafeString) self.assertIs(type(pgettext("month name", s2)), SafeString) self.assertEqual("aPassword", SafeString("a") + s1) self.assertEqual("Passworda", s1 + SafeString("a")) self.assertEqual("Passworda", s1 + mark_safe("a")) self.assertEqual("aPassword", mark_safe("a") + s1) self.assertEqual("as", mark_safe("a") + mark_safe("s")) def test_maclines(self): """ Translations on files with Mac or DOS end of lines will be converted to unix EOF in .po catalogs. """ ca_translation = trans_real.translation("ca") ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n" ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n" with translation.override("ca", deactivate=True): self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r")) self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n")) def test_to_locale(self): tests = ( ("en", "en"), ("EN", "en"), ("en-us", "en_US"), ("EN-US", "en_US"), ("en_US", "en_US"), # With > 2 characters after the dash. ("sr-latn", "sr_Latn"), ("sr-LATN", "sr_Latn"), ("sr_Latn", "sr_Latn"), # 3-char language codes. ("ber-MA", "ber_MA"), ("BER-MA", "ber_MA"), ("BER_MA", "ber_MA"), ("ber_MA", "ber_MA"), # With private use subtag (x-informal). ("nl-nl-x-informal", "nl_NL-x-informal"), ("NL-NL-X-INFORMAL", "nl_NL-x-informal"), ("sr-latn-x-informal", "sr_Latn-x-informal"), ("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"), ) for lang, locale in tests: with self.subTest(lang=lang): self.assertEqual(to_locale(lang), locale) def test_to_language(self): self.assertEqual(to_language("en_US"), "en-us") self.assertEqual(to_language("sr_Lat"), "sr-lat") def test_language_bidi(self): self.assertIs(get_language_bidi(), False) with translation.override(None): self.assertIs(get_language_bidi(), False) def test_language_bidi_null(self): self.assertIs(trans_null.get_language_bidi(), False) with override_settings(LANGUAGE_CODE="he"): self.assertIs(get_language_bidi(), True) class TranslationLoadingTests(SimpleTestCase): def setUp(self): """Clear translation state.""" self._old_language = get_language() self._old_translations = trans_real._translations deactivate() trans_real._translations = {} def tearDown(self): trans_real._translations = self._old_translations activate(self._old_language) @override_settings( USE_I18N=True, LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("en-ca", "English (Canada)"), ("en-nz", "English (New Zealand)"), ("en-au", "English (Australia)"), ], LOCALE_PATHS=[os.path.join(here, "loading")], INSTALLED_APPS=["i18n.loading_app"], ) def test_translation_loading(self): """ "loading_app" does not have translations for all languages provided by "loading". Catalogs are merged correctly. """ tests = [ ("en", "local country person"), ("en_AU", "aussie"), ("en_NZ", "kiwi"), ("en_CA", "canuck"), ] # Load all relevant translations. for language, _ in tests: activate(language) # Catalogs are merged correctly. for language, nickname in tests: with self.subTest(language=language): activate(language) self.assertEqual(gettext("local country person"), nickname) class TranslationThreadSafetyTests(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *args, **kwargs): res = str.split(self, *args, **kwargs) trans_real._translations["en-YY"] = None return res trans_real._translations = {sideeffect_str("en-XX"): None} def tearDown(self): trans_real._translations = self._translations activate(self._old_language) def test_bug14894_translation_activate_thread_safety(self): translation_count = len(trans_real._translations) # May raise RuntimeError if translation.activate() isn't thread-safe. translation.activate("pl") # make sure sideeffect_str actually added a new translation self.assertLess(translation_count, len(trans_real._translations)) class FormattingTests(SimpleTestCase): def setUp(self): super().setUp() self.n = decimal.Decimal("66666.666") self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.long = 10000 self.ctxt = Context( { "n": self.n, "t": self.t, "d": self.d, "dt": self.dt, "f": self.f, "l": self.long, } ) def test_all_format_strings(self): all_locales = LANG_INFO.keys() some_date = datetime.date(2017, 10, 14) some_datetime = datetime.datetime(2017, 10, 14, 10, 23) for locale in all_locales: with self.subTest(locale=locale), translation.override(locale): self.assertIn( "2017", date_format(some_date) ) # Uses DATE_FORMAT by default self.assertIn( "23", time_format(some_datetime) ) # Uses TIME_FORMAT by default self.assertIn( "2017", date_format(some_datetime, format=get_format("DATETIME_FORMAT")), ) self.assertIn( "2017", date_format(some_date, format=get_format("YEAR_MONTH_FORMAT")), ) self.assertIn( "14", date_format(some_date, format=get_format("MONTH_DAY_FORMAT")) ) self.assertIn( "2017", date_format(some_date, format=get_format("SHORT_DATE_FORMAT")), ) self.assertIn( "2017", date_format( some_datetime, format=get_format("SHORT_DATETIME_FORMAT") ), ) def test_locale_independent(self): """ Localization of numbers """ with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual( "66666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "66666A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "66666", nformat( self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y" ), ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( "66,666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "6B6B6B6B6A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10,00,00,000.00", nformat( 100000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, 0), thousand_sep=",", ), ) self.assertEqual( "1,0,00,000,0000.00", nformat( 10000000000.00, decimal_sep=".", decimal_pos=2, grouping=(4, 3, 2, 1, 0), thousand_sep=",", ), ) self.assertEqual( "10000,00,000.00", nformat( 1000000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, -1), thousand_sep=",", ), ) # This unusual grouping/force_grouping combination may be triggered # by the intcomma filter. self.assertEqual( "10000", nformat( self.long, decimal_sep=".", decimal_pos=0, grouping=0, force_grouping=True, ), ) # date filter self.assertEqual( "31.12.2009 в 20:50", Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt), ) self.assertEqual( "⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt) ) @ignore_warnings(category=RemovedInDjango50Warning) @override_settings(USE_L10N=False) def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ with translation.override("ca", deactivate=True): self.maxDiff = 3000 self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15 a.m.", time_format(self.t)) self.assertEqual("Des. 31, 2009", date_format(self.d)) self.assertEqual("desembre 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Des. 31, 2009", localize(self.d)) self.assertEqual("Des. 31, 2009, 8:50 p.m.", localize(self.dt)) self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Des. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Des. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template('{{ n|floatformat:"2u" }}').render(self.ctxt) ) self.assertEqual( "100000.0", Template('{{ f|floatformat:"u" }}').render(self.ctxt) ) self.assertEqual( "66666.67", Template('{{ n|floatformat:"2gu" }}').render(self.ctxt), ) self.assertEqual( "100000.0", Template('{{ f|floatformat:"ug" }}').render(self.ctxt), ) self.assertEqual( "10:15 a.m.", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertFalse(form.is_valid()) self.assertEqual(["Introdu\xefu un n\xfamero."], form.errors["float_field"]) self.assertEqual( ["Introdu\xefu un n\xfamero."], form.errors["decimal_field"] ) self.assertEqual( ["Introdu\xefu una data v\xe0lida."], form.errors["date_field"] ) self.assertEqual( ["Introdu\xefu una data/hora v\xe0lides."], form.errors["datetime_field"], ) self.assertEqual( ["Introdu\xefu un n\xfamero enter."], form.errors["integer_field"] ) form2 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form2.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form2.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # We shouldn't change the behavior of the floatformat filter re: # thousand separator and grouping when localization is disabled # even if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and # THOUSAND_SEPARATOR settings are specified. with self.settings( USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR="!" ): self.assertEqual( "66666.67", Template('{{ n|floatformat:"2u" }}').render(self.ctxt) ) self.assertEqual( "100000.0", Template('{{ f|floatformat:"u" }}').render(self.ctxt) ) def test_false_like_locale_formats(self): """ The active locale's formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string) (#16938). """ with translation.override("fr"): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"): self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) # Even a second time (after the format has been cached)... self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) with self.settings(FIRST_DAY_OF_WEEK=0): self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) # Even a second time (after the format has been cached)... self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) def test_l10n_enabled(self): self.maxDiff = 3000 # Catalan locale with translation.override("ca", deactivate=True): self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT")) self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(",", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15", time_format(self.t)) self.assertEqual("31 de desembre de 2009", date_format(self.d)) self.assertEqual( "1 d'abril de 2009", date_format(datetime.date(2009, 4, 1)) ) self.assertEqual( "desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT") ) self.assertEqual( "31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", localize(self.n)) self.assertEqual("99.999,999", localize(self.f)) self.assertEqual("10.000", localize(self.long)) self.assertEqual("True", localize(True)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", localize(self.n)) self.assertEqual("99999,999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("31 de desembre de 2009", localize(self.d)) self.assertEqual( "31 de desembre de 2009 a les 20:50", localize(self.dt) ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=True): form3 = I18nForm( { "decimal_field": "66.666,666", "float_field": "99.999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertTrue(form3.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form3.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form3.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form3.cleaned_data["time_field"] ) self.assertEqual(1234, form3.cleaned_data["integer_field"]) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual( "31 de desembre de 2009", Template("{{ d }}").render(self.ctxt) ) self.assertEqual( "31 de desembre de 2009 a les 20:50", Template("{{ dt }}").render(self.ctxt), ) self.assertEqual( "66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000,0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66.666,67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100.000,0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "31/12/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "31/12/2009 20:50", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) self.assertEqual( date_format(datetime.datetime.now(), "DATE_FORMAT"), Template('{% now "DATE_FORMAT" %}').render(self.ctxt), ) with self.settings(USE_THOUSAND_SEPARATOR=False): form4 = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form4.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form4.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form4.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form4.cleaned_data["time_field"] ) self.assertEqual(1234, form4.cleaned_data["integer_field"]) form5 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form5.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # Russian locale (with E as month) with translation.override("ru", deactivate=True): self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' '<option value="3">\u041c\u0430\u0440\u0442</option>' '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' '<option value="5">\u041c\u0430\u0439</option>' '<option value="6">\u0418\u044e\u043d\u044c</option>' '<option value="7">\u0418\u044e\u043b\u044c</option>' '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c' "</option>" '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c' "</option>" "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # English locale with translation.override("en", deactivate=True): self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("Dec. 31, 2009", date_format(self.d)) self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", localize(self.n)) self.assertEqual("99,999.999", localize(self.f)) self.assertEqual("10,000", localize(self.long)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Dec. 31, 2009", localize(self.d)) self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000.0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66,666.67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100,000.0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form5 = I18nForm( { "decimal_field": "66666.666", "float_field": "99999.999", "date_field": "12/31/2009", "datetime_field": "12/31/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form5.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form5.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data["datetime_field"], ) self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"]) self.assertEqual(1234, form5.cleaned_data["integer_field"]) form6 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form6.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form6.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">January</option>' '<option value="2">February</option>' '<option value="3">March</option>' '<option value="4">April</option>' '<option value="5">May</option>' '<option value="6">June</option>' '<option value="7">July</option>' '<option value="8">August</option>' '<option value="9">September</option>' '<option value="10">October</option>' '<option value="11">November</option>' '<option value="12" selected>December</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de-at", deactivate=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) with translation.override("es-us", deactivate=True): self.assertEqual("31 de Diciembre de 2009", date_format(self.d)) def test_localized_input(self): """ Tests if form input is correctly localized """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): form6 = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertTrue(form6.is_valid()) self.assertHTMLEqual( form6.as_ul(), '<li><label for="id_name">Name:</label>' '<input id="id_name" type="text" name="name" value="acme" ' ' maxlength="50" required></li>' '<li><label for="id_date_added">Date added:</label>' '<input type="text" name="date_added" value="31.12.2009 06:00:00" ' ' id="id_date_added" required></li>' '<li><label for="id_cents_paid">Cents paid:</label>' '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" ' " required></li>" '<li><label for="id_products_delivered">Products delivered:</label>' '<input type="text" name="products_delivered" value="12000" ' ' id="id_products_delivered" required>' "</li>", ) self.assertEqual( localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00", ) self.assertEqual( datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"], ) with self.settings(USE_THOUSAND_SEPARATOR=True): # Checking for the localized "products_delivered" field self.assertInHTML( '<input type="text" name="products_delivered" ' 'value="12.000" id="id_products_delivered" required>', form6.as_ul(), ) def test_localized_input_func(self): tests = ( (True, "True"), (datetime.date(1, 1, 1), "0001-01-01"), (datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"), ) with self.settings(USE_THOUSAND_SEPARATOR=True): for value, expected in tests: with self.subTest(value=value): self.assertEqual(localize_input(value), expected) def test_sanitize_strftime_format(self): for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%C", "%02d" % (year // 100)), ("%F", "%04d-01-01" % year), ("%G", "%04d" % year), ("%Y", "%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_strftime_format_with_escaped_percent(self): dt = datetime.date(1, 1, 1) for fmt, expected in [ ("%%C", "%C"), ("%%F", "%F"), ("%%G", "%G"), ("%%Y", "%Y"), ("%%%%C", "%%C"), ("%%%%F", "%%F"), ("%%%%G", "%%G"), ("%%%%Y", "%%Y"), ]: with self.subTest(fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%%%C", "%%%02d" % (year // 100)), ("%%%F", "%%%04d-01-01" % year), ("%%%G", "%%%04d" % year), ("%%%Y", "%%%04d" % year), ("%%%%%C", "%%%%%02d" % (year // 100)), ("%%%%%F", "%%%%%04d-01-01" % year), ("%%%%%G", "%%%%%04d" % year), ("%%%%%Y", "%%%%%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_separators(self): """ Tests django.utils.formats.sanitize_separators. """ # Non-strings are untouched self.assertEqual(sanitize_separators(123), 123) with translation.override("ru", deactivate=True): # Russian locale has non-breaking space (\xa0) as thousand separator # Usual space is accepted too when sanitizing inputs with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567") self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777") self.assertEqual(sanitize_separators("12 345"), "12345") self.assertEqual(sanitize_separators("77 777,777"), "77777.777") with translation.override(None): # RemovedInDjango50Warning with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."): self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345") with self.settings(USE_THOUSAND_SEPARATOR=True): with patch_formats( get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR="," ): self.assertEqual(sanitize_separators("10.234"), "10234") # Suspicion that user entered dot as decimal separator (#22171) self.assertEqual(sanitize_separators("10.10"), "10.10") # RemovedInDjango50Warning: When the deprecation ends, remove # @ignore_warnings and USE_L10N=False. The assertions should remain # because format-related settings will take precedence over # locale-dictated formats. with ignore_warnings(category=RemovedInDjango50Warning): with self.settings(USE_L10N=False): with self.settings(DECIMAL_SEPARATOR=","): self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") with self.settings( DECIMAL_SEPARATOR=",", THOUSAND_SEPARATOR=".", USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(sanitize_separators("1.001,10"), "1001.10") self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") # Invalid output. self.assertEqual(sanitize_separators("1,001.10"), "1.001.10") def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ # Importing some format modules so that we can compare the returned # modules with these expected modules default_mod = import_module("django.conf.locale.de.formats") test_mod = import_module("i18n.other.locale.de.formats") test_mod2 = import_module("i18n.other2.locale.de.formats") with translation.override("de-at", deactivate=True): # Should return the correct default module when no setting is set self.assertEqual(list(iter_format_modules("de")), [default_mod]) # When the setting is a string, should return the given module and # the default module self.assertEqual( list(iter_format_modules("de", "i18n.other.locale")), [test_mod, default_mod], ) # When setting is a list of strings, should return the given # modules and the default module self.assertEqual( list( iter_format_modules( "de", ["i18n.other.locale", "i18n.other2.locale"] ) ), [test_mod, test_mod2, default_mod], ) def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ en_format_mod = import_module("django.conf.locale.en.formats") en_gb_format_mod = import_module("django.conf.locale.en_GB.formats") self.assertEqual( list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod] ) def test_get_format_modules_lang(self): with translation.override("de", deactivate=True): self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en")) def test_get_format_lazy_format(self): self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y") def test_localize_templatetag_and_filter(self): """ Test the {% localize %} templatetag and the localize/unlocalize filters. """ context = Context( {"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)} ) template1 = Template( "{% load l10n %}{% localize %}" "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; " "{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}" ) template2 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} " "{{ int }}/{{ float }}/{{ date }}" ) template3 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}" ) template4 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|localize }}/{{ float|localize }}/{{ date|localize }}" ) expected_localized = "1.455/3,14/31. Dezember 2016" expected_unlocalized = "1455/3.14/Dez. 31, 2016" output1 = "; ".join([expected_localized, expected_localized]) output2 = "; ".join( [expected_localized, expected_unlocalized, expected_localized] ) output3 = "; ".join([expected_localized, expected_unlocalized]) output4 = "; ".join([expected_unlocalized, expected_localized]) with translation.override("de", deactivate=True): # RemovedInDjango50Warning: When the deprecation ends, remove # @ignore_warnings and USE_L10N=False. The assertions should remain # because format-related settings will take precedence over # locale-dictated formats. with ignore_warnings(category=RemovedInDjango50Warning): with self.settings( USE_L10N=False, DATE_FORMAT="N j, Y", DECIMAL_SEPARATOR=".", NUMBER_GROUPING=0, USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(template1.render(context), output1) self.assertEqual(template4.render(context), output4) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) def test_localized_off_numbers(self): """A string representation is returned for unlocalized numbers.""" template = Template( "{% load l10n %}{% localize off %}" "{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}" ) context = Context( {"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")} ) with self.settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") # RemovedInDjango50Warning. with ignore_warnings(category=RemovedInDjango50Warning): with self.settings( USE_L10N=False, DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") def test_localized_as_text_as_hidden_input(self): """ Form input with 'as_hidden' or 'as_text' is correctly localized. """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): template = Template( "{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}" ) template_as_text = Template( "{% load l10n %}" "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}" ) template_as_hidden = Template( "{% load l10n %}" "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}" ) form = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) context = Context({"form": form}) self.assertTrue(form.is_valid()) self.assertHTMLEqual( template.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_text.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_hidden.render(context), '<input id="id_date_added" name="date_added" type="hidden" ' 'value="31.12.2009 06:00:00">;' '<input id="id_cents_paid" name="cents_paid" type="hidden" ' 'value="59,47">', ) def test_format_arbitrary_settings(self): self.assertEqual(get_format("DEBUG"), "DEBUG") def test_get_custom_format(self): reset_format_cache() with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"): with translation.override("fr", deactivate=True): self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT")) def test_admin_javascript_supported_input_formats(self): """ The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by the admin's time picker widget. """ regex = re.compile("%([^BcdHImMpSwxXyY%])") for language_code, language_name in settings.LANGUAGES: for format_name in ( "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ): with self.subTest(language=language_code, format=format_name): formatter = get_format(format_name, lang=language_code)[0] self.assertEqual( regex.findall(formatter), [], "%s locale's %s uses an unsupported format code." % (language_code, format_name), ) class MiscTests(SimpleTestCase): rf = RequestFactory() @override_settings(LANGUAGE_CODE="de") def test_english_fallback(self): """ With a non-English LANGUAGE_CODE and if the active language is English or one of its variants, the untranslated string should be returned (instead of falling back to LANGUAGE_CODE) (See #24413). """ self.assertEqual(gettext("Image"), "Bild") with translation.override("en"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-us"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-ca"): self.assertEqual(gettext("Image"), "Image") def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ tests = [ # Good headers ("de", [("de", 1.0)]), ("en-AU", [("en-au", 1.0)]), ("es-419", [("es-419", 1.0)]), ("*;q=1.00", [("*", 1.0)]), ("en-AU;q=0.123", [("en-au", 0.123)]), ("en-au;q=0.5", [("en-au", 0.5)]), ("en-au;q=1.0", [("en-au", 1.0)]), ("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]), ("en-au-xx", [("en-au-xx", 1.0)]), ( "de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125", [ ("de", 1.0), ("en-au", 0.75), ("en-us", 0.5), ("en", 0.25), ("es", 0.125), ("fa", 0.125), ], ), ("*", [("*", 1.0)]), ("de;q=0.", [("de", 0.0)]), ("en; q=1,", [("en", 1.0)]), ("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]), # Bad headers ("en-gb;q=1.0000", []), ("en;q=0.1234", []), ("en;q=.2", []), ("abcdefghi-au", []), ("**", []), ("en,,gb", []), ("en-au;q=0.1.0", []), (("X" * 97) + "Z,en", []), ("da, en-gb;q=0.8, en;q=0.7,#", []), ("de;q=2.0", []), ("de;q=0.a", []), ("12-345", []), ("", []), ("en;q=1e0", []), ("en-au;q=1.0", []), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual( trans_real.parse_accept_lang_header(value), tuple(expected) ) def test_parse_literal_http_header(self): """ Now test that we parse a literal HTTP header correctly. """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt-br"} self.assertEqual("pt-br", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "pt"} self.assertEqual("pt", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "es,de"} self.assertEqual("es", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "es-ar,de"} self.assertEqual("es-ar", g(r)) # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.META = {"HTTP_ACCEPT_LANGUAGE": "es-us"} self.assertEqual(g(r), "es") # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh-hans) # the user sets zh-hans as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-hans,de"} self.assertEqual(g(r), "zh-hans") r.META = {"HTTP_ACCEPT_LANGUAGE": "NL"} self.assertEqual("nl", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "fy"} self.assertEqual("fy", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "ia"} self.assertEqual("ia", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "sr-latn"} self.assertEqual("sr-latn", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-hans"} self.assertEqual("zh-hans", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-hant"} self.assertEqual("zh-hant", g(r)) @override_settings( LANGUAGES=[ ("en", "English"), ("zh-hans", "Simplified Chinese"), ("zh-hant", "Traditional Chinese"), ] ) def test_support_for_deprecated_chinese_language_codes(self): """ Some browsers (Firefox, IE, etc.) use deprecated language codes. As these language codes will be removed in Django 1.9, these will be incorrectly matched. For example zh-tw (traditional) will be interpreted as zh-hans (simplified), which is wrong. So we should also accept these deprecated language codes. refs #18419 -- this is explicitly for browser compatibility """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-cn,en"} self.assertEqual(g(r), "zh-hans") r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-tw,en"} self.assertEqual(g(r), "zh-hant") def test_special_fallback_language(self): """ Some languages may have special fallbacks that don't follow the simple 'fr-ca' -> 'fr' logic (notably Chinese codes). """ r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-my,en"} self.assertEqual(get_language_from_request(r), "zh-hans") def test_subsequent_code_fallback_language(self): """ Subsequent language codes should be used when the language code is not supported. """ tests = [ ("zh-Hans-CN", "zh-hans"), ("zh-hans-mo", "zh-hans"), ("zh-hans-HK", "zh-hans"), ("zh-Hant-HK", "zh-hant"), ("zh-hant-tw", "zh-hant"), ("zh-hant-SG", "zh-hant"), ] r = self.rf.get("/") r.COOKIES = {} for value, expected in tests: with self.subTest(value=value): r.META = {"HTTP_ACCEPT_LANGUAGE": f"{value},en"} self.assertEqual(get_language_from_request(r), expected) def test_parse_language_cookie(self): """ Now test that we parse language preferences stored in a cookie correctly. """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "pt-br"} r.META = {} self.assertEqual("pt-br", g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "pt"} r.META = {} self.assertEqual("pt", g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "es"} r.META = {"HTTP_ACCEPT_LANGUAGE": "de"} self.assertEqual("es", g(r)) # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "es-us"} r.META = {} self.assertEqual(g(r), "es") # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh-hans) # the user sets zh-hans as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "zh-hans"} r.META = {"HTTP_ACCEPT_LANGUAGE": "de"} self.assertEqual(g(r), "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("ar-dz", "Algerian Arabic"), ("de", "German"), ("de-at", "Austrian German"), ("pt-BR", "Portuguese (Brazil)"), ], ) def test_get_supported_language_variant_real(self): g = trans_real.get_supported_language_variant self.assertEqual(g("en"), "en") self.assertEqual(g("en-gb"), "en") self.assertEqual(g("de"), "de") self.assertEqual(g("de-at"), "de-at") self.assertEqual(g("de-ch"), "de") self.assertEqual(g("pt-br"), "pt-br") self.assertEqual(g("pt-BR"), "pt-BR") self.assertEqual(g("pt"), "pt-br") self.assertEqual(g("pt-pt"), "pt-br") self.assertEqual(g("ar-dz"), "ar-dz") self.assertEqual(g("ar-DZ"), "ar-DZ") with self.assertRaises(LookupError): g("pt", strict=True) with self.assertRaises(LookupError): g("pt-pt", strict=True) with self.assertRaises(LookupError): g("xyz") with self.assertRaises(LookupError): g("xy-zz") def test_get_supported_language_variant_null(self): g = trans_null.get_supported_language_variant self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) with self.assertRaises(LookupError): g("pt") with self.assertRaises(LookupError): g("de") with self.assertRaises(LookupError): g("de-at") with self.assertRaises(LookupError): g("de", strict=True) with self.assertRaises(LookupError): g("de-at", strict=True) with self.assertRaises(LookupError): g("xyz") @override_settings( LANGUAGES=[ ("en", "English"), ("en-latn-us", "Latin English"), ("de", "German"), ("de-1996", "German, orthography of 1996"), ("de-at", "Austrian German"), ("de-ch-1901", "German, Swiss variant, traditional orthography"), ("i-mingo", "Mingo"), ("kl-tunumiit", "Tunumiisiut"), ("nan-hani-tw", "Hanji"), ("pl", "Polish"), ], ) def test_get_language_from_path_real(self): g = trans_real.get_language_from_path tests = [ ("/pl/", "pl"), ("/pl", "pl"), ("/xyz/", None), ("/en/", "en"), ("/en-gb/", "en"), ("/en-latn-us/", "en-latn-us"), ("/en-Latn-US/", "en-Latn-US"), ("/de/", "de"), ("/de-1996/", "de-1996"), ("/de-at/", "de-at"), ("/de-AT/", "de-AT"), ("/de-ch/", "de"), ("/de-ch-1901/", "de-ch-1901"), ("/de-simple-page-test/", None), ("/i-mingo/", "i-mingo"), ("/kl-tunumiit/", "kl-tunumiit"), ("/nan-hani-tw/", "nan-hani-tw"), ] for path, language in tests: with self.subTest(path=path): self.assertEqual(g(path), language) def test_get_language_from_path_null(self): g = trans_null.get_language_from_path self.assertIsNone(g("/pl/")) self.assertIsNone(g("/pl")) self.assertIsNone(g("/xyz/")) def test_cache_resetting(self): """ After setting LANGUAGE, the cache should be cleared and languages previously valid should not be used (#14170). """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt-br"} self.assertEqual("pt-br", g(r)) with self.settings(LANGUAGES=[("en", "English")]): self.assertNotEqual("pt-br", g(r)) def test_i18n_patterns_returns_list(self): with override_settings(USE_I18N=False): self.assertIsInstance(i18n_patterns([]), list) with override_settings(USE_I18N=True): self.assertIsInstance(i18n_patterns([]), list) class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): super().setUp() activate("de") def tearDown(self): deactivate() super().tearDown() def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the translation of '%s'; the actual result is " "'%s'." % (msgstr, msgid, result), ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): @override_settings(LANGUAGE_CODE="de") def test_app_translation(self): # Original translation. self.assertGettext("Date/time", "Datum/Zeit") # Different translation. with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}): # Force refreshing translations. activate("de") # Doesn't work because it's added later in the list. self.assertGettext("Date/time", "Datum/Zeit") with self.modify_settings( INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"} ): # Force refreshing translations. activate("de") # Unless the original is removed from the list. self.assertGettext("Date/time", "Datum/Zeit (APP)") @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext("Time", "LOCALE_PATHS") def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=["i18n.resolution"]): self.assertGettext("Time", "LOCALE_PATHS") class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(gettext("Date/time"), "Datum/Zeit") @override_settings(INSTALLED_APPS=["i18n.territorial_fallback"]) class TranslationFallbackI18NTests(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override("de-de"): self.assertGettext("Test 1 (en)", "(de-de)") self.assertGettext("Test 2 (en)", "(de)") class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_paid=12, products_delivered=1) c.name = SafeString("Iñtërnâtiônàlizætiøn1") c.save() class TestLanguageInfo(SimpleTestCase): def test_localized_language_info(self): li = get_language_info("de") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx"): get_language_info("xx") with translation.override("xx"): # A language with no translation catalogs should fallback to the # untranslated string. self.assertEqual(gettext("Title"), "Title") def test_unknown_only_country_code(self): li = get_language_info("de-xx") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code_and_country_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): get_language_info("xx-xx") def test_fallback_language_code(self): """ get_language_info return the first fallback language info if the lang_info struct does not contain the 'name' key. """ li = get_language_info("zh-my") self.assertEqual(li["code"], "zh-hans") li = get_language_info("zh-hans") self.assertEqual(li["code"], "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class LocaleMiddlewareTests(TestCase): def test_streaming_response(self): # Regression test for #5241 response = self.client.get("/fr/streaming/") self.assertContains(response, "Oui/Non") response = self.client.get("/en/streaming/") self.assertContains(response, "Yes/No") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("de", "German"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="en", ) class UnprefixedDefaultLanguageTests(SimpleTestCase): def test_default_lang_without_prefix(self): """ With i18n_patterns(..., prefix_default_language=False), the default language (settings.LANGUAGE_CODE) should be accessible without a prefix. """ response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") def test_other_lang_with_prefix(self): response = self.client.get("/fr/simple/") self.assertEqual(response.content, b"Oui") def test_unprefixed_language_other_than_accept_language(self): response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fr") self.assertEqual(response.content, b"Yes") def test_page_with_dash(self): # A page starting with /de* shouldn't match the 'de' language code. response = self.client.get("/de-simple-page-test/") self.assertEqual(response.content, b"Yes") def test_no_redirect_on_404(self): """ A request for a nonexistent URL shouldn't cause a redirect to /<default_language>/<request_url> when prefix_default_language=False and /<default_language>/<request_url> has a URL match (#27402). """ # A match for /group1/group2/ must exist for this to act as a # regression test. response = self.client.get("/group1/group2/") self.assertEqual(response.status_code, 200) response = self.client.get("/nonexistent/") self.assertEqual(response.status_code, 404) @override_settings( USE_I18N=True, LANGUAGES=[ ("bg", "Bulgarian"), ("en-us", "English"), ("pt-br", "Portuguese (Brazil)"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class CountrySpecificLanguageTests(SimpleTestCase): rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language("en")) self.assertTrue(check_for_language("en-us")) self.assertTrue(check_for_language("en-US")) self.assertFalse(check_for_language("en_US")) self.assertTrue(check_for_language("be")) self.assertTrue(check_for_language("be@latin")) self.assertTrue(check_for_language("sr-RS@latin")) self.assertTrue(check_for_language("sr-RS@12345")) self.assertFalse(check_for_language("en-ü")) self.assertFalse(check_for_language("en\x00")) self.assertFalse(check_for_language(None)) self.assertFalse(check_for_language("be@ ")) # Specifying encoding is not supported (Django enforces UTF-8) self.assertFalse(check_for_language("tr-TR.UTF-8")) self.assertFalse(check_for_language("tr-TR.UTF8")) self.assertFalse(check_for_language("de-DE.utf-8")) def test_check_for_language_null(self): self.assertIs(trans_null.check_for_language("en"), True) def test_get_language_from_request(self): # issue 19919 r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("en-us", lang) r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("bg", lang) def test_get_language_from_request_null(self): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, "en") with override_settings(LANGUAGE_CODE="de"): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, "de") def test_specific_language_codes(self): # issue 11915 r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("pt-br", lang) r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("pt-br", lang) class TranslationFilesMissing(SimpleTestCase): def setUp(self): super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None def test_failure_finding_default_mo_files(self): """OSError is raised if the default language is unparseable.""" self.patchGettextFind() trans_real._translations = {} with self.assertRaises(OSError): activate("en") class NonDjangoLanguageTests(SimpleTestCase): """ A language non present in default Django languages can still be installed/used by a Django project. """ @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), ("xxx", "Somelanguage"), ], LANGUAGE_CODE="xxx", LOCALE_PATHS=[os.path.join(here, "commands", "locale")], ) def test_non_django_language(self): self.assertEqual(get_language(), "xxx") self.assertEqual(gettext("year"), "reay") @override_settings(USE_I18N=True) def test_check_for_language(self): with tempfile.TemporaryDirectory() as app_dir: os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES")) open( os.path.join( app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo" ), "w", ).close() app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir])) with mock.patch( "django.apps.apps.get_app_configs", return_value=[app_config] ): self.assertIs(check_for_language("dummy-lang"), True) @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), # xyz language has no locale files ("xyz", "XYZ"), ], ) @translation.override("xyz") def test_plural_non_django_language(self): self.assertEqual(get_language(), "xyz") self.assertEqual(ngettext("year", "years", 2), "years") @override_settings(USE_I18N=True) class WatchForTranslationChangesTests(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / "sampleproject" / "locale" mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") def test_i18n_app_dirs_ignore_django_apps(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["django.contrib.admin"]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / "locale" mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo") class TranslationFileChangedTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext_module._translations.copy() self.trans_real_translations = trans_real._translations.copy() def tearDown(self): gettext._translations = self.gettext_translations trans_real._translations = self.trans_real_translations def test_ignores_non_mo_files(self): gettext_module._translations = {"foo": "bar"} path = Path("test.py") self.assertIsNone(translation_file_changed(None, path)) self.assertEqual(gettext_module._translations, {"foo": "bar"}) def test_resets_cache_with_mo_files(self): gettext_module._translations = {"foo": "bar"} trans_real._translations = {"foo": "bar"} trans_real._default = 1 trans_real._active = False path = Path("test.mo") self.assertIs(translation_file_changed(None, path), True) self.assertEqual(gettext_module._translations, {}) self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, Local) class UtilsTests(SimpleTestCase): def test_round_away_from_one(self): tests = [ (0, 0), (0.0, 0), (0.25, 0), (0.5, 0), (0.75, 0), (1, 1), (1.0, 1), (1.25, 2), (1.5, 2), (1.75, 2), (-0.0, 0), (-0.25, -1), (-0.5, -1), (-0.75, -1), (-1, -1), (-1.0, -1), (-1.25, -2), (-1.5, -2), (-1.75, -2), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(round_away_from_one(value), expected)
ebc99b77f284fe7d1d941bedd6afae2fe445e5e6cc9ad191b8512efc139e8231
from datetime import datetime from django.db.models import Avg from django.test import TestCase from .models import Article, Comment, IndexErrorArticle, Person class EarliestOrLatestTests(TestCase): """Tests for the earliest() and latest() objects methods""" @classmethod def setUpClass(cls): super().setUpClass() cls._article_get_latest_by = Article._meta.get_latest_by def tearDown(self): Article._meta.get_latest_by = self._article_get_latest_by def test_earliest(self): # Because no Articles exist yet, earliest() raises ArticleDoesNotExist. with self.assertRaises(Article.DoesNotExist): Article.objects.earliest() a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1), ) a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 7, 28), ) a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 28), expire_date=datetime(2005, 8, 27), ) a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28), expire_date=datetime(2005, 7, 30), ) # Get the earliest Article. self.assertEqual(Article.objects.earliest(), a1) # Get the earliest Article that matches certain filters. self.assertEqual( Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).earliest(), a2 ) # Pass a custom field name to earliest() to change the field that's used # to determine the earliest object. self.assertEqual(Article.objects.earliest("expire_date"), a2) self.assertEqual( Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).earliest( "expire_date" ), a2, ) # earliest() overrides any other ordering specified on the query. # Refs #11283. self.assertEqual(Article.objects.order_by("id").earliest(), a1) # Error is raised if the user forgot to add a get_latest_by # in the Model.Meta Article.objects.model._meta.get_latest_by = None with self.assertRaisesMessage( ValueError, "earliest() and latest() require either fields as positional " "arguments or 'get_latest_by' in the model's Meta.", ): Article.objects.earliest() # Earliest publication date, earliest expire date. self.assertEqual( Article.objects.filter(pub_date=datetime(2005, 7, 28)).earliest( "pub_date", "expire_date" ), a4, ) # Earliest publication date, latest expire date. self.assertEqual( Article.objects.filter(pub_date=datetime(2005, 7, 28)).earliest( "pub_date", "-expire_date" ), a3, ) # Meta.get_latest_by may be a tuple. Article.objects.model._meta.get_latest_by = ("pub_date", "expire_date") self.assertEqual( Article.objects.filter(pub_date=datetime(2005, 7, 28)).earliest(), a4 ) def test_earliest_sliced_queryset(self): msg = "Cannot change a query once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): Article.objects.all()[0:5].earliest() def test_latest(self): # Because no Articles exist yet, latest() raises ArticleDoesNotExist. with self.assertRaises(Article.DoesNotExist): Article.objects.latest() a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1), ) a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 7, 28), ) a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 8, 27), ) a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28), expire_date=datetime(2005, 7, 30), ) # Get the latest Article. self.assertEqual(Article.objects.latest(), a4) # Get the latest Article that matches certain filters. self.assertEqual( Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(), a1 ) # Pass a custom field name to latest() to change the field that's used # to determine the latest object. self.assertEqual(Article.objects.latest("expire_date"), a1) self.assertEqual( Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest( "expire_date" ), a3, ) # latest() overrides any other ordering specified on the query (#11283). self.assertEqual(Article.objects.order_by("id").latest(), a4) # Error is raised if get_latest_by isn't in Model.Meta. Article.objects.model._meta.get_latest_by = None with self.assertRaisesMessage( ValueError, "earliest() and latest() require either fields as positional " "arguments or 'get_latest_by' in the model's Meta.", ): Article.objects.latest() # Latest publication date, latest expire date. self.assertEqual( Article.objects.filter(pub_date=datetime(2005, 7, 27)).latest( "pub_date", "expire_date" ), a3, ) # Latest publication date, earliest expire date. self.assertEqual( Article.objects.filter(pub_date=datetime(2005, 7, 27)).latest( "pub_date", "-expire_date" ), a2, ) # Meta.get_latest_by may be a tuple. Article.objects.model._meta.get_latest_by = ("pub_date", "expire_date") self.assertEqual( Article.objects.filter(pub_date=datetime(2005, 7, 27)).latest(), a3 ) def test_latest_sliced_queryset(self): msg = "Cannot change a query once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): Article.objects.all()[0:5].latest() def test_latest_manual(self): # You can still use latest() with a model that doesn't have # "get_latest_by" set -- just pass in the field name manually. Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1)) p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3)) msg = ( "earliest() and latest() require either fields as positional arguments " "or 'get_latest_by' in the model's Meta." ) with self.assertRaisesMessage(ValueError, msg): Person.objects.latest() self.assertEqual(Person.objects.latest("birthday"), p2) class TestFirstLast(TestCase): def test_first(self): p1 = Person.objects.create(name="Bob", birthday=datetime(1950, 1, 1)) p2 = Person.objects.create(name="Alice", birthday=datetime(1961, 2, 3)) self.assertEqual(Person.objects.first(), p1) self.assertEqual(Person.objects.order_by("name").first(), p2) self.assertEqual( Person.objects.filter(birthday__lte=datetime(1955, 1, 1)).first(), p1 ) self.assertIsNone( Person.objects.filter(birthday__lte=datetime(1940, 1, 1)).first() ) def test_last(self): p1 = Person.objects.create(name="Alice", birthday=datetime(1950, 1, 1)) p2 = Person.objects.create(name="Bob", birthday=datetime(1960, 2, 3)) # Note: by default PK ordering. self.assertEqual(Person.objects.last(), p2) self.assertEqual(Person.objects.order_by("-name").last(), p1) self.assertEqual( Person.objects.filter(birthday__lte=datetime(1955, 1, 1)).last(), p1 ) self.assertIsNone( Person.objects.filter(birthday__lte=datetime(1940, 1, 1)).last() ) def test_index_error_not_suppressed(self): """ #23555 -- Unexpected IndexError exceptions in QuerySet iteration shouldn't be suppressed. """ def check(): # We know that we've broken the __iter__ method, so the queryset # should always raise an exception. with self.assertRaises(IndexError): IndexErrorArticle.objects.all()[:10:2] with self.assertRaises(IndexError): IndexErrorArticle.objects.first() with self.assertRaises(IndexError): IndexErrorArticle.objects.last() check() # And it does not matter if there are any records in the DB. IndexErrorArticle.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1), ) check() def test_first_last_unordered_qs_aggregation_error(self): a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1), ) Comment.objects.create(article=a1, likes_count=5) qs = Comment.objects.values("article").annotate(avg_likes=Avg("likes_count")) msg = ( "Cannot use QuerySet.%s() on an unordered queryset performing aggregation. " "Add an ordering with order_by()." ) with self.assertRaisesMessage(TypeError, msg % "first"): qs.first() with self.assertRaisesMessage(TypeError, msg % "last"): qs.last()
dd357d9e1a5b6a1f49970104f6581533d289a9362e8081a21894eea50e8b21f1
from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() expire_date = models.DateField() class Meta: get_latest_by = "pub_date" class Person(models.Model): name = models.CharField(max_length=30) birthday = models.DateField() # Note that this model doesn't have "get_latest_by" set. class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) likes_count = models.PositiveIntegerField() # Ticket #23555 - model with an intentionally broken QuerySet.__iter__ method. class IndexErrorQuerySet(models.QuerySet): """ Emulates the case when some internal code raises an unexpected IndexError. """ def __iter__(self): raise IndexError class IndexErrorArticle(Article): objects = IndexErrorQuerySet.as_manager()
c199682fee6a0f8f6ac7ff0fac519a01d66a58732629d7884997577298f28f7e
import gettext import os import re from datetime import datetime, timedelta from importlib import import_module try: import zoneinfo except ImportError: from backports import zoneinfo from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import ( CharField, DateField, DateTimeField, ForeignKey, ManyToManyField, UUIDField, ) from django.test import SimpleTestCase, TestCase, override_settings from django.urls import reverse from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual, Inventory, Member, MyFileField, Profile, ReleaseEvent, School, Student, UnsafeLimitChoicesTo, VideoStream, ) from .widgetadmin import site as widget_admin_site class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email=None ) cls.u2 = User.objects.create_user(username="testser", password="secret") Car.objects.create(owner=cls.superuser, make="Volkswagen", model="Passat") Car.objects.create(owner=cls.u2, make="BMW", model="M3") class AdminFormfieldForDBFieldTests(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget self.assertIsInstance(widget, widgetclass) # Return the formfield so that other tests can continue return ff def test_DateField(self): self.assertFormfield(Event, "start_date", widgets.AdminDateWidget) def test_DateTimeField(self): self.assertFormfield(Member, "birthdate", widgets.AdminSplitDateTime) def test_TimeField(self): self.assertFormfield(Event, "start_time", widgets.AdminTimeWidget) def test_TextField(self): self.assertFormfield(Event, "description", widgets.AdminTextareaWidget) def test_URLField(self): self.assertFormfield(Event, "link", widgets.AdminURLFieldWidget) def test_IntegerField(self): self.assertFormfield(Event, "min_age", widgets.AdminIntegerFieldWidget) def test_CharField(self): self.assertFormfield(Member, "name", widgets.AdminTextInputWidget) def test_EmailField(self): self.assertFormfield(Member, "email", widgets.AdminEmailInputWidget) def test_FileField(self): self.assertFormfield(Album, "cover_art", widgets.AdminFileWidget) def test_ForeignKey(self): self.assertFormfield(Event, "main_band", forms.Select) def test_raw_id_ForeignKey(self): self.assertFormfield( Event, "main_band", widgets.ForeignKeyRawIdWidget, raw_id_fields=["main_band"], ) def test_radio_fields_ForeignKey(self): ff = self.assertFormfield( Event, "main_band", widgets.AdminRadioSelect, radio_fields={"main_band": admin.VERTICAL}, ) self.assertIsNone(ff.empty_label) def test_radio_fields_foreignkey_formfield_overrides_empty_label(self): class MyModelAdmin(admin.ModelAdmin): radio_fields = {"parent": admin.VERTICAL} formfield_overrides = { ForeignKey: {"empty_label": "Custom empty label"}, } ma = MyModelAdmin(Inventory, admin.site) ff = ma.formfield_for_dbfield(Inventory._meta.get_field("parent"), request=None) self.assertEqual(ff.empty_label, "Custom empty label") def test_many_to_many(self): self.assertFormfield(Band, "members", forms.SelectMultiple) def test_raw_id_many_to_many(self): self.assertFormfield( Band, "members", widgets.ManyToManyRawIdWidget, raw_id_fields=["members"] ) def test_filtered_many_to_many(self): self.assertFormfield( Band, "members", widgets.FilteredSelectMultiple, filter_vertical=["members"] ) def test_formfield_overrides(self): self.assertFormfield( Event, "start_date", forms.TextInput, formfield_overrides={DateField: {"widget": forms.TextInput}}, ) def test_formfield_overrides_widget_instances(self): """ Widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {"widget": forms.TextInput(attrs={"size": "10"})} } ma = BandAdmin(Band, admin.site) f1 = ma.formfield_for_dbfield(Band._meta.get_field("name"), request=None) f2 = ma.formfield_for_dbfield(Band._meta.get_field("style"), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs["maxlength"], "100") self.assertEqual(f2.widget.attrs["maxlength"], "20") self.assertEqual(f2.widget.attrs["size"], "10") def test_formfield_overrides_m2m_filter_widget(self): """ The autocomplete_fields, raw_id_fields, filter_vertical, and filter_horizontal widgets for ManyToManyFields may be overridden by specifying a widget in formfield_overrides. """ class BandAdmin(admin.ModelAdmin): filter_vertical = ["members"] formfield_overrides = { ManyToManyField: {"widget": forms.CheckboxSelectMultiple}, } ma = BandAdmin(Band, admin.site) field = ma.formfield_for_dbfield(Band._meta.get_field("members"), request=None) self.assertIsInstance(field.widget.widget, forms.CheckboxSelectMultiple) def test_formfield_overrides_for_datetime_field(self): """ Overriding the widget for DateTimeField doesn't overrides the default form_class for that field (#26449). """ class MemberAdmin(admin.ModelAdmin): formfield_overrides = { DateTimeField: {"widget": widgets.AdminSplitDateTime} } ma = MemberAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield(Member._meta.get_field("birthdate"), request=None) self.assertIsInstance(f1.widget, widgets.AdminSplitDateTime) self.assertIsInstance(f1, forms.SplitDateTimeField) def test_formfield_overrides_for_custom_field(self): """ formfield_overrides works for a custom field class. """ class AlbumAdmin(admin.ModelAdmin): formfield_overrides = {MyFileField: {"widget": forms.TextInput()}} ma = AlbumAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield( Album._meta.get_field("backside_art"), request=None ) self.assertIsInstance(f1.widget, forms.TextInput) def test_field_with_choices(self): self.assertFormfield(Member, "gender", forms.Select) def test_choices_with_radio_fields(self): self.assertFormfield( Member, "gender", widgets.AdminRadioSelect, radio_fields={"gender": admin.VERTICAL}, ) def test_inheritance(self): self.assertFormfield(Album, "backside_art", widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual( f.help_text, "Hold down “Control”, or “Command” on a Mac, to select more than one.", ) def test_m2m_widgets_no_allow_multiple_selected(self): class NoAllowMultipleSelectedWidget(forms.SelectMultiple): allow_multiple_selected = False class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] formfield_overrides = { ManyToManyField: {"widget": NoAllowMultipleSelectedWidget}, } self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual(f.help_text, "") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase): def test_filter_choices_by_request_user(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.force_login(self.superuser) response = self.client.get(reverse("admin:admin_widgets_cartire_add")) self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagen Passat") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_changelist_ForeignKey(self): response = self.client.get(reverse("admin:admin_widgets_car_changelist")) self.assertContains(response, "/auth/user/add/") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_nonexistent_target_id(self): band = Band.objects.create(name="Bogey Blues") pk = band.pk band.delete() post_data = { "main_band": str(pk), } # Try posting with a nonexistent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post(reverse("admin:admin_widgets_event_add"), post_data) self.assertContains( response, "Select a valid choice. That choice is not one of the available choices.", ) def test_invalid_target_id(self): for test_str in ("Iñtërnâtiônàlizætiøn", "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post( reverse("admin:admin_widgets_event_add"), {"main_band": test_str} ) self.assertContains( response, "Select a valid choice. That choice is not one of the available " "choices.", ) def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({"color__in": ("red", "blue")}) lookup2 = widgets.url_params_from_lookup_dict({"color__in": ["red", "blue"]}) self.assertEqual(lookup1, {"color__in": "red,blue"}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return "works" lookup1 = widgets.url_params_from_lookup_dict({"myfield": my_callable}) lookup2 = widgets.url_params_from_lookup_dict({"myfield": my_callable()}) self.assertEqual(lookup1, lookup2) def test_label_and_url_for_value_invalid_uuid(self): field = Bee._meta.get_field("honeycomb") self.assertIsInstance(field.target_field, UUIDField) widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site) self.assertEqual(widget.label_and_url_for_value("invalid-uuid"), ("", "")) class FilteredSelectMultipleWidgetTest(SimpleTestCase): def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", False) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilter" ' 'data-field-name="test\\" data-is-stacked="0">\n</select>', ) def test_stacked_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", True) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilterstacked" ' 'data-field-name="test\\" data-is-stacked="1">\n</select>', ) class AdminDateWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="vDateField" name="test" ' 'size="10">', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="myDateField" name="test" ' 'size="20">', ) class AdminTimeWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="vTimeField" name="test" ' 'size="8">', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="myTimeField" name="test" ' 'size="20">', ) class AdminSplitDateTimeWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Date: <input value="2007-12-01" type="text" class="vDateField" ' 'name="test_0" size="10"><br>' 'Time: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>', ) def test_localization(self): w = widgets.AdminSplitDateTime() with translation.override("de-at"): w.is_localized = True self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Datum: <input value="01.12.2007" type="text" ' 'class="vDateField" name="test_0"size="10"><br>' 'Zeit: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>', ) class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ["", "/not/a/full/url/", 'javascript:alert("Danger XSS!")']: with self.subTest(url=invalid): self.assertFalse(w.get_context("name", invalid, {})["url_valid"]) self.assertTrue(w.get_context("name", "http://example.com", {})["url_valid"]) def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", ""), '<input class="vURLField" name="test" type="url">' ) self.assertHTMLEqual( w.render("test", "http://example.com"), '<p class="url">Currently:<a href="http://example.com">' "http://example.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example.com"></p>', ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", "http://example-äüö.com"), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">' "http://example-äüö.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example-äüö.com"></p>', ) def test_render_quoting(self): """ WARNING: This test doesn't use assertHTMLEqual since it will get rid of some escapes which are tested here! """ HREF_RE = re.compile('href="([^"]+)"') VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile("<a[^>]+>([^>]+)</a>") w = widgets.AdminURLFieldWidget() output = w.render("test", "http://example.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://example.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render("test", "http://example-äüö.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://xn--example--7za4pnc.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render( "test", 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"' ) self.assertEqual( HREF_RE.search(output)[1], "http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)" "%3C/script%3E%22", ) self.assertEqual( TEXT_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) class AdminUUIDWidgetTests(SimpleTestCase): def test_attrs(self): w = widgets.AdminUUIDInputWidget() self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="vUUIDField" name="test">', ) w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"}) self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="myUUIDInput" name="test">', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() band = Band.objects.create(name="Linkin Park") cls.album = band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) def test_render(self): w = widgets.AdminFileWidget() self.assertHTMLEqual( w.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id"> ' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) self.assertHTMLEqual( w.render("test", SimpleUploadedFile("test", b"content")), '<input type="file" name="test">', ) def test_render_required(self): widget = widgets.AdminFileWidget() widget.is_required = True self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_render_disabled(self): widget = widgets.AdminFileWidget(attrs={"disabled": True}) self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id" disabled>' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test" disabled></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_readonly_fields(self): """ File widgets should render as a link when they're marked "read only." """ self.client.force_login(self.superuser) response = self.client.get( reverse("admin:admin_widgets_album_change", args=(self.album.id,)) ) self.assertContains( response, '<div class="readonly"><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">' r"albums\hybrid_theory.jpg</a></div>" % {"STORAGE_URL": default_storage.url("")}, html=True, ) self.assertNotContains( response, '<input type="file" name="cover_art" id="id_cover_art">', html=True, ) response = self.client.get(reverse("admin:admin_widgets_album_add")) self.assertContains( response, '<div class="readonly"></div>', html=True, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ForeignKeyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) rel_uuid = Album._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel_uuid, widget_admin_site) self.assertHTMLEqual( w.render("test", band.uuid, attrs={}), '<input type="text" name="test" value="%(banduuid)s" ' 'class="vForeignKeyRawIdAdminField vUUIDField">' '<a href="/admin_widgets/band/?_to_field=uuid" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>&nbsp;<strong>' '<a href="/admin_widgets/band/%(bandpk)s/change/">Linkin Park</a>' "</strong>" % {"banduuid": band.uuid, "bandpk": band.pk}, ) rel_id = ReleaseEvent._meta.get_field("album").remote_field w = widgets.ForeignKeyRawIdWidget(rel_id, widget_admin_site) self.assertHTMLEqual( w.render("test", None, attrs={}), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/album/?_to_field=id" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>', ) def test_relations_to_non_primary_key(self): # ForeignKeyRawIdWidget works with fields which aren't related to # the model's primary key. apple = Inventory.objects.create(barcode=86, name="Apple") Inventory.objects.create(barcode=22, name="Pear") core = Inventory.objects.create(barcode=87, name="Core", parent=apple) rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", core.parent_id, attrs={}), '<input type="text" name="test" value="86" ' 'class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Apple</a></strong>" % {"pk": apple.pk}, ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = Honeycomb.objects.create(location="Old tree") big_honeycomb.bee_set.create() rel = Bee._meta.get_field("honeycomb").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("honeycomb_widget", big_honeycomb.pk, attrs={}), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s">' "&nbsp;<strong>%(hcomb)s</strong>" % {"hcombpk": big_honeycomb.pk, "hcomb": big_honeycomb}, ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = Individual.objects.create(name="Subject #1") Individual.objects.create(name="Child", parent=subject1) rel = Individual._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("individual_widget", subject1.pk, attrs={}), '<input type="text" name="individual_widget" value="%(subj1pk)s">' "&nbsp;<strong>%(subj1)s</strong>" % {"subj1pk": subject1.pk, "subj1": subject1}, ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = Inventory.objects.create(barcode=93, name="Hidden", hidden=True) child_of_hidden = Inventory.objects.create( barcode=94, name="Child of hidden", parent=hidden ) self.assertHTMLEqual( w.render("test", child_of_hidden.parent_id, attrs={}), '<input type="text" name="test" value="93" ' ' class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Hidden</a></strong>" % {"pk": hidden.pk}, ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n' '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;' '_to_field=artist_ptr" class="related-lookup" id="lookup_id_test" ' 'title="Lookup"></a>', ) def test_render_fk_as_pk_model(self): rel = VideoStream._meta.get_field("release_event").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n' '<a href="/admin_widgets/releaseevent/?_to_field=album" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ManyToManyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") m1 = Member.objects.create(name="Chester") m2 = Member.objects.create(name="Mike") band.members.add(m1, m2) rel = Band._meta.get_field("members").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", [m1.pk, m2.pk], attrs={}), ( '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" ' ' class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" ' ' id="lookup_id_test" title="Lookup"></a>' ) % {"m1pk": m1.pk, "m2pk": m2.pk}, ) self.assertHTMLEqual( w.render("test", [m1.pk]), ( '<input type="text" name="test" value="%(m1pk)s" ' ' class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" ' ' id="lookup_id_test" title="Lookup"></a>' ) % {"m1pk": m1.pk}, ) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID # widget should have no magnifying glass link. See #16542 consultor1 = Advisor.objects.create(name="Rockstar Techie") c1 = Company.objects.create(name="Doodle") c2 = Company.objects.create(name="Pear") consultor1.companies.add(c1, c2) rel = Advisor._meta.get_field("companies").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("company_widget1", [c1.pk, c2.pk], attrs={}), '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s">' % {"c1pk": c1.pk, "c2pk": c2.pk}, ) self.assertHTMLEqual( w.render("company_widget2", [c1.pk]), '<input type="text" name="company_widget2" value="%(c1pk)s">' % {"c1pk": c1.pk}, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class RelatedFieldWidgetWrapperTests(SimpleTestCase): def test_no_can_add_related(self): rel = Individual._meta.get_field("parent").remote_field w = widgets.AdminRadioSelect() # Used to fail with a name error. w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site) self.assertFalse(w.can_add_related) def test_select_multiple_widget_cant_change_delete_related(self): rel = Individual._meta.get_field("parent").remote_field widget = forms.SelectMultiple() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertFalse(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_on_delete_cascade_rel_cant_delete_related(self): rel = Individual._meta.get_field("soulmate").remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertTrue(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_custom_widget_render(self): class CustomWidget(forms.Select): def render(self, *args, **kwargs): return "custom render output" rel = Album._meta.get_field("band").remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) output = wrapper.render("name", "value") self.assertIn("custom render output", output) def test_widget_delegates_value_omitted_from_data(self): class CustomWidget(forms.Select): def value_omitted_from_data(self, data, files, name): return False rel = Album._meta.get_field("band").remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.value_omitted_from_data({}, {}, "band"), False) def test_widget_is_hidden(self): rel = Album._meta.get_field("band").remote_field widget = forms.HiddenInput() widget.choices = () wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, True) context = wrapper.get_context("band", None, {}) self.assertIs(context["is_hidden"], True) output = wrapper.render("name", "value") # Related item links are hidden. self.assertNotIn("<a ", output) def test_widget_is_not_hidden(self): rel = Album._meta.get_field("band").remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, False) context = wrapper.get_context("band", None, {}) self.assertIs(context["is_hidden"], False) output = wrapper.render("name", "value") # Related item links are present. self.assertIn("<a ", output) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminWidgetSeleniumTestCase(AdminSeleniumTestCase): available_apps = ["admin_widgets"] + AdminSeleniumTestCase.available_apps def setUp(self): self.u1 = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): def test_show_hide_date_time_picker_widgets(self): """ Pressing the ESC key or clicking on a widget value closes the date and time picker widgets. """ from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # First, with the date picker widget --------------------------------- cal_icon = self.selenium.find_element(By.ID, "calendarlink0") # The date picker is hidden self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Click the calendar icon cal_icon.click() # The date picker is visible self.assertTrue( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Press the ESC key self.selenium.find_element(By.TAG_NAME, "body").send_keys([Keys.ESCAPE]) # The date picker is hidden again self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Click the calendar icon, then on the 15th of current month cal_icon.click() self.selenium.find_element(By.XPATH, "//a[contains(text(), '15')]").click() self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) self.assertEqual( self.selenium.find_element(By.ID, "id_birthdate_0").get_attribute("value"), datetime.today().strftime("%Y-%m-") + "15", ) # Then, with the time picker widget ---------------------------------- time_icon = self.selenium.find_element(By.ID, "clocklink0") # The time picker is hidden self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) # Click the time icon time_icon.click() # The time picker is visible self.assertTrue(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) self.assertEqual( [ x.text for x in self.selenium.find_elements( By.XPATH, "//ul[@class='timelist']/li/a" ) ], ["Now", "Midnight", "6 a.m.", "Noon", "6 p.m."], ) # Press the ESC key self.selenium.find_element(By.TAG_NAME, "body").send_keys([Keys.ESCAPE]) # The time picker is hidden again self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) # Click the time icon, then select the 'Noon' value time_icon.click() self.selenium.find_element(By.XPATH, "//a[contains(text(), 'Noon')]").click() self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) self.assertEqual( self.selenium.find_element(By.ID, "id_birthdate_1").get_attribute("value"), "12:00:00", ) def test_calendar_nonday_class(self): """ Ensure cells that are not days of the month have the `nonday` CSS class. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # fill in the birth date. self.selenium.find_element(By.ID, "id_birthdate_0").send_keys("2013-06-01") # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # make sure the first and last 6 cells have class nonday for td in tds[:6] + tds[-6:]: self.assertEqual(td.get_attribute("class"), "nonday") def test_calendar_selected_class(self): """ Ensure cell for the day in the input has the `selected` CSS class. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # fill in the birth date. self.selenium.find_element(By.ID, "id_birthdate_0").send_keys("2013-06-01") # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # verify the selected cell selected = tds[6] self.assertEqual(selected.get_attribute("class"), "selected") self.assertEqual(selected.text, "1") def test_calendar_no_selected_class(self): """ Ensure no cells are given the selected class when the field is empty. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # verify there are no cells with the selected class selected = [td for td in tds if td.get_attribute("class") == "selected"] self.assertEqual(len(selected), 0) def test_calendar_show_date_from_input(self): """ The calendar shows the date from the input field for every locale supported by Django. """ from selenium.webdriver.common.by import By self.selenium.set_window_size(1024, 768) self.admin_login(username="super", password="secret", login_url="/") # Enter test data member = Member.objects.create( name="Bob", birthdate=datetime(1984, 5, 15), gender="M" ) # Get month name translations for every locale month_string = "May" path = os.path.join( os.path.dirname(import_module("django.contrib.admin").__file__), "locale" ) for language_code, language_name in settings.LANGUAGES: try: catalog = gettext.translation("djangojs", path, [language_code]) except OSError: continue if month_string in catalog._catalog: month_name = catalog._catalog[month_string] else: month_name = month_string # Get the expected caption may_translation = month_name expected_caption = "{:s} {:d}".format(may_translation.upper(), 1984) # Test with every locale with override_settings(LANGUAGE_CODE=language_code): # Open a page that has a date picker widget url = reverse("admin:admin_widgets_member_change", args=(member.pk,)) self.selenium.get(self.live_server_url + url) # Click on the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # Make sure that the right month and year are displayed self.wait_for_text("#calendarin0 caption", expected_caption) @override_settings(TIME_ZONE="Asia/Singapore") class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase): def test_date_time_picker_shortcuts(self): """ date/time/datetime picker shortcuts work in the current time zone. Refs #20663. This test case is fairly tricky, it relies on selenium still running the browser in the default time zone "America/Chicago" despite `override_settings` changing the time zone to "Asia/Singapore". """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") error_margin = timedelta(seconds=10) # If we are neighbouring a DST, we add an hour of error margin. tz = zoneinfo.ZoneInfo("America/Chicago") utc_now = datetime.now(zoneinfo.ZoneInfo("UTC")) tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname() tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname() if tz_yesterday != tz_tomorrow: error_margin += timedelta(hours=1) self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) self.selenium.find_element(By.ID, "id_name").send_keys("test") # Click on the "today" and "now" shortcuts. shortcuts = self.selenium.find_elements( By.CSS_SELECTOR, ".field-birthdate .datetimeshortcuts" ) now = datetime.now() for shortcut in shortcuts: shortcut.find_element(By.TAG_NAME, "a").click() # There is a time zone mismatch warning. # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. self.assertCountSeleniumElements(".field-birthdate .timezonewarning", 1) # Submit the form. with self.wait_page_loaded(): self.selenium.find_element(By.NAME, "_save").click() # Make sure that "now" in JavaScript is within 10 seconds # from "now" on the server side. member = Member.objects.get(name="test") self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) # The above tests run with Asia/Singapore which are on the positive side of # UTC. Here we test with a timezone on the negative side. @override_settings(TIME_ZONE="US/Eastern") class DateTimePickerAltTimezoneSeleniumTests(DateTimePickerShortcutsSeleniumTests): pass class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() self.lisa = Student.objects.create(name="Lisa") self.john = Student.objects.create(name="John") self.bob = Student.objects.create(name="Bob") self.peter = Student.objects.create(name="Peter") self.jenny = Student.objects.create(name="Jenny") self.jason = Student.objects.create(name="Jason") self.cliff = Student.objects.create(name="Cliff") self.arthur = Student.objects.create(name="Arthur") self.school = School.objects.create(name="School of Awesome") def assertActiveButtons( self, mode, field_name, choose, remove, choose_all=None, remove_all=None ): choose_link = "#id_%s_add_link" % field_name choose_all_link = "#id_%s_add_all_link" % field_name remove_link = "#id_%s_remove_link" % field_name remove_all_link = "#id_%s_remove_all_link" % field_name self.assertEqual(self.has_css_class(choose_link, "active"), choose) self.assertEqual(self.has_css_class(remove_link, "active"), remove) if mode == "horizontal": self.assertEqual(self.has_css_class(choose_all_link, "active"), choose_all) self.assertEqual(self.has_css_class(remove_all_link, "active"), remove_all) def execute_basic_operations(self, mode, field_name): from selenium.webdriver.common.by import By original_url = self.selenium.current_url from_box = "#id_%s_from" % field_name to_box = "#id_%s_to" % field_name choose_link = "id_%s_add_link" % field_name choose_all_link = "id_%s_add_all_link" % field_name remove_link = "id_%s_remove_link" % field_name remove_all_link = "id_%s_remove_all_link" % field_name # Initial positions --------------------------------------------------- self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- if mode == "horizontal": self.selenium.find_element(By.ID, choose_all_link).click() elif mode == "vertical": # There 's no 'Choose all' button in vertical mode, so individually # select all options and click 'Choose'. for option in self.selenium.find_elements( By.CSS_SELECTOR, from_box + " > option" ): option.click() self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions(from_box, []) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- if mode == "horizontal": self.selenium.find_element(By.ID, remove_all_link).click() elif mode == "vertical": # There 's no 'Remove all' button in vertical mode, so individually # select all options and click 'Remove'. for option in self.selenium.find_elements( By.CSS_SELECTOR, to_box + " > option" ): option.click() self.selenium.find_element(By.ID, remove_link).click() self.assertSelectOptions( from_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) # Choose some options ------------------------------------------------ from_lisa_select_option = self.selenium.find_element( By.CSS_SELECTOR, '{} > option[value="{}"]'.format(from_box, self.lisa.id) ) # Check the title attribute is there for tool tips: ticket #20821 self.assertEqual( from_lisa_select_option.get_attribute("title"), from_lisa_select_option.get_attribute("text"), ) self.select_option(from_box, str(self.lisa.id)) self.select_option(from_box, str(self.jason.id)) self.select_option(from_box, str(self.bob.id)) self.select_option(from_box, str(self.john.id)) self.assertActiveButtons(mode, field_name, True, False, True, False) self.selenium.find_element(By.ID, choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), ], ) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id), ], ) # Check the tooltip is still there after moving: ticket #20821 to_lisa_select_option = self.selenium.find_element( By.CSS_SELECTOR, '{} > option[value="{}"]'.format(to_box, self.lisa.id) ) self.assertEqual( to_lisa_select_option.get_attribute("title"), to_lisa_select_option.get_attribute("text"), ) # Remove some options ------------------------------------------------- self.select_option(to_box, str(self.lisa.id)) self.select_option(to_box, str(self.bob.id)) self.assertActiveButtons(mode, field_name, False, True, True, True) self.selenium.find_element(By.ID, remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ], ) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.select_option(from_box, str(self.arthur.id)) self.select_option(from_box, str(self.cliff.id)) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ], ) self.assertSelectOptions( to_box, [ str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id), ], ) # Choose some more options -------------------------------------------- self.select_option(from_box, str(self.peter.id)) self.select_option(from_box, str(self.lisa.id)) # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) self.selenium.find_element(By.ID, remove_link).click() self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) # Unselect the options ------------------------------------------------ self.deselect_option(from_box, str(self.peter.id)) self.deselect_option(from_box, str(self.lisa.id)) # Choose some more options -------------------------------------------- self.select_option(to_box, str(self.jason.id)) self.select_option(to_box, str(self.john.id)) # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Unselect the options ------------------------------------------------ self.deselect_option(to_box, str(self.jason.id)) self.deselect_option(to_box, str(self.john.id)) # Pressing buttons shouldn't change the URL. self.assertEqual(self.selenium.current_url, original_url) def test_basic(self): from selenium.webdriver.common.by import By self.selenium.set_window_size(1024, 768) self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_school_change", args=(self.school.id,)) ) self.wait_page_ready() self.execute_basic_operations("vertical", "students") self.execute_basic_operations("horizontal", "alumni") # Save and check that everything is properly stored in the database --- self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_page_ready() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual( list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john], ) self.assertEqual( list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john], ) def test_filter(self): """ Typing in the search box filters out options displayed in the 'from' box. """ from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.selenium.set_window_size(1024, 768) self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_school_change", args=(self.school.id,)) ) for field_name in ["students", "alumni"]: from_box = "#id_%s_from" % field_name to_box = "#id_%s_to" % field_name choose_link = "id_%s_add_link" % field_name remove_link = "id_%s_remove_link" % field_name input = self.selenium.find_element(By.ID, "id_%s_input" % field_name) # Initial values self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) # Typing in some characters filters out non-matching options input.send_keys("a") self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) input.send_keys("R") self.assertSelectOptions(from_box, [str(self.arthur.id)]) # Clearing the text box makes the other options reappear input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) # ----------------------------------------------------------------- # Choosing a filtered option sends it properly to the 'to' box. input.send_keys("a") self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) self.select_option(from_box, str(self.jason.id)) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.peter.id), str(self.jason.id), ], ) self.select_option(to_box, str(self.lisa.id)) self.selenium.find_element(By.ID, remove_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id), ], ) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # ----------------------------------------------------------------- # Pressing enter on a filtered option sends it properly to # the 'to' box. self.select_option(to_box, str(self.jason.id)) self.selenium.find_element(By.ID, remove_link).click() input.send_keys("ja") self.assertSelectOptions(from_box, [str(self.jason.id)]) input.send_keys([Keys.ENTER]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE]) # Save and check that everything is properly stored in the database --- with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) def test_back_button_bug(self): """ Some browsers had a bug where navigating away from the change page and then clicking the browser's back button would clear the filter_horizontal/filter_vertical widgets (#13614). """ from selenium.webdriver.common.by import By self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") change_url = reverse( "admin:admin_widgets_school_change", args=(self.school.id,) ) self.selenium.get(self.live_server_url + change_url) # Navigate away and go back to the change form page. self.selenium.find_element(By.LINK_TEXT, "Home").click() self.selenium.back() expected_unselected_values = [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ] expected_selected_values = [str(self.lisa.id), str(self.peter.id)] # Everything is still in place self.assertSelectOptions("#id_students_from", expected_unselected_values) self.assertSelectOptions("#id_students_to", expected_selected_values) self.assertSelectOptions("#id_alumni_from", expected_unselected_values) self.assertSelectOptions("#id_alumni_to", expected_selected_values) def test_refresh_page(self): """ Horizontal and vertical filter widgets keep selected options on page reload (#22955). """ self.school.students.add(self.arthur, self.jason) self.school.alumni.add(self.arthur, self.jason) self.admin_login(username="super", password="secret", login_url="/") change_url = reverse( "admin:admin_widgets_school_change", args=(self.school.id,) ) self.selenium.get(self.live_server_url + change_url) self.assertCountSeleniumElements("#id_students_to > option", 2) # self.selenium.refresh() or send_keys(Keys.F5) does hard reload and # doesn't replicate what happens when a user clicks the browser's # 'Refresh' button. with self.wait_page_loaded(): self.selenium.execute_script("location.reload()") self.assertCountSeleniumElements("#id_students_to > option", 2) class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() Band.objects.create(id=42, name="Bogey Blues") Band.objects.create(id=98, name="Green Potatoes") def test_ForeignKey(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_event_add") ) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element(By.ID, "id_main_band").get_attribute("value"), "" ) # Open the popup window and click on a band self.selenium.find_element(By.ID, "lookup_id_main_band").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Bogey Blues") self.assertIn("/band/42/", link.get_attribute("href")) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_main_band", "42") # Reopen the popup window and click on another band self.selenium.find_element(By.ID, "lookup_id_main_band").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Green Potatoes") self.assertIn("/band/98/", link.get_attribute("href")) link.click() # The field now contains the other selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_main_band", "98") def test_many_to_many(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_event_add") ) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element(By.ID, "id_supporting_bands").get_attribute( "value" ), "", ) # Help text for the field is displayed self.assertEqual( self.selenium.find_element( By.CSS_SELECTOR, ".field-supporting_bands div.help" ).text, "Supporting Bands.", ) # Open the popup window and click on a band self.selenium.find_element(By.ID, "lookup_id_supporting_bands").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Bogey Blues") self.assertIn("/band/42/", link.get_attribute("href")) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_supporting_bands", "42") # Reopen the popup window and click on another band self.selenium.find_element(By.ID, "lookup_id_supporting_bands").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Green Potatoes") self.assertIn("/band/98/", link.get_attribute("href")) link.click() # The field now contains the two selected bands' ids self.selenium.switch_to.window(main_window) self.wait_for_value("#id_supporting_bands", "42,98") class RelatedFieldWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_ForeignKey_using_to_field(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_profile_add") ) main_window = self.selenium.current_window_handle # Click the Add User button to add new self.selenium.find_element(By.ID, "add_id_user").click() self.wait_for_and_switch_to_popup() password_field = self.selenium.find_element(By.ID, "id_password") password_field.send_keys("password") username_field = self.selenium.find_element(By.ID, "id_username") username_value = "newuser" username_field.send_keys(username_value) save_button_css_selector = ".submit-row > input[type=submit]" self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.selenium.switch_to.window(main_window) # The field now contains the new user self.selenium.find_element(By.CSS_SELECTOR, "#id_user option[value=newuser]") self.selenium.find_element(By.ID, "view_id_user").click() self.wait_for_value("#id_username", "newuser") self.selenium.back() select = Select(self.selenium.find_element(By.ID, "id_user")) select.select_by_value("newuser") # Click the Change User button to change it self.selenium.find_element(By.ID, "change_id_user").click() self.wait_for_and_switch_to_popup() username_field = self.selenium.find_element(By.ID, "id_username") username_value = "changednewuser" username_field.clear() username_field.send_keys(username_value) save_button_css_selector = ".submit-row > input[type=submit]" self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.selenium.switch_to.window(main_window) self.selenium.find_element( By.CSS_SELECTOR, "#id_user option[value=changednewuser]" ) self.selenium.find_element(By.ID, "view_id_user").click() self.wait_for_value("#id_username", "changednewuser") self.selenium.back() select = Select(self.selenium.find_element(By.ID, "id_user")) select.select_by_value("changednewuser") # Go ahead and submit the form to make sure it works self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.wait_for_text( "li.success", "The profile “changednewuser” was added successfully." ) profiles = Profile.objects.all() self.assertEqual(len(profiles), 1) self.assertEqual(profiles[0].user.username, username_value)
f1b968d9c84831128f79f4b8d4609744c608bff88ee62e90be7113cbece2926b
from django.contrib.gis.db.models import F, GeometryField, Value, functions from django.contrib.gis.geos import Point, Polygon from django.db import connection from django.db.models import Count, Min from django.test import TestCase, skipUnlessDBFeature from .models import City, ManyPointModel, MultiFields class GeoExpressionsTests(TestCase): fixtures = ["initial"] def test_geometry_value_annotation(self): p = Point(1, 1, srid=4326) point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p self.assertEqual(point, p) @skipUnlessDBFeature("supports_transform") def test_geometry_value_annotation_different_srid(self): p = Point(1, 1, srid=32140) point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p self.assertTrue(point.equals_exact(p.transform(4326, clone=True), 10**-5)) self.assertEqual(point.srid, 4326) @skipUnlessDBFeature("supports_geography") def test_geography_value(self): p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))) area = ( City.objects.annotate( a=functions.Area(Value(p, GeometryField(srid=4326, geography=True))) ) .first() .a ) self.assertAlmostEqual(area.sq_km, 12305.1, 0) def test_update_from_other_field(self): p1 = Point(1, 1, srid=4326) p2 = Point(2, 2, srid=4326) obj = ManyPointModel.objects.create( point1=p1, point2=p2, point3=p2.transform(3857, clone=True), ) # Updating a point to a point of the same SRID. ManyPointModel.objects.filter(pk=obj.pk).update(point2=F("point1")) obj.refresh_from_db() self.assertEqual(obj.point2, p1) # Updating a point to a point with a different SRID. if connection.features.supports_transform: ManyPointModel.objects.filter(pk=obj.pk).update(point3=F("point1")) obj.refresh_from_db() self.assertTrue( obj.point3.equals_exact(p1.transform(3857, clone=True), 0.1) ) def test_multiple_annotation(self): multi_field = MultiFields.objects.create( point=Point(1, 1), city=City.objects.get(name="Houston"), poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))), ) qs = ( City.objects.values("name") .order_by("name") .annotate( distance=Min( functions.Distance("multifields__point", multi_field.city.point) ), ) .annotate(count=Count("multifields")) ) self.assertTrue(qs.first()) @skipUnlessDBFeature("has_Translate_function") def test_update_with_expression(self): city = City.objects.create(point=Point(1, 1, srid=4326)) City.objects.filter(pk=city.pk).update(point=functions.Translate("point", 1, 1)) city.refresh_from_db() self.assertEqual(city.point, Point(2, 2, srid=4326))
aa810c5539623e98b9413681696d14962ce4cb5c008958f9484600eb995cc5f3
import tempfile from io import StringIO from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union, functions from django.contrib.gis.geos import ( GeometryCollection, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import DatabaseError, NotSupportedError, connection from django.db.models import F, OuterRef, Subquery from django.test import TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..utils import skipUnlessGISLookup from .models import ( City, Country, Feature, MinusOneSRID, MultiFields, NonConcreteModel, PennsylvaniaCity, State, Track, ) class GeoModelTest(TestCase): fixtures = ["initial"] def test_fixtures(self): "Testing geographic model initialization from fixtures." # Ensuring that data was loaded from initial data fixtures. self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) self.assertEqual(2, State.objects.count()) def test_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." # Testing on a Point pnt = Point(0, 0) nullcity = City(name="NullCity", point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: with self.assertRaisesMessage(TypeError, "Cannot set"): nullcity.point = bad # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name="NullCity").point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual( Point(23, 5, srid=4326), City.objects.get(name="NullCity").point ) nullcity.save() self.assertEqual( Point(23, 5, srid=4326), City.objects.get(name="NullCity").point ) nullcity.delete() # Testing on a Polygon shell = LinearRing((0, 0), (0, 90), (100, 90), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name="NullState", poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name="NullState") self.assertEqual(connection.ops.Adapter._fix_polygon(ply), ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertIsInstance(ns.poly.srs, gdal.SpatialReference) self.assertEqual("WGS 84", ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual( connection.ops.Adapter._fix_polygon(ply), State.objects.get(name="NullState").poly, ) ns.delete() @skipUnlessDBFeature("supports_transform") def test_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." # San Antonio in 'WGS84' (SRID 4326) sa_4326 = "POINT (-98.493183 29.424170)" wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857) other_srid_pnt = wgs_pnt.transform(3857, clone=True) # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. if connection.ops.oracle: tx = Country.objects.get(mpoly__contains=other_srid_pnt) else: tx = Country.objects.get(mpoly__intersects=other_srid_pnt) self.assertEqual("Texas", tx.name) # Creating San Antonio. Remember the Alamo. sa = City.objects.create(name="San Antonio", point=other_srid_pnt) # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name="San Antonio") self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid) def test_createnull(self): "Testing creating a model instance and the geometry being None" c = City() self.assertIsNone(c.point) def test_geometryfield(self): "Testing the general GeometryField." Feature(name="Point", geom=Point(1, 1)).save() Feature(name="LineString", geom=LineString((0, 0), (1, 1), (5, 5))).save() Feature( name="Polygon", geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), ).save() Feature( name="GeometryCollection", geom=GeometryCollection( Point(2, 2), LineString((0, 0), (2, 2)), Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), ), ).save() f_1 = Feature.objects.get(name="Point") self.assertIsInstance(f_1.geom, Point) self.assertEqual((1.0, 1.0), f_1.geom.tuple) f_2 = Feature.objects.get(name="LineString") self.assertIsInstance(f_2.geom, LineString) self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) f_3 = Feature.objects.get(name="Polygon") self.assertIsInstance(f_3.geom, Polygon) f_4 = Feature.objects.get(name="GeometryCollection") self.assertIsInstance(f_4.geom, GeometryCollection) self.assertEqual(f_3.geom, f_4.geom[2]) @skipUnlessDBFeature("supports_transform") def test_inherited_geofields(self): "Database functions on inherited Geometry fields." # Creating a Pennsylvanian city. PennsylvaniaCity.objects.create( name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)" ) # All transformation SQL will need to be performed on the # _parent_ table. qs = PennsylvaniaCity.objects.annotate( new_point=functions.Transform("point", srid=32128) ) self.assertEqual(1, qs.count()) for pc in qs: self.assertEqual(32128, pc.new_point.srid) def test_raw_sql_query(self): "Testing raw SQL query." cities1 = City.objects.all() point_select = connection.ops.select % "point" cities2 = list( City.objects.raw( "select id, name, %s as point from geoapp_city" % point_select ) ) self.assertEqual(len(cities1), len(cities2)) with self.assertNumQueries(0): # Ensure point isn't deferred. self.assertIsInstance(cities2[0].point, Point) def test_gis_query_as_string(self): """GIS queries can be represented as strings.""" query = City.objects.filter(point__within=Polygon.from_bbox((0, 0, 2, 2))) self.assertIn( connection.ops.quote_name(City._meta.db_table), str(query.query), ) def test_dumpdata_loaddata_cycle(self): """ Test a dumpdata/loaddata cycle with geographic data. """ out = StringIO() original_data = list(City.objects.order_by("name")) call_command("dumpdata", "geoapp.City", stdout=out) result = out.getvalue() houston = City.objects.get(name="Houston") self.assertIn('"point": "%s"' % houston.point.ewkt, result) # Reload now dumped data with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as tmp: tmp.write(result) tmp.seek(0) call_command("loaddata", tmp.name, verbosity=0) self.assertEqual(original_data, list(City.objects.order_by("name"))) @skipUnlessDBFeature("supports_empty_geometries") def test_empty_geometries(self): geometry_classes = [ Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection, ] for klass in geometry_classes: g = klass(srid=4326) feature = Feature.objects.create(name="Empty %s" % klass.__name__, geom=g) feature.refresh_from_db() if klass is LinearRing: # LinearRing isn't representable in WKB, so GEOSGeomtry.wkb # uses LineString instead. g = LineString(srid=4326) self.assertEqual(feature.geom, g) self.assertEqual(feature.geom.srid, g.srid) class GeoLookupTest(TestCase): fixtures = ["initial"] def test_disjoint_lookup(self): "Testing the `disjoint` lookup type." ptown = City.objects.get(name="Pueblo") qs1 = City.objects.filter(point__disjoint=ptown.point) self.assertEqual(7, qs1.count()) qs2 = State.objects.filter(poly__disjoint=ptown.point) self.assertEqual(1, qs2.count()) self.assertEqual("Kansas", qs2[0].name) def test_contains_contained_lookups(self): "Testing the 'contained', 'contains', and 'bbcontains' lookup types." # Getting Texas, yes we were a country -- once ;) texas = Country.objects.get(name="Texas") # Seeing what cities are in Texas, should get Houston and Dallas, # and Oklahoma City because 'contained' only checks on the # _bounding box_ of the Geometries. if connection.features.supports_contained_lookup: qs = City.objects.filter(point__contained=texas.mpoly) self.assertEqual(3, qs.count()) cities = ["Houston", "Dallas", "Oklahoma City"] for c in qs: self.assertIn(c.name, cities) # Pulling out some cities. houston = City.objects.get(name="Houston") wellington = City.objects.get(name="Wellington") pueblo = City.objects.get(name="Pueblo") okcity = City.objects.get(name="Oklahoma City") lawrence = City.objects.get(name="Lawrence") # Now testing contains on the countries using the points for # Houston and Wellington. tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry nz = Country.objects.get( mpoly__contains=wellington.point.hex ) # Query w/EWKBHEX self.assertEqual("Texas", tx.name) self.assertEqual("New Zealand", nz.name) # Testing `contains` on the states using the point for Lawrence. ks = State.objects.get(poly__contains=lawrence.point) self.assertEqual("Kansas", ks.name) # Pueblo and Oklahoma City (even though OK City is within the bounding # box of Texas) are not contained in Texas or New Zealand. self.assertEqual( len(Country.objects.filter(mpoly__contains=pueblo.point)), 0 ) # Query w/GEOSGeometry object self.assertEqual( len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0 ) # Query w/WKT # OK City is contained w/in bounding box of Texas. if connection.features.supports_bbcontains_lookup: qs = Country.objects.filter(mpoly__bbcontains=okcity.point) self.assertEqual(1, len(qs)) self.assertEqual("Texas", qs[0].name) @skipUnlessDBFeature("supports_crosses_lookup") def test_crosses_lookup(self): Track.objects.create(name="Line1", line=LineString([(-95, 29), (-60, 0)])) self.assertEqual( Track.objects.filter( line__crosses=LineString([(-95, 0), (-60, 29)]) ).count(), 1, ) self.assertEqual( Track.objects.filter( line__crosses=LineString([(-95, 30), (0, 30)]) ).count(), 0, ) @skipUnlessDBFeature("supports_isvalid_lookup") def test_isvalid_lookup(self): invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") State.objects.create(name="invalid", poly=invalid_geom) qs = State.objects.all() if connection.ops.oracle or ( connection.ops.mysql and connection.mysql_version < (8, 0, 0) ): # Kansas has adjacent vertices with distance 6.99244813842e-12 # which is smaller than the default Oracle tolerance. # It's invalid on MySQL < 8 also. qs = qs.exclude(name="Kansas") self.assertEqual( State.objects.filter(name="Kansas", poly__isvalid=False).count(), 1 ) self.assertEqual(qs.filter(poly__isvalid=False).count(), 1) self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1) @skipUnlessGISLookup("left", "right") def test_left_right_lookups(self): "Testing the 'left' and 'right' lookup types." # Left: A << B => true if xmax(A) < xmin(B) # Right: A >> B => true if xmin(A) > xmax(B) # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. # Getting the borders for Colorado & Kansas co_border = State.objects.get(name="Colorado").poly ks_border = State.objects.get(name="Kansas").poly # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # These cities should be strictly to the right of the CO border. cities = [ "Houston", "Dallas", "Oklahoma City", "Lawrence", "Chicago", "Wellington", ] qs = City.objects.filter(point__right=co_border) self.assertEqual(6, len(qs)) for c in qs: self.assertIn(c.name, cities) # These cities should be strictly to the right of the KS border. cities = ["Chicago", "Wellington"] qs = City.objects.filter(point__right=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. vic = City.objects.get(point__left=co_border) self.assertEqual("Victoria", vic.name) cities = ["Pueblo", "Victoria"] qs = City.objects.filter(point__left=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) @skipUnlessGISLookup("strictly_above", "strictly_below") def test_strictly_above_below_lookups(self): dallas = City.objects.get(name="Dallas") self.assertQuerysetEqual( City.objects.filter(point__strictly_above=dallas.point).order_by("name"), ["Chicago", "Lawrence", "Oklahoma City", "Pueblo", "Victoria"], lambda b: b.name, ) self.assertQuerysetEqual( City.objects.filter(point__strictly_below=dallas.point).order_by("name"), ["Houston", "Wellington"], lambda b: b.name, ) def test_equals_lookups(self): "Testing the 'same_as' and 'equals' lookup types." pnt = fromstr("POINT (-95.363151 29.763374)", srid=4326) c1 = City.objects.get(point=pnt) c2 = City.objects.get(point__same_as=pnt) c3 = City.objects.get(point__equals=pnt) for c in [c1, c2, c3]: self.assertEqual("Houston", c.name) @skipUnlessDBFeature("supports_null_geometries") def test_null_geometries(self): "Testing NULL geometry support, and the `isnull` lookup type." # Creating a state with a NULL boundary. State.objects.create(name="Puerto Rico") # Querying for both NULL and Non-NULL values. nullqs = State.objects.filter(poly__isnull=True) validqs = State.objects.filter(poly__isnull=False) # Puerto Rico should be NULL (it's a commonwealth unincorporated territory) self.assertEqual(1, len(nullqs)) self.assertEqual("Puerto Rico", nullqs[0].name) # GeometryField=None is an alias for __isnull=True. self.assertCountEqual(State.objects.filter(poly=None), nullqs) self.assertCountEqual(State.objects.exclude(poly=None), validqs) # The valid states should be Colorado & Kansas self.assertEqual(2, len(validqs)) state_names = [s.name for s in validqs] self.assertIn("Colorado", state_names) self.assertIn("Kansas", state_names) # Saving another commonwealth w/a NULL geometry. nmi = State.objects.create(name="Northern Mariana Islands", poly=None) self.assertIsNone(nmi.poly) # Assigning a geometry and saving -- then UPDATE back to NULL. nmi.poly = "POLYGON((0 0,1 0,1 1,1 0,0 0))" nmi.save() State.objects.filter(name="Northern Mariana Islands").update(poly=None) self.assertIsNone(State.objects.get(name="Northern Mariana Islands").poly) @skipUnlessDBFeature( "supports_null_geometries", "supports_crosses_lookup", "supports_relate_lookup" ) def test_null_geometries_excluded_in_lookups(self): """NULL features are excluded in spatial lookup functions.""" null = State.objects.create(name="NULL", poly=None) queries = [ ("equals", Point(1, 1)), ("disjoint", Point(1, 1)), ("touches", Point(1, 1)), ("crosses", LineString((0, 0), (1, 1), (5, 5))), ("within", Point(1, 1)), ("overlaps", LineString((0, 0), (1, 1), (5, 5))), ("contains", LineString((0, 0), (1, 1), (5, 5))), ("intersects", LineString((0, 0), (1, 1), (5, 5))), ("relate", (Point(1, 1), "T*T***FF*")), ("same_as", Point(1, 1)), ("exact", Point(1, 1)), ("coveredby", Point(1, 1)), ("covers", Point(1, 1)), ] for lookup, geom in queries: with self.subTest(lookup=lookup): self.assertNotIn( null, State.objects.filter(**{"poly__%s" % lookup: geom}) ) def test_wkt_string_in_lookup(self): # Valid WKT strings don't emit error logs. with self.assertNoLogs("django.contrib.gis", "ERROR"): State.objects.filter(poly__intersects="LINESTRING(0 0, 1 1, 5 5)") @skipUnlessDBFeature("supports_relate_lookup") def test_relate_lookup(self): "Testing the 'relate' lookup type." # To make things more interesting, we will have our Texas reference point in # different SRIDs. pnt1 = fromstr("POINT (649287.0363174 4177429.4494686)", srid=2847) pnt2 = fromstr("POINT(-98.4919715741052 29.4333344025053)", srid=4326) # Not passing in a geometry as first param raises a TypeError when # initializing the QuerySet. with self.assertRaises(ValueError): Country.objects.filter(mpoly__relate=(23, "foo")) # Making sure the right exception is raised for the given # bad arguments. for bad_args, e in [ ((pnt1, 0), ValueError), ((pnt2, "T*T***FF*", 0), ValueError), ]: qs = Country.objects.filter(mpoly__relate=bad_args) with self.assertRaises(e): qs.count() contains_mask = "T*T***FF*" within_mask = "T*F**F***" intersects_mask = "T********" # Relate works differently on Oracle. if connection.ops.oracle: contains_mask = "contains" within_mask = "inside" # TODO: This is not quite the same as the PostGIS mask above intersects_mask = "overlapbdyintersect" # Testing contains relation mask. if connection.features.supports_transform: self.assertEqual( Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name, "Texas", ) self.assertEqual( "Texas", Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name ) # Testing within relation mask. ks = State.objects.get(name="Kansas") self.assertEqual( "Lawrence", City.objects.get(point__relate=(ks.poly, within_mask)).name ) # Testing intersection relation mask. if not connection.ops.oracle: if connection.features.supports_transform: self.assertEqual( Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name, "Texas", ) self.assertEqual( "Texas", Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name ) self.assertEqual( "Lawrence", City.objects.get(point__relate=(ks.poly, intersects_mask)).name, ) # With a complex geometry expression mask = "anyinteract" if connection.ops.oracle else within_mask self.assertFalse( City.objects.exclude( point__relate=(functions.Union("point", "point"), mask) ) ) def test_gis_lookups_with_complex_expressions(self): multiple_arg_lookups = { "dwithin", "relate", } # These lookups are tested elsewhere. lookups = connection.ops.gis_operators.keys() - multiple_arg_lookups self.assertTrue(lookups, "No lookups found") for lookup in lookups: with self.subTest(lookup): City.objects.filter( **{"point__" + lookup: functions.Union("point", "point")} ).exists() def test_subquery_annotation(self): multifields = MultiFields.objects.create( city=City.objects.create(point=Point(1, 1)), point=Point(2, 2), poly=Polygon.from_bbox((0, 0, 2, 2)), ) qs = MultiFields.objects.annotate( city_point=Subquery( City.objects.filter( id=OuterRef("city"), ).values("point") ), ).filter( city_point__within=F("poly"), ) self.assertEqual(qs.get(), multifields) class GeoQuerySetTest(TestCase): # TODO: GeoQuerySet is removed, organize these test better. fixtures = ["initial"] @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): """ Testing the `Extent` aggregate. """ # Reference query: # SELECT ST_extent(point) # FROM geoapp_city # WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) expected = ( -96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820, ) qs = City.objects.filter(name__in=("Houston", "Dallas")) extent = qs.aggregate(Extent("point"))["point__extent"] for val, exp in zip(extent, expected): self.assertAlmostEqual(exp, val, 4) self.assertIsNone( City.objects.filter(name=("Smalltown")).aggregate(Extent("point"))[ "point__extent" ] ) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_with_limit(self): """ Testing if extent supports limit. """ extent1 = City.objects.aggregate(Extent("point"))["point__extent"] extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"] self.assertNotEqual(extent1, extent2) def test_make_line(self): """ Testing the `MakeLine` aggregate. """ if not connection.features.supports_make_line_aggr: with self.assertRaises(NotSupportedError): City.objects.aggregate(MakeLine("point")) return # MakeLine on an inappropriate field returns simply None self.assertIsNone(State.objects.aggregate(MakeLine("poly"))["poly__makeline"]) # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; ref_line = GEOSGeometry( "LINESTRING(-95.363151 29.763374,-96.801611 32.782057," "-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001," "-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)", srid=4326, ) # We check for equality with a tolerance of 10e-5 which is a lower bound # of the precisions of ref_line coordinates line = City.objects.aggregate(MakeLine("point"))["point__makeline"] self.assertTrue( ref_line.equals_exact(line, tolerance=10e-5), "%s != %s" % (ref_line, line) ) @skipUnlessDBFeature("supports_union_aggr") def test_unionagg(self): """ Testing the `Union` aggregate. """ tx = Country.objects.get(name="Texas").mpoly # Houston, Dallas -- Ordering may differ depending on backend or GEOS version. union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") qs = City.objects.filter(point__within=tx) with self.assertRaises(ValueError): qs.aggregate(Union("name")) # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) u1 = qs.aggregate(Union("point"))["point__union"] u2 = qs.order_by("name").aggregate(Union("point"))["point__union"] self.assertTrue(union.equals(u1)) self.assertTrue(union.equals(u2)) qs = City.objects.filter(name="NotACity") self.assertIsNone(qs.aggregate(Union("point"))["point__union"]) @skipUnlessDBFeature("supports_union_aggr") def test_geoagg_subquery(self): tx = Country.objects.get(name="Texas") union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") # Use distinct() to force the usage of a subquery for aggregation. with CaptureQueriesContext(connection) as ctx: self.assertIs( union.equals( City.objects.filter(point__within=tx.mpoly) .distinct() .aggregate( Union("point"), )["point__union"], ), True, ) self.assertIn("subquery", ctx.captured_queries[0]["sql"]) @skipUnlessDBFeature("supports_tolerance_parameter") def test_unionagg_tolerance(self): City.objects.create( point=fromstr("POINT(-96.467222 32.751389)", srid=4326), name="Forney", ) tx = Country.objects.get(name="Texas").mpoly # Tolerance is greater than distance between Forney and Dallas, that's # why Dallas is ignored. forney_houston = GEOSGeometry( "MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)", srid=4326, ) self.assertIs( forney_houston.equals_exact( City.objects.filter(point__within=tx).aggregate( Union("point", tolerance=32000), )["point__union"], tolerance=10e-6, ), True, ) @skipUnlessDBFeature("supports_tolerance_parameter") def test_unionagg_tolerance_escaping(self): tx = Country.objects.get(name="Texas").mpoly with self.assertRaises(DatabaseError): City.objects.filter(point__within=tx).aggregate( Union("point", tolerance="0.05))), (((1"), ) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery) (#14483). """ tex_cities = City.objects.filter( point__within=Country.objects.filter(name="Texas").values("mpoly") ).order_by("name") self.assertEqual( list(tex_cities.values_list("name", flat=True)), ["Dallas", "Houston"] ) def test_non_concrete_field(self): NonConcreteModel.objects.create(point=Point(0, 0), name="name") list(NonConcreteModel.objects.all()) def test_values_srid(self): for c, v in zip(City.objects.all(), City.objects.values()): self.assertEqual(c.point.srid, v["point"].srid)
0b01eba78548bca93b8c9e592f64fbfed15cf6a800d07b8332c3f81257317e02
import json from django.contrib.gis.geos import LinearRing, Point, Polygon from django.core import serializers from django.test import TestCase from .models import City, MultiFields, PennsylvaniaCity class GeoJSONSerializerTests(TestCase): fixtures = ["initial"] def test_builtin_serializers(self): """ 'geojson' should be listed in available serializers. """ all_formats = set(serializers.get_serializer_formats()) public_formats = set(serializers.get_public_serializer_formats()) self.assertIn("geojson", all_formats), self.assertIn("geojson", public_formats) def test_serialization_base(self): geojson = serializers.serialize("geojson", City.objects.order_by("name")) geodata = json.loads(geojson) self.assertEqual(len(geodata["features"]), len(City.objects.all())) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point") self.assertEqual(geodata["features"][0]["properties"]["name"], "Chicago") first_city = City.objects.order_by("name").first() self.assertEqual(geodata["features"][0]["id"], first_city.pk) self.assertEqual(geodata["features"][0]["properties"]["pk"], str(first_city.pk)) def test_geometry_field_option(self): """ When a model has several geometry fields, the 'geometry_field' option can be used to specify the field to use as the 'geometry' key. """ MultiFields.objects.create( city=City.objects.first(), name="Name", point=Point(5, 23), poly=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), ) geojson = serializers.serialize("geojson", MultiFields.objects.all()) geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point") geojson = serializers.serialize( "geojson", MultiFields.objects.all(), geometry_field="poly" ) geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Polygon") # geometry_field is considered even if not in fields (#26138). geojson = serializers.serialize( "geojson", MultiFields.objects.all(), geometry_field="poly", fields=("city",), ) geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Polygon") def test_id_field_option(self): """ By default Django uses the pk of the object as the id for a feature. The 'id_field' option can be used to specify a different field to use as the id. """ cities = City.objects.order_by("name") geojson = serializers.serialize("geojson", cities, id_field="name") geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["id"], cities[0].name) def test_fields_option(self): """ The fields option allows to define a subset of fields to be present in the 'properties' of the generated output. """ PennsylvaniaCity.objects.create( name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)" ) geojson = serializers.serialize( "geojson", PennsylvaniaCity.objects.all(), fields=("county", "point"), ) geodata = json.loads(geojson) self.assertIn("county", geodata["features"][0]["properties"]) self.assertNotIn("founded", geodata["features"][0]["properties"]) self.assertNotIn("pk", geodata["features"][0]["properties"]) def test_srid_option(self): geojson = serializers.serialize( "geojson", City.objects.order_by("name"), srid=2847 ) geodata = json.loads(geojson) coordinates = geodata["features"][0]["geometry"]["coordinates"] # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. self.assertAlmostEqual(coordinates[0], 1564802, -1) self.assertAlmostEqual(coordinates[1], 5613214, -1) def test_deserialization_exception(self): """ GeoJSON cannot be deserialized. """ with self.assertRaises(serializers.base.SerializerDoesNotExist): serializers.deserialize("geojson", "{}")
7ec512d5b167e9b7c706b78c2450707beb580c077fe5b289e272197f181bd4bc
import ctypes import itertools import json import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock, skipIf from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile, fromstr, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.contrib.gis.shortcuts import numpy from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = fromstr(g.wkt) if geom.hasz: self.assertEqual(g.ewkt, geom.wkt) def test_wkt_invalid(self): msg = "String input unrecognized as WKT EWKT, and HEXEWKB." with self.assertRaisesMessage(ValueError, msg): fromstr("POINT(٠٠١ ٠)") with self.assertRaisesMessage(ValueError, msg): fromstr("SRID=٧٥٨٣;POINT(100 0)") def test_hex(self): "Testing HEX output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode()) def test_hexewkb(self): "Testing (HEX)EWKB output." # For testing HEX(EWKB). ogc_hex = b"01010000000000000000000000000000000000F03F" ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040" # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));` hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F" # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));` hexewkb_3d = ( b"01010000A0E61000000000000000000000000000000000F03F0000000000000040" ) pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) # OGC-compliant HEX will not have SRID value. self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) # HEXEWKB should be appropriate for its dimension -- have to use an # a WKBWriter w/dimension set accordingly, else GEOS will insert # garbage into 3D coordinate if there is none. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True) # Same for EWKB. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) # Redundant sanity check. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid) def test_kml(self): "Testing KML output." for tg in self.geometries.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, "kml", False) if kml: self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): fromstr(err.wkt) # Bad WKB with self.assertRaises(GEOSException): GEOSGeometry(memoryview(b"0")) class NotAGeometry: pass # Some other object with self.assertRaises(TypeError): GEOSGeometry(NotAGeometry()) # None with self.assertRaises(TypeError): GEOSGeometry(None) def test_wkb(self): "Testing WKB output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(wkb.hex().upper(), g.hex) def test_create_hex(self): "Testing creation from HEX." for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_create_wkb(self): "Testing creation from WKB." for g in self.geometries.hex_wkt: wkb = memoryview(bytes.fromhex(g.hex)) geom_h = GEOSGeometry(wkb) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_ewkt(self): "Testing EWKT." srids = (-1, 32140) for srid in srids: for p in self.geometries.polygons: ewkt = "SRID=%d;%s" % (srid, p.wkt) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export def test_json(self): "Testing GeoJSON input/output (via GDAL)." for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if not hasattr(g, "not_equal"): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json)) def test_json_srid(self): geojson_data = { "type": "Point", "coordinates": [2, 49], "crs": { "type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::4322"}, }, } self.assertEqual( GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322) ) def test_fromfile(self): "Testing the fromfile() factory." ref_pnt = GEOSGeometry("POINT(5 23)") wkt_f = BytesIO() wkt_f.write(ref_pnt.wkt.encode()) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) # Other tests use `fromfile()` on string filenames so those # aren't tested here. for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt) def test_eq(self): "Testing equivalence." p = fromstr("POINT(5 23)") self.assertEqual(p, p.wkt) self.assertNotEqual(p, "foo") ls = fromstr("LINESTRING(0 0, 1 1, 5 5)") self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, "bar") self.assertEqual(p, "POINT(5.0 23.0)") # Error shouldn't be raise on equivalence testing with # an invalid type. for g in (p, ls): self.assertIsNotNone(g) self.assertNotEqual(g, {"foo": "bar"}) self.assertIsNot(g, False) def test_hash(self): point_1 = Point(5, 23) point_2 = Point(5, 23, srid=4326) point_3 = Point(5, 23, srid=32632) multipoint_1 = MultiPoint(point_1, srid=4326) multipoint_2 = MultiPoint(point_2) multipoint_3 = MultiPoint(point_3) self.assertNotEqual(hash(point_1), hash(point_2)) self.assertNotEqual(hash(point_1), hash(point_3)) self.assertNotEqual(hash(point_2), hash(point_3)) self.assertNotEqual(hash(multipoint_1), hash(multipoint_2)) self.assertEqual(hash(multipoint_2), hash(multipoint_3)) self.assertNotEqual(hash(multipoint_1), hash(point_1)) self.assertNotEqual(hash(multipoint_2), hash(point_2)) self.assertNotEqual(hash(multipoint_3), hash(point_3)) def test_eq_with_srid(self): "Testing non-equivalence with different srids." p0 = Point(5, 23) p1 = Point(5, 23, srid=4326) p2 = Point(5, 23, srid=32632) # GEOS self.assertNotEqual(p0, p1) self.assertNotEqual(p1, p2) # EWKT self.assertNotEqual(p0, p1.ewkt) self.assertNotEqual(p1, p0.ewkt) self.assertNotEqual(p1, p2.ewkt) # Equivalence with matching SRIDs self.assertEqual(p2, p2) self.assertEqual(p2, p2.ewkt) # WKT contains no SRID so will not equal self.assertNotEqual(p2, p2.wkt) # SRID of 0 self.assertEqual(p0, "SRID=0;POINT (5 23)") self.assertNotEqual(p1, "SRID=0;POINT (5 23)") def test_points(self): "Testing Point objects." prev = fromstr("POINT(0 0)") for p in self.geometries.points: # Creating the point from the WKT pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, "Point") self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(pnt.dims, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(pnt, fromstr(p.wkt)) self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__. # Making sure that the point's X, Y components are what we expect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, "z"): self.assertIs(pnt.hasz, True) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertIs(pnt.hasz, False) self.assertIsNone(pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) # Centroid operation on point should be point itself self.assertEqual(p.centroid, pnt.centroid.tuple) # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(pnt, pnt2) self.assertEqual(pnt, pnt3) # Now testing setting the x and y pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) # Setting via the tuple/coords property pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt # setting the previous geometry def test_point_reverse(self): point = GEOSGeometry("POINT(144.963 -37.8143)", 4326) self.assertEqual(point.srid, 4326) point.reverse() self.assertEqual(point.ewkt, "SRID=4326;POINT (-37.8143 144.963)") def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, "MultiPoint") self.assertEqual(mpnt.geom_typeid, 4) self.assertEqual(mpnt.dims, 0) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) with self.assertRaises(IndexError): mpnt.__getitem__(len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) for p in mpnt: self.assertEqual(p.geom_type, "Point") self.assertEqual(p.geom_typeid, 0) self.assertIs(p.empty, False) self.assertIs(p.valid, True) def test_linestring(self): "Testing LineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.linestrings: ls = fromstr(line.wkt) self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.dims, 1) self.assertIs(ls.empty, False) self.assertIs(ls.ring, False) if hasattr(line, "centroid"): self.assertEqual(line.centroid, ls.centroid.tuple) if hasattr(line, "tup"): self.assertEqual(line.tup, ls.tuple) self.assertEqual(ls, fromstr(line.wkt)) self.assertIs(ls == prev, False) # Use assertIs() to test __eq__. with self.assertRaises(IndexError): ls.__getitem__(len(ls)) prev = ls # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list # Point individual arguments self.assertEqual( ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt ) if numpy: self.assertEqual( ls, LineString(numpy.array(ls.tuple)) ) # as numpy array with self.assertRaisesMessage( TypeError, "Each coordinate should be a sequence (list or tuple)" ): LineString((0, 0)) with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString(numpy.array([(0, 0)])) with mock.patch("django.contrib.gis.geos.linestring.numpy", False): with self.assertRaisesMessage( TypeError, "Invalid initialization input for LineStrings." ): LineString("wrong input") # Test __iter__(). self.assertEqual( list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)] ) def test_linestring_reverse(self): line = GEOSGeometry("LINESTRING(144.963 -37.8143,151.2607 -33.887)", 4326) self.assertEqual(line.srid, 4326) line.reverse() self.assertEqual( line.ewkt, "SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)" ) def _test_is_counterclockwise(self): lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0)) self.assertIs(lr.is_counterclockwise, True) lr.reverse() self.assertIs(lr.is_counterclockwise, False) msg = "Orientation of an empty LinearRing cannot be determined." with self.assertRaisesMessage(ValueError, msg): LinearRing().is_counterclockwise @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise(self): self._test_is_counterclockwise() @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise_geos_error(self): with mock.patch("django.contrib.gis.geos.prototypes.cs_is_ccw") as mocked: mocked.return_value = 0 mocked.func_name = "GEOSCoordSeq_isCCW" msg = 'Error encountered in GEOS C function "GEOSCoordSeq_isCCW".' with self.assertRaisesMessage(GEOSException, msg): LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.6.9") def test_is_counterclockwise_fallback(self): self._test_is_counterclockwise() def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.multilinestrings: ml = fromstr(line.wkt) self.assertEqual(ml.geom_type, "MultiLineString") self.assertEqual(ml.geom_typeid, 5) self.assertEqual(ml.dims, 1) self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9) self.assertEqual(ml, fromstr(line.wkt)) self.assertIs(ml == prev, False) # Use assertIs() to test __eq__. prev = ml for ls in ml: self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertIs(ls.empty, False) with self.assertRaises(IndexError): ml.__getitem__(len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual( ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)) ) def test_linearring(self): "Testing LinearRing objects." for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, "LinearRing") self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.dims, 1) self.assertEqual(rr.n_p, len(lr)) self.assertIs(lr.valid, True) self.assertIs(lr.empty, False) # Creating a LinearRing from a tuple, list, and numpy array self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple))) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 3." ): LinearRing((0, 0), (1, 1), (0, 0)) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing(numpy.array([(0, 0)])) def test_linearring_json(self): self.assertJSONEqual( LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json, '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}', ) def test_polygons_from_bbox(self): "Testing `from_bbox` class method." bbox = (-180, -90, 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) # Testing numerical precision x = 3.14159265358979323 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[-1] self.assertEqual(format(x, ".13f"), format(y, ".13f")) def test_polygons(self): "Testing Polygon objects." prev = fromstr("POINT(0 0)") for p in self.geometries.polygons: # Creating the Polygon, testing its properties. poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, "Polygon") self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.dims, 2) self.assertIs(poly.empty, False) self.assertIs(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) # Testing the geometry equivalence self.assertEqual(poly, fromstr(p.wkt)) # Should not be equal to previous geometry self.assertIs(poly == prev, False) # Use assertIs() to test __eq__. self.assertIs(poly != prev, True) # Use assertIs() to test __ne__. # Testing the exterior ring ring = poly.exterior_ring self.assertEqual(ring.geom_type, "LinearRing") self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices with self.assertRaises(IndexError): poly.__getitem__(len(poly)) with self.assertRaises(IndexError): poly.__setitem__(len(poly), False) with self.assertRaises(IndexError): poly.__getitem__(-1 * len(poly) - 1) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, "LinearRing") self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. with self.assertRaises(TypeError): Polygon(0, [1, 2, 3]) with self.assertRaises(TypeError): Polygon("foo") # Polygon(shell, (hole1, ... holeN)) ext_ring, *int_rings = poly self.assertEqual(poly, Polygon(ext_ring, int_rings)) # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN) ring_tuples = tuple(r.tuple for r in poly) self.assertEqual(poly, Polygon(*ring_tuples)) # Constructing with tuples of LinearRings. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt) self.assertEqual( poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt ) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content) def test_polygon_comparison(self): p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0))) self.assertGreater(p1, p2) self.assertLess(p2, p1) p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0))) p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0))) self.assertGreater(p4, p3) self.assertLess(p3, p4) def test_multipolygons(self): "Testing MultiPolygon objects." fromstr("POINT (0 0)") for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, "MultiPolygon") self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mpoly.dims, 2) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) with self.assertRaises(IndexError): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, "Polygon") self.assertEqual(p.geom_typeid, 3) self.assertIs(p.valid, True) self.assertEqual( mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt ) def test_memory_hijinks(self): "Testing Geometry __del__() on rings and polygons." # #### Memory issues with rings and poly # These tests are needed to ensure sanity with writable geometries. # Getting a polygon with interior rings, and pulling out the interior rings poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] # These deletes should be 'harmless' since they are done on child geometries del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] # Deleting the polygon del poly # Access to these rings is OK since they are clones. str(ring1) str(ring2) def test_coord_seq(self): "Testing Coordinate Sequence objects." for p in self.geometries.polygons: if p.ext_ring_cs: # Constructing the polygon and getting the coordinate sequence poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq self.assertEqual( p.ext_ring_cs, cs.tuple ) # done in the Polygon test too. self.assertEqual( len(p.ext_ring_cs), len(cs) ) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in range(len(p.ext_ring_cs)): c1 = p.ext_ring_cs[i] # Expected value c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with if len(c1) == 2: tset = (5, 23) else: tset = (5, 23, 8) cs[i] = tset # Making sure every set point matches what we expect for j in range(len(tset)): cs[i] = tset self.assertEqual(tset[j], cs[i][j]) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr("POINT (0 0)") with self.assertRaises(GEOSException): g.relate_pattern(0, "invalid pattern, yo") for rg in self.geometries.relate_geoms: a = fromstr(rg.wkt_a) b = fromstr(rg.wkt_b) self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern)) self.assertEqual(rg.pattern, a.relate(b)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) i1 = fromstr(self.geometries.intersect_geoms[i].wkt) self.assertIs(a.intersects(b), True) i2 = a.intersection(b) self.assertTrue(i1.equals(i2)) self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator a &= b # testing __iand__ self.assertTrue(i1.equals(a)) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertTrue(u1.equals(u2)) self.assertTrue(u1.equals(a | b)) # __or__ is union operator a |= b # testing __ior__ self.assertTrue(u1.equals(a)) def test_unary_union(self): "Testing unary_union." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = GeometryCollection(a, b).unary_union self.assertTrue(u1.equals(u2)) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator a -= b # testing __isub__ self.assertTrue(d1.equals(a)) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue( d1.equals(a ^ b) ) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertTrue(d1.equals(a)) def test_buffer(self): bg = self.geometries.buffer_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer(bg.width, quadsegs=1.1) self._test_buffer(self.geometries.buffer_geoms, "buffer") def test_buffer_with_style(self): bg = self.geometries.buffer_with_style_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, quadsegs=1.1) # Can't use a floating-point for the end cap style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, end_cap_style=1.2) # Can't use a end cap style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, end_cap_style=55) # Can't use a floating-point for the join style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, join_style=1.3) # Can't use a join style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, join_style=66) self._test_buffer( itertools.chain( self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms ), "buffer_with_style", ) def _test_buffer(self, geometries, buffer_method_name): for bg in geometries: g = fromstr(bg.wkt) # The buffer we expect exp_buf = fromstr(bg.buffer_wkt) # Constructing our buffer buf_kwargs = { kwarg_name: getattr(bg, kwarg_name) for kwarg_name in ( "width", "quadsegs", "end_cap_style", "join_style", "mitre_limit", ) if hasattr(bg, kwarg_name) } buf = getattr(g, buffer_method_name)(**buf_kwargs) self.assertEqual(exp_buf.num_coords, buf.num_coords) self.assertEqual(len(exp_buf), len(buf)) # Now assuring that each point in the buffer is almost equal for j in range(len(exp_buf)): exp_ring = exp_buf[j] buf_ring = buf[j] self.assertEqual(len(exp_ring), len(buf_ring)) for k in range(len(exp_ring)): # Asserting the X, Y of each point are almost equal (due to # floating point imprecision). self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9) self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9) def test_covers(self): poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0))) self.assertTrue(poly.covers(Point(5, 5))) self.assertFalse(poly.covers(Point(100, 100))) def test_closed(self): ls_closed = LineString((0, 0), (1, 1), (0, 0)) ls_not_closed = LineString((0, 0), (1, 1)) self.assertFalse(ls_not_closed.closed) self.assertTrue(ls_closed.closed) def test_srid(self): "Testing the SRID property and keyword." # Testing SRID keyword on Point pnt = Point(5, 23, srid=4326) self.assertEqual(4326, pnt.srid) pnt.srid = 3084 self.assertEqual(3084, pnt.srid) with self.assertRaises(ctypes.ArgumentError): pnt.srid = "4326" # Testing SRID keyword on fromstr(), and on Polygon rings. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269) self.assertEqual(4269, poly.srid) for ring in poly: self.assertEqual(4269, ring.srid) poly.srid = 4326 self.assertEqual(4326, poly.shell.srid) # Testing SRID keyword on GeometryCollection gc = GeometryCollection( Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021 ) self.assertEqual(32021, gc.srid) for i in range(len(gc)): self.assertEqual(32021, gc[i].srid) # GEOS may get the SRID from HEXEWKB # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS # using `SELECT GeomFromText('POINT (5 23)', 4326);`. hex = "0101000020E610000000000000000014400000000000003740" p1 = fromstr(hex) self.assertEqual(4326, p1.srid) p2 = fromstr(p1.hex) self.assertIsNone(p2.srid) p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) # Testing that geometry SRID could be set to its own value pnt_wo_srid = Point(1, 1) pnt_wo_srid.srid = pnt_wo_srid.srid # Input geometries that have an SRID. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid) self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkt, srid=1) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkb, srid=1) def test_custom_srid(self): """Test with a null srid and a srid unknown to GDAL.""" for srid in [None, 999999]: pnt = Point(111200, 220900, srid=srid) self.assertTrue( pnt.ewkt.startswith( ("SRID=%s;" % srid if srid else "") + "POINT (111200" ) ) self.assertIsInstance(pnt.ogr, gdal.OGRGeometry) self.assertIsNone(pnt.srs) # Test conversion from custom to a known srid c2w = gdal.CoordTransform( gdal.SpatialReference( "+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 " "+datum=WGS84 +units=m +no_defs" ), gdal.SpatialReference(4326), ) new_pnt = pnt.transform(c2w, clone=True) self.assertEqual(new_pnt.srid, 4326) self.assertAlmostEqual(new_pnt.x, 1, 1) self.assertAlmostEqual(new_pnt.y, 2, 1) def test_mutable_geometries(self): "Testing the mutability of Polygons and Geometry Collections." # ### Testing the mutability of Polygons ### for p in self.geometries.polygons: poly = fromstr(p.wkt) # Should only be able to use __setitem__ with LinearRing geometries. with self.assertRaises(TypeError): poly.__setitem__(0, LineString((1, 1), (2, 2))) # Constructing the new shell by adding 500 to every point in the old shell. shell_tup = poly.shell.tuple new_coords = [] for point in shell_tup: new_coords.append((point[0] + 500.0, point[1] + 500.0)) new_shell = LinearRing(*tuple(new_coords)) # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) # ### Testing the mutability of Geometry Collections for tg in self.geometries.multipoints: mp = fromstr(tg.wkt) for i in range(len(mp)): # Creating a random point. pnt = mp[i] new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) # MultiPolygons involve much more memory management because each # Polygon w/in the collection has its own rings. for tg in self.geometries.multipolygons: mpoly = fromstr(tg.wkt) for i in range(len(mpoly)): poly = mpoly[i] old_poly = mpoly[i] # Offsetting the each ring in the polygon by 500. for j in range(len(poly)): r = poly[j] for k in range(len(r)): r[k] = (r[k][0] + 500.0, r[k][1] + 500.0) poly[j] = r self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) # Extreme (!!) __setitem__ -- no longer works, have to detect # in the first object that __setitem__ is called in the subsequent # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)? # mpoly[0][0][0] = (3.14, 2.71) # self.assertEqual((3.14, 2.71), mpoly[0][0][0]) # Doing it more slowly.. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0]) # del mpoly def test_point_list_assignment(self): p = Point(0, 0) p[:] = (1, 2, 3) self.assertEqual(p, Point(1, 2, 3)) p[:] = () self.assertEqual(p.wkt, Point()) p[:] = (1, 2) self.assertEqual(p.wkt, Point(1, 2)) with self.assertRaises(ValueError): p[:] = (1,) with self.assertRaises(ValueError): p[:] = (1, 2, 3, 4, 5) def test_linestring_list_assignment(self): ls = LineString((0, 0), (1, 1)) ls[:] = () self.assertEqual(ls, LineString()) ls[:] = ((0, 0), (1, 1), (2, 2)) self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2))) with self.assertRaises(ValueError): ls[:] = (1,) def test_linearring_list_assignment(self): ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) ls[:] = () self.assertEqual(ls, LinearRing()) ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) with self.assertRaises(ValueError): ls[:] = ((0, 0), (1, 1), (2, 2)) def test_polygon_list_assignment(self): pol = Polygon() pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),) self.assertEqual( pol, Polygon( ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), ), ) pol[:] = () self.assertEqual(pol, Polygon()) def test_geometry_collection_list_assignment(self): p = Point() gc = GeometryCollection() gc[:] = [p] self.assertEqual(gc, GeometryCollection(p)) gc[:] = () self.assertEqual(gc, GeometryCollection()) def test_threed(self): "Testing three-dimensional geometries." # Testing a 3D Point pnt = Point(2, 3, 8) self.assertEqual((2.0, 3.0, 8.0), pnt.coords) with self.assertRaises(TypeError): pnt.tuple = (1.0, 2.0) pnt.coords = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), pnt.coords) # Testing a 3D LineString ls = LineString((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)) self.assertEqual(((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)), ls.tuple) with self.assertRaises(TypeError): ls.__setitem__(0, (1.0, 2.0)) ls[0] = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), ls[0]) def test_distance(self): "Testing the distance() function." # Distance to self should be 0. pnt = Point(0, 0) self.assertEqual(0.0, pnt.distance(Point(0, 0))) # Distance should be 1 self.assertEqual(1.0, pnt.distance(Point(0, 1))) # Distance should be ~ sqrt(2) self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11) # Distances are from the closest vertex in each geometry -- # should be 3 (distance from (2, 2) to (5, 2)). ls1 = LineString((0, 0), (1, 1), (2, 2)) ls2 = LineString((5, 2), (6, 1), (7, 0)) self.assertEqual(3, ls1.distance(ls2)) def test_length(self): "Testing the length property." # Points have 0 length. pnt = Point(0, 0) self.assertEqual(0.0, pnt.length) # Should be ~ sqrt(2) ls = LineString((0, 0), (1, 1)) self.assertAlmostEqual(1.41421356237, ls.length, 11) # Should be circumference of Polygon poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) self.assertEqual(4.0, poly.length) # Should be sum of each element's length in collection. mpoly = MultiPolygon(poly.clone(), poly) self.assertEqual(8.0, mpoly.length) def test_emptyCollections(self): "Testing empty geometries and collections." geoms = [ GeometryCollection([]), fromstr("GEOMETRYCOLLECTION EMPTY"), GeometryCollection(), fromstr("POINT EMPTY"), Point(), fromstr("LINESTRING EMPTY"), LineString(), fromstr("POLYGON EMPTY"), Polygon(), fromstr("MULTILINESTRING EMPTY"), MultiLineString(), fromstr("MULTIPOLYGON EMPTY"), MultiPolygon(()), MultiPolygon(), ] if numpy: geoms.append(LineString(numpy.array([]))) for g in geoms: self.assertIs(g.empty, True) # Testing len() and num_geom. if isinstance(g, Polygon): self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g)) else: self.assertEqual(0, g.num_geom) self.assertEqual(0, len(g)) # Testing __getitem__ (doesn't work on Point or Polygon) if isinstance(g, Point): # IndexError is not raised in GEOS 3.8.0. if geos_version_tuple() != (3, 8, 0): with self.assertRaises(IndexError): g.x elif isinstance(g, Polygon): lr = g.shell self.assertEqual("LINEARRING EMPTY", lr.wkt) self.assertEqual(0, len(lr)) self.assertIs(lr.empty, True) with self.assertRaises(IndexError): lr.__getitem__(0) else: with self.assertRaises(IndexError): g.__getitem__(0) def test_collection_dims(self): gc = GeometryCollection([]) self.assertEqual(gc.dims, -1) gc = GeometryCollection(Point(0, 0)) self.assertEqual(gc.dims, 0) gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0)) self.assertEqual(gc.dims, 1) gc = GeometryCollection( LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0), ) self.assertEqual(gc.dims, 2) def test_collections_of_collections(self): "Testing GeometryCollection handling of other collections." # Creating a GeometryCollection WKT string composed of other # collections and polygons. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid] coll.extend(mls.wkt for mls in self.geometries.multilinestrings) coll.extend(p.wkt for p in self.geometries.polygons) coll.extend(mp.wkt for mp in self.geometries.multipoints) gc_wkt = "GEOMETRYCOLLECTION(%s)" % ",".join(coll) # Should construct ok from WKT gc1 = GEOSGeometry(gc_wkt) # Should also construct ok from individual geometry arguments. gc2 = GeometryCollection(*tuple(g for g in gc1)) # And, they should be equal. self.assertEqual(gc1, gc2) def test_gdal(self): "Testing `ogr` and `srs` properties." g1 = fromstr("POINT(5 23)") self.assertIsInstance(g1.ogr, gdal.OGRGeometry) self.assertIsNone(g1.srs) g1_3d = fromstr("POINT(5 23 8)") self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry) self.assertEqual(g1_3d.ogr.z, 8) g2 = fromstr("LINESTRING(0 0, 5 5, 23 23)", srid=4326) self.assertIsInstance(g2.ogr, gdal.OGRGeometry) self.assertIsInstance(g2.srs, gdal.SpatialReference) self.assertEqual(g2.hex, g2.ogr.hex) self.assertEqual("WGS 84", g2.srs.name) def test_copy(self): "Testing use with the Python `copy` module." import copy poly = GEOSGeometry( "POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))" ) cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr) def test_transform(self): "Testing `transform` method." orig = GEOSGeometry("POINT (-104.609 38.255)", 4326) trans = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) # Using a srid, a SpatialReference object, and a CoordTransform object # for transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(gdal.SpatialReference("EPSG:2774")) ct = gdal.CoordTransform( gdal.SpatialReference("WGS84"), gdal.SpatialReference(2774) ) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_3d(self): p3d = GEOSGeometry("POINT (5 23 100)", 4326) p3d.transform(2774) self.assertAlmostEqual(p3d.z, 100, 3) def test_transform_noop(self): """Testing `transform` method (SRID match)""" # transform() should no-op if source & dest SRIDs match, # regardless of whether GDAL is available. g = GEOSGeometry("POINT (-104.609 38.255)", 4326) gt = g.tuple g.transform(4326) self.assertEqual(g.tuple, gt) self.assertEqual(g.srid, 4326) g = GEOSGeometry("POINT (-104.609 38.255)", 4326) g1 = g.transform(4326, clone=True) self.assertEqual(g1.tuple, g.tuple) self.assertEqual(g1.srid, 4326) self.assertIsNot(g1, g, "Clone didn't happen") def test_transform_nosrid(self): """Testing `transform` method (no SRID or negative SRID)""" g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774, clone=True) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774, clone=True) def test_extent(self): "Testing `extent` method." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50)) self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) pnt = Point(5.23, 17.8) # Extent of points is just the point itself repeated. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent) # Testing on the 'real world' Polygon. poly = fromstr(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_pickle(self): "Testing pickling and unpickling support." # Creating a list of test geometries for pickling, # and setting the SRID on some of them. def get_geoms(lst, srid=None): return [GEOSGeometry(tg.wkt, srid) for tg in lst] tgeoms = get_geoms(self.geometries.points) tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326)) tgeoms.extend(get_geoms(self.geometries.polygons, 3084)) tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857)) tgeoms.append(Point(srid=4326)) tgeoms.append(Point()) for geom in tgeoms: s1 = pickle.dumps(geom) g1 = pickle.loads(s1) self.assertEqual(geom, g1) self.assertEqual(geom.srid, g1.srid) def test_prepared(self): "Testing PreparedGeometry support." # Creating a simple multipolygon and getting a prepared version. mpoly = GEOSGeometry( "MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))" ) prep = mpoly.prepared # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] for pnt in pnts: # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt)) self.assertEqual(mpoly.covers(pnt), prep.covers(pnt)) self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)"))) self.assertTrue(prep.disjoint(Point(-5, -5))) poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1))) self.assertTrue(prep.overlaps(poly)) poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0))) self.assertTrue(prep.touches(poly)) poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1))) self.assertTrue(prep.within(poly)) # Original geometry deletion should not crash the prepared one (#21662) del mpoly self.assertTrue(prep.covers(Point(5, 5))) def test_line_merge(self): "Testing line merge support" ref_geoms = ( fromstr("LINESTRING(1 1, 1 1, 3 3)"), fromstr("MULTILINESTRING((1 1, 3 3), (3 3, 4 2))"), ) ref_merged = ( fromstr("LINESTRING(1 1, 3 3)"), fromstr("LINESTRING (1 1, 3 3, 4 2)"), ) for geom, merged in zip(ref_geoms, ref_merged): self.assertEqual(merged, geom.merged) def test_valid_reason(self): "Testing IsValidReason support" g = GEOSGeometry("POINT(0 0)") self.assertTrue(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertEqual(g.valid_reason, "Valid Geometry") g = GEOSGeometry("LINESTRING(0 0, 0 0)") self.assertFalse(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertTrue( g.valid_reason.startswith("Too few points in geometry component") ) def test_linearref(self): "Testing linear referencing" ls = fromstr("LINESTRING(0 0, 0 10, 10 10, 10 0)") mls = fromstr("MULTILINESTRING((0 0, 0 10), (10 0, 10 10))") self.assertEqual(ls.project(Point(0, 20)), 10.0) self.assertEqual(ls.project(Point(7, 6)), 24) self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3) self.assertEqual(ls.interpolate(10), Point(0, 10)) self.assertEqual(ls.interpolate(24), Point(10, 6)) self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10)) self.assertEqual(mls.project(Point(0, 20)), 10) self.assertEqual(mls.project(Point(7, 6)), 16) self.assertEqual(mls.interpolate(9), Point(0, 9)) self.assertEqual(mls.interpolate(17), Point(10, 7)) def test_deconstructible(self): """ Geometry classes should be deconstructible. """ point = Point(4.337844, 50.827537, srid=4326) path, args, kwargs = point.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.point.Point") self.assertEqual(args, (4.337844, 50.827537)) self.assertEqual(kwargs, {"srid": 4326}) ls = LineString(((0, 0), (1, 1))) path, args, kwargs = ls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, (((0, 0), (1, 1)),)) self.assertEqual(kwargs, {}) ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326) path, args, kwargs = ls2.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, ([Point(0, 0), Point(1, 1)],)) self.assertEqual(kwargs, {"srid": 4326}) ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) poly = Polygon(ext_coords, int_coords) path, args, kwargs = poly.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.polygon.Polygon") self.assertEqual(args, (ext_coords, int_coords)) self.assertEqual(kwargs, {}) lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) path, args, kwargs = lr.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LinearRing") self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0))) self.assertEqual(kwargs, {}) mp = MultiPoint(Point(0, 0), Point(1, 1)) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPoint") self.assertEqual(args, (Point(0, 0), Point(1, 1))) self.assertEqual(kwargs, {}) ls1 = LineString((0, 0), (1, 1)) ls2 = LineString((2, 2), (3, 3)) mls = MultiLineString(ls1, ls2) path, args, kwargs = mls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiLineString") self.assertEqual(args, (ls1, ls2)) self.assertEqual(kwargs, {}) p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1))) mp = MultiPolygon(p1, p2) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPolygon") self.assertEqual(args, (p1, p2)) self.assertEqual(kwargs, {}) poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) path, args, kwargs = gc.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.GeometryCollection") self.assertEqual( args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) ) self.assertEqual(kwargs, {}) def test_subclassing(self): """ GEOSGeometry subclass may itself be subclassed without being forced-cast to the parent class during `__init__`. """ class ExtendedPolygon(Polygon): def __init__(self, *args, data=0, **kwargs): super().__init__(*args, **kwargs) self._data = data def __str__(self): return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt) ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3) self.assertEqual(type(ext_poly), ExtendedPolygon) # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__). self.assertEqual( str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))" ) self.assertJSONEqual( ext_poly.json, '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}', ) def test_geos_version_tuple(self): versions = ( (b"3.0.0rc4-CAPI-1.3.3", (3, 0, 0)), (b"3.0.0-CAPI-1.4.1", (3, 0, 0)), (b"3.4.0dev-CAPI-1.8.0", (3, 4, 0)), (b"3.4.0dev-CAPI-1.8.0 r0", (3, 4, 0)), (b"3.6.2-CAPI-1.10.2 4d2925d6", (3, 6, 2)), ) for version_string, version_tuple in versions: with self.subTest(version_string=version_string): with mock.patch( "django.contrib.gis.geos.libgeos.geos_version", lambda: version_string, ): self.assertEqual(geos_version_tuple(), version_tuple) def test_from_gml(self): self.assertEqual( GEOSGeometry("POINT(0 0)"), GEOSGeometry.from_gml( '<gml:Point gml:id="p21" ' 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' "</gml:Point>" ), ) def test_from_ewkt(self): self.assertEqual( GEOSGeometry.from_ewkt("SRID=1;POINT(1 1)"), Point(1, 1, srid=1) ) self.assertEqual(GEOSGeometry.from_ewkt("POINT(1 1)"), Point(1, 1)) def test_from_ewkt_empty_string(self): msg = "Expected WKT but got an empty string." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=1;") def test_from_ewkt_invalid_srid(self): msg = "EWKT has invalid SRID part." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRUD=1;POINT(1 1)") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=WGS84;POINT(1 1)") def test_fromstr_scientific_wkt(self): self.assertEqual(GEOSGeometry("POINT(1.0e-1 1.0e+1)"), Point(0.1, 10)) def test_normalize(self): multipoint = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1)) normalized = MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0)) # Geometry is normalized in-place and nothing is returned. multipoint_1 = multipoint.clone() self.assertIsNone(multipoint_1.normalize()) self.assertEqual(multipoint_1, normalized) # If the `clone` keyword is set, then the geometry is not modified and # a normalized clone of the geometry is returned instead. multipoint_2 = multipoint.normalize(clone=True) self.assertEqual(multipoint_2, normalized) self.assertNotEqual(multipoint, normalized) @skipIf(geos_version_tuple() < (3, 8), "GEOS >= 3.8.0 is required") def test_make_valid(self): poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") self.assertIs(poly.valid, False) valid_poly = poly.make_valid() self.assertIs(valid_poly.valid, True) self.assertNotEqual(valid_poly, poly) valid_poly2 = valid_poly.make_valid() self.assertIs(valid_poly2.valid, True) self.assertEqual(valid_poly, valid_poly2) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.7.3") def test_make_valid_geos_version(self): msg = "GEOSGeometry.make_valid() requires GEOS >= 3.8.0." poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") with self.assertRaisesMessage(GEOSException, msg): poly.make_valid() def test_empty_point(self): p = Point(srid=4326) self.assertEqual(p.ogr.ewkt, p.ewkt) self.assertEqual(p.transform(2774, clone=True), Point(srid=2774)) p.transform(2774) self.assertEqual(p, Point(srid=2774)) def test_linestring_iter(self): ls = LineString((0, 0), (1, 1)) it = iter(ls) # Step into CoordSeq iterator. next(it) ls[:] = [] with self.assertRaises(IndexError): next(it)
386cba78e809308c648c0cee519f5303d5863d5b6a3eaffbb0e8fd95a932fd91
import asyncio import inspect import warnings from asgiref.sync import sync_to_async class RemovedInDjango50Warning(DeprecationWarning): pass class RemovedInDjango51Warning(PendingDeprecationWarning): pass RemovedInNextVersionWarning = RemovedInDjango50Warning RemovedAfterNextVersionWarning = RemovedInDjango51Warning class warn_about_renamed_method: def __init__( self, class_name, old_method_name, new_method_name, deprecation_warning ): self.class_name = class_name self.old_method_name = old_method_name self.new_method_name = new_method_name self.deprecation_warning = deprecation_warning def __call__(self, f): def wrapper(*args, **kwargs): warnings.warn( "`%s.%s` is deprecated, use `%s` instead." % (self.class_name, self.old_method_name, self.new_method_name), self.deprecation_warning, 2, ) return f(*args, **kwargs) return wrapper class RenameMethodsBase(type): """ Handles the deprecation paths when renaming a method. It does the following: 1) Define the new method if missing and complain about it. 2) Define the old method if missing. 3) Complain whenever an old method is called. See #15363 for more details. """ renamed_methods = () def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ for renamed_method in cls.renamed_methods: old_method_name = renamed_method[0] old_method = base.__dict__.get(old_method_name) new_method_name = renamed_method[1] new_method = base.__dict__.get(new_method_name) deprecation_warning = renamed_method[2] wrapper = warn_about_renamed_method(class_name, *renamed_method) # Define the new method if missing and complain about it if not new_method and old_method: warnings.warn( "`%s.%s` method should be renamed `%s`." % (class_name, old_method_name, new_method_name), deprecation_warning, 2, ) setattr(base, new_method_name, old_method) setattr(base, old_method_name, wrapper(old_method)) # Define the old method as a wrapped call to the new method. if not old_method and new_method: setattr(base, old_method_name, wrapper(new_method)) return new_class class DeprecationInstanceCheck(type): def __instancecheck__(self, instance): warnings.warn( "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative), self.deprecation_warning, 2, ) return super().__instancecheck__(instance) class MiddlewareMixin: sync_capable = True async_capable = True def __init__(self, get_response): if get_response is None: raise ValueError("get_response must be provided.") self.get_response = get_response self._async_check() super().__init__() def __repr__(self): return "<%s get_response=%s>" % ( self.__class__.__qualname__, getattr( self.get_response, "__qualname__", self.get_response.__class__.__name__, ), ) def _async_check(self): """ If get_response is a coroutine function, turns us into async mode so a thread is not consumed during a whole request. """ if asyncio.iscoroutinefunction(self.get_response): # Mark the class as async-capable, but do the actual switch # inside __call__ to avoid swapping out dunder methods self._is_coroutine = asyncio.coroutines._is_coroutine else: self._is_coroutine = None def __call__(self, request): # Exit out to async mode, if needed if self._is_coroutine: return self.__acall__(request) response = None if hasattr(self, "process_request"): response = self.process_request(request) response = response or self.get_response(request) if hasattr(self, "process_response"): response = self.process_response(request, response) return response async def __acall__(self, request): """ Async version of __call__ that is swapped in when an async request is running. """ response = None if hasattr(self, "process_request"): response = await sync_to_async( self.process_request, thread_sensitive=True, )(request) response = response or await self.get_response(request) if hasattr(self, "process_response"): response = await sync_to_async( self.process_response, thread_sensitive=True, )(request, response) return response class DeprecationForHistoricalMigrationMixin: system_check_deprecated_details = None system_check_removed_details = None check_type = "" def check_deprecation_details(self): from django.core import checks if self.system_check_removed_details is not None: return [ checks.Error( self.system_check_removed_details.get( "msg", "%s has been removed except for support in historical " "migrations." % self.__class__.__name__, ), hint=self.system_check_removed_details.get("hint"), obj=self, id=self.system_check_removed_details.get( "id", f"{self.check_type}.EXXX" ), ) ] elif self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( "msg", "%s has been deprecated." % self.__class__.__name__ ), hint=self.system_check_deprecated_details.get("hint"), obj=self, id=self.system_check_deprecated_details.get( "id", f"{self.check_type}.WXXX" ), ) ] return []
cd3b50cd84f34fc251c51271e40f43bd9d65f6821c9b553ed7f5e76e30b116ab
""" Helper functions for creating Form classes from Django models and database field objects. """ from itertools import chain from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.forms.fields import ChoiceField, Field from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass from django.forms.formsets import BaseFormSet, formset_factory from django.forms.utils import ErrorList from django.forms.widgets import ( HiddenInput, MultipleHiddenInput, RadioSelect, SelectMultiple, ) from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ __all__ = ( "ModelForm", "BaseModelForm", "model_to_dict", "fields_for_model", "ModelChoiceField", "ModelMultipleChoiceField", "ALL_FIELDS", "BaseModelFormSet", "modelformset_factory", "BaseInlineFormSet", "inlineformset_factory", "modelform_factory", ) ALL_FIELDS = "__all__" def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_data file_field_list = [] for f in opts.fields: if ( not f.editable or isinstance(f, models.AutoField) or f.name not in cleaned_data ): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue # Leave defaults for fields that aren't in POST data, except for # checkbox inputs because they don't appear in POST data if not checked. if ( f.has_default() and form[f.name].field.widget.value_omitted_from_data( form.data, form.files, form.add_prefix(f.name) ) and cleaned_data.get(f.name) in form[f.name].field.empty_values ): continue # Defer saving file-type fields until after the other fields, so a # callable upload_to can use the values from other fields. if isinstance(f, models.FileField): file_field_list.append(f) else: f.save_form_data(instance, cleaned_data[f.name]) for f in file_field_list: f.save_form_data(instance, cleaned_data[f.name]) return instance # ModelForms ################################################################# def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, return only the named. ``exclude`` is an optional list of field names. If provided, exclude the named from the returned dict, even if they are listed in the ``fields`` argument. """ opts = instance._meta data = {} for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if not getattr(f, "editable", False): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue data[f.name] = f.value_from_object(instance) return data def apply_limit_choices_to_to_formfield(formfield): """Apply limit_choices_to to the formfield's queryset if needed.""" from django.db.models import Exists, OuterRef, Q if hasattr(formfield, "queryset") and hasattr(formfield, "get_limit_choices_to"): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to: complex_filter = limit_choices_to if not isinstance(complex_filter, Q): complex_filter = Q(**limit_choices_to) complex_filter &= Q(pk=OuterRef("pk")) # Use Exists() to avoid potential duplicates. formfield.queryset = formfield.queryset.filter( Exists(formfield.queryset.model._base_manager.filter(complex_filter)), ) def fields_for_model( model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, *, apply_limit_choices_to=True, ): """ Return a dictionary containing form fields for the given model. ``fields`` is an optional list of field names. If provided, return only the named fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``localized_fields`` is a list of names of fields which should be localized. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to should be applied to a field's queryset. """ field_dict = {} ignored = [] opts = model._meta # Avoid circular import from django.db.models import Field as ModelField sortable_private_fields = [ f for f in opts.private_fields if isinstance(f, ModelField) ] for f in sorted( chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many) ): if not getattr(f, "editable", False): if ( fields is not None and f.name in fields and (exclude is None or f.name not in exclude) ): raise FieldError( "'%s' cannot be specified for %s model form as it is a " "non-editable field" % (f.name, model.__name__) ) continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue kwargs = {} if widgets and f.name in widgets: kwargs["widget"] = widgets[f.name] if localized_fields == ALL_FIELDS or ( localized_fields and f.name in localized_fields ): kwargs["localize"] = True if labels and f.name in labels: kwargs["label"] = labels[f.name] if help_texts and f.name in help_texts: kwargs["help_text"] = help_texts[f.name] if error_messages and f.name in error_messages: kwargs["error_messages"] = error_messages[f.name] if field_classes and f.name in field_classes: kwargs["form_class"] = field_classes[f.name] if formfield_callback is None: formfield = f.formfield(**kwargs) elif not callable(formfield_callback): raise TypeError("formfield_callback must be a function or callable") else: formfield = formfield_callback(f, **kwargs) if formfield: if apply_limit_choices_to: apply_limit_choices_to_to_formfield(formfield) field_dict[f.name] = formfield else: ignored.append(f.name) if fields: field_dict = { f: field_dict.get(f) for f in fields if (not exclude or f not in exclude) and f not in ignored } return field_dict class ModelFormOptions: def __init__(self, options=None): self.model = getattr(options, "model", None) self.fields = getattr(options, "fields", None) self.exclude = getattr(options, "exclude", None) self.widgets = getattr(options, "widgets", None) self.localized_fields = getattr(options, "localized_fields", None) self.labels = getattr(options, "labels", None) self.help_texts = getattr(options, "help_texts", None) self.error_messages = getattr(options, "error_messages", None) self.field_classes = getattr(options, "field_classes", None) class ModelFormMetaclass(DeclarativeFieldsMetaclass): def __new__(mcs, name, bases, attrs): base_formfield_callback = None for b in bases: if hasattr(b, "Meta") and hasattr(b.Meta, "formfield_callback"): base_formfield_callback = b.Meta.formfield_callback break formfield_callback = attrs.pop("formfield_callback", base_formfield_callback) new_class = super().__new__(mcs, name, bases, attrs) if bases == (BaseModelForm,): return new_class opts = new_class._meta = ModelFormOptions(getattr(new_class, "Meta", None)) # We check if a string was passed to `fields` or `exclude`, # which is likely to be a mistake where the user typed ('foo') instead # of ('foo',) for opt in ["fields", "exclude", "localized_fields"]: value = getattr(opts, opt) if isinstance(value, str) and value != ALL_FIELDS: msg = ( "%(model)s.Meta.%(opt)s cannot be a string. " "Did you mean to type: ('%(value)s',)?" % { "model": new_class.__name__, "opt": opt, "value": value, } ) raise TypeError(msg) if opts.model: # If a model is defined, extract form fields from it. if opts.fields is None and opts.exclude is None: raise ImproperlyConfigured( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form %s " "needs updating." % name ) if opts.fields == ALL_FIELDS: # Sentinel for fields_for_model to indicate "get the list of # fields from the model" opts.fields = None fields = fields_for_model( opts.model, opts.fields, opts.exclude, opts.widgets, formfield_callback, opts.localized_fields, opts.labels, opts.help_texts, opts.error_messages, opts.field_classes, # limit_choices_to will be applied during ModelForm.__init__(). apply_limit_choices_to=False, ) # make sure opts.fields doesn't specify an invalid field none_model_fields = {k for k, v in fields.items() if not v} missing_fields = none_model_fields.difference(new_class.declared_fields) if missing_fields: message = "Unknown field(s) (%s) specified for %s" message = message % (", ".join(missing_fields), opts.model.__name__) raise FieldError(message) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(new_class.declared_fields) else: fields = new_class.declared_fields new_class.base_fields = fields return new_class class BaseModelForm(BaseForm): def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None, ): opts = self._meta if opts.model is None: raise ValueError("ModelForm has no model class specified.") if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_unique will be set to True by BaseModelForm.clean(). # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False super().__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, renderer=renderer, ) for formfield in self.fields.values(): apply_limit_choices_to_to_formfield(formfield) def _get_validation_exclusions(self): """ For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553. """ exclude = set() # Build up a list of fields that should be excluded from model field # validation and unique checks. for f in self.instance._meta.fields: field = f.name # Exclude fields that aren't on the form. The developer may be # adding these values to the model after form validation. if field not in self.fields: exclude.add(f.name) # Don't perform model validation on fields that were defined # manually on the form and excluded via the ModelForm's Meta # class. See #12901. elif self._meta.fields and field not in self._meta.fields: exclude.add(f.name) elif self._meta.exclude and field in self._meta.exclude: exclude.add(f.name) # Exclude fields that failed form validation. There's no need for # the model fields to validate them as well. elif field in self._errors: exclude.add(f.name) # Exclude empty fields that are not required by the form, if the # underlying model field is required. This keeps the model field # from raising a required error. Note: don't exclude the field from # validation if the model field allows blanks. If it does, the blank # value may be included in a unique check, so cannot be excluded # from validation. else: form_field = self.fields[field] field_value = self.cleaned_data.get(field) if ( not f.blank and not form_field.required and field_value in form_field.empty_values ): exclude.add(f.name) return exclude def clean(self): self._validate_unique = True return self.cleaned_data def _update_errors(self, errors): # Override any validation error messages defined at the model level # with those defined at the form level. opts = self._meta # Allow the model generated by construct_instance() to raise # ValidationError and have them handled in the same way as others. if hasattr(errors, "error_dict"): error_dict = errors.error_dict else: error_dict = {NON_FIELD_ERRORS: errors} for field, messages in error_dict.items(): if ( field == NON_FIELD_ERRORS and opts.error_messages and NON_FIELD_ERRORS in opts.error_messages ): error_messages = opts.error_messages[NON_FIELD_ERRORS] elif field in self.fields: error_messages = self.fields[field].error_messages else: continue for message in messages: if ( isinstance(message, ValidationError) and message.code in error_messages ): message.message = error_messages[message.code] self.add_error(None, errors) def _post_clean(self): opts = self._meta exclude = self._get_validation_exclusions() # Foreign Keys being used to represent inline relationships # are excluded from basic field value validation. This is for two # reasons: firstly, the value may not be supplied (#12507; the # case of providing new values to the admin); secondly the # object being referred to may not yet fully exist (#12749). # However, these fields *must* be included in uniqueness checks, # so this can't be part of _get_validation_exclusions(). for name, field in self.fields.items(): if isinstance(field, InlineForeignKeyField): exclude.add(name) try: self.instance = construct_instance( self, self.instance, opts.fields, opts.exclude ) except ValidationError as e: self._update_errors(e) try: self.instance.full_clean(exclude=exclude, validate_unique=False) except ValidationError as e: self._update_errors(e) # Validate uniqueness if needed. if self._validate_unique: self.validate_unique() def validate_unique(self): """ Call the instance's validate_unique() method and update the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) except ValidationError as e: self._update_errors(e) def _save_m2m(self): """ Save the many-to-many fields and generic relations for this form. """ cleaned_data = self.cleaned_data exclude = self._meta.exclude fields = self._meta.fields opts = self.instance._meta # Note that for historical reasons we want to include also # private_fields here. (GenericRelation was previously a fake # m2m field). for f in chain(opts.many_to_many, opts.private_fields): if not hasattr(f, "save_form_data"): continue if fields and f.name not in fields: continue if exclude and f.name in exclude: continue if f.name in cleaned_data: f.save_form_data(self.instance, cleaned_data[f.name]) def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, "created" if self.instance._state.adding else "changed", ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save() self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance save.alters_data = True class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass): pass def modelform_factory( model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, ): """ Return a ModelForm containing form fields for the given model. You can optionally pass a `form` argument to use as a starting point for constructing the ModelForm. ``fields`` is an optional list of field names. If provided, include only the named fields in the returned fields. If omitted or '__all__', use all fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``localized_fields`` is a list of names of fields which should be localized. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. """ # Create the inner Meta class. FIXME: ideally, we should be able to # construct a ModelForm without creating and passing in a temporary # inner class. # Build up a list of attributes that the Meta object will have. attrs = {"model": model} if fields is not None: attrs["fields"] = fields if exclude is not None: attrs["exclude"] = exclude if widgets is not None: attrs["widgets"] = widgets if localized_fields is not None: attrs["localized_fields"] = localized_fields if labels is not None: attrs["labels"] = labels if help_texts is not None: attrs["help_texts"] = help_texts if error_messages is not None: attrs["error_messages"] = error_messages if field_classes is not None: attrs["field_classes"] = field_classes # If parent form class already has an inner Meta, the Meta we're # creating needs to inherit from the parent's inner meta. bases = (form.Meta,) if hasattr(form, "Meta") else () Meta = type("Meta", bases, attrs) if formfield_callback: Meta.formfield_callback = staticmethod(formfield_callback) # Give this new form class a reasonable name. class_name = model.__name__ + "Form" # Class attributes for the new form class. form_class_attrs = {"Meta": Meta, "formfield_callback": formfield_callback} if getattr(Meta, "fields", None) is None and getattr(Meta, "exclude", None) is None: raise ImproperlyConfigured( "Calling modelform_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) # Instantiate type(form) in order to use the same metaclass as form. return type(form)(class_name, (form,), form_class_attrs) # ModelFormSets ############################################################## class BaseModelFormSet(BaseFormSet): """ A ``FormSet`` for editing a queryset and/or adding new objects to it. """ model = None edit_only = False # Set of fields that must be unique among forms of this set. unique_fields = set() def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, queryset=None, *, initial=None, **kwargs, ): self.queryset = queryset self.initial_extra = initial super().__init__( **{ "data": data, "files": files, "auto_id": auto_id, "prefix": prefix, **kwargs, } ) def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count() def _existing_object(self, pk): if not hasattr(self, "_object_dict"): self._object_dict = {o.pk: o for o in self.get_queryset()} return self._object_dict.get(pk) def _get_to_python(self, field): """ If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python. """ while field.remote_field is not None: field = field.remote_field.get_related_field() return field.to_python def _construct_form(self, i, **kwargs): pk_required = i < self.initial_form_count() if pk_required: if self.is_bound: pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name) try: pk = self.data[pk_key] except KeyError: # The primary key is missing. The user may have tampered # with POST data. pass else: to_python = self._get_to_python(self.model._meta.pk) try: pk = to_python(pk) except ValidationError: # The primary key exists but is an invalid value. The # user may have tampered with POST data. pass else: kwargs["instance"] = self._existing_object(pk) else: kwargs["instance"] = self.get_queryset()[i] elif self.initial_extra: # Set initial values for extra forms try: kwargs["initial"] = self.initial_extra[i - self.initial_form_count()] except IndexError: pass form = super()._construct_form(i, **kwargs) if pk_required: form.fields[self.model._meta.pk.name].required = True return form def get_queryset(self): if not hasattr(self, "_queryset"): if self.queryset is not None: qs = self.queryset else: qs = self.model._default_manager.get_queryset() # If the queryset isn't already ordered we need to add an # artificial ordering here to make sure that all formsets # constructed from this queryset have the same form order. if not qs.ordered: qs = qs.order_by(self.model._meta.pk.name) # Removed queryset limiting here. As per discussion re: #13023 # on django-dev, max_num should not prevent existing # related objects/inlines from being displayed. self._queryset = qs return self._queryset def save_new(self, form, commit=True): """Save and return a new model instance for the given form.""" return form.save(commit=commit) def save_existing(self, form, instance, commit=True): """Save and return an existing model instance for the given form.""" return form.save(commit=commit) def delete_existing(self, obj, commit=True): """Deletes an existing model instance.""" if commit: obj.delete() def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: form.save_m2m() self.save_m2m = save_m2m if self.edit_only: return self.save_existing_objects(commit) else: return self.save_existing_objects(commit) + self.save_new_objects(commit) save.alters_data = True def clean(self): self.validate_unique() def validate_unique(self): # Collect unique_checks and date_checks to run from all the forms. all_unique_checks = set() all_date_checks = set() forms_to_delete = self.deleted_forms valid_forms = [ form for form in self.forms if form.is_valid() and form not in forms_to_delete ] for form in valid_forms: exclude = form._get_validation_exclusions() unique_checks, date_checks = form.instance._get_unique_checks( exclude=exclude, include_meta_constraints=True, ) all_unique_checks.update(unique_checks) all_date_checks.update(date_checks) errors = [] # Do each of the unique checks (unique and unique_together) for uclass, unique_check in all_unique_checks: seen_data = set() for form in valid_forms: # Get the data for the set of fields that must be unique among # the forms. row_data = ( field if field in self.unique_fields else form.cleaned_data[field] for field in unique_check if field in form.cleaned_data ) # Reduce Model instances to their primary key values row_data = tuple( d._get_pk_val() if hasattr(d, "_get_pk_val") # Prevent "unhashable type: list" errors later on. else tuple(d) if isinstance(d, list) else d for d in row_data ) if row_data and None not in row_data: # if we've already seen it then we have a uniqueness failure if row_data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_unique_error_message(unique_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. for field in unique_check: if field in form.cleaned_data: del form.cleaned_data[field] # mark the data as seen seen_data.add(row_data) # iterate over each of the date checks now for date_check in all_date_checks: seen_data = set() uclass, lookup, field, unique_for = date_check for form in valid_forms: # see if we have data for both fields if ( form.cleaned_data and form.cleaned_data[field] is not None and form.cleaned_data[unique_for] is not None ): # if it's a date lookup we need to get the data for all the fields if lookup == "date": date = form.cleaned_data[unique_for] date_data = (date.year, date.month, date.day) # otherwise it's just the attribute on the date/datetime # object else: date_data = (getattr(form.cleaned_data[unique_for], lookup),) data = (form.cleaned_data[field],) + date_data # if we've already seen it then we have a uniqueness failure if data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_date_error_message(date_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. del form.cleaned_data[field] # mark the data as seen seen_data.add(data) if errors: raise ValidationError(errors) def get_unique_error_message(self, unique_check): if len(unique_check) == 1: return gettext("Please correct the duplicate data for %(field)s.") % { "field": unique_check[0], } else: return gettext( "Please correct the duplicate data for %(field)s, which must be unique." ) % { "field": get_text_list(unique_check, _("and")), } def get_date_error_message(self, date_check): return gettext( "Please correct the duplicate data for %(field_name)s " "which must be unique for the %(lookup)s in %(date_field)s." ) % { "field_name": date_check[2], "date_field": date_check[3], "lookup": str(date_check[1]), } def get_form_error(self): return gettext("Please correct the duplicate values below.") def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.initial_forms: return [] saved_instances = [] forms_to_delete = self.deleted_forms for form in self.initial_forms: obj = form.instance # If the pk is None, it means either: # 1. The object is an unexpected empty model, created by invalid # POST data such as an object outside the formset's queryset. # 2. The object was already deleted from the database. if obj.pk is None: continue if form in forms_to_delete: self.deleted_objects.append(obj) self.delete_existing(obj, commit=commit) elif form.has_changed(): self.changed_objects.append((obj, form.changed_data)) saved_instances.append(self.save_existing(form, obj, commit=commit)) if not commit: self.saved_forms.append(form) return saved_instances def save_new_objects(self, commit=True): self.new_objects = [] for form in self.extra_forms: if not form.has_changed(): continue # If someone has marked an add form for deletion, don't save the # object. if self.can_delete and self._should_delete_form(form): continue self.new_objects.append(self.save_new(form, commit=commit)) if not commit: self.saved_forms.append(form) return self.new_objects def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, ForeignKey, OneToOneField self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ( (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or ( pk.remote_field and pk.remote_field.parent_link and pk_is_not_editable(pk.remote_field.model._meta.pk) ) ) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key # as it could be an auto-generated default which isn't actually # in the database. pk_value = None if form.instance._state.adding else form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, (ForeignKey, OneToOneField)): qs = pk.remote_field.model._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField( qs, initial=pk_value, required=False, widget=widget ) super().add_fields(form, index) def modelformset_factory( model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False, ): """Return a FormSet class for the given Django model class.""" meta = getattr(form, "Meta", None) if ( getattr(meta, "fields", fields) is None and getattr(meta, "exclude", exclude) is None ): raise ImproperlyConfigured( "Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) form = modelform_factory( model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages, field_classes=field_classes, ) FormSet = formset_factory( form, formset, extra=extra, min_num=min_num, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_min=validate_min, validate_max=validate_max, absolute_max=absolute_max, can_delete_extra=can_delete_extra, renderer=renderer, ) FormSet.model = model FormSet.edit_only = edit_only return FormSet # InlineFormSets ############################################################# class BaseInlineFormSet(BaseModelFormSet): """A formset for child objects related to a parent.""" def __init__( self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None, **kwargs, ): if instance is None: self.instance = self.fk.remote_field.model() else: self.instance = instance self.save_as_new = save_as_new if queryset is None: queryset = self.model._default_manager if self.instance.pk is not None: qs = queryset.filter(**{self.fk.name: self.instance}) else: qs = queryset.none() self.unique_fields = {self.fk.name} super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs) # Add the generated field to form._meta.fields if it's defined to make # sure validation isn't skipped on that field. if self.form._meta.fields and self.fk.name not in self.form._meta.fields: if isinstance(self.form._meta.fields, tuple): self.form._meta.fields = list(self.form._meta.fields) self.form._meta.fields.append(self.fk.name) def initial_form_count(self): if self.save_as_new: return 0 return super().initial_form_count() def _construct_form(self, i, **kwargs): form = super()._construct_form(i, **kwargs) if self.save_as_new: mutable = getattr(form.data, "_mutable", None) # Allow modifying an immutable QueryDict. if mutable is not None: form.data._mutable = True # Remove the primary key from the form's data, we are only # creating new instances form.data[form.add_prefix(self._pk_field.name)] = None # Remove the foreign key from the form's data form.data[form.add_prefix(self.fk.name)] = None if mutable is not None: form.data._mutable = mutable # Set the fk value here so that the form can do its validation. fk_value = self.instance.pk if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: fk_value = getattr(self.instance, self.fk.remote_field.field_name) fk_value = getattr(fk_value, "pk", fk_value) setattr(form.instance, self.fk.get_attname(), fk_value) return form @classmethod def get_default_prefix(cls): return cls.fk.remote_field.get_accessor_name(model=cls.model).replace("+", "") def save_new(self, form, commit=True): # Ensure the latest copy of the related instance is present on each # form (it may have been saved after the formset was originally # instantiated). setattr(form.instance, self.fk.name, self.instance) return super().save_new(form, commit=commit) def add_fields(self, form, index): super().add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {"pk_field": True} else: # The foreign key field might not be on the form, so we poke at the # Model field to get the label, since we need that for error messages. name = self.fk.name kwargs = { "label": getattr( form.fields.get(name), "label", capfirst(self.fk.verbose_name) ) } # The InlineForeignKeyField assumes that the foreign key relation is # based on the parent model's pk. If this isn't the case, set to_field # to correctly resolve the initial form value. if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: kwargs["to_field"] = self.fk.remote_field.field_name # If we're adding a new object, ignore a parent's auto-generated key # as it will be regenerated on the save request. if self.instance._state.adding: if kwargs.get("to_field") is not None: to_field = self.instance._meta.get_field(kwargs["to_field"]) else: to_field = self.instance._meta.pk if to_field.has_default(): setattr(self.instance, to_field.attname, None) form.fields[name] = InlineForeignKeyField(self.instance, **kwargs) def get_unique_error_message(self, unique_check): unique_check = [field for field in unique_check if field != self.fk.name] return super().get_unique_error_message(unique_check) def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): """ Find and return the ForeignKey from model to parent if there is one (return None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, raise an exception if there isn't a ForeignKey from model to parent_model. """ # avoid circular import from django.db.models import ForeignKey opts = model._meta if fk_name: fks_to_parent = [f for f in opts.fields if f.name == fk_name] if len(fks_to_parent) == 1: fk = fks_to_parent[0] parent_list = parent_model._meta.get_parent_list() if ( not isinstance(fk, ForeignKey) or ( # ForeignKey to proxy models. fk.remote_field.model._meta.proxy and fk.remote_field.model._meta.proxy_for_model not in parent_list ) or ( # ForeignKey to concrete models. not fk.remote_field.model._meta.proxy and fk.remote_field.model != parent_model and fk.remote_field.model not in parent_list ) ): raise ValueError( "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label) ) elif not fks_to_parent: raise ValueError( "'%s' has no field named '%s'." % (model._meta.label, fk_name) ) else: # Try to discover what the ForeignKey from model to parent_model is parent_list = parent_model._meta.get_parent_list() fks_to_parent = [ f for f in opts.fields if isinstance(f, ForeignKey) and ( f.remote_field.model == parent_model or f.remote_field.model in parent_list or ( f.remote_field.model._meta.proxy and f.remote_field.model._meta.proxy_for_model in parent_list ) ) ] if len(fks_to_parent) == 1: fk = fks_to_parent[0] elif not fks_to_parent: if can_fail: return raise ValueError( "'%s' has no ForeignKey to '%s'." % ( model._meta.label, parent_model._meta.label, ) ) else: raise ValueError( "'%s' has more than one ForeignKey to '%s'. You must specify " "a 'fk_name' attribute." % ( model._meta.label, parent_model._meta.label, ) ) return fk def inlineformset_factory( parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False, ): """ Return an ``InlineFormSet`` for the given kwargs. ``fk_name`` must be provided if ``model`` has more than one ``ForeignKey`` to ``parent_model``. """ fk = _get_foreign_key(parent_model, model, fk_name=fk_name) # enforce a max_num=1 when the foreign key to the parent model is unique. if fk.unique: max_num = 1 kwargs = { "form": form, "formfield_callback": formfield_callback, "formset": formset, "extra": extra, "can_delete": can_delete, "can_order": can_order, "fields": fields, "exclude": exclude, "min_num": min_num, "max_num": max_num, "widgets": widgets, "validate_min": validate_min, "validate_max": validate_max, "localized_fields": localized_fields, "labels": labels, "help_texts": help_texts, "error_messages": error_messages, "field_classes": field_classes, "absolute_max": absolute_max, "can_delete_extra": can_delete_extra, "renderer": renderer, "edit_only": edit_only, } FormSet = modelformset_factory(model, **kwargs) FormSet.fk = fk return FormSet # Fields ##################################################################### class InlineForeignKeyField(Field): """ A basic integer field that deals with validating the given value to a given parent instance in an inline. """ widget = HiddenInput default_error_messages = { "invalid_choice": _("The inline value did not match the parent instance."), } def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs): self.parent_instance = parent_instance self.pk_field = pk_field self.to_field = to_field if self.parent_instance is not None: if self.to_field: kwargs["initial"] = getattr(self.parent_instance, self.to_field) else: kwargs["initial"] = self.parent_instance.pk kwargs["required"] = False super().__init__(*args, **kwargs) def clean(self, value): if value in self.empty_values: if self.pk_field: return None # if there is no value act as we did before. return self.parent_instance # ensure the we compare the values as equal types. if self.to_field: orig = getattr(self.parent_instance, self.to_field) else: orig = self.parent_instance.pk if str(value) != str(orig): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice" ) return self.parent_instance def has_changed(self, initial, data): return False class ModelChoiceIteratorValue: def __init__(self, value, instance): self.value = value self.instance = instance def __str__(self): return str(self.value) def __hash__(self): return hash(self.value) def __eq__(self, other): if isinstance(other, ModelChoiceIteratorValue): other = other.value return self.value == other class ModelChoiceIterator: def __init__(self, field): self.field = field self.queryset = field.queryset def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) queryset = self.queryset # Can't use iterator() when queryset uses prefetch_related() if not queryset._prefetch_related_lookups: queryset = queryset.iterator() for obj in queryset: yield self.choice(obj) def __len__(self): # count() adds a query but uses less memory since the QuerySet results # won't be cached. In most cases, the choices will only be iterated on, # and __len__() won't be called. return self.queryset.count() + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or self.queryset.exists() def choice(self, obj): return ( ModelChoiceIteratorValue(self.field.prepare_value(obj), obj), self.field.label_from_instance(obj), ) class ModelChoiceField(ChoiceField): """A ChoiceField whose choices are a model QuerySet.""" # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. default_error_messages = { "invalid_choice": _( "Select a valid choice. That choice is not one of the available choices." ), } iterator = ModelChoiceIterator def __init__( self, queryset, *, empty_label="---------", required=True, widget=None, label=None, initial=None, help_text="", to_field_name=None, limit_choices_to=None, blank=False, **kwargs, ): # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__( self, required=required, widget=widget, label=label, initial=initial, help_text=help_text, **kwargs, ) if (required and initial is not None) or ( isinstance(self.widget, RadioSelect) and not blank ): self.empty_label = None else: self.empty_label = empty_label self.queryset = queryset self.limit_choices_to = limit_choices_to # limit the queryset later. self.to_field_name = to_field_name def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this form field. If it is a callable, invoke it and return the result. """ if callable(self.limit_choices_to): return self.limit_choices_to() return self.limit_choices_to def __deepcopy__(self, memo): result = super(ChoiceField, self).__deepcopy__(memo) # Need to force a new ModelChoiceIterator to be created, bug #11183 if self.queryset is not None: result.queryset = self.queryset.all() return result def _get_queryset(self): return self._queryset def _set_queryset(self, queryset): self._queryset = None if queryset is None else queryset.all() self.widget.choices = self.choices queryset = property(_get_queryset, _set_queryset) # this method will be used to create object labels by the QuerySetIterator. # Override it to customize the label. def label_from_instance(self, obj): """ Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ return str(obj) def _get_choices(self): # If self._choices is set, then somebody must have manually set # the property self.choices. In this case, just return self._choices. if hasattr(self, "_choices"): return self._choices # Otherwise, execute the QuerySet in self.queryset to determine the # choices dynamically. Return a fresh ModelChoiceIterator that has not been # consumed. Note that we're instantiating a new ModelChoiceIterator *each* # time _get_choices() is called (and, thus, each time self.choices is # accessed) so that we can ensure the QuerySet has not been consumed. This # construct might look complicated but it allows for lazy evaluation of # the queryset. return self.iterator(self) choices = property(_get_choices, ChoiceField._set_choices) def prepare_value(self, value): if hasattr(value, "_meta"): if self.to_field_name: return value.serializable_value(self.to_field_name) else: return value.pk return super().prepare_value(value) def to_python(self, value): if value in self.empty_values: return None try: key = self.to_field_name or "pk" if isinstance(value, self.queryset.model): value = getattr(value, key) value = self.queryset.get(**{key: value}) except (ValueError, TypeError, self.queryset.model.DoesNotExist): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) return value def validate(self, value): return Field.validate(self, value) def has_changed(self, initial, data): if self.disabled: return False initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return str(self.prepare_value(initial_value)) != str(data_value) class ModelMultipleChoiceField(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { "invalid_list": _("Enter a list of values."), "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_pk_value": _("“%(pk)s” is not a valid value."), } def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label=None, **kwargs) def to_python(self, value): if not value: return [] return list(self._check_values(value)) def clean(self, value): value = self.prepare_value(value) if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") elif not self.required and not value: return self.queryset.none() if not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) qs = self._check_values(value) # Since this overrides the inherited ModelChoiceField.clean # we run custom validators here self.run_validators(value) return qs def _check_values(self, value): """ Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.) """ key = self.to_field_name or "pk" # deduplicate given values to avoid creating many querysets or # requiring the database backend deduplicate efficiently. try: value = frozenset(value) except TypeError: # list of lists isn't hashable, for example raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) for pk in value: try: self.queryset.filter(**{key: pk}) except (ValueError, TypeError): raise ValidationError( self.error_messages["invalid_pk_value"], code="invalid_pk_value", params={"pk": pk}, ) qs = self.queryset.filter(**{"%s__in" % key: value}) pks = {str(getattr(o, key)) for o in qs} for val in value: if str(val) not in pks: raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) return qs def prepare_value(self, value): if ( hasattr(value, "__iter__") and not isinstance(value, str) and not hasattr(value, "_meta") ): prepare_value = super().prepare_value return [prepare_value(v) for v in value] return super().prepare_value(value) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in self.prepare_value(initial)} data_set = {str(value) for value in data} return data_set != initial_set def modelform_defines_fields(form_class): return hasattr(form_class, "_meta") and ( form_class._meta.fields is not None or form_class._meta.exclude is not None )
bcebfc268cb7f772f685d687abd9b0641952a356581c3c5ae45877a9df6eba34
from decimal import Decimal from django.conf import settings from django.template import Library, Node, TemplateSyntaxError, Variable from django.template.base import TokenType, render_value_in_context from django.template.defaulttags import token_kwargs from django.utils import translation from django.utils.safestring import SafeData, SafeString, mark_safe register = Library() class GetAvailableLanguagesNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = [ (k, translation.gettext(v)) for k, v in settings.LANGUAGES ] return "" class GetLanguageInfoNode(Node): def __init__(self, lang_code, variable): self.lang_code = lang_code self.variable = variable def render(self, context): lang_code = self.lang_code.resolve(context) context[self.variable] = translation.get_language_info(lang_code) return "" class GetLanguageInfoListNode(Node): def __init__(self, languages, variable): self.languages = languages self.variable = variable def get_language_info(self, language): # ``language`` is either a language code string or a sequence # with the language code as its first item if len(language[0]) > 1: return translation.get_language_info(language[0]) else: return translation.get_language_info(str(language)) def render(self, context): langs = self.languages.resolve(context) context[self.variable] = [self.get_language_info(lang) for lang in langs] return "" class GetCurrentLanguageNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return "" class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return "" class TranslateNode(Node): child_nodelists = () def __init__(self, filter_expression, noop, asvar=None, message_context=None): self.noop = noop self.asvar = asvar self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, str): self.filter_expression.is_var = True self.filter_expression.var = Variable("'%s'" % self.filter_expression.var) def render(self, context): self.filter_expression.var.translate = not self.noop if self.message_context: self.filter_expression.var.message_context = self.message_context.resolve( context ) output = self.filter_expression.resolve(context) value = render_value_in_context(output, context) # Restore percent signs. Percent signs in template text are doubled # so they are not interpreted as string format flags. is_safe = isinstance(value, SafeData) value = value.replace("%%", "%") value = mark_safe(value) if is_safe else value if self.asvar: context[self.asvar] = value return "" else: return value class BlockTranslateNode(Node): def __init__( self, extra_context, singular, plural=None, countervar=None, counter=None, message_context=None, trimmed=False, asvar=None, tag_name="blocktranslate", ): self.extra_context = extra_context self.singular = singular self.plural = plural self.countervar = countervar self.counter = counter self.message_context = message_context self.trimmed = trimmed self.asvar = asvar self.tag_name = tag_name def __repr__(self): return ( f"<{self.__class__.__qualname__}: " f"extra_context={self.extra_context!r} " f"singular={self.singular!r} plural={self.plural!r}>" ) def render_token_list(self, tokens): result = [] vars = [] for token in tokens: if token.token_type == TokenType.TEXT: result.append(token.contents.replace("%", "%%")) elif token.token_type == TokenType.VAR: result.append("%%(%s)s" % token.contents) vars.append(token.contents) msg = "".join(result) if self.trimmed: msg = translation.trim_whitespace(msg) return msg, vars def render(self, context, nested=False): if self.message_context: message_context = self.message_context.resolve(context) else: message_context = None # Update() works like a push(), so corresponding context.pop() is at # the end of function context.update( {var: val.resolve(context) for var, val in self.extra_context.items()} ) singular, vars = self.render_token_list(self.singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) if not isinstance(count, (Decimal, float, int)): raise TemplateSyntaxError( "%r argument to %r tag must be a number." % (self.countervar, self.tag_name) ) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) if message_context: result = translation.npgettext(message_context, singular, plural, count) else: result = translation.ngettext(singular, plural, count) vars.extend(plural_vars) else: if message_context: result = translation.pgettext(message_context, singular) else: result = translation.gettext(singular) default_value = context.template.engine.string_if_invalid def render_value(key): if key in context: val = context[key] else: val = default_value % key if "%s" in default_value else default_value return render_value_in_context(val, context) data = {v: render_value(v) for v in vars} context.pop() try: result = result % data except (KeyError, ValueError): if nested: # Either string is malformed, or it's a bug raise TemplateSyntaxError( "%r is unable to format string returned by gettext: %r " "using %r" % (self.tag_name, result, data) ) with translation.override(None): result = self.render(context, nested=True) if self.asvar: context[self.asvar] = SafeString(result) return "" else: return result class LanguageNode(Node): def __init__(self, nodelist, language): self.nodelist = nodelist self.language = language def render(self, context): with translation.override(self.language.resolve(context)): output = self.nodelist.render(context) return output @register.tag("get_available_languages") def do_get_available_languages(parser, token): """ Store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This puts settings.LANGUAGES into the named variable. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( "'get_available_languages' requires 'as variable' (got %r)" % args ) return GetAvailableLanguagesNode(args[2]) @register.tag("get_language_info") def do_get_language_info(parser, token): """ Store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} """ args = token.split_contents() if len(args) != 5 or args[1] != "for" or args[3] != "as": raise TemplateSyntaxError( "'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:]) ) return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4]) @register.tag("get_language_info_list") def do_get_language_info_list(parser, token): """ Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes). Usage:: {% get_language_info_list for LANGUAGES as langs %} {% for l in langs %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} {% endfor %} """ args = token.split_contents() if len(args) != 5 or args[1] != "for" or args[3] != "as": raise TemplateSyntaxError( "'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]) ) return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4]) @register.filter def language_name(lang_code): return translation.get_language_info(lang_code)["name"] @register.filter def language_name_translated(lang_code): english_name = translation.get_language_info(lang_code)["name"] return translation.gettext(english_name) @register.filter def language_name_local(lang_code): return translation.get_language_info(lang_code)["name_local"] @register.filter def language_bidi(lang_code): return translation.get_language_info(lang_code)["bidi"] @register.tag("get_current_language") def do_get_current_language(parser, token): """ Store the current language in the context. Usage:: {% get_current_language as language %} This fetches the currently active language and puts its value into the ``language`` context variable. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( "'get_current_language' requires 'as variable' (got %r)" % args ) return GetCurrentLanguageNode(args[2]) @register.tag("get_current_language_bidi") def do_get_current_language_bidi(parser, token): """ Store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This fetches the currently active language's layout and puts its value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( "'get_current_language_bidi' requires 'as variable' (got %r)" % args ) return GetCurrentLanguageBidiNode(args[2]) @register.tag("translate") @register.tag("trans") def do_translate(parser, token): """ Mark a string for translation and translate the string for the current language. Usage:: {% translate "this is a test" %} This marks the string for translation so it will be pulled out by makemessages into the .po files and runs the string through the translation engine. There is a second form:: {% translate "this is a test" noop %} This marks the string for translation, but returns the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% translate variable %} This tries to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% translate "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% translate "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext. """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0]) message_string = parser.compile_filter(bits[1]) remaining = bits[2:] noop = False asvar = None message_context = None seen = set() invalid_context = {"as", "noop"} while remaining: option = remaining.pop(0) if option in seen: raise TemplateSyntaxError( "The '%s' option was specified more than once." % option, ) elif option == "noop": noop = True elif option == "context": try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the context option." % bits[0] ) if value in invalid_context: raise TemplateSyntaxError( "Invalid argument '%s' provided to the '%s' tag for the context " "option" % (value, bits[0]), ) message_context = parser.compile_filter(value) elif option == "as": try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the as option." % bits[0] ) asvar = value else: raise TemplateSyntaxError( "Unknown argument for '%s' tag: '%s'. The only options " "available are 'noop', 'context' \"xxx\", and 'as VAR'." % ( bits[0], option, ) ) seen.add(option) return TranslateNode(message_string, noop, asvar, message_context) @register.tag("blocktranslate") @register.tag("blocktrans") def do_block_translate(parser, token): """ Translate a block of text with parameters. Usage:: {% blocktranslate with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} Additionally, this supports pluralization:: {% blocktranslate count count=var|length %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktranslate %} This is much like ngettext, only in template syntax. The "var as value" legacy format is still supported:: {% blocktranslate with foo|filter as bar and baz|filter as boo %} {% blocktranslate count var|length as count %} The translated string can be stored in a variable using `asvar`:: {% blocktranslate with bar=foo|filter boo=baz|filter asvar var %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} {{ var }} Contextual translations are supported:: {% blocktranslate with bar=foo|filter context "greeting" %} This is {{ bar }}. {% endblocktranslate %} This is equivalent to calling pgettext/npgettext instead of (u)gettext/(u)ngettext. """ bits = token.split_contents() options = {} remaining_bits = bits[1:] asvar = None while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError( "The %r option was specified more than once." % option ) if option == "with": value = token_kwargs(remaining_bits, parser, support_legacy=True) if not value: raise TemplateSyntaxError( '"with" in %r tag needs at least one keyword argument.' % bits[0] ) elif option == "count": value = token_kwargs(remaining_bits, parser, support_legacy=True) if len(value) != 1: raise TemplateSyntaxError( '"count" in %r tag expected exactly ' "one keyword argument." % bits[0] ) elif option == "context": try: value = remaining_bits.pop(0) value = parser.compile_filter(value) except Exception: raise TemplateSyntaxError( '"context" in %r tag expected exactly one argument.' % bits[0] ) elif option == "trimmed": value = True elif option == "asvar": try: value = remaining_bits.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the asvar option." % bits[0] ) asvar = value else: raise TemplateSyntaxError( "Unknown argument for %r tag: %r." % (bits[0], option) ) options[option] = value if "count" in options: countervar, counter = next(iter(options["count"].items())) else: countervar, counter = None, None if "context" in options: message_context = options["context"] else: message_context = None extra_context = options.get("with", {}) trimmed = options.get("trimmed", False) singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TokenType.VAR, TokenType.TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != "plural": raise TemplateSyntaxError( "%r doesn't allow other block tags inside it" % bits[0] ) while parser.tokens: token = parser.next_token() if token.token_type in (TokenType.VAR, TokenType.TEXT): plural.append(token) else: break end_tag_name = "end%s" % bits[0] if token.contents.strip() != end_tag_name: raise TemplateSyntaxError( "%r doesn't allow other block tags (seen %r) inside it" % (bits[0], token.contents) ) return BlockTranslateNode( extra_context, singular, plural, countervar, counter, message_context, trimmed=trimmed, asvar=asvar, tag_name=bits[0], ) @register.tag def language(parser, token): """ Enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(("endlanguage",)) parser.delete_first_token() return LanguageNode(nodelist, language)
40ceb7157bcccb7a85505e23140c4506205124378b83996d51142752ff864cd5
import copy from collections import defaultdict from contextlib import contextmanager from functools import partial from django.apps import AppConfig from django.apps.registry import Apps from django.apps.registry import apps as global_apps from django.conf import settings from django.core.exceptions import FieldDoesNotExist from django.db import models from django.db.migrations.utils import field_is_referenced, get_references from django.db.models import NOT_PROVIDED from django.db.models.fields.related import RECURSIVE_RELATIONSHIP_CONSTANT from django.db.models.options import DEFAULT_NAMES, normalize_together from django.db.models.utils import make_model_tuple from django.utils.functional import cached_property from django.utils.module_loading import import_string from django.utils.version import get_docs_version from .exceptions import InvalidBasesError from .utils import resolve_relation def _get_app_label_and_model_name(model, app_label=""): if isinstance(model, str): split = model.split(".", 1) return tuple(split) if len(split) == 2 else (app_label, split[0]) else: return model._meta.app_label, model._meta.model_name def _get_related_models(m): """Return all models that have a direct relationship to the given model.""" related_models = [ subclass for subclass in m.__subclasses__() if issubclass(subclass, models.Model) ] related_fields_models = set() for f in m._meta.get_fields(include_parents=True, include_hidden=True): if ( f.is_relation and f.related_model is not None and not isinstance(f.related_model, str) ): related_fields_models.add(f.model) related_models.append(f.related_model) # Reverse accessors of foreign keys to proxy models are attached to their # concrete proxied model. opts = m._meta if opts.proxy and m in related_fields_models: related_models.append(opts.concrete_model) return related_models def get_related_models_tuples(model): """ Return a list of typical (app_label, model_name) tuples for all related models for the given model. """ return { (rel_mod._meta.app_label, rel_mod._meta.model_name) for rel_mod in _get_related_models(model) } def get_related_models_recursive(model): """ Return all models that have a direct or indirect relationship to the given model. Relationships are either defined by explicit relational fields, like ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another model (a superclass is related to its subclasses, but not vice versa). Note, however, that a model inheriting from a concrete model is also related to its superclass through the implicit *_ptr OneToOneField on the subclass. """ seen = set() queue = _get_related_models(model) for rel_mod in queue: rel_app_label, rel_model_name = ( rel_mod._meta.app_label, rel_mod._meta.model_name, ) if (rel_app_label, rel_model_name) in seen: continue seen.add((rel_app_label, rel_model_name)) queue.extend(_get_related_models(rel_mod)) return seen - {(model._meta.app_label, model._meta.model_name)} class ProjectState: """ Represent the entire project's overall state. This is the item that is passed around - do it here rather than at the app level so that cross-app FKs/etc. resolve properly. """ def __init__(self, models=None, real_apps=None): self.models = models or {} # Apps to include from main registry, usually unmigrated ones if real_apps is None: real_apps = set() else: assert isinstance(real_apps, set) self.real_apps = real_apps self.is_delayed = False # {remote_model_key: {model_key: {field_name: field}}} self._relations = None @property def relations(self): if self._relations is None: self.resolve_fields_and_relations() return self._relations def add_model(self, model_state): model_key = model_state.app_label, model_state.name_lower self.models[model_key] = model_state if self._relations is not None: self.resolve_model_relations(model_key) if "apps" in self.__dict__: # hasattr would cache the property self.reload_model(*model_key) def remove_model(self, app_label, model_name): model_key = app_label, model_name del self.models[model_key] if self._relations is not None: self._relations.pop(model_key, None) # Call list() since _relations can change size during iteration. for related_model_key, model_relations in list(self._relations.items()): model_relations.pop(model_key, None) if not model_relations: del self._relations[related_model_key] if "apps" in self.__dict__: # hasattr would cache the property self.apps.unregister_model(*model_key) # Need to do this explicitly since unregister_model() doesn't clear # the cache automatically (#24513) self.apps.clear_cache() def rename_model(self, app_label, old_name, new_name): # Add a new model. old_name_lower = old_name.lower() new_name_lower = new_name.lower() renamed_model = self.models[app_label, old_name_lower].clone() renamed_model.name = new_name self.models[app_label, new_name_lower] = renamed_model # Repoint all fields pointing to the old model to the new one. old_model_tuple = (app_label, old_name_lower) new_remote_model = f"{app_label}.{new_name}" to_reload = set() for model_state, name, field, reference in get_references( self, old_model_tuple ): changed_field = None if reference.to: changed_field = field.clone() changed_field.remote_field.model = new_remote_model if reference.through: if changed_field is None: changed_field = field.clone() changed_field.remote_field.through = new_remote_model if changed_field: model_state.fields[name] = changed_field to_reload.add((model_state.app_label, model_state.name_lower)) if self._relations is not None: old_name_key = app_label, old_name_lower new_name_key = app_label, new_name_lower if old_name_key in self._relations: self._relations[new_name_key] = self._relations.pop(old_name_key) for model_relations in self._relations.values(): if old_name_key in model_relations: model_relations[new_name_key] = model_relations.pop(old_name_key) # Reload models related to old model before removing the old model. self.reload_models(to_reload, delay=True) # Remove the old model. self.remove_model(app_label, old_name_lower) self.reload_model(app_label, new_name_lower, delay=True) def alter_model_options(self, app_label, model_name, options, option_keys=None): model_state = self.models[app_label, model_name] model_state.options = {**model_state.options, **options} if option_keys: for key in option_keys: if key not in options: model_state.options.pop(key, False) self.reload_model(app_label, model_name, delay=True) def remove_model_options(self, app_label, model_name, option_name, value_to_remove): model_state = self.models[app_label, model_name] if objs := model_state.options.get(option_name): model_state.options[option_name] = [ obj for obj in objs if tuple(obj) != tuple(value_to_remove) ] self.reload_model(app_label, model_name, delay=True) def alter_model_managers(self, app_label, model_name, managers): model_state = self.models[app_label, model_name] model_state.managers = list(managers) self.reload_model(app_label, model_name, delay=True) def _append_option(self, app_label, model_name, option_name, obj): model_state = self.models[app_label, model_name] model_state.options[option_name] = [*model_state.options[option_name], obj] self.reload_model(app_label, model_name, delay=True) def _remove_option(self, app_label, model_name, option_name, obj_name): model_state = self.models[app_label, model_name] objs = model_state.options[option_name] model_state.options[option_name] = [obj for obj in objs if obj.name != obj_name] self.reload_model(app_label, model_name, delay=True) def add_index(self, app_label, model_name, index): self._append_option(app_label, model_name, "indexes", index) def remove_index(self, app_label, model_name, index_name): self._remove_option(app_label, model_name, "indexes", index_name) def rename_index(self, app_label, model_name, old_index_name, new_index_name): model_state = self.models[app_label, model_name] objs = model_state.options["indexes"] new_indexes = [] for obj in objs: if obj.name == old_index_name: obj = obj.clone() obj.name = new_index_name new_indexes.append(obj) model_state.options["indexes"] = new_indexes self.reload_model(app_label, model_name, delay=True) def add_constraint(self, app_label, model_name, constraint): self._append_option(app_label, model_name, "constraints", constraint) def remove_constraint(self, app_label, model_name, constraint_name): self._remove_option(app_label, model_name, "constraints", constraint_name) def add_field(self, app_label, model_name, name, field, preserve_default): # If preserve default is off, don't use the default for future state. if not preserve_default: field = field.clone() field.default = NOT_PROVIDED else: field = field model_key = app_label, model_name self.models[model_key].fields[name] = field if self._relations is not None: self.resolve_model_field_relations(model_key, name, field) # Delay rendering of relationships if it's not a relational field. delay = not field.is_relation self.reload_model(*model_key, delay=delay) def remove_field(self, app_label, model_name, name): model_key = app_label, model_name model_state = self.models[model_key] old_field = model_state.fields.pop(name) if self._relations is not None: self.resolve_model_field_relations(model_key, name, old_field) # Delay rendering of relationships if it's not a relational field. delay = not old_field.is_relation self.reload_model(*model_key, delay=delay) def alter_field(self, app_label, model_name, name, field, preserve_default): if not preserve_default: field = field.clone() field.default = NOT_PROVIDED else: field = field model_key = app_label, model_name fields = self.models[model_key].fields if self._relations is not None: old_field = fields.pop(name) if old_field.is_relation: self.resolve_model_field_relations(model_key, name, old_field) fields[name] = field if field.is_relation: self.resolve_model_field_relations(model_key, name, field) else: fields[name] = field # TODO: investigate if old relational fields must be reloaded or if # it's sufficient if the new field is (#27737). # Delay rendering of relationships if it's not a relational field and # not referenced by a foreign key. delay = not field.is_relation and not field_is_referenced( self, model_key, (name, field) ) self.reload_model(*model_key, delay=delay) def rename_field(self, app_label, model_name, old_name, new_name): model_key = app_label, model_name model_state = self.models[model_key] # Rename the field. fields = model_state.fields try: found = fields.pop(old_name) except KeyError: raise FieldDoesNotExist( f"{app_label}.{model_name} has no field named '{old_name}'" ) fields[new_name] = found for field in fields.values(): # Fix from_fields to refer to the new field. from_fields = getattr(field, "from_fields", None) if from_fields: field.from_fields = tuple( [ new_name if from_field_name == old_name else from_field_name for from_field_name in from_fields ] ) # Fix index/unique_together to refer to the new field. options = model_state.options for option in ("index_together", "unique_together"): if option in options: options[option] = [ [new_name if n == old_name else n for n in together] for together in options[option] ] # Fix to_fields to refer to the new field. delay = True references = get_references(self, model_key, (old_name, found)) for *_, field, reference in references: delay = False if reference.to: remote_field, to_fields = reference.to if getattr(remote_field, "field_name", None) == old_name: remote_field.field_name = new_name if to_fields: field.to_fields = tuple( [ new_name if to_field_name == old_name else to_field_name for to_field_name in to_fields ] ) if self._relations is not None: old_name_lower = old_name.lower() new_name_lower = new_name.lower() for to_model in self._relations.values(): if old_name_lower in to_model[model_key]: field = to_model[model_key].pop(old_name_lower) field.name = new_name_lower to_model[model_key][new_name_lower] = field self.reload_model(*model_key, delay=delay) def _find_reload_model(self, app_label, model_name, delay=False): if delay: self.is_delayed = True related_models = set() try: old_model = self.apps.get_model(app_label, model_name) except LookupError: pass else: # Get all relations to and from the old model before reloading, # as _meta.apps may change if delay: related_models = get_related_models_tuples(old_model) else: related_models = get_related_models_recursive(old_model) # Get all outgoing references from the model to be rendered model_state = self.models[(app_label, model_name)] # Directly related models are the models pointed to by ForeignKeys, # OneToOneFields, and ManyToManyFields. direct_related_models = set() for field in model_state.fields.values(): if field.is_relation: if field.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT: continue rel_app_label, rel_model_name = _get_app_label_and_model_name( field.related_model, app_label ) direct_related_models.add((rel_app_label, rel_model_name.lower())) # For all direct related models recursively get all related models. related_models.update(direct_related_models) for rel_app_label, rel_model_name in direct_related_models: try: rel_model = self.apps.get_model(rel_app_label, rel_model_name) except LookupError: pass else: if delay: related_models.update(get_related_models_tuples(rel_model)) else: related_models.update(get_related_models_recursive(rel_model)) # Include the model itself related_models.add((app_label, model_name)) return related_models def reload_model(self, app_label, model_name, delay=False): if "apps" in self.__dict__: # hasattr would cache the property related_models = self._find_reload_model(app_label, model_name, delay) self._reload(related_models) def reload_models(self, models, delay=True): if "apps" in self.__dict__: # hasattr would cache the property related_models = set() for app_label, model_name in models: related_models.update( self._find_reload_model(app_label, model_name, delay) ) self._reload(related_models) def _reload(self, related_models): # Unregister all related models with self.apps.bulk_update(): for rel_app_label, rel_model_name in related_models: self.apps.unregister_model(rel_app_label, rel_model_name) states_to_be_rendered = [] # Gather all models states of those models that will be rerendered. # This includes: # 1. All related models of unmigrated apps for model_state in self.apps.real_models: if (model_state.app_label, model_state.name_lower) in related_models: states_to_be_rendered.append(model_state) # 2. All related models of migrated apps for rel_app_label, rel_model_name in related_models: try: model_state = self.models[rel_app_label, rel_model_name] except KeyError: pass else: states_to_be_rendered.append(model_state) # Render all models self.apps.render_multiple(states_to_be_rendered) def update_model_field_relation( self, model, model_key, field_name, field, concretes, ): remote_model_key = resolve_relation(model, *model_key) if remote_model_key[0] not in self.real_apps and remote_model_key in concretes: remote_model_key = concretes[remote_model_key] relations_to_remote_model = self._relations[remote_model_key] if field_name in self.models[model_key].fields: # The assert holds because it's a new relation, or an altered # relation, in which case references have been removed by # alter_field(). assert field_name not in relations_to_remote_model[model_key] relations_to_remote_model[model_key][field_name] = field else: del relations_to_remote_model[model_key][field_name] if not relations_to_remote_model[model_key]: del relations_to_remote_model[model_key] def resolve_model_field_relations( self, model_key, field_name, field, concretes=None, ): remote_field = field.remote_field if not remote_field: return if concretes is None: concretes, _ = self._get_concrete_models_mapping_and_proxy_models() self.update_model_field_relation( remote_field.model, model_key, field_name, field, concretes, ) through = getattr(remote_field, "through", None) if not through: return self.update_model_field_relation( through, model_key, field_name, field, concretes ) def resolve_model_relations(self, model_key, concretes=None): if concretes is None: concretes, _ = self._get_concrete_models_mapping_and_proxy_models() model_state = self.models[model_key] for field_name, field in model_state.fields.items(): self.resolve_model_field_relations(model_key, field_name, field, concretes) def resolve_fields_and_relations(self): # Resolve fields. for model_state in self.models.values(): for field_name, field in model_state.fields.items(): field.name = field_name # Resolve relations. # {remote_model_key: {model_key: {field_name: field}}} self._relations = defaultdict(partial(defaultdict, dict)) concretes, proxies = self._get_concrete_models_mapping_and_proxy_models() for model_key in concretes: self.resolve_model_relations(model_key, concretes) for model_key in proxies: self._relations[model_key] = self._relations[concretes[model_key]] def get_concrete_model_key(self, model): ( concrete_models_mapping, _, ) = self._get_concrete_models_mapping_and_proxy_models() model_key = make_model_tuple(model) return concrete_models_mapping[model_key] def _get_concrete_models_mapping_and_proxy_models(self): concrete_models_mapping = {} proxy_models = {} # Split models to proxy and concrete models. for model_key, model_state in self.models.items(): if model_state.options.get("proxy"): proxy_models[model_key] = model_state # Find a concrete model for the proxy. concrete_models_mapping[ model_key ] = self._find_concrete_model_from_proxy( proxy_models, model_state, ) else: concrete_models_mapping[model_key] = model_key return concrete_models_mapping, proxy_models def _find_concrete_model_from_proxy(self, proxy_models, model_state): for base in model_state.bases: if not (isinstance(base, str) or issubclass(base, models.Model)): continue base_key = make_model_tuple(base) base_state = proxy_models.get(base_key) if not base_state: # Concrete model found, stop looking at bases. return base_key return self._find_concrete_model_from_proxy(proxy_models, base_state) def clone(self): """Return an exact copy of this ProjectState.""" new_state = ProjectState( models={k: v.clone() for k, v in self.models.items()}, real_apps=self.real_apps, ) if "apps" in self.__dict__: new_state.apps = self.apps.clone() new_state.is_delayed = self.is_delayed return new_state def clear_delayed_apps_cache(self): if self.is_delayed and "apps" in self.__dict__: del self.__dict__["apps"] @cached_property def apps(self): return StateApps(self.real_apps, self.models) @classmethod def from_apps(cls, apps): """Take an Apps and return a ProjectState matching it.""" app_models = {} for model in apps.get_models(include_swapped=True): model_state = ModelState.from_model(model) app_models[(model_state.app_label, model_state.name_lower)] = model_state return cls(app_models) def __eq__(self, other): return self.models == other.models and self.real_apps == other.real_apps class AppConfigStub(AppConfig): """Stub of an AppConfig. Only provides a label and a dict of models.""" def __init__(self, label): self.apps = None self.models = {} # App-label and app-name are not the same thing, so technically passing # in the label here is wrong. In practice, migrations don't care about # the app name, but we need something unique, and the label works fine. self.label = label self.name = label def import_models(self): self.models = self.apps.all_models[self.label] class StateApps(Apps): """ Subclass of the global Apps registry class to better handle dynamic model additions and removals. """ def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [ AppConfigStub(label) for label in sorted([*real_apps, *app_labels]) ] super().__init__(app_configs) # These locks get in the way of copying as implemented in clone(), # which is called whenever Django duplicates a StateApps before # updating it. self._lock = None self.ready_event = None self.render_multiple([*models.values(), *self.real_models]) # There shouldn't be any operations pending at this point. from django.core.checks.model_checks import _check_lazy_references ignore = ( {make_model_tuple(settings.AUTH_USER_MODEL)} if ignore_swappable else set() ) errors = _check_lazy_references(self, ignore=ignore) if errors: raise ValueError("\n".join(error.msg for error in errors)) @contextmanager def bulk_update(self): # Avoid clearing each model's cache for each change. Instead, clear # all caches when we're finished updating the model instances. ready = self.ready self.ready = False try: yield finally: self.ready = ready self.clear_cache() def render_multiple(self, model_states): # We keep trying to render the models in a loop, ignoring invalid # base errors, until the size of the unrendered models doesn't # decrease by at least one, meaning there's a base dependency loop/ # missing base. if not model_states: return # Prevent that all model caches are expired for each render. with self.bulk_update(): unrendered_models = model_states while unrendered_models: new_unrendered_models = [] for model in unrendered_models: try: model.render(self) except InvalidBasesError: new_unrendered_models.append(model) if len(new_unrendered_models) == len(unrendered_models): raise InvalidBasesError( "Cannot resolve bases for %r\nThis can happen if you are " "inheriting models from an app with migrations (e.g. " "contrib.auth)\n in an app with no migrations; see " "https://docs.djangoproject.com/en/%s/topics/migrations/" "#dependencies for more" % (new_unrendered_models, get_docs_version()) ) unrendered_models = new_unrendered_models def clone(self): """Return a clone of this registry.""" clone = StateApps([], {}) clone.all_models = copy.deepcopy(self.all_models) for app_label in self.app_configs: app_config = AppConfigStub(app_label) app_config.apps = clone app_config.import_models() clone.app_configs[app_label] = app_config # No need to actually clone them, they'll never change clone.real_models = self.real_models return clone def register_model(self, app_label, model): self.all_models[app_label][model._meta.model_name] = model if app_label not in self.app_configs: self.app_configs[app_label] = AppConfigStub(app_label) self.app_configs[app_label].apps = self self.app_configs[app_label].models[model._meta.model_name] = model self.do_pending_operations(model) self.clear_cache() def unregister_model(self, app_label, model_name): try: del self.all_models[app_label][model_name] del self.app_configs[app_label].models[model_name] except KeyError: pass class ModelState: """ Represent a Django Model. Don't use the actual Model class as it's not designed to have its options changed - instead, mutate this one and then render it into a Model as required. Note that while you are allowed to mutate .fields, you are not allowed to mutate the Field instances inside there themselves - you must instead assign new ones, as these are not detached during a clone. """ def __init__( self, app_label, name, fields, options=None, bases=None, managers=None ): self.app_label = app_label self.name = name self.fields = dict(fields) self.options = options or {} self.options.setdefault("indexes", []) self.options.setdefault("constraints", []) self.bases = bases or (models.Model,) self.managers = managers or [] for name, field in self.fields.items(): # Sanity-check that fields are NOT already bound to a model. if hasattr(field, "model"): raise ValueError( 'ModelState.fields cannot be bound to a model - "%s" is.' % name ) # Sanity-check that relation fields are NOT referring to a model class. if field.is_relation and hasattr(field.related_model, "_meta"): raise ValueError( 'ModelState.fields cannot refer to a model class - "%s.to" does. ' "Use a string reference instead." % name ) if field.many_to_many and hasattr(field.remote_field.through, "_meta"): raise ValueError( 'ModelState.fields cannot refer to a model class - "%s.through" ' "does. Use a string reference instead." % name ) # Sanity-check that indexes have their name set. for index in self.options["indexes"]: if not index.name: raise ValueError( "Indexes passed to ModelState require a name attribute. " "%r doesn't have one." % index ) @cached_property def name_lower(self): return self.name.lower() def get_field(self, field_name): if field_name == "_order": field_name = self.options.get("order_with_respect_to", field_name) return self.fields[field_name] @classmethod def from_model(cls, model, exclude_rels=False): """Given a model, return a ModelState representing it.""" # Deconstruct the fields fields = [] for field in model._meta.local_fields: if getattr(field, "remote_field", None) and exclude_rels: continue if isinstance(field, models.OrderWrt): continue name = field.name try: fields.append((name, field.clone())) except TypeError as e: raise TypeError( "Couldn't reconstruct field %s on %s: %s" % ( name, model._meta.label, e, ) ) if not exclude_rels: for field in model._meta.local_many_to_many: name = field.name try: fields.append((name, field.clone())) except TypeError as e: raise TypeError( "Couldn't reconstruct m2m field %s on %s: %s" % ( name, model._meta.object_name, e, ) ) # Extract the options options = {} for name in DEFAULT_NAMES: # Ignore some special options if name in ["apps", "app_label"]: continue elif name in model._meta.original_attrs: if name == "unique_together": ut = model._meta.original_attrs["unique_together"] options[name] = set(normalize_together(ut)) elif name == "index_together": it = model._meta.original_attrs["index_together"] options[name] = set(normalize_together(it)) elif name == "indexes": indexes = [idx.clone() for idx in model._meta.indexes] for index in indexes: if not index.name: index.set_name_with_model(model) options["indexes"] = indexes elif name == "constraints": options["constraints"] = [ con.clone() for con in model._meta.constraints ] else: options[name] = model._meta.original_attrs[name] # If we're ignoring relationships, remove all field-listing model # options (that option basically just means "make a stub model") if exclude_rels: for key in ["unique_together", "index_together", "order_with_respect_to"]: if key in options: del options[key] # Private fields are ignored, so remove options that refer to them. elif options.get("order_with_respect_to") in { field.name for field in model._meta.private_fields }: del options["order_with_respect_to"] def flatten_bases(model): bases = [] for base in model.__bases__: if hasattr(base, "_meta") and base._meta.abstract: bases.extend(flatten_bases(base)) else: bases.append(base) return bases # We can't rely on __mro__ directly because we only want to flatten # abstract models and not the whole tree. However by recursing on # __bases__ we may end up with duplicates and ordering issues, we # therefore discard any duplicates and reorder the bases according # to their index in the MRO. flattened_bases = sorted( set(flatten_bases(model)), key=lambda x: model.__mro__.index(x) ) # Make our record bases = tuple( (base._meta.label_lower if hasattr(base, "_meta") else base) for base in flattened_bases ) # Ensure at least one base inherits from models.Model if not any( (isinstance(base, str) or issubclass(base, models.Model)) for base in bases ): bases = (models.Model,) managers = [] manager_names = set() default_manager_shim = None for manager in model._meta.managers: if manager.name in manager_names: # Skip overridden managers. continue elif manager.use_in_migrations: # Copy managers usable in migrations. new_manager = copy.copy(manager) new_manager._set_creation_counter() elif manager is model._base_manager or manager is model._default_manager: # Shim custom managers used as default and base managers. new_manager = models.Manager() new_manager.model = manager.model new_manager.name = manager.name if manager is model._default_manager: default_manager_shim = new_manager else: continue manager_names.add(manager.name) managers.append((manager.name, new_manager)) # Ignore a shimmed default manager called objects if it's the only one. if managers == [("objects", default_manager_shim)]: managers = [] # Construct the new ModelState return cls( model._meta.app_label, model._meta.object_name, fields, options, bases, managers, ) def construct_managers(self): """Deep-clone the managers using deconstruction.""" # Sort all managers by their creation counter sorted_managers = sorted(self.managers, key=lambda v: v[1].creation_counter) for mgr_name, manager in sorted_managers: as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct() if as_manager: qs_class = import_string(qs_path) yield mgr_name, qs_class.as_manager() else: manager_class = import_string(manager_path) yield mgr_name, manager_class(*args, **kwargs) def clone(self): """Return an exact copy of this ModelState.""" return self.__class__( app_label=self.app_label, name=self.name, fields=dict(self.fields), # Since options are shallow-copied here, operations such as # AddIndex must replace their option (e.g 'indexes') rather # than mutating it. options=dict(self.options), bases=self.bases, managers=list(self.managers), ) def render(self, apps): """Create a Model object from our current state into the given apps.""" # First, make a Meta object meta_contents = {"app_label": self.app_label, "apps": apps, **self.options} meta = type("Meta", (), meta_contents) # Then, work out our bases try: bases = tuple( (apps.get_model(base) if isinstance(base, str) else base) for base in self.bases ) except LookupError: raise InvalidBasesError( "Cannot resolve one or more bases from %r" % (self.bases,) ) # Clone fields for the body, add other bits. body = {name: field.clone() for name, field in self.fields.items()} body["Meta"] = meta body["__module__"] = "__fake__" # Restore managers body.update(self.construct_managers()) # Then, make a Model object (apps.register_model is called in __new__) return type(self.name, bases, body) def get_index_by_name(self, name): for index in self.options["indexes"]: if index.name == name: return index raise ValueError("No index named %s on model %s" % (name, self.name)) def get_constraint_by_name(self, name): for constraint in self.options["constraints"]: if constraint.name == name: return constraint raise ValueError("No constraint named %s on model %s" % (name, self.name)) def __repr__(self): return "<%s: '%s.%s'>" % (self.__class__.__name__, self.app_label, self.name) def __eq__(self, other): return ( (self.app_label == other.app_label) and (self.name == other.name) and (len(self.fields) == len(other.fields)) and all( k1 == k2 and f1.deconstruct()[1:] == f2.deconstruct()[1:] for (k1, f1), (k2, f2) in zip( sorted(self.fields.items()), sorted(other.fields.items()), ) ) and (self.options == other.options) and (self.bases == other.bases) and (self.managers == other.managers) )
95ee38e1731755672ae5ea112416e7a65180528661c2d6a03f60edd5a67e8988
from django.db.migrations.utils import get_migration_name_timestamp from django.db.transaction import atomic from .exceptions import IrreversibleError class Migration: """ The base class for all migrations. Migration files will import this from django.db.migrations.Migration and subclass it as a class called Migration. It will have one or more of the following attributes: - operations: A list of Operation instances, probably from django.db.migrations.operations - dependencies: A list of tuples of (app_path, migration_name) - run_before: A list of tuples of (app_path, migration_name) - replaces: A list of migration_names Note that all migrations come out of migrations and into the Loader or Graph as instances, having been initialized with their app label and name. """ # Operations to apply during this migration, in order. operations = [] # Other migrations that should be run before this migration. # Should be a list of (app, migration_name). dependencies = [] # Other migrations that should be run after this one (i.e. have # this migration added to their dependencies). Useful to make third-party # apps' migrations run after your AUTH_USER replacement, for example. run_before = [] # Migration names in this app that this migration replaces. If this is # non-empty, this migration will only be applied if all these migrations # are not applied. replaces = [] # Is this an initial migration? Initial migrations are skipped on # --fake-initial if the table or fields already exist. If None, check if # the migration has any dependencies to determine if there are dependencies # to tell if db introspection needs to be done. If True, always perform # introspection. If False, never perform introspection. initial = None # Whether to wrap the whole migration in a transaction. Only has an effect # on database backends which support transactional DDL. atomic = True def __init__(self, name, app_label): self.name = name self.app_label = app_label # Copy dependencies & other attrs as we might mutate them at runtime self.operations = list(self.__class__.operations) self.dependencies = list(self.__class__.dependencies) self.run_before = list(self.__class__.run_before) self.replaces = list(self.__class__.replaces) def __eq__(self, other): return ( isinstance(other, Migration) and self.name == other.name and self.app_label == other.app_label ) def __repr__(self): return "<Migration %s.%s>" % (self.app_label, self.name) def __str__(self): return "%s.%s" % (self.app_label, self.name) def __hash__(self): return hash("%s.%s" % (self.app_label, self.name)) def mutate_state(self, project_state, preserve=True): """ Take a ProjectState and return a new one with the migration's operations applied to it. Preserve the original object state by default and return a mutated state from a copy. """ new_state = project_state if preserve: new_state = project_state.clone() for operation in self.operations: operation.state_forwards(self.app_label, new_state) return new_state def apply(self, project_state, schema_editor, collect_sql=False): """ Take a project_state representing all migrations prior to this one and a schema_editor for a live database and apply the migration in a forwards order. Return the resulting project state for efficient reuse by following Migrations. """ for operation in self.operations: # If this operation cannot be represented as SQL, place a comment # there instead if collect_sql: schema_editor.collected_sql.append("--") schema_editor.collected_sql.append("-- %s" % operation.describe()) schema_editor.collected_sql.append("--") if not operation.reduces_to_sql: schema_editor.collected_sql.append( "-- THIS OPERATION CANNOT BE WRITTEN AS SQL" ) continue collected_sql_before = len(schema_editor.collected_sql) # Save the state before the operation has run old_state = project_state.clone() operation.state_forwards(self.app_label, project_state) # Run the operation atomic_operation = operation.atomic or ( self.atomic and operation.atomic is not False ) if not schema_editor.atomic_migration and atomic_operation: # Force a transaction on a non-transactional-DDL backend or an # atomic operation inside a non-atomic migration. with atomic(schema_editor.connection.alias): operation.database_forwards( self.app_label, schema_editor, old_state, project_state ) else: # Normal behaviour operation.database_forwards( self.app_label, schema_editor, old_state, project_state ) if collect_sql and collected_sql_before == len(schema_editor.collected_sql): schema_editor.collected_sql.append("-- (no-op)") return project_state def unapply(self, project_state, schema_editor, collect_sql=False): """ Take a project_state representing all migrations prior to this one and a schema_editor for a live database and apply the migration in a reverse order. The backwards migration process consists of two phases: 1. The intermediate states from right before the first until right after the last operation inside this migration are preserved. 2. The operations are applied in reverse order using the states recorded in step 1. """ # Construct all the intermediate states we need for a reverse migration to_run = [] new_state = project_state # Phase 1 for operation in self.operations: # If it's irreversible, error out if not operation.reversible: raise IrreversibleError( "Operation %s in %s is not reversible" % (operation, self) ) # Preserve new state from previous run to not tamper the same state # over all operations new_state = new_state.clone() old_state = new_state.clone() operation.state_forwards(self.app_label, new_state) to_run.insert(0, (operation, old_state, new_state)) # Phase 2 for operation, to_state, from_state in to_run: if collect_sql: schema_editor.collected_sql.append("--") schema_editor.collected_sql.append("-- %s" % operation.describe()) schema_editor.collected_sql.append("--") if not operation.reduces_to_sql: schema_editor.collected_sql.append( "-- THIS OPERATION CANNOT BE WRITTEN AS SQL" ) continue collected_sql_before = len(schema_editor.collected_sql) atomic_operation = operation.atomic or ( self.atomic and operation.atomic is not False ) if not schema_editor.atomic_migration and atomic_operation: # Force a transaction on a non-transactional-DDL backend or an # atomic operation inside a non-atomic migration. with atomic(schema_editor.connection.alias): operation.database_backwards( self.app_label, schema_editor, from_state, to_state ) else: # Normal behaviour operation.database_backwards( self.app_label, schema_editor, from_state, to_state ) if collect_sql and collected_sql_before == len(schema_editor.collected_sql): schema_editor.collected_sql.append("-- (no-op)") return project_state def suggest_name(self): """ Suggest a name for the operations this migration might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible. """ if self.initial: return "initial" raw_fragments = [op.migration_name_fragment for op in self.operations] fragments = [name for name in raw_fragments if name] if not fragments or len(fragments) != len(self.operations): return "auto_%s" % get_migration_name_timestamp() name = fragments[0] for fragment in fragments[1:]: new_name = f"{name}_{fragment}" if len(new_name) > 52: name = f"{name}_and_more" break name = new_name return name def check(self): errors = [] for operation in self.operations: errors.extend(operation.check_deprecation_details()) return errors class SwappableTuple(tuple): """ Subclass of tuple so Django can tell this was originally a swappable dependency when it reads the migration file. """ def __new__(cls, value, setting): self = tuple.__new__(cls, value) self.setting = setting return self def swappable_dependency(value): """Turn a setting value into a dependency.""" return SwappableTuple((value.split(".", 1)[0], "__first__"), value)
83717a8b944cef6ff728644806d7a2c273853388590ca0dda591c928c73e18a1
import bisect import copy import inspect import warnings from collections import defaultdict from django.apps import apps from django.conf import settings from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured from django.db import connections from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint from django.db.models.query_utils import PathInfo from django.utils.datastructures import ImmutableList, OrderedSet from django.utils.deprecation import RemovedInDjango51Warning from django.utils.functional import cached_property from django.utils.module_loading import import_string from django.utils.text import camel_case_to_spaces, format_lazy from django.utils.translation import override PROXY_PARENTS = object() EMPTY_RELATION_TREE = () IMMUTABLE_WARNING = ( "The return type of '%s' should never be mutated. If you want to manipulate this " "list for your own use, make a copy first." ) DEFAULT_NAMES = ( "verbose_name", "verbose_name_plural", "db_table", "ordering", "unique_together", "permissions", "get_latest_by", "order_with_respect_to", "app_label", "db_tablespace", "abstract", "managed", "proxy", "swappable", "auto_created", "index_together", "apps", "default_permissions", "select_on_save", "default_related_name", "required_db_features", "required_db_vendor", "base_manager_name", "default_manager_name", "indexes", "constraints", ) def normalize_together(option_together): """ option_together can be either a tuple of tuples, or a single tuple of two strings. Normalize it to a tuple of tuples, so that calling code can uniformly expect that. """ try: if not option_together: return () if not isinstance(option_together, (tuple, list)): raise TypeError first_element = option_together[0] if not isinstance(first_element, (tuple, list)): option_together = (option_together,) # Normalize everything to tuples return tuple(tuple(ot) for ot in option_together) except TypeError: # If the value of option_together isn't valid, return it # verbatim; this will be picked up by the check framework later. return option_together def make_immutable_fields_list(name, data): return ImmutableList(data, warning=IMMUTABLE_WARNING % name) class Options: FORWARD_PROPERTIES = { "fields", "many_to_many", "concrete_fields", "local_concrete_fields", "_forward_fields_map", "managers", "managers_map", "base_manager", "default_manager", } REVERSE_PROPERTIES = {"related_objects", "fields_map", "_relation_tree"} default_apps = apps def __init__(self, meta, app_label=None): self._get_fields_cache = {} self.local_fields = [] self.local_many_to_many = [] self.private_fields = [] self.local_managers = [] self.base_manager_name = None self.default_manager_name = None self.model_name = None self.verbose_name = None self.verbose_name_plural = None self.db_table = "" self.ordering = [] self._ordering_clash = False self.indexes = [] self.constraints = [] self.unique_together = [] self.index_together = [] self.select_on_save = False self.default_permissions = ("add", "change", "delete", "view") self.permissions = [] self.object_name = None self.app_label = app_label self.get_latest_by = None self.order_with_respect_to = None self.db_tablespace = settings.DEFAULT_TABLESPACE self.required_db_features = [] self.required_db_vendor = None self.meta = meta self.pk = None self.auto_field = None self.abstract = False self.managed = True self.proxy = False # For any class that is a proxy (including automatically created # classes for deferred object loading), proxy_for_model tells us # which class this model is proxying. Note that proxy_for_model # can create a chain of proxy models. For non-proxy models, the # variable is always None. self.proxy_for_model = None # For any non-abstract class, the concrete class is the model # in the end of the proxy_for_model chain. In particular, for # concrete models, the concrete_model is always the class itself. self.concrete_model = None self.swappable = None self.parents = {} self.auto_created = False # List of all lookups defined in ForeignKey 'limit_choices_to' options # from *other* models. Needed for some admin checks. Internal use only. self.related_fkey_lookups = [] # A custom app registry to use, if you're making a separate model set. self.apps = self.default_apps self.default_related_name = None @property def label(self): return "%s.%s" % (self.app_label, self.object_name) @property def label_lower(self): return "%s.%s" % (self.app_label, self.model_name) @property def app_config(self): # Don't go through get_app_config to avoid triggering imports. return self.apps.app_configs.get(self.app_label) def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith("_"): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) if self.index_together: warnings.warn( f"'index_together' is deprecated. Use 'Meta.indexes' in " f"{self.label!r} instead.", RemovedInDjango51Warning, ) # App label/class name interpolation for names of constraints and # indexes. if not getattr(cls._meta, "abstract", False): for attr_name in {"constraints", "indexes"}: objs = getattr(self, attr_name, []) setattr(self, attr_name, self._format_names_with_class(cls, objs)) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError( "'class Meta' got invalid attribute(s): %s" % ",".join(meta_attrs) ) else: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name( self.db_table, connection.ops.max_name_length() ) def _format_names_with_class(self, cls, objs): """App label/class name interpolation for object names.""" new_objs = [] for obj in objs: obj = obj.clone() obj.name = obj.name % { "app_label": cls._meta.app_label.lower(), "class": cls.__name__.lower(), } new_objs.append(obj) return new_objs def _get_default_pk_class(self): pk_class_path = getattr( self.app_config, "default_auto_field", settings.DEFAULT_AUTO_FIELD, ) if self.app_config and self.app_config._is_default_auto_field_overridden: app_config_class = type(self.app_config) source = ( f"{app_config_class.__module__}." f"{app_config_class.__qualname__}.default_auto_field" ) else: source = "DEFAULT_AUTO_FIELD" if not pk_class_path: raise ImproperlyConfigured(f"{source} must not be empty.") try: pk_class = import_string(pk_class_path) except ImportError as e: msg = ( f"{source} refers to the module '{pk_class_path}' that could " f"not be imported." ) raise ImproperlyConfigured(msg) from e if not issubclass(pk_class, AutoField): raise ValueError( f"Primary key '{pk_class_path}' referred by {source} must " f"subclass AutoField." ) return pk_class def _prepare(self, model): if self.order_with_respect_to: # The app registry will not be ready at this point, so we cannot # use get_field(). query = self.order_with_respect_to try: self.order_with_respect_to = next( f for f in self._get_fields(reverse=False) if f.name == query or f.attname == query ) except StopIteration: raise FieldDoesNotExist( "%s has no field named '%s'" % (self.object_name, query) ) self.ordering = ("_order",) if not any( isinstance(field, OrderWrt) for field in model._meta.local_fields ): model.add_to_class("_order", OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = next(iter(self.parents.values())) # Look for a local field with the same name as the # first parent link. If a local field has already been # created, use it instead of promoting the parent already_created = [ fld for fld in self.local_fields if fld.name == field.name ] if already_created: field = already_created[0] field.primary_key = True self.setup_pk(field) else: pk_class = self._get_default_pk_class() auto = pk_class(verbose_name="ID", primary_key=True, auto_created=True) model.add_to_class("id", auto) def add_manager(self, manager): self.local_managers.append(manager) self._expire_cache() def add_field(self, field, private=False): # Insert the given field in the order in which it was created, using # the "creation_counter" attribute of the field. # Move many-to-many related fields from self.fields into # self.many_to_many. if private: self.private_fields.append(field) elif field.is_relation and field.many_to_many: bisect.insort(self.local_many_to_many, field) else: bisect.insort(self.local_fields, field) self.setup_pk(field) # If the field being added is a relation to another known field, # expire the cache on this field and the forward cache on the field # being referenced, because there will be new relationships in the # cache. Otherwise, expire the cache of references *to* this field. # The mechanism for getting at the related model is slightly odd - # ideally, we'd just ask for field.related_model. However, related_model # is a cached property, and all the models haven't been loaded yet, so # we need to make sure we don't cache a string reference. if ( field.is_relation and hasattr(field.remote_field, "model") and field.remote_field.model ): try: field.remote_field.model._meta._expire_cache(forward=False) except AttributeError: pass self._expire_cache() else: self._expire_cache(reverse=False) def setup_pk(self, field): if not self.pk and field.primary_key: self.pk = field field.serialize = False def setup_proxy(self, target): """ Do the internal setup so that the current model is a proxy for "target". """ self.pk = target._meta.pk self.proxy_for_model = target self.db_table = target._meta.db_table def __repr__(self): return "<Options for %s>" % self.object_name def __str__(self): return self.label_lower def can_migrate(self, connection): """ Return True if the model can/should be migrated on the `connection`. `connection` can be either a real connection or a connection alias. """ if self.proxy or self.swapped or not self.managed: return False if isinstance(connection, str): connection = connections[connection] if self.required_db_vendor: return self.required_db_vendor == connection.vendor if self.required_db_features: return all( getattr(connection.features, feat, False) for feat in self.required_db_features ) return True @property def verbose_name_raw(self): """Return the untranslated verbose name.""" with override(None): return str(self.verbose_name) @property def swapped(self): """ Has this model been swapped out for another? If so, return the model name of the replacement; otherwise, return None. For historical reasons, model name lookups using get_model() are case insensitive, so we make sure we are case insensitive here. """ if self.swappable: swapped_for = getattr(settings, self.swappable, None) if swapped_for: try: swapped_label, swapped_object = swapped_for.split(".") except ValueError: # setting not in the format app_label.model_name # raising ImproperlyConfigured here causes problems with # test cleanup code - instead it is raised in get_user_model # or as part of validation. return swapped_for if ( "%s.%s" % (swapped_label, swapped_object.lower()) != self.label_lower ): return swapped_for return None @cached_property def managers(self): managers = [] seen_managers = set() bases = (b for b in self.model.mro() if hasattr(b, "_meta")) for depth, base in enumerate(bases): for manager in base._meta.local_managers: if manager.name in seen_managers: continue manager = copy.copy(manager) manager.model = self.model seen_managers.add(manager.name) managers.append((depth, manager.creation_counter, manager)) return make_immutable_fields_list( "managers", (m[2] for m in sorted(managers)), ) @cached_property def managers_map(self): return {manager.name: manager for manager in self.managers} @cached_property def base_manager(self): base_manager_name = self.base_manager_name if not base_manager_name: # Get the first parent's base_manager_name if there's one. for parent in self.model.mro()[1:]: if hasattr(parent, "_meta"): if parent._base_manager.name != "_base_manager": base_manager_name = parent._base_manager.name break if base_manager_name: try: return self.managers_map[base_manager_name] except KeyError: raise ValueError( "%s has no manager named %r" % ( self.object_name, base_manager_name, ) ) manager = Manager() manager.name = "_base_manager" manager.model = self.model manager.auto_created = True return manager @cached_property def default_manager(self): default_manager_name = self.default_manager_name if not default_manager_name and not self.local_managers: # Get the first parent's default_manager_name if there's one. for parent in self.model.mro()[1:]: if hasattr(parent, "_meta"): default_manager_name = parent._meta.default_manager_name break if default_manager_name: try: return self.managers_map[default_manager_name] except KeyError: raise ValueError( "%s has no manager named %r" % ( self.object_name, default_manager_name, ) ) if self.managers: return self.managers[0] @cached_property def fields(self): """ Return a list of all forward fields on the model and its parents, excluding ManyToManyFields. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ # For legacy reasons, the fields property should only contain forward # fields that are not private or with a m2m cardinality. Therefore we # pass these three filters as filters to the generator. # The third lambda is a longwinded way of checking f.related_model - we don't # use that property directly because related_model is a cached property, # and all the models may not have been loaded yet; we don't want to cache # the string reference to the related_model. def is_not_an_m2m_field(f): return not (f.is_relation and f.many_to_many) def is_not_a_generic_relation(f): return not (f.is_relation and f.one_to_many) def is_not_a_generic_foreign_key(f): return not ( f.is_relation and f.many_to_one and not (hasattr(f.remote_field, "model") and f.remote_field.model) ) return make_immutable_fields_list( "fields", ( f for f in self._get_fields(reverse=False) if is_not_an_m2m_field(f) and is_not_a_generic_relation(f) and is_not_a_generic_foreign_key(f) ), ) @cached_property def concrete_fields(self): """ Return a list of all concrete fields on the model and its parents. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ return make_immutable_fields_list( "concrete_fields", (f for f in self.fields if f.concrete) ) @cached_property def local_concrete_fields(self): """ Return a list of all concrete fields on the model. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ return make_immutable_fields_list( "local_concrete_fields", (f for f in self.local_fields if f.concrete) ) @cached_property def many_to_many(self): """ Return a list of all many to many fields on the model and its parents. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this list. """ return make_immutable_fields_list( "many_to_many", ( f for f in self._get_fields(reverse=False) if f.is_relation and f.many_to_many ), ) @cached_property def related_objects(self): """ Return all related objects pointing to the current model. The related objects can come from a one-to-one, one-to-many, or many-to-many field relation type. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this field list. """ all_related_fields = self._get_fields( forward=False, reverse=True, include_hidden=True ) return make_immutable_fields_list( "related_objects", ( obj for obj in all_related_fields if not obj.hidden or obj.field.many_to_many ), ) @cached_property def _forward_fields_map(self): res = {} fields = self._get_fields(reverse=False) for field in fields: res[field.name] = field # Due to the way Django's internals work, get_field() should also # be able to fetch a field by attname. In the case of a concrete # field with relation, includes the *_id name too try: res[field.attname] = field except AttributeError: pass return res @cached_property def fields_map(self): res = {} fields = self._get_fields(forward=False, include_hidden=True) for field in fields: res[field.name] = field # Due to the way Django's internals work, get_field() should also # be able to fetch a field by attname. In the case of a concrete # field with relation, includes the *_id name too try: res[field.attname] = field except AttributeError: pass return res def get_field(self, field_name): """ Return a field instance given the name of a forward or reverse field. """ try: # In order to avoid premature loading of the relation tree # (expensive) we prefer checking if the field is a forward field. return self._forward_fields_map[field_name] except KeyError: # If the app registry is not ready, reverse fields are # unavailable, therefore we throw a FieldDoesNotExist exception. if not self.apps.models_ready: raise FieldDoesNotExist( "%s has no field named '%s'. The app cache isn't ready yet, " "so if this is an auto-created related field, it won't " "be available yet." % (self.object_name, field_name) ) try: # Retrieve field instance by name from cached or just-computed # field map. return self.fields_map[field_name] except KeyError: raise FieldDoesNotExist( "%s has no field named '%s'" % (self.object_name, field_name) ) def get_base_chain(self, model): """ Return a list of parent classes leading to `model` (ordered from closest to most distant ancestor). This has to handle the case where `model` is a grandparent or even more distant relation. """ if not self.parents: return [] if model in self.parents: return [model] for parent in self.parents: res = parent._meta.get_base_chain(model) if res: res.insert(0, parent) return res return [] def get_parent_list(self): """ Return all the ancestors of this model as a list ordered by MRO. Useful for determining if something is an ancestor, regardless of lineage. """ result = OrderedSet(self.parents) for parent in self.parents: for ancestor in parent._meta.get_parent_list(): result.add(ancestor) return list(result) def get_ancestor_link(self, ancestor): """ Return the field on the current model which points to the given "ancestor". This is possible an indirect link (a pointer to a parent model, which points, eventually, to the ancestor). Used when constructing table joins for model inheritance. Return None if the model isn't an ancestor of this one. """ if ancestor in self.parents: return self.parents[ancestor] for parent in self.parents: # Tries to get a link field from the immediate parent parent_link = parent._meta.get_ancestor_link(ancestor) if parent_link: # In case of a proxied model, the first link # of the chain to the ancestor is that parent # links return self.parents[parent] or parent_link def get_path_to_parent(self, parent): """ Return a list of PathInfos containing the path from the current model to the parent model, or an empty list if parent is not a parent of the current model. """ if self.model is parent: return [] # Skip the chain of proxy to the concrete proxied model. proxied_model = self.concrete_model path = [] opts = self for int_model in self.get_base_chain(parent): if int_model is proxied_model: opts = int_model._meta else: final_field = opts.parents[int_model] targets = (final_field.remote_field.get_related_field(),) opts = int_model._meta path.append( PathInfo( from_opts=final_field.model._meta, to_opts=opts, target_fields=targets, join_field=final_field, m2m=False, direct=True, filtered_relation=None, ) ) return path def get_path_from_parent(self, parent): """ Return a list of PathInfos containing the path from the parent model to the current model, or an empty list if parent is not a parent of the current model. """ if self.model is parent: return [] model = self.concrete_model # Get a reversed base chain including both the current and parent # models. chain = model._meta.get_base_chain(parent) chain.reverse() chain.append(model) # Construct a list of the PathInfos between models in chain. path = [] for i, ancestor in enumerate(chain[:-1]): child = chain[i + 1] link = child._meta.get_ancestor_link(ancestor) path.extend(link.reverse_path_infos) return path def _populate_directed_relation_graph(self): """ This method is used by each model to find its reverse objects. As this method is very expensive and is accessed frequently (it looks up every field in a model, in every app), it is computed on first access and then is set as a property on every model. """ related_objects_graph = defaultdict(list) all_models = self.apps.get_models(include_auto_created=True) for model in all_models: opts = model._meta # Abstract model's fields are copied to child models, hence we will # see the fields from the child models. if opts.abstract: continue fields_with_relations = ( f for f in opts._get_fields(reverse=False, include_parents=False) if f.is_relation and f.related_model is not None ) for f in fields_with_relations: if not isinstance(f.remote_field.model, str): remote_label = f.remote_field.model._meta.concrete_model._meta.label related_objects_graph[remote_label].append(f) for model in all_models: # Set the relation_tree using the internal __dict__. In this way # we avoid calling the cached property. In attribute lookup, # __dict__ takes precedence over a data descriptor (such as # @cached_property). This means that the _meta._relation_tree is # only called if related_objects is not in __dict__. related_objects = related_objects_graph[ model._meta.concrete_model._meta.label ] model._meta.__dict__["_relation_tree"] = related_objects # It seems it is possible that self is not in all_models, so guard # against that with default for get(). return self.__dict__.get("_relation_tree", EMPTY_RELATION_TREE) @cached_property def _relation_tree(self): return self._populate_directed_relation_graph() def _expire_cache(self, forward=True, reverse=True): # This method is usually called by apps.cache_clear(), when the # registry is finalized, or when a new field is added. if forward: for cache_key in self.FORWARD_PROPERTIES: if cache_key in self.__dict__: delattr(self, cache_key) if reverse and not self.abstract: for cache_key in self.REVERSE_PROPERTIES: if cache_key in self.__dict__: delattr(self, cache_key) self._get_fields_cache = {} def get_fields(self, include_parents=True, include_hidden=False): """ Return a list of fields associated to the model. By default, include forward and reverse fields, fields derived from inheritance, but not hidden fields. The returned fields can be changed using the parameters: - include_parents: include fields derived from inheritance - include_hidden: include fields that have a related_name that starts with a "+" """ if include_parents is False: include_parents = PROXY_PARENTS return self._get_fields( include_parents=include_parents, include_hidden=include_hidden ) def _get_fields( self, forward=True, reverse=True, include_parents=True, include_hidden=False, seen_models=None, ): """ Internal helper function to return fields of the model. * If forward=True, then fields defined on this model are returned. * If reverse=True, then relations pointing to this model are returned. * If include_hidden=True, then fields with is_hidden=True are returned. * The include_parents argument toggles if fields from parent models should be included. It has three values: True, False, and PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all fields defined for the current model or any of its parents in the parent chain to the model's concrete model. """ if include_parents not in (True, False, PROXY_PARENTS): raise TypeError( "Invalid argument for include_parents: %s" % (include_parents,) ) # This helper function is used to allow recursion in ``get_fields()`` # implementation and to provide a fast way for Django's internals to # access specific subsets of fields. # We must keep track of which models we have already seen. Otherwise we # could include the same field multiple times from different models. topmost_call = seen_models is None if topmost_call: seen_models = set() seen_models.add(self.model) # Creates a cache key composed of all arguments cache_key = (forward, reverse, include_parents, include_hidden, topmost_call) try: # In order to avoid list manipulation. Always return a shallow copy # of the results. return self._get_fields_cache[cache_key] except KeyError: pass fields = [] # Recursively call _get_fields() on each parent, with the same # options provided in this call. if include_parents is not False: for parent in self.parents: # In diamond inheritance it is possible that we see the same # model from two different routes. In that case, avoid adding # fields from the same parent again. if parent in seen_models: continue if ( parent._meta.concrete_model != self.concrete_model and include_parents == PROXY_PARENTS ): continue for obj in parent._meta._get_fields( forward=forward, reverse=reverse, include_parents=include_parents, include_hidden=include_hidden, seen_models=seen_models, ): if ( not getattr(obj, "parent_link", False) or obj.model == self.concrete_model ): fields.append(obj) if reverse and not self.proxy: # Tree is computed once and cached until the app cache is expired. # It is composed of a list of fields pointing to the current model # from other models. all_fields = self._relation_tree for field in all_fields: # If hidden fields should be included or the relation is not # intentionally hidden, add to the fields dict. if include_hidden or not field.remote_field.hidden: fields.append(field.remote_field) if forward: fields += self.local_fields fields += self.local_many_to_many # Private fields are recopied to each child model, and they get a # different model as field.model in each child. Hence we have to # add the private fields separately from the topmost call. If we # did this recursively similar to local_fields, we would get field # instances with field.model != self.model. if topmost_call: fields += self.private_fields # In order to avoid list manipulation. Always # return a shallow copy of the results fields = make_immutable_fields_list("get_fields()", fields) # Store result into cache for later access self._get_fields_cache[cache_key] = fields return fields @cached_property def total_unique_constraints(self): """ Return a list of total unique constraints. Useful for determining set of fields guaranteed to be unique for all rows. """ return [ constraint for constraint in self.constraints if ( isinstance(constraint, UniqueConstraint) and constraint.condition is None and not constraint.contains_expressions ) ] @cached_property def _property_names(self): """Return a set of the names of the properties defined on the model.""" names = [] for name in dir(self.model): attr = inspect.getattr_static(self.model, name) if isinstance(attr, property): names.append(name) return frozenset(names) @cached_property def db_returning_fields(self): """ Private API intended only to be used by Django itself. Fields to be returned after a database insert. """ return [ field for field in self._get_fields( forward=True, reverse=False, include_parents=PROXY_PARENTS ) if getattr(field, "db_returning", False) ]
6d4f3705150416ce901e80591f517b0f3dc88d981014756eb8c5c4d5c832dd58
from enum import Enum from django.core.exceptions import FieldError, ValidationError from django.db import connections from django.db.models.expressions import Exists, ExpressionList, F from django.db.models.indexes import IndexExpression from django.db.models.lookups import Exact from django.db.models.query_utils import Q from django.db.models.sql.query import Query from django.db.utils import DEFAULT_DB_ALIAS from django.utils.translation import gettext_lazy as _ __all__ = ["BaseConstraint", "CheckConstraint", "Deferrable", "UniqueConstraint"] class BaseConstraint: default_violation_error_message = _("Constraint “%(name)s” is violated.") violation_error_message = None def __init__(self, name, violation_error_message=None): self.name = name if violation_error_message is not None: self.violation_error_message = violation_error_message else: self.violation_error_message = self.default_violation_error_message @property def contains_expressions(self): return False def constraint_sql(self, model, schema_editor): raise NotImplementedError("This method must be implemented by a subclass.") def create_sql(self, model, schema_editor): raise NotImplementedError("This method must be implemented by a subclass.") def remove_sql(self, model, schema_editor): raise NotImplementedError("This method must be implemented by a subclass.") def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): raise NotImplementedError("This method must be implemented by a subclass.") def get_violation_error_message(self): return self.violation_error_message % {"name": self.name} def deconstruct(self): path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) path = path.replace("django.db.models.constraints", "django.db.models") kwargs = {"name": self.name} if ( self.violation_error_message is not None and self.violation_error_message != self.default_violation_error_message ): kwargs["violation_error_message"] = self.violation_error_message return (path, (), kwargs) def clone(self): _, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) class CheckConstraint(BaseConstraint): def __init__(self, *, check, name, violation_error_message=None): self.check = check if not getattr(check, "conditional", False): raise TypeError( "CheckConstraint.check must be a Q instance or boolean expression." ) super().__init__(name, violation_error_message=violation_error_message) def _get_check_sql(self, model, schema_editor): query = Query(model=model, alias_cols=False) where = query.build_where(self.check) compiler = query.get_compiler(connection=schema_editor.connection) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params) def constraint_sql(self, model, schema_editor): check = self._get_check_sql(model, schema_editor) return schema_editor._check_sql(self.name, check) def create_sql(self, model, schema_editor): check = self._get_check_sql(model, schema_editor) return schema_editor._create_check_sql(model, self.name, check) def remove_sql(self, model, schema_editor): return schema_editor._delete_check_sql(model, self.name) def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): against = instance._get_field_value_map(meta=model._meta, exclude=exclude) try: if not Q(self.check).check(against, using=using): raise ValidationError(self.get_violation_error_message()) except FieldError: pass def __repr__(self): return "<%s: check=%s name=%s>" % ( self.__class__.__qualname__, self.check, repr(self.name), ) def __eq__(self, other): if isinstance(other, CheckConstraint): return ( self.name == other.name and self.check == other.check and self.violation_error_message == other.violation_error_message ) return super().__eq__(other) def deconstruct(self): path, args, kwargs = super().deconstruct() kwargs["check"] = self.check return path, args, kwargs class Deferrable(Enum): DEFERRED = "deferred" IMMEDIATE = "immediate" # A similar format was proposed for Python 3.10. def __repr__(self): return f"{self.__class__.__qualname__}.{self._name_}" class UniqueConstraint(BaseConstraint): def __init__( self, *expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None, ): if not name: raise ValueError("A unique constraint must be named.") if not expressions and not fields: raise ValueError( "At least one field or expression is required to define a " "unique constraint." ) if expressions and fields: raise ValueError( "UniqueConstraint.fields and expressions are mutually exclusive." ) if not isinstance(condition, (type(None), Q)): raise ValueError("UniqueConstraint.condition must be a Q instance.") if condition and deferrable: raise ValueError("UniqueConstraint with conditions cannot be deferred.") if include and deferrable: raise ValueError("UniqueConstraint with include fields cannot be deferred.") if opclasses and deferrable: raise ValueError("UniqueConstraint with opclasses cannot be deferred.") if expressions and deferrable: raise ValueError("UniqueConstraint with expressions cannot be deferred.") if expressions and opclasses: raise ValueError( "UniqueConstraint.opclasses cannot be used with expressions. " "Use django.contrib.postgres.indexes.OpClass() instead." ) if not isinstance(deferrable, (type(None), Deferrable)): raise ValueError( "UniqueConstraint.deferrable must be a Deferrable instance." ) if not isinstance(include, (type(None), list, tuple)): raise ValueError("UniqueConstraint.include must be a list or tuple.") if not isinstance(opclasses, (list, tuple)): raise ValueError("UniqueConstraint.opclasses must be a list or tuple.") if opclasses and len(fields) != len(opclasses): raise ValueError( "UniqueConstraint.fields and UniqueConstraint.opclasses must " "have the same number of elements." ) self.fields = tuple(fields) self.condition = condition self.deferrable = deferrable self.include = tuple(include) if include else () self.opclasses = opclasses self.expressions = tuple( F(expression) if isinstance(expression, str) else expression for expression in expressions ) super().__init__(name, violation_error_message=violation_error_message) @property def contains_expressions(self): return bool(self.expressions) def _get_condition_sql(self, model, schema_editor): if self.condition is None: return None query = Query(model=model, alias_cols=False) where = query.build_where(self.condition) compiler = query.get_compiler(connection=schema_editor.connection) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params) def _get_index_expressions(self, model, schema_editor): if not self.expressions: return None index_expressions = [] for expression in self.expressions: index_expression = IndexExpression(expression) index_expression.set_wrapper_classes(schema_editor.connection) index_expressions.append(index_expression) return ExpressionList(*index_expressions).resolve_expression( Query(model, alias_cols=False), ) def constraint_sql(self, model, schema_editor): fields = [model._meta.get_field(field_name) for field_name in self.fields] include = [ model._meta.get_field(field_name).column for field_name in self.include ] condition = self._get_condition_sql(model, schema_editor) expressions = self._get_index_expressions(model, schema_editor) return schema_editor._unique_sql( model, fields, self.name, condition=condition, deferrable=self.deferrable, include=include, opclasses=self.opclasses, expressions=expressions, ) def create_sql(self, model, schema_editor): fields = [model._meta.get_field(field_name) for field_name in self.fields] include = [ model._meta.get_field(field_name).column for field_name in self.include ] condition = self._get_condition_sql(model, schema_editor) expressions = self._get_index_expressions(model, schema_editor) return schema_editor._create_unique_sql( model, fields, self.name, condition=condition, deferrable=self.deferrable, include=include, opclasses=self.opclasses, expressions=expressions, ) def remove_sql(self, model, schema_editor): condition = self._get_condition_sql(model, schema_editor) include = [ model._meta.get_field(field_name).column for field_name in self.include ] expressions = self._get_index_expressions(model, schema_editor) return schema_editor._delete_unique_sql( model, self.name, condition=condition, deferrable=self.deferrable, include=include, opclasses=self.opclasses, expressions=expressions, ) def __repr__(self): return "<%s:%s%s%s%s%s%s%s>" % ( self.__class__.__qualname__, "" if not self.fields else " fields=%s" % repr(self.fields), "" if not self.expressions else " expressions=%s" % repr(self.expressions), " name=%s" % repr(self.name), "" if self.condition is None else " condition=%s" % self.condition, "" if self.deferrable is None else " deferrable=%r" % self.deferrable, "" if not self.include else " include=%s" % repr(self.include), "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), ) def __eq__(self, other): if isinstance(other, UniqueConstraint): return ( self.name == other.name and self.fields == other.fields and self.condition == other.condition and self.deferrable == other.deferrable and self.include == other.include and self.opclasses == other.opclasses and self.expressions == other.expressions and self.violation_error_message == other.violation_error_message ) return super().__eq__(other) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fields: kwargs["fields"] = self.fields if self.condition: kwargs["condition"] = self.condition if self.deferrable: kwargs["deferrable"] = self.deferrable if self.include: kwargs["include"] = self.include if self.opclasses: kwargs["opclasses"] = self.opclasses return path, self.expressions, kwargs def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): queryset = model._default_manager.using(using) if self.fields: lookup_kwargs = {} for field_name in self.fields: if exclude and field_name in exclude: return field = model._meta.get_field(field_name) lookup_value = getattr(instance, field.attname) if lookup_value is None or ( lookup_value == "" and connections[using].features.interprets_empty_strings_as_nulls ): # A composite constraint containing NULL value cannot cause # a violation since NULL != NULL in SQL. return lookup_kwargs[field.name] = lookup_value queryset = queryset.filter(**lookup_kwargs) else: # Ignore constraints with excluded fields. if exclude: for expression in self.expressions: for expr in expression.flatten(): if isinstance(expr, F) and expr.name in exclude: return replacement_map = instance._get_field_value_map( meta=model._meta, exclude=exclude ) expressions = [ Exact(expr, expr.replace_references(replacement_map)) for expr in self.expressions ] queryset = queryset.filter(*expressions) model_class_pk = instance._get_pk_val(model._meta) if not instance._state.adding and model_class_pk is not None: queryset = queryset.exclude(pk=model_class_pk) if not self.condition: if queryset.exists(): if self.expressions: raise ValidationError(self.get_violation_error_message()) # When fields are defined, use the unique_error_message() for # backward compatibility. for model, constraints in instance.get_constraints(): for constraint in constraints: if constraint is self: raise ValidationError( instance.unique_error_message(model, self.fields) ) else: against = instance._get_field_value_map(meta=model._meta, exclude=exclude) try: if (self.condition & Exists(queryset.filter(self.condition))).check( against, using=using ): raise ValidationError(self.get_violation_error_message()) except FieldError: pass
1c426d95e192ef4b86520e686c82cd2a7354987abe59b36c2c3199b6b21f5966
from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.state import ModelState from django.db.migrations.utils import field_references, resolve_relation from django.db.models.options import normalize_together from django.utils.functional import cached_property from .fields import AddField, AlterField, FieldOperation, RemoveField, RenameField def _check_for_duplicates(arg_name, objs): used_vals = set() for val in objs: if val in used_vals: raise ValueError( "Found duplicate value %s in CreateModel %s argument." % (val, arg_name) ) used_vals.add(val) class ModelOperation(Operation): def __init__(self, name): self.name = name @cached_property def name_lower(self): return self.name.lower() def references_model(self, name, app_label): return name.lower() == self.name_lower def reduce(self, operation, app_label): return super().reduce(operation, app_label) or self.can_reduce_through( operation, app_label ) def can_reduce_through(self, operation, app_label): return not operation.references_model(self.name, app_label) class CreateModel(ModelOperation): """Create a model's table.""" serialization_expand_args = ["fields", "options", "managers"] def __init__(self, name, fields, options=None, bases=None, managers=None): self.fields = fields self.options = options or {} self.bases = bases or (models.Model,) self.managers = managers or [] super().__init__(name) # Sanity-check that there are no duplicated field names, bases, or # manager names _check_for_duplicates("fields", (name for name, _ in self.fields)) _check_for_duplicates( "bases", ( base._meta.label_lower if hasattr(base, "_meta") else base.lower() if isinstance(base, str) else base for base in self.bases ), ) _check_for_duplicates("managers", (name for name, _ in self.managers)) def deconstruct(self): kwargs = { "name": self.name, "fields": self.fields, } if self.options: kwargs["options"] = self.options if self.bases and self.bases != (models.Model,): kwargs["bases"] = self.bases if self.managers and self.managers != [("objects", models.Manager())]: kwargs["managers"] = self.managers return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.add_model( ModelState( app_label, self.name, list(self.fields), dict(self.options), tuple(self.bases), list(self.managers), ) ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def describe(self): return "Create %smodel %s" % ( "proxy " if self.options.get("proxy", False) else "", self.name, ) @property def migration_name_fragment(self): return self.name_lower def references_model(self, name, app_label): name_lower = name.lower() if name_lower == self.name_lower: return True # Check we didn't inherit from the model reference_model_tuple = (app_label, name_lower) for base in self.bases: if ( base is not models.Model and isinstance(base, (models.base.ModelBase, str)) and resolve_relation(base, app_label) == reference_model_tuple ): return True # Check we have no FKs/M2Ms with it for _name, field in self.fields: if field_references( (app_label, self.name_lower), field, reference_model_tuple ): return True return False def reduce(self, operation, app_label): if ( isinstance(operation, DeleteModel) and self.name_lower == operation.name_lower and not self.options.get("proxy", False) ): return [] elif ( isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower ): return [ CreateModel( operation.new_name, fields=self.fields, options=self.options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower ): options = {**self.options, **operation.options} for key in operation.ALTER_OPTION_KEYS: if key not in operation.options: options.pop(key, None) return [ CreateModel( self.name, fields=self.fields, options=options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelManagers) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options=self.options, bases=self.bases, managers=operation.managers, ), ] elif ( isinstance(operation, AlterTogetherOptionOperation) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, **{operation.option_name: operation.option_value}, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterOrderWithRespectTo) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "order_with_respect_to": operation.order_with_respect_to, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower ): if isinstance(operation, AddField): return [ CreateModel( self.name, fields=self.fields + [(operation.name, operation.field)], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterField): return [ CreateModel( self.name, fields=[ (n, operation.field if n == operation.name else v) for n, v in self.fields ], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RemoveField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.pop(option_name, None) if option: option = set( filter( bool, ( tuple( f for f in fields if f != operation.name_lower ) for fields in option ), ) ) if option: options[option_name] = option order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.name_lower: del options["order_with_respect_to"] return [ CreateModel( self.name, fields=[ (n, v) for n, v in self.fields if n.lower() != operation.name_lower ], options=options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RenameField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.get(option_name) if option: options[option_name] = { tuple( operation.new_name if f == operation.old_name else f for f in fields ) for fields in option } order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.old_name: options["order_with_respect_to"] = operation.new_name return [ CreateModel( self.name, fields=[ (operation.new_name if n == operation.old_name else n, v) for n, v in self.fields ], options=options, bases=self.bases, managers=self.managers, ), ] return super().reduce(operation, app_label) class DeleteModel(ModelOperation): """Drop a model's table.""" def deconstruct(self): kwargs = { "name": self.name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.remove_model(app_label, self.name_lower) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def references_model(self, name, app_label): # The deleted model could be referencing the specified model through # related fields. return True def describe(self): return "Delete model %s" % self.name @property def migration_name_fragment(self): return "delete_%s" % self.name_lower class RenameModel(ModelOperation): """Rename a model.""" def __init__(self, old_name, new_name): self.old_name = old_name self.new_name = new_name super().__init__(old_name) @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "old_name": self.old_name, "new_name": self.new_name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.rename_model(app_label, self.old_name, self.new_name) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.new_name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.old_name) old_db_table = old_model._meta.db_table new_db_table = new_model._meta.db_table # Don't alter when a table name is not changed. if old_db_table == new_db_table: return # Move the main table schema_editor.alter_db_table(new_model, old_db_table, new_db_table) # Alter the fields pointing to us for related_object in old_model._meta.related_objects: if related_object.related_model == old_model: model = new_model related_key = (app_label, self.new_name_lower) else: model = related_object.related_model related_key = ( related_object.related_model._meta.app_label, related_object.related_model._meta.model_name, ) to_field = to_state.apps.get_model(*related_key)._meta.get_field( related_object.field.name ) schema_editor.alter_field( model, related_object.field, to_field, ) # Rename M2M fields whose name is based on this model's name. fields = zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ) for (old_field, new_field) in fields: # Skip self-referential fields as these are renamed above. if ( new_field.model == new_field.related_model or not new_field.remote_field.through._meta.auto_created ): continue # Rename the M2M table that's based on this model's name. old_m2m_model = old_field.remote_field.through new_m2m_model = new_field.remote_field.through schema_editor.alter_db_table( new_m2m_model, old_m2m_model._meta.db_table, new_m2m_model._meta.db_table, ) # Rename the column in the M2M table that's based on this # model's name. schema_editor.alter_field( new_m2m_model, old_m2m_model._meta.get_field(old_model._meta.model_name), new_m2m_model._meta.get_field(new_model._meta.model_name), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def references_model(self, name, app_label): return ( name.lower() == self.old_name_lower or name.lower() == self.new_name_lower ) def describe(self): return "Rename model %s to %s" % (self.old_name, self.new_name) @property def migration_name_fragment(self): return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) def reduce(self, operation, app_label): if ( isinstance(operation, RenameModel) and self.new_name_lower == operation.old_name_lower ): return [ RenameModel( self.old_name, operation.new_name, ), ] # Skip `ModelOperation.reduce` as we want to run `references_model` # against self.new_name. return super(ModelOperation, self).reduce( operation, app_label ) or not operation.references_model(self.new_name, app_label) class ModelOptionOperation(ModelOperation): def reduce(self, operation, app_label): if ( isinstance(operation, (self.__class__, DeleteModel)) and self.name_lower == operation.name_lower ): return [operation] return super().reduce(operation, app_label) class AlterModelTable(ModelOptionOperation): """Rename a model's table.""" def __init__(self, name, table): self.table = table super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table": self.table, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options(app_label, self.name_lower, {"db_table": self.table}) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Rename M2M fields whose name is based on this model's db_table for (old_field, new_field) in zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ): if new_field.remote_field.through._meta.auto_created: schema_editor.alter_db_table( new_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return "Rename table for %s to %s" % ( self.name, self.table if self.table is not None else "(default)", ) @property def migration_name_fragment(self): return "alter_%s_table" % self.name_lower class AlterTogetherOptionOperation(ModelOptionOperation): option_name = None def __init__(self, name, option_value): if option_value: option_value = set(normalize_together(option_value)) setattr(self, self.option_name, option_value) super().__init__(name) @cached_property def option_value(self): return getattr(self, self.option_name) def deconstruct(self): kwargs = { "name": self.name, self.option_name: self.option_value, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.option_value}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) alter_together = getattr(schema_editor, "alter_%s" % self.option_name) alter_together( new_model, getattr(old_model._meta, self.option_name, set()), getattr(new_model._meta, self.option_name, set()), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( not self.option_value or any((name in fields) for fields in self.option_value) ) def describe(self): return "Alter %s for %s (%s constraint(s))" % ( self.option_name, self.name, len(self.option_value or ""), ) @property def migration_name_fragment(self): return "alter_%s_%s" % (self.name_lower, self.option_name) def can_reduce_through(self, operation, app_label): return super().can_reduce_through(operation, app_label) or ( isinstance(operation, AlterTogetherOptionOperation) and type(operation) is not type(self) ) class AlterUniqueTogether(AlterTogetherOptionOperation): """ Change the value of unique_together to the target one. Input value of unique_together must be a set of tuples. """ option_name = "unique_together" def __init__(self, name, unique_together): super().__init__(name, unique_together) class AlterIndexTogether(AlterTogetherOptionOperation): """ Change the value of index_together to the target one. Input value of index_together must be a set of tuples. """ option_name = "index_together" system_check_deprecated_details = { "msg": ( "AlterIndexTogether is deprecated. Support for it (except in historical " "migrations) will be removed in Django 5.1." ), "id": "migrations.W001", } def __init__(self, name, index_together): super().__init__(name, index_together) class AlterOrderWithRespectTo(ModelOptionOperation): """Represent a change with the order_with_respect_to option.""" option_name = "order_with_respect_to" def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "order_with_respect_to": self.order_with_respect_to, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.order_with_respect_to}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.name) # Remove a field if we need to if ( from_model._meta.order_with_respect_to and not to_model._meta.order_with_respect_to ): schema_editor.remove_field( from_model, from_model._meta.get_field("_order") ) # Add a field if we need to (altering the column is untouched as # it's likely a rename) elif ( to_model._meta.order_with_respect_to and not from_model._meta.order_with_respect_to ): field = to_model._meta.get_field("_order") if not field.has_default(): field.default = 0 schema_editor.add_field( from_model, field, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( self.order_with_respect_to is None or name == self.order_with_respect_to ) def describe(self): return "Set order_with_respect_to on %s to %s" % ( self.name, self.order_with_respect_to, ) @property def migration_name_fragment(self): return "alter_%s_order_with_respect_to" % self.name_lower class AlterModelOptions(ModelOptionOperation): """ Set new model options that don't directly affect the database schema (like verbose_name, permissions, ordering). Python code in migrations may still need them. """ # Model options we want to compare and preserve in an AlterModelOptions op ALTER_OPTION_KEYS = [ "base_manager_name", "default_manager_name", "default_related_name", "get_latest_by", "managed", "ordering", "permissions", "default_permissions", "select_on_save", "verbose_name", "verbose_name_plural", ] def __init__(self, name, options): self.options = options super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "options": self.options, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, self.options, self.ALTER_OPTION_KEYS, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change Meta options on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_options" % self.name_lower class AlterModelManagers(ModelOptionOperation): """Alter the model's managers.""" serialization_expand_args = ["managers"] def __init__(self, name, managers): self.managers = managers super().__init__(name) def deconstruct(self): return (self.__class__.__qualname__, [self.name, self.managers], {}) def state_forwards(self, app_label, state): state.alter_model_managers(app_label, self.name_lower, self.managers) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change managers on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_managers" % self.name_lower class IndexOperation(Operation): option_name = "indexes" @cached_property def model_name_lower(self): return self.model_name.lower() class AddIndex(IndexOperation): """Add an index on a model.""" def __init__(self, model_name, index): self.model_name = model_name if not index.name: raise ValueError( "Indexes passed to AddIndex operations require a name " "argument. %r doesn't have one." % index ) self.index = index def state_forwards(self, app_label, state): state.add_index(app_label, self.model_name_lower, self.index) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_index(model, self.index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_index(model, self.index) def deconstruct(self): kwargs = { "model_name": self.model_name, "index": self.index, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): if self.index.expressions: return "Create index %s on %s on model %s" % ( self.index.name, ", ".join([str(expression) for expression in self.index.expressions]), self.model_name, ) return "Create index %s on field(s) %s of model %s" % ( self.index.name, ", ".join(self.index.fields), self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.index.name.lower()) class RemoveIndex(IndexOperation): """Remove an index from a model.""" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_index(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] index = from_model_state.get_index_by_name(self.name) schema_editor.remove_index(model, index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] index = to_model_state.get_index_by_name(self.name) schema_editor.add_index(model, index) def deconstruct(self): kwargs = { "model_name": self.model_name, "name": self.name, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): return "Remove index %s from %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower()) class RenameIndex(IndexOperation): """Rename an index.""" def __init__(self, model_name, new_name, old_name=None, old_fields=None): if not old_name and not old_fields: raise ValueError( "RenameIndex requires one of old_name and old_fields arguments to be " "set." ) if old_name and old_fields: raise ValueError( "RenameIndex.old_name and old_fields are mutually exclusive." ) self.model_name = model_name self.new_name = new_name self.old_name = old_name self.old_fields = old_fields @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "model_name": self.model_name, "new_name": self.new_name, } if self.old_name: kwargs["old_name"] = self.old_name if self.old_fields: kwargs["old_fields"] = self.old_fields return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): if self.old_fields: state.add_index( app_label, self.model_name_lower, models.Index(fields=self.old_fields, name=self.new_name), ) state.remove_model_options( app_label, self.model_name_lower, AlterIndexTogether.option_name, self.old_fields, ) else: state.rename_index( app_label, self.model_name_lower, self.old_name, self.new_name ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if not self.allow_migrate_model(schema_editor.connection.alias, model): return if self.old_fields: from_model = from_state.apps.get_model(app_label, self.model_name) columns = [ from_model._meta.get_field(field).column for field in self.old_fields ] matching_index_name = schema_editor._constraint_names( from_model, column_names=columns, index=True ) if len(matching_index_name) != 1: raise ValueError( "Found wrong number (%s) of indexes for %s(%s)." % ( len(matching_index_name), from_model._meta.db_table, ", ".join(columns), ) ) old_index = models.Index( fields=self.old_fields, name=matching_index_name[0], ) else: from_model_state = from_state.models[app_label, self.model_name_lower] old_index = from_model_state.get_index_by_name(self.old_name) # Don't alter when the index name is not changed. if old_index.name == self.new_name: return to_model_state = to_state.models[app_label, self.model_name_lower] new_index = to_model_state.get_index_by_name(self.new_name) schema_editor.rename_index(model, old_index, new_index) def database_backwards(self, app_label, schema_editor, from_state, to_state): if self.old_fields: # Backward operation with unnamed index is a no-op. return self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def describe(self): if self.old_name: return ( f"Rename index {self.old_name} on {self.model_name} to {self.new_name}" ) return ( f"Rename unnamed index for {self.old_fields} on {self.model_name} to " f"{self.new_name}" ) @property def migration_name_fragment(self): if self.old_name: return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) return "rename_%s_%s_%s" % ( self.model_name_lower, "_".join(self.old_fields), self.new_name_lower, ) def reduce(self, operation, app_label): if ( isinstance(operation, RenameIndex) and self.model_name_lower == operation.model_name_lower and operation.old_name and self.new_name_lower == operation.old_name_lower ): return [ RenameIndex( self.model_name, new_name=operation.new_name, old_name=self.old_name, old_fields=self.old_fields, ) ] return super().reduce(operation, app_label) class AddConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, constraint): self.model_name = model_name self.constraint = constraint def state_forwards(self, app_label, state): state.add_constraint(app_label, self.model_name_lower, self.constraint) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_constraint(model, self.constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_constraint(model, self.constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "constraint": self.constraint, }, ) def describe(self): return "Create constraint %s on model %s" % ( self.constraint.name, self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.constraint.name.lower()) class RemoveConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_constraint(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] constraint = from_model_state.get_constraint_by_name(self.name) schema_editor.remove_constraint(model, constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] constraint = to_model_state.get_constraint_by_name(self.name) schema_editor.add_constraint(model, constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "name": self.name, }, ) def describe(self): return "Remove constraint %s from model %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower())
a024f34ff6e7d2da32ae3f67ca876593a64b71942b99dc598c57d8b0a65f50df
from django.db import router from django.utils.deprecation import DeprecationForHistoricalMigrationMixin class Operation(DeprecationForHistoricalMigrationMixin): """ Base class for migration operations. It's responsible for both mutating the in-memory model state (see db/migrations/state.py) to represent what it performs, as well as actually performing it against a live database. Note that some operations won't modify memory state at all (e.g. data copying operations), and some will need their modifications to be optionally specified by the user (e.g. custom Python code snippets) Due to the way this class deals with deconstruction, it should be considered immutable. """ # If this migration can be run in reverse. # Some operations are impossible to reverse, like deleting data. reversible = True # Can this migration be represented as SQL? (things like RunPython cannot) reduces_to_sql = True # Should this operation be forced as atomic even on backends with no # DDL transaction support (i.e., does it have no DDL, like RunPython) atomic = False # Should this operation be considered safe to elide and optimize across? elidable = False serialization_expand_args = [] check_type = "migrations" def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial self = object.__new__(cls) self._constructor_args = (args, kwargs) return self def deconstruct(self): """ Return a 3-tuple of class import path (or just name if it lives under django.db.migrations), positional arguments, and keyword arguments. """ return ( self.__class__.__name__, self._constructor_args[0], self._constructor_args[1], ) def state_forwards(self, app_label, state): """ Take the state from the previous migration, and mutate it so that it matches what this migration would perform. """ raise NotImplementedError( "subclasses of Operation must provide a state_forwards() method" ) def database_forwards(self, app_label, schema_editor, from_state, to_state): """ Perform the mutation on the database schema in the normal (forwards) direction. """ raise NotImplementedError( "subclasses of Operation must provide a database_forwards() method" ) def database_backwards(self, app_label, schema_editor, from_state, to_state): """ Perform the mutation on the database schema in the reverse direction - e.g. if this were CreateModel, it would in fact drop the model's table. """ raise NotImplementedError( "subclasses of Operation must provide a database_backwards() method" ) def describe(self): """ Output a brief summary of what the action does. """ return "%s: %s" % (self.__class__.__name__, self._constructor_args) @property def migration_name_fragment(self): """ A filename part suitable for automatically naming a migration containing this operation, or None if not applicable. """ return None def references_model(self, name, app_label): """ Return True if there is a chance this operation references the given model name (as a string), with an app label for accuracy. Used for optimization. If in doubt, return True; returning a false positive will merely make the optimizer a little less efficient, while returning a false negative may result in an unusable optimized migration. """ return True def references_field(self, model_name, name, app_label): """ Return True if there is a chance this operation references the given field name, with an app label for accuracy. Used for optimization. If in doubt, return True. """ return self.references_model(model_name, app_label) def allow_migrate_model(self, connection_alias, model): """ Return whether or not a model may be migrated. This is a thin wrapper around router.allow_migrate_model() that preemptively rejects any proxy, swapped out, or unmanaged model. """ if not model._meta.can_migrate(connection_alias): return False return router.allow_migrate_model(connection_alias, model) def reduce(self, operation, app_label): """ Return either a list of operations the actual operation should be replaced with or a boolean that indicates whether or not the specified operation can be optimized across. """ if self.elidable: return [operation] elif operation.elidable: return [self] return False def __repr__(self): return "<%s %s%s>" % ( self.__class__.__name__, ", ".join(map(repr, self._constructor_args[0])), ",".join(" %s=%r" % x for x in self._constructor_args[1].items()), )
d458362bf81447bb196e0689bc75d9fb7c003d56bc1ad2557427726e701f3724
import collections.abc import copy import datetime import decimal import math import operator import uuid import warnings from base64 import b64decode, b64encode from functools import partialmethod, total_ordering from django import forms from django.apps import apps from django.conf import settings from django.core import checks, exceptions, validators from django.db import connection, connections, router from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin from django.utils import timezone from django.utils.datastructures import DictWrapper from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.deprecation import DeprecationForHistoricalMigrationMixin from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property from django.utils.ipv6 import clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ __all__ = [ "AutoField", "BLANK_CHOICE_DASH", "BigAutoField", "BigIntegerField", "BinaryField", "BooleanField", "CharField", "CommaSeparatedIntegerField", "DateField", "DateTimeField", "DecimalField", "DurationField", "EmailField", "Empty", "Field", "FilePathField", "FloatField", "GenericIPAddressField", "IPAddressField", "IntegerField", "NOT_PROVIDED", "NullBooleanField", "PositiveBigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", "SlugField", "SmallAutoField", "SmallIntegerField", "TextField", "TimeField", "URLField", "UUIDField", ] class Empty: pass class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): return apps.get_model(app_label, model_name)._meta.get_field(field_name) # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) def _empty(of_cls): new = Empty() new.__class__ = of_cls return new def return_None(): return None @total_ordering class Field(DeprecationForHistoricalMigrationMixin, RegisterLookupMixin): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True empty_values = list(validators.EMPTY_VALUES) # These track each time a Field instance is created. Used to retain order. # The auto_creation_counter is used for fields that Django implicitly # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { "invalid_choice": _("Value %(value)r is not a valid choice."), "null": _("This field cannot be null."), "blank": _("This field cannot be blank."), "unique": _("%(model_name)s with this %(field_label)s already exists."), "unique_for_date": _( # Translators: The 'lookup_type' is one of 'date', 'year' or # 'month'. Eg: "Title must be unique for pub_date year" "%(field_label)s must be unique for " "%(date_field_label)s %(lookup_type)s." ), } check_type = "fields" # Attributes that don't affect a column definition. # These attributes are ignored when altering the field. non_db_attrs = ( "blank", "choices", "db_column", "editable", "error_messages", "help_text", "limit_choices_to", # Database-level options are not supported, see #21961. "on_delete", "related_name", "related_query_name", "validators", "verbose_name", ) # Field flags hidden = False many_to_many = None many_to_one = None one_to_many = None one_to_one = None related_model = None descriptor_class = DeferredAttribute # Generic field type description, usually overridden by subclasses def _description(self): return _("Field of type: %(field_type)s") % { "field_type": self.__class__.__name__ } description = property(_description) def __init__( self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text="", db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None, ): self.name = name self.verbose_name = verbose_name # May be set by set_attributes_from_name self._verbose_name = verbose_name # Store original for deconstruction self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null self.remote_field = rel self.is_relation = self.remote_field is not None self.default = default self.editable = editable self.serialize = serialize self.unique_for_date = unique_for_date self.unique_for_month = unique_for_month self.unique_for_year = unique_for_year if isinstance(choices, collections.abc.Iterator): choices = list(choices) self.choices = choices self.help_text = help_text self.db_index = db_index self.db_column = db_column self._db_tablespace = db_tablespace self.auto_created = auto_created # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = list(validators) # Store for deconstruction later self._error_messages = error_messages # Store for deconstruction later def __str__(self): """ Return "app_label.model_label.field_name" for fields attached to models. """ if not hasattr(self, "model"): return super().__str__() model = self.model return "%s.%s" % (model._meta.label, self.name) def __repr__(self): """Display the module, class, and name of the field.""" path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) name = getattr(self, "name", None) if name is not None: return "<%s: %s>" % (path, name) return "<%s>" % path def check(self, **kwargs): return [ *self._check_field_name(), *self._check_choices(), *self._check_db_index(), *self._check_null_allowed_for_primary_keys(), *self._check_backend_specific_checks(**kwargs), *self._check_validators(), *self.check_deprecation_details(), ] def _check_field_name(self): """ Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith("_"): return [ checks.Error( "Field names must not end with an underscore.", obj=self, id="fields.E001", ) ] elif LOOKUP_SEP in self.name: return [ checks.Error( 'Field names must not contain "%s".' % LOOKUP_SEP, obj=self, id="fields.E002", ) ] elif self.name == "pk": return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", obj=self, id="fields.E003", ) ] else: return [] @classmethod def _choices_is_value(cls, value): return isinstance(value, (str, Promise)) or not is_iterable(value) def _check_choices(self): if not self.choices: return [] if not is_iterable(self.choices) or isinstance(self.choices, str): return [ checks.Error( "'choices' must be an iterable (e.g., a list or tuple).", obj=self, id="fields.E004", ) ] choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: group_name, group_choices = choices_group except (TypeError, ValueError): # Containing non-pairs break try: if not all( self._choices_is_value(value) and self._choices_is_value(human_name) for value, human_name in group_choices ): break if self.max_length is not None and group_choices: choice_max_length = max( [ choice_max_length, *( len(value) for value, _ in group_choices if isinstance(value, str) ), ] ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not self._choices_is_value(value) or not self._choices_is_value( human_name ): break if self.max_length is not None and isinstance(value, str): choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: if self.max_length is not None and choice_max_length > self.max_length: return [ checks.Error( "'max_length' is too small to fit the longest value " "in 'choices' (%d characters)." % choice_max_length, obj=self, id="fields.E009", ), ] return [] return [ checks.Error( "'choices' must be an iterable containing " "(actual value, human readable name) tuples.", obj=self, id="fields.E005", ) ] def _check_db_index(self): if self.db_index not in (None, True, False): return [ checks.Error( "'db_index' must be None, True or False.", obj=self, id="fields.E006", ) ] else: return [] def _check_null_allowed_for_primary_keys(self): if ( self.primary_key and self.null and not connection.features.interprets_empty_strings_as_nulls ): # We cannot reliably check this for backends like Oracle which # consider NULL and '' to be equal (and thus set up # character-based fields a little differently). return [ checks.Error( "Primary keys must not have null=True.", hint=( "Set null=False on the field, or " "remove primary_key=True argument." ), obj=self, id="fields.E007", ) ] else: return [] def _check_backend_specific_checks(self, databases=None, **kwargs): if databases is None: return [] app_label = self.model._meta.app_label errors = [] for alias in databases: if router.allow_migrate( alias, app_label, model_name=self.model._meta.model_name ): errors.extend(connections[alias].validation.check_field(self, **kwargs)) return errors def _check_validators(self): errors = [] for i, validator in enumerate(self.validators): if not callable(validator): errors.append( checks.Error( "All 'validators' must be callable.", hint=( "validators[{i}] ({repr}) isn't a function or " "instance of a validator class.".format( i=i, repr=repr(validator), ) ), obj=self, id="fields.E008", ) ) return errors def get_col(self, alias, output_field=None): if alias == self.model._meta.db_table and ( output_field is None or output_field == self ): return self.cached_col from django.db.models.expressions import Col return Col(alias, self, output_field) @cached_property def cached_col(self): from django.db.models.expressions import Col return Col(self.model._meta.db_table, self) def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django. """ return sql, params def deconstruct(self): """ Return enough information to recreate the field as a 4-tuple: * The name of the field on the model, if contribute_to_class() has been run. * The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better. * A list of positional arguments. * A dict of keyword arguments. Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types): * None, bool, str, int, float, complex, set, frozenset, list, tuple, dict * UUID * datetime.datetime (naive), datetime.date * top-level classes, top-level functions - will be referenced by their full import path * Storage instances - these have their own deconstruct() method This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values. """ # Short-form way of fetching all the default parameters keywords = {} possibles = { "verbose_name": None, "primary_key": False, "max_length": None, "unique": False, "blank": False, "null": False, "db_index": False, "default": NOT_PROVIDED, "editable": True, "serialize": True, "unique_for_date": None, "unique_for_month": None, "unique_for_year": None, "choices": None, "help_text": "", "db_column": None, "db_tablespace": None, "auto_created": False, "validators": [], "error_messages": None, } attr_overrides = { "unique": "_unique", "error_messages": "_error_messages", "validators": "_validators", "verbose_name": "_verbose_name", "db_tablespace": "_db_tablespace", } equals_comparison = {"choices", "validators"} for name, default in possibles.items(): value = getattr(self, attr_overrides.get(name, name)) # Unroll anything iterable for choices into a concrete list if name == "choices" and isinstance(value, collections.abc.Iterable): value = list(value) # Do correct kind of comparison if name in equals_comparison: if value != default: keywords[name] = value else: if value is not default: keywords[name] = value # Work out path - we shorten it for known Django core fields path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) if path.startswith("django.db.models.fields.related"): path = path.replace("django.db.models.fields.related", "django.db.models") elif path.startswith("django.db.models.fields.files"): path = path.replace("django.db.models.fields.files", "django.db.models") elif path.startswith("django.db.models.fields.json"): path = path.replace("django.db.models.fields.json", "django.db.models") elif path.startswith("django.db.models.fields.proxy"): path = path.replace("django.db.models.fields.proxy", "django.db.models") elif path.startswith("django.db.models.fields"): path = path.replace("django.db.models.fields", "django.db.models") # Return basic info - other fields should override this. return (self.name, path, [], keywords) def clone(self): """ Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names. """ name, path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) def __eq__(self, other): # Needed for @total_ordering if isinstance(other, Field): return self.creation_counter == other.creation_counter and getattr( self, "model", None ) == getattr(other, "model", None) return NotImplemented def __lt__(self, other): # This is needed because bisect does not take a comparison function. # Order by creation_counter first for backward compatibility. if isinstance(other, Field): if ( self.creation_counter != other.creation_counter or not hasattr(self, "model") and not hasattr(other, "model") ): return self.creation_counter < other.creation_counter elif hasattr(self, "model") != hasattr(other, "model"): return not hasattr(self, "model") # Order no-model fields first else: # creation_counter's are equal, compare only models. return (self.model._meta.app_label, self.model._meta.model_name) < ( other.model._meta.app_label, other.model._meta.model_name, ) return NotImplemented def __hash__(self): return hash(self.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.remote_field: obj.remote_field = copy.copy(self.remote_field) if hasattr(self.remote_field, "field") and self.remote_field.field is self: obj.remote_field.field = obj memodict[id(self)] = obj return obj def __copy__(self): # We need to avoid hitting __reduce__, so define this # slightly weird copy construct. obj = Empty() obj.__class__ = self.__class__ obj.__dict__ = self.__dict__.copy() return obj def __reduce__(self): """ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, use the app registry to load the model and then the field back. """ if not hasattr(self, "model"): # Fields are sometimes used without attaching them to models (for # example in aggregation). In this case give back a plain field # instance. The code below will create a new empty instance of # class self.__class__, then update its dict with self.__dict__ # values - so, this is very close to normal pickle. state = self.__dict__.copy() # The _get_default cached_property can't be pickled due to lambda # usage. state.pop("_get_default", None) return _empty, (self.__class__,), state return _load_field, ( self.model._meta.app_label, self.model._meta.object_name, self.name, ) def get_pk_value_on_save(self, instance): """ Hook to generate new PK values on save. This method is called when saving instances with no primary key value set. If this method returns something else than None, then the returned value is used when saving the new instance. """ if self.default: return self.get_default() return None def to_python(self, value): """ Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this. """ return value @cached_property def error_messages(self): messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(self._error_messages or {}) return messages @cached_property def validators(self): """ Some validators can't be created at field initialization time. This method provides a way to delay their creation until required. """ return [*self.default_validators, *self._validators] def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self.choices is not None and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages["null"], code="null") if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type_parameters(self, connection): return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") def db_check(self, connection): """ Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field. """ data = self.db_type_parameters(connection) try: return ( connection.data_type_check_constraints[self.get_internal_type()] % data ) except KeyError: return None def db_type(self, connection): """ Return the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific data_types dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = self.db_type_parameters(connection) try: return connection.data_types[self.get_internal_type()] % data except KeyError: return None def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type. """ return self.db_type(connection) def cast_db_type(self, connection): """Return the data type to use in the Cast() function.""" db_type = connection.ops.cast_data_types.get(self.get_internal_type()) if db_type: return db_type % self.db_type_parameters(connection) return self.db_type(connection) def db_parameters(self, connection): """ Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it. """ type_string = self.db_type(connection) check_string = self.db_check(connection) return { "type": type_string, "check": check_string, } def db_type_suffix(self, connection): return connection.data_types_suffix.get(self.get_internal_type()) def get_db_converters(self, connection): if hasattr(self, "from_db_value"): return [self.from_db_value] return [] @property def unique(self): return self._unique or self.primary_key @property def db_tablespace(self): return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE @property def db_returning(self): """ Private API intended only to be used by Django itself. Currently only the PostgreSQL backend supports returning multiple fields on a model. """ return False def set_attributes_from_name(self, name): self.name = self.name or name self.attname, self.column = self.get_attname_column() self.concrete = self.column is not None if self.verbose_name is None and self.name: self.verbose_name = self.name.replace("_", " ") def contribute_to_class(self, cls, name, private_only=False): """ Register the field with the model class it belongs to. If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model. """ self.set_attributes_from_name(name) self.model = cls cls._meta.add_field(self, private=private_only) if self.column: setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: # Don't override a get_FOO_display() method defined explicitly on # this class, but don't check methods derived from inheritance, to # allow overriding inherited choices. For more complex inheritance # structures users should override contribute_to_class(). if "get_%s_display" % self.name not in cls.__dict__: setattr( cls, "get_%s_display" % self.name, partialmethod(cls._get_FIELD_display, field=self), ) def get_filter_kwargs_for_object(self, obj): """ Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has. """ return {self.name: getattr(obj, self.attname)} def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """Return field's value just before saving.""" return getattr(model_instance, self.attname) def get_prep_value(self, value): """Perform preliminary non-db specific value checks and conversions.""" if isinstance(value, Promise): value = value._proxy____cast() return value def get_db_prep_value(self, value, connection, prepared=False): """ Return field's value prepared for interacting with the database backend. Used by the default implementations of get_db_prep_save(). """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """Return field's value prepared for saving into a database.""" return self.get_db_prep_value(value, connection=connection, prepared=False) def has_default(self): """Return a boolean of whether this field has a default value.""" return self.default is not NOT_PROVIDED def get_default(self): """Return the default value for this field.""" return self._get_default() @cached_property def _get_default(self): if self.has_default(): if callable(self.default): return self.default return lambda: self.default if ( not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls ): return return_None return str # return empty string def get_choices( self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None, ordering=(), ): """ Return choices with a default blank choices included, for use as <select> choices for this field. """ if self.choices is not None: choices = list(self.choices) if include_blank: blank_defined = any( choice in ("", None) for choice, _ in self.flatchoices ) if not blank_defined: choices = blank_choice + choices return choices rel_model = self.remote_field.model limit_choices_to = limit_choices_to or self.get_limit_choices_to() choice_func = operator.attrgetter( self.remote_field.get_related_field().attname if hasattr(self.remote_field, "get_related_field") else "pk" ) qs = rel_model._default_manager.complex_filter(limit_choices_to) if ordering: qs = qs.order_by(*ordering) return (blank_choice if include_blank else []) + [ (choice_func(x), str(x)) for x in qs ] def value_to_string(self, obj): """ Return a string value of this field from the passed obj. This is used by the serialization framework. """ return str(self.value_from_object(obj)) def _get_flatchoices(self): """Flattened version of choices tuple.""" if self.choices is None: return [] flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = { "required": not self.blank, "label": capfirst(self.verbose_name), "help_text": self.help_text, } if self.has_default(): if callable(self.default): defaults["initial"] = self.default defaults["show_hidden_initial"] = True else: defaults["initial"] = self.get_default() if self.choices is not None: # Fields with choices get special treatment. include_blank = self.blank or not ( self.has_default() or "initial" in kwargs ) defaults["choices"] = self.get_choices(include_blank=include_blank) defaults["coerce"] = self.to_python if self.null: defaults["empty_value"] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ( "coerce", "empty_value", "choices", "required", "widget", "label", "initial", "help_text", "error_messages", "show_hidden_initial", "disabled", ): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults) def value_from_object(self, obj): """Return the value of this field in the given model instance.""" return getattr(obj, self.attname) class BooleanField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be either True or False."), "invalid_nullable": _("“%(value)s” value must be either True, False, or None."), } description = _("Boolean (Either True or False)") def get_internal_type(self): return "BooleanField" def to_python(self, value): if self.null and value in self.empty_values: return None if value in (True, False): # 1/0 are equal to True/False. bool() converts former to latter. return bool(value) if value in ("t", "True", "1"): return True if value in ("f", "False", "0"): return False raise exceptions.ValidationError( self.error_messages["invalid_nullable" if self.null else "invalid"], code="invalid", params={"value": value}, ) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return self.to_python(value) def formfield(self, **kwargs): if self.choices is not None: include_blank = not (self.has_default() or "initial" in kwargs) defaults = {"choices": self.get_choices(include_blank=include_blank)} else: form_class = forms.NullBooleanField if self.null else forms.BooleanField # In HTML checkboxes, 'required' means "must be checked" which is # different from the choices case ("must select some value"). # required=False allows unchecked checkboxes. defaults = {"form_class": form_class, "required": False} return super().formfield(**{**defaults, **kwargs}) def select_format(self, compiler, sql, params): sql, params = super().select_format(compiler, sql, params) # Filters that match everything are handled as empty strings in the # WHERE clause, but in SELECT or GROUP BY list they must use a # predicate that's always True. if sql == "": sql = "1" return sql, params class CharField(Field): description = _("String (up to %(max_length)s)") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), *self._check_max_length_attribute(**kwargs), ] def _check_max_length_attribute(self, **kwargs): if self.max_length is None: return [ checks.Error( "CharFields must define a 'max_length' attribute.", obj=self, id="fields.E120", ) ] elif ( not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or self.max_length <= 0 ): return [ checks.Error( "'max_length' must be a positive integer.", obj=self, id="fields.E121", ) ] else: return [] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_charfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_charfield ): errors.append( checks.Error( "%s does not support a database collation on " "CharFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def cast_db_type(self, connection): if self.max_length is None: return connection.ops.cast_char_field_without_max_length return super().cast_db_type(connection) def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {"max_length": self.max_length} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") system_check_removed_details = { "msg": ( "CommaSeparatedIntegerField is removed except for support in " "historical migrations." ), "hint": ( "Use CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), "id": "fields.E901", } def _to_naive(value): if timezone.is_aware(value): value = timezone.make_naive(value, datetime.timezone.utc) return value def _get_naive_now(): return _to_naive(timezone.now()) class DateTimeCheckMixin: def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_mutually_exclusive_options(), *self._check_fix_default_value(), ] def _check_mutually_exclusive_options(self): # auto_now, auto_now_add, and default are mutually exclusive # options. The use of more than one of these options together # will trigger an Error mutually_exclusive_options = [ self.auto_now_add, self.auto_now, self.has_default(), ] enabled_options = [ option not in (None, False) for option in mutually_exclusive_options ].count(True) if enabled_options > 1: return [ checks.Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", obj=self, id="fields.E160", ) ] else: return [] def _check_fix_default_value(self): return [] # Concrete subclasses use this in their implementations of # _check_fix_default_value(). def _check_if_value_fixed(self, value, now=None): """ Check if the given value appears to have been provided as a "fixed" time value, and include a warning in the returned list if it does. The value argument must be a date object or aware/naive datetime object. If now is provided, it must be a naive datetime object. """ if now is None: now = _get_naive_now() offset = datetime.timedelta(seconds=10) lower = now - offset upper = now + offset if isinstance(value, datetime.datetime): value = _to_naive(value) else: assert isinstance(value, datetime.date) lower = lower.date() upper = upper.date() if lower <= value <= upper: return [ checks.Warning( "Fixed default value provided.", hint=( "It seems you set a fixed date / time / datetime " "value as default for this field. This may not be " "what you want. If you want to have the current date " "as default, use `django.utils.timezone.now`" ), obj=self, id="fields.W161", ) ] return [] class DateField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid date format. It must be " "in YYYY-MM-DD format." ), "invalid_date": _( "“%(value)s” value has the correct format (YYYY-MM-DD) " "but it is an invalid date." ), } description = _("Date (without time)") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): value = _to_naive(value).date() elif isinstance(value, datetime.date): pass else: # No explicit date / datetime value -- no checks necessary return [] # At this point, value is a date object. return self._check_if_value_fixed(value) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now: kwargs["auto_now"] = True if self.auto_now_add: kwargs["auto_now_add"] = True if self.auto_now or self.auto_now_add: del kwargs["editable"] del kwargs["blank"] return name, path, args, kwargs def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, "get_next_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=True ), ) setattr( cls, "get_previous_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=False ), ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateField, **kwargs, } ) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format." ), "invalid_date": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date." ), "invalid_datetime": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " "but it is an invalid date/time." ), } description = _("Date (with time)") # __init__ is inherited from DateField def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, (datetime.datetime, datetime.date)): return self._check_if_value_fixed(value) # No explicit date / datetime value -- no checks necessary. return [] def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn( "DateTimeField %s.%s received a naive datetime " "(%s) while time zone support is active." % (self.model.__name__, self.name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_datetime"], code="invalid_datetime", params={"value": value}, ) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = "%s.%s" % (self.model.__name__, self.name) except AttributeError: name = "(unbound)" warnings.warn( "DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datetimefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateTimeField, **kwargs, } ) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a decimal number."), } description = _("Decimal number") def __init__( self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super().check(**kwargs) digits_errors = [ *self._check_decimal_places(), *self._check_max_digits(), ] if not digits_errors: errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) else: errors.extend(digits_errors) return errors def _check_decimal_places(self): try: decimal_places = int(self.decimal_places) if decimal_places < 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'decimal_places' attribute.", obj=self, id="fields.E130", ) ] except ValueError: return [ checks.Error( "'decimal_places' must be a non-negative integer.", obj=self, id="fields.E131", ) ] else: return [] def _check_max_digits(self): try: max_digits = int(self.max_digits) if max_digits <= 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'max_digits' attribute.", obj=self, id="fields.E132", ) ] except ValueError: return [ checks.Error( "'max_digits' must be a positive integer.", obj=self, id="fields.E133", ) ] else: return [] def _check_decimal_places_and_max_digits(self, **kwargs): if int(self.decimal_places) > int(self.max_digits): return [ checks.Error( "'max_digits' must be greater or equal to 'decimal_places'.", obj=self, id="fields.E134", ) ] return [] @cached_property def validators(self): return super().validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ] @cached_property def context(self): return decimal.Context(prec=self.max_digits) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.max_digits is not None: kwargs["max_digits"] = self.max_digits if self.decimal_places is not None: kwargs["decimal_places"] = self.decimal_places return name, path, args, kwargs def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value if isinstance(value, float): if math.isnan(value): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return self.context.create_decimal_from_float(value) try: return decimal.Decimal(value) except (decimal.InvalidOperation, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_save(self, value, connection): return connection.ops.adapt_decimalfield_value( self.to_python(value), self.max_digits, self.decimal_places ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): return super().formfield( **{ "max_digits": self.max_digits, "decimal_places": self.decimal_places, "form_class": forms.DecimalField, **kwargs, } ) class DurationField(Field): """ Store timedelta objects. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "[DD] [[HH:]MM:]ss[.uuuuuu] format." ) } description = _("Duration") def get_internal_type(self): return "DurationField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_value(self, value, connection, prepared=False): if connection.features.has_native_duration_field: return value if value is None: return None return duration_microseconds(value) def get_db_converters(self, connection): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) return converters + super().get_db_converters(connection) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else duration_string(val) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DurationField, **kwargs, } ) class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs.setdefault("max_length", 254) super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. return super().formfield( **{ "form_class": forms.EmailField, **kwargs, } ) class FilePathField(Field): description = _("File path") def __init__( self, verbose_name=None, name=None, path="", match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_allowing_files_or_folders(**kwargs), ] def _check_allowing_files_or_folders(self, **kwargs): if not self.allow_files and not self.allow_folders: return [ checks.Error( "FilePathFields must have either 'allow_files' or 'allow_folders' " "set to True.", obj=self, id="fields.E140", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.path != "": kwargs["path"] = self.path if self.match is not None: kwargs["match"] = self.match if self.recursive is not False: kwargs["recursive"] = self.recursive if self.allow_files is not True: kwargs["allow_files"] = self.allow_files if self.allow_folders is not False: kwargs["allow_folders"] = self.allow_folders if kwargs.get("max_length") == 100: del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def formfield(self, **kwargs): return super().formfield( **{ "path": self.path() if callable(self.path) else self.path, "match": self.match, "recursive": self.recursive, "form_class": forms.FilePathField, "allow_files": self.allow_files, "allow_folders": self.allow_folders, **kwargs, } ) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return float(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FloatField, **kwargs, } ) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be an integer."), } description = _("Integer") def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_max_length_warning(), ] def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with %s." % self.__class__.__name__, hint="Remove 'max_length' from field", obj=self, id="fields.W122", ) ] return [] @cached_property def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. validators_ = super().validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None and not any( ( isinstance(validator, validators.MinValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) >= min_value ) for validator in validators_ ): validators_.append(validators.MinValueValidator(min_value)) if max_value is not None and not any( ( isinstance(validator, validators.MaxValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) <= max_value ) for validator in validators_ ): validators_.append(validators.MaxValueValidator(max_value)) return validators_ def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.IntegerField, **kwargs, } ) class BigIntegerField(IntegerField): description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": -BigIntegerField.MAX_BIGINT - 1, "max_value": BigIntegerField.MAX_BIGINT, **kwargs, } ) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") system_check_removed_details = { "msg": ( "IPAddressField has been removed except for support in " "historical migrations." ), "hint": "Use GenericIPAddressField instead.", "id": "fields.E900", } def __init__(self, *args, **kwargs): kwargs["max_length"] = 15 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def get_internal_type(self): return "IPAddressField" class GenericIPAddressField(Field): empty_strings_allowed = False description = _("IP address") default_error_messages = {} def __init__( self, verbose_name=None, name=None, protocol="both", unpack_ipv4=False, *args, **kwargs, ): self.unpack_ipv4 = unpack_ipv4 self.protocol = protocol ( self.default_validators, invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message kwargs["max_length"] = 39 super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_blank_and_null_values(**kwargs), ] def _check_blank_and_null_values(self, **kwargs): if not getattr(self, "null", False) and getattr(self, "blank", False): return [ checks.Error( "GenericIPAddressFields cannot have blank=True if null=False, " "as blank values are stored as nulls.", obj=self, id="fields.E150", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.unpack_ipv4 is not False: kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol if kwargs.get("max_length") == 39: del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value is None: return None if not isinstance(value, str): value = str(value) value = value.strip() if ":" in value: return clean_ipv6_address( value, self.unpack_ipv4, self.error_messages["invalid"] ) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_ipaddressfield_value(value) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None if value and ":" in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return str(value) def formfield(self, **kwargs): return super().formfield( **{ "protocol": self.protocol, "form_class": forms.GenericIPAddressField, **kwargs, } ) class NullBooleanField(BooleanField): default_error_messages = { "invalid": _("“%(value)s” value must be either None, True or False."), "invalid_nullable": _("“%(value)s” value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") system_check_removed_details = { "msg": ( "NullBooleanField is removed except for support in historical " "migrations." ), "hint": "Use BooleanField(null=True) instead.", "id": "fields.E903", } def __init__(self, *args, **kwargs): kwargs["null"] = True kwargs["blank"] = True super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["null"] del kwargs["blank"] return name, path, args, kwargs class PositiveIntegerRelDbTypeMixin: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not hasattr(cls, "integer_field_class"): cls.integer_field_class = next( ( parent for parent in cls.__mro__[1:] if issubclass(parent, IntegerField) ), None, ) def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. In most cases, a foreign key pointing to a positive integer primary key will have an integer column data type but some databases (e.g. MySQL) have an unsigned integer type. In that case (related_fields_match_type=True), the primary key should return its db_type. """ if connection.features.related_fields_match_type: return self.db_type(connection) else: return self.integer_field_class().db_type(connection=connection) class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField): description = _("Positive big integer") def get_internal_type(self): return "PositiveBigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__( self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs ): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs["max_length"] if self.db_index is False: kwargs["db_index"] = False else: del kwargs["db_index"] if self.allow_unicode is not False: kwargs["allow_unicode"] = self.allow_unicode return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.SlugField, "allow_unicode": self.allow_unicode, **kwargs, } ) class TextField(Field): description = _("Text") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), ] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_textfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_textfield ): errors.append( checks.Error( "%s does not support a database collation on " "TextFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "TextField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). return super().formfield( **{ "max_length": self.max_length, **({} if self.choices is not None else {"widget": forms.Textarea}), **kwargs, } ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class TimeField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "HH:MM[:ss[.uuuuuu]] format." ), "invalid_time": _( "“%(value)s” value has the correct format " "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time." ), } description = _("Time") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): now = None elif isinstance(value, datetime.time): now = _get_naive_now() # This will not use the right date in the race condition where now # is just before the date change and value is just past 0:00. value = datetime.datetime.combine(now.date(), value) else: # No explicit time / datetime value -- no checks necessary return [] # At this point, value is a datetime object. return self._check_if_value_fixed(value, now=now) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: kwargs["auto_now_add"] = self.auto_now_add if self.auto_now or self.auto_now_add: del kwargs["blank"] del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_time"], code="invalid_time", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_timefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.TimeField, **kwargs, } ) class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault("max_length", 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs["max_length"] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. return super().formfield( **{ "form_class": forms.URLField, **kwargs, } ) class BinaryField(Field): description = _("Raw binary data") empty_values = [None, b""] def __init__(self, *args, **kwargs): kwargs.setdefault("editable", False) super().__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): return [*super().check(**kwargs), *self._check_str_default_value()] def _check_str_default_value(self): if self.has_default() and isinstance(self.default, str): return [ checks.Error( "BinaryField's default cannot be a string. Use bytes " "content instead.", obj=self, id="fields.E170", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.editable: kwargs["editable"] = True else: del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "BinaryField" def get_placeholder(self, value, compiler, connection): return connection.ops.binary_placeholder_sql(value) def get_default(self): if self.has_default() and not callable(self.default): return self.default default = super().get_default() if default == "": return b"" return default def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value def value_to_string(self, obj): """Binary data is serialized as base64""" return b64encode(self.value_from_object(obj)).decode("ascii") def to_python(self, value): # If it's a string, it should be base64-encoded data if isinstance(value, str): return memoryview(b64decode(value.encode("ascii"))) return value class UUIDField(Field): default_error_messages = { "invalid": _("“%(value)s” is not a valid UUID."), } description = _("Universally unique identifier") empty_strings_allowed = False def __init__(self, verbose_name=None, **kwargs): kwargs["max_length"] = 32 super().__init__(verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "UUIDField" def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): value = self.to_python(value) if connection.features.has_native_uuid_field: return value return value.hex def to_python(self, value): if value is not None and not isinstance(value, uuid.UUID): input_form = "int" if isinstance(value, int) else "hex" try: return uuid.UUID(**{input_form: value}) except (AttributeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return value def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.UUIDField, **kwargs, } ) class AutoFieldMixin: db_returning = True def __init__(self, *args, **kwargs): kwargs["blank"] = True super().__init__(*args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), ] def _check_primary_key(self): if not self.primary_key: return [ checks.Error( "AutoFields must set primary_key=True.", obj=self, id="fields.E100", ), ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["blank"] kwargs["primary_key"] = True return name, path, args, kwargs def validate(self, value, model_instance): pass def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) value = connection.ops.validate_autopk_value(value) return value def contribute_to_class(self, cls, name, **kwargs): if cls._meta.auto_field: raise ValueError( "Model %s can't have more than one auto-generated field." % cls._meta.label ) super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self def formfield(self, **kwargs): return None class AutoFieldMeta(type): """ Metaclass to maintain backward inheritance compatibility for AutoField. It is intended that AutoFieldMixin become public API when it is possible to create a non-integer automatically-generated field using column defaults stored in the database. In many areas Django also relies on using isinstance() to check for an automatically-generated field as a subclass of AutoField. A new flag needs to be implemented on Field to be used instead. When these issues have been addressed, this metaclass could be used to deprecate inheritance from AutoField and use of isinstance() with AutoField for detecting automatically-generated fields. """ @property def _subclasses(self): return (BigAutoField, SmallAutoField) def __instancecheck__(self, instance): return isinstance(instance, self._subclasses) or super().__instancecheck__( instance ) def __subclasscheck__(self, subclass): return issubclass(subclass, self._subclasses) or super().__subclasscheck__( subclass ) class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta): def get_internal_type(self): return "AutoField" def rel_db_type(self, connection): return IntegerField().db_type(connection=connection) class BigAutoField(AutoFieldMixin, BigIntegerField): def get_internal_type(self): return "BigAutoField" def rel_db_type(self, connection): return BigIntegerField().db_type(connection=connection) class SmallAutoField(AutoFieldMixin, SmallIntegerField): def get_internal_type(self): return "SmallAutoField" def rel_db_type(self, connection): return SmallIntegerField().db_type(connection=connection)
3c74187972b5be773cb373b2de25d8aa25e2c3fa939b67031fa538e30f6a8fcb
from datetime import datetime from django.conf import settings from django.db.models.expressions import Func from django.db.models.fields import ( DateField, DateTimeField, DurationField, Field, IntegerField, TimeField, ) from django.db.models.lookups import ( Transform, YearExact, YearGt, YearGte, YearLt, YearLte, ) from django.utils import timezone class TimezoneMixin: tzinfo = None def get_tzname(self): # Timezone conversions must happen to the input datetime *before* # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the # database as 2016-01-01 01:00:00 +00:00. Any results should be # based on the input datetime not the stored datetime. tzname = None if settings.USE_TZ: if self.tzinfo is None: tzname = timezone.get_current_timezone_name() else: tzname = timezone._get_timezone_name(self.tzinfo) return tzname class Extract(TimezoneMixin, Transform): lookup_name = None output_field = IntegerField() def __init__(self, expression, lookup_name=None, tzinfo=None, **extra): if self.lookup_name is None: self.lookup_name = lookup_name if self.lookup_name is None: raise ValueError("lookup_name must be provided") self.tzinfo = tzinfo super().__init__(expression, **extra) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) lhs_output_field = self.lhs.output_field if isinstance(lhs_output_field, DateTimeField): tzname = self.get_tzname() sql, params = connection.ops.datetime_extract_sql( self.lookup_name, sql, tuple(params), tzname ) elif self.tzinfo is not None: raise ValueError("tzinfo can only be used with DateTimeField.") elif isinstance(lhs_output_field, DateField): sql, params = connection.ops.date_extract_sql( self.lookup_name, sql, tuple(params) ) elif isinstance(lhs_output_field, TimeField): sql, params = connection.ops.time_extract_sql( self.lookup_name, sql, tuple(params) ) elif isinstance(lhs_output_field, DurationField): if not connection.features.has_native_duration_field: raise ValueError( "Extract requires native DurationField database support." ) sql, params = connection.ops.time_extract_sql( self.lookup_name, sql, tuple(params) ) else: # resolve_expression has already validated the output_field so this # assert should never be hit. assert False, "Tried to Extract from an invalid type." return sql, params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): copy = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) field = getattr(copy.lhs, "output_field", None) if field is None: return copy if not isinstance(field, (DateField, DateTimeField, TimeField, DurationField)): raise ValueError( "Extract input expression must be DateField, DateTimeField, " "TimeField, or DurationField." ) # Passing dates to functions expecting datetimes is most likely a mistake. if type(field) == DateField and copy.lookup_name in ( "hour", "minute", "second", ): raise ValueError( "Cannot extract time component '%s' from DateField '%s'." % (copy.lookup_name, field.name) ) if isinstance(field, DurationField) and copy.lookup_name in ( "year", "iso_year", "month", "week", "week_day", "iso_week_day", "quarter", ): raise ValueError( "Cannot extract component '%s' from DurationField '%s'." % (copy.lookup_name, field.name) ) return copy class ExtractYear(Extract): lookup_name = "year" class ExtractIsoYear(Extract): """Return the ISO-8601 week-numbering year.""" lookup_name = "iso_year" class ExtractMonth(Extract): lookup_name = "month" class ExtractDay(Extract): lookup_name = "day" class ExtractWeek(Extract): """ Return 1-52 or 53, based on ISO-8601, i.e., Monday is the first of the week. """ lookup_name = "week" class ExtractWeekDay(Extract): """ Return Sunday=1 through Saturday=7. To replicate this in Python: (mydatetime.isoweekday() % 7) + 1 """ lookup_name = "week_day" class ExtractIsoWeekDay(Extract): """Return Monday=1 through Sunday=7, based on ISO-8601.""" lookup_name = "iso_week_day" class ExtractQuarter(Extract): lookup_name = "quarter" class ExtractHour(Extract): lookup_name = "hour" class ExtractMinute(Extract): lookup_name = "minute" class ExtractSecond(Extract): lookup_name = "second" DateField.register_lookup(ExtractYear) DateField.register_lookup(ExtractMonth) DateField.register_lookup(ExtractDay) DateField.register_lookup(ExtractWeekDay) DateField.register_lookup(ExtractIsoWeekDay) DateField.register_lookup(ExtractWeek) DateField.register_lookup(ExtractIsoYear) DateField.register_lookup(ExtractQuarter) TimeField.register_lookup(ExtractHour) TimeField.register_lookup(ExtractMinute) TimeField.register_lookup(ExtractSecond) DateTimeField.register_lookup(ExtractHour) DateTimeField.register_lookup(ExtractMinute) DateTimeField.register_lookup(ExtractSecond) ExtractYear.register_lookup(YearExact) ExtractYear.register_lookup(YearGt) ExtractYear.register_lookup(YearGte) ExtractYear.register_lookup(YearLt) ExtractYear.register_lookup(YearLte) ExtractIsoYear.register_lookup(YearExact) ExtractIsoYear.register_lookup(YearGt) ExtractIsoYear.register_lookup(YearGte) ExtractIsoYear.register_lookup(YearLt) ExtractIsoYear.register_lookup(YearLte) class Now(Func): template = "CURRENT_TIMESTAMP" output_field = DateTimeField() def as_postgresql(self, compiler, connection, **extra_context): # PostgreSQL's CURRENT_TIMESTAMP means "the time at the start of the # transaction". Use STATEMENT_TIMESTAMP to be cross-compatible with # other databases. return self.as_sql( compiler, connection, template="STATEMENT_TIMESTAMP()", **extra_context ) class TruncBase(TimezoneMixin, Transform): kind = None tzinfo = None # RemovedInDjango50Warning: when the deprecation ends, remove is_dst # argument. def __init__( self, expression, output_field=None, tzinfo=None, is_dst=timezone.NOT_PASSED, **extra, ): self.tzinfo = tzinfo self.is_dst = is_dst super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) tzname = None if isinstance(self.lhs.output_field, DateTimeField): tzname = self.get_tzname() elif self.tzinfo is not None: raise ValueError("tzinfo can only be used with DateTimeField.") if isinstance(self.output_field, DateTimeField): sql, params = connection.ops.datetime_trunc_sql( self.kind, sql, tuple(params), tzname ) elif isinstance(self.output_field, DateField): sql, params = connection.ops.date_trunc_sql( self.kind, sql, tuple(params), tzname ) elif isinstance(self.output_field, TimeField): sql, params = connection.ops.time_trunc_sql( self.kind, sql, tuple(params), tzname ) else: raise ValueError( "Trunc only valid on DateField, TimeField, or DateTimeField." ) return sql, params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): copy = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) field = copy.lhs.output_field # DateTimeField is a subclass of DateField so this works for both. if not isinstance(field, (DateField, TimeField)): raise TypeError( "%r isn't a DateField, TimeField, or DateTimeField." % field.name ) # If self.output_field was None, then accessing the field will trigger # the resolver to assign it to self.lhs.output_field. if not isinstance(copy.output_field, (DateField, DateTimeField, TimeField)): raise ValueError( "output_field must be either DateField, TimeField, or DateTimeField" ) # Passing dates or times to functions expecting datetimes is most # likely a mistake. class_output_field = ( self.__class__.output_field if isinstance(self.__class__.output_field, Field) else None ) output_field = class_output_field or copy.output_field has_explicit_output_field = ( class_output_field or field.__class__ is not copy.output_field.__class__ ) if type(field) == DateField and ( isinstance(output_field, DateTimeField) or copy.kind in ("hour", "minute", "second", "time") ): raise ValueError( "Cannot truncate DateField '%s' to %s." % ( field.name, output_field.__class__.__name__ if has_explicit_output_field else "DateTimeField", ) ) elif isinstance(field, TimeField) and ( isinstance(output_field, DateTimeField) or copy.kind in ("year", "quarter", "month", "week", "day", "date") ): raise ValueError( "Cannot truncate TimeField '%s' to %s." % ( field.name, output_field.__class__.__name__ if has_explicit_output_field else "DateTimeField", ) ) return copy def convert_value(self, value, expression, connection): if isinstance(self.output_field, DateTimeField): if not settings.USE_TZ: pass elif value is not None: value = value.replace(tzinfo=None) value = timezone.make_aware(value, self.tzinfo, is_dst=self.is_dst) elif not connection.features.has_zoneinfo_database: raise ValueError( "Database returned an invalid datetime value. Are time " "zone definitions for your database installed?" ) elif isinstance(value, datetime): if value is None: pass elif isinstance(self.output_field, DateField): value = value.date() elif isinstance(self.output_field, TimeField): value = value.time() return value class Trunc(TruncBase): # RemovedInDjango50Warning: when the deprecation ends, remove is_dst # argument. def __init__( self, expression, kind, output_field=None, tzinfo=None, is_dst=timezone.NOT_PASSED, **extra, ): self.kind = kind super().__init__( expression, output_field=output_field, tzinfo=tzinfo, is_dst=is_dst, **extra ) class TruncYear(TruncBase): kind = "year" class TruncQuarter(TruncBase): kind = "quarter" class TruncMonth(TruncBase): kind = "month" class TruncWeek(TruncBase): """Truncate to midnight on the Monday of the week.""" kind = "week" class TruncDay(TruncBase): kind = "day" class TruncDate(TruncBase): kind = "date" lookup_name = "date" output_field = DateField() def as_sql(self, compiler, connection): # Cast to date rather than truncate to date. sql, params = compiler.compile(self.lhs) tzname = self.get_tzname() return connection.ops.datetime_cast_date_sql(sql, tuple(params), tzname) class TruncTime(TruncBase): kind = "time" lookup_name = "time" output_field = TimeField() def as_sql(self, compiler, connection): # Cast to time rather than truncate to time. sql, params = compiler.compile(self.lhs) tzname = self.get_tzname() return connection.ops.datetime_cast_time_sql(sql, tuple(params), tzname) class TruncHour(TruncBase): kind = "hour" class TruncMinute(TruncBase): kind = "minute" class TruncSecond(TruncBase): kind = "second" DateTimeField.register_lookup(TruncDate) DateTimeField.register_lookup(TruncTime)
4ada1378c31302757c40bb15f4d065a818dfd4ceee9966104e43de50b81534af
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ import copy import difflib import functools import sys from collections import Counter, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product from string import ascii_uppercase from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections from django.db.models.aggregates import Count from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import ( BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef, Value, ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ["Query", "RawQuery"] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def get_field_names_from_opts(opts): if opts is None: return set() return set( chain.from_iterable( (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields() ) ) def get_children_from_q(q): for child in q.children: if isinstance(child, Node): yield from get_children_from_q(child) else: yield child JoinInfo = namedtuple( "JoinInfo", ("final_field", "targets", "opts", "joins", "path", "transform_function"), ) class RawQuery: """A single raw SQL query.""" def __init__(self, sql, using, params=()): self.params = params self.sql = sql self.using = using self.cursor = None # Mirror some properties of a normal query so that # the compiler can be used to process results. self.low_mark, self.high_mark = 0, None # Used for offset/limit self.extra_select = {} self.annotation_select = {} def chain(self, using): return self.clone(using) def clone(self, using): return RawQuery(self.sql, using, params=self.params) def get_columns(self): if self.cursor is None: self._execute_query() converter = connections[self.using].introspection.identifier_converter return [converter(column_meta[0]) for column_meta in self.cursor.description] def __iter__(self): # Always execute a new query for a new iterator. # This could be optimized with a cache at the expense of RAM. self._execute_query() if not connections[self.using].features.can_use_chunked_reads: # If the database can't use chunked reads we need to make sure we # evaluate the entire query up front. result = list(self.cursor) else: result = self.cursor return iter(result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) @property def params_type(self): if self.params is None: return None return dict if isinstance(self.params, Mapping) else tuple def __str__(self): if self.params_type is None: return self.sql return self.sql % self.params_type(self.params) def _execute_query(self): connection = connections[self.using] # Adapt parameters to the database, as much as possible considering # that the target type isn't known. See #17755. params_type = self.params_type adapter = connection.ops.adapt_unknown_value if params_type is tuple: params = tuple(adapter(val) for val in self.params) elif params_type is dict: params = {key: adapter(val) for key, val in self.params.items()} elif params_type is None: params = None else: raise RuntimeError("Unexpected params type: %s" % params_type) self.cursor = connection.cursor() self.cursor.execute(self.sql, params) ExplainInfo = namedtuple("ExplainInfo", ("format", "options")) class Query(BaseExpression): """A single SQL query.""" alias_prefix = "T" empty_result_set_value = None subq_aliases = frozenset([alias_prefix]) compiler = "SQLCompiler" base_table_class = BaseTable join_class = Join default_cols = True default_ordering = True standard_ordering = True filter_is_sticky = False subquery = False # SQL-related attributes. # Select and related select clauses are expressions to use in the SELECT # clause of the query. The select is used for cases where we want to set up # the select clause to contain other than default fields (values(), # subqueries...). Note that annotations go to annotations dictionary. select = () # The group_by attribute can have one of the following forms: # - None: no group by at all in the query # - A tuple of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. group_by = None order_by = () low_mark = 0 # Used for offset/limit. high_mark = None # Used for offset/limit. distinct = False distinct_fields = () select_for_update = False select_for_update_nowait = False select_for_update_skip_locked = False select_for_update_of = () select_for_no_key_update = False select_related = False # Arbitrary limit for select_related to prevents infinite recursion. max_depth = 5 # Holds the selects defined by a call to values() or values_list() # excluding annotation_select and extra_select. values_select = () # SQL annotation-related attributes. annotation_select_mask = None _annotation_select_cache = None # Set combination attributes. combinator = None combinator_all = False combined_queries = () # These are for extensions. The contents are more or less appended verbatim # to the appropriate clause. extra_select_mask = None _extra_select_cache = None extra_tables = () extra_order_by = () # A tuple that is a set of model field names and either True, if these are # the fields to defer, or False if these are the only fields to load. deferred_loading = (frozenset(), True) explain_info = None def __init__(self, model, alias_cols=True): self.model = model self.alias_refcount = {} # alias_map is the most important data structure regarding joins. # It's used for recording which joins exist in the query and what # types they are. The key is the alias of the joined table (possibly # the table name) and the value is a Join-like object (see # sql.datastructures.Join for more information). self.alias_map = {} # Whether to provide alias to columns during reference resolving. self.alias_cols = alias_cols # Sometimes the query contains references to aliases in outer queries (as # a result of split_exclude). Correct alias quoting needs to know these # aliases too. # Map external tables to whether they are aliased. self.external_aliases = {} self.table_map = {} # Maps table names to list of aliases. self.used_aliases = set() self.where = WhereNode() # Maps alias -> Annotation Expression. self.annotations = {} # These are for extensions. The contents are more or less appended # verbatim to the appropriate clause. self.extra = {} # Maps col_alias -> (col_sql, params). self._filtered_relations = {} @property def output_field(self): if len(self.select) == 1: select = self.select[0] return getattr(select, "target", None) or select.field elif len(self.annotation_select) == 1: return next(iter(self.annotation_select.values())).output_field @property def has_select_fields(self): return bool( self.select or self.annotation_select_mask or self.extra_select_mask ) @cached_property def base_table(self): for alias in self.alias_map: return alias def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params def sql_with_params(self): """ Return the query as an SQL string and the parameters that will be substituted into the query. """ return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() def __deepcopy__(self, memo): """Limit the amount of work when a Query is deepcopied.""" result = self.clone() memo[id(self)] = result return result def get_compiler(self, using=None, connection=None, elide_empty=True): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return connection.ops.compiler(self.compiler)( self, connection, using, elide_empty ) def get_meta(self): """ Return the Options instance (the model._meta) from which to start processing. Normally, this is self.model._meta, but it can be changed by subclasses. """ if self.model: return self.model._meta def clone(self): """ Return a copy of the current Query. A lightweight alternative to deepcopy(). """ obj = Empty() obj.__class__ = self.__class__ # Copy references to everything. obj.__dict__ = self.__dict__.copy() # Clone attributes that can't use shallow copy. obj.alias_refcount = self.alias_refcount.copy() obj.alias_map = self.alias_map.copy() obj.external_aliases = self.external_aliases.copy() obj.table_map = self.table_map.copy() obj.where = self.where.clone() obj.annotations = self.annotations.copy() if self.annotation_select_mask is not None: obj.annotation_select_mask = self.annotation_select_mask.copy() if self.combined_queries: obj.combined_queries = tuple( [query.clone() for query in self.combined_queries] ) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. # It will get re-populated in the cloned queryset the next time it's # used. obj._annotation_select_cache = None obj.extra = self.extra.copy() if self.extra_select_mask is not None: obj.extra_select_mask = self.extra_select_mask.copy() if self._extra_select_cache is not None: obj._extra_select_cache = self._extra_select_cache.copy() if self.select_related is not False: # Use deepcopy because select_related stores fields in nested # dicts. obj.select_related = copy.deepcopy(obj.select_related) if "subq_aliases" in self.__dict__: obj.subq_aliases = self.subq_aliases.copy() obj.used_aliases = self.used_aliases.copy() obj._filtered_relations = self._filtered_relations.copy() # Clear the cached_property, if it exists. obj.__dict__.pop("base_table", None) return obj def chain(self, klass=None): """ Return a copy of the current Query that's ready for another operation. The klass argument changes the type of the Query, e.g. UpdateQuery. """ obj = self.clone() if klass and obj.__class__ != klass: obj.__class__ = klass if not obj.filter_is_sticky: obj.used_aliases = set() obj.filter_is_sticky = False if hasattr(obj, "_setup_query"): obj._setup_query() return obj def relabeled_clone(self, change_map): clone = self.clone() clone.change_aliases(change_map) return clone def _get_col(self, target, field, alias): if not self.alias_cols: alias = None return target.get_col(alias, field) def rewrite_cols(self, annotation, col_cnt): # We must make sure the inner query has the referred columns in it. # If we are aggregating over an annotation, then Django uses Ref() # instances to note this. However, if we are annotating over a column # of a related model, then it might be that column isn't part of the # SELECT clause of the inner query, and we must manually make sure # the column is selected. An example case is: # .aggregate(Sum('author__awards')) # Resolving this expression results in a join to author, but there # is no guarantee the awards column of author is in the select clause # of the query. Thus we must manually add the column to the inner # query. orig_exprs = annotation.get_source_expressions() new_exprs = [] for expr in orig_exprs: # FIXME: These conditions are fairly arbitrary. Identify a better # method of having expressions decide which code path they should # take. if isinstance(expr, Ref): # Its already a Ref to subquery (see resolve_ref() for # details) new_exprs.append(expr) elif isinstance(expr, (WhereNode, Lookup)): # Decompose the subexpressions further. The code here is # copied from the else clause, but this condition must appear # before the contains_aggregate/is_summary condition below. new_expr, col_cnt = self.rewrite_cols(expr, col_cnt) new_exprs.append(new_expr) else: # Reuse aliases of expressions already selected in subquery. for col_alias, selected_annotation in self.annotation_select.items(): if selected_annotation is expr: new_expr = Ref(col_alias, expr) break else: # An expression that is not selected the subquery. if isinstance(expr, Col) or ( expr.contains_aggregate and not expr.is_summary ): # Reference column or another aggregate. Select it # under a non-conflicting alias. col_cnt += 1 col_alias = "__col%d" % col_cnt self.annotations[col_alias] = expr self.append_annotation_mask([col_alias]) new_expr = Ref(col_alias, expr) else: # Some other expression not referencing database values # directly. Its subexpression might contain Cols. new_expr, col_cnt = self.rewrite_cols(expr, col_cnt) new_exprs.append(new_expr) annotation.set_source_expressions(new_exprs) return annotation, col_cnt def get_aggregation(self, using, added_aggregate_names): """ Return the dictionary with the values of the existing aggregations. """ if not self.annotation_select: return {} existing_annotations = [ annotation for alias, annotation in self.annotations.items() if alias not in added_aggregate_names ] # Decide if we need to use a subquery. # # Existing annotations would cause incorrect results as get_aggregation() # must produce just one result and thus must not use GROUP BY. But we # aren't smart enough to remove the existing annotations from the # query, so those would force us to use GROUP BY. # # If the query has limit or distinct, or uses set operations, then # those operations must be done in a subquery so that the query # aggregates on the limit and/or distinct results instead of applying # the distinct and limit after the aggregation. if ( isinstance(self.group_by, tuple) or self.is_sliced or existing_annotations or self.distinct or self.combinator ): from django.db.models.sql.subqueries import AggregateQuery inner_query = self.clone() inner_query.subquery = True outer_query = AggregateQuery(self.model, inner_query) inner_query.select_for_update = False inner_query.select_related = False inner_query.set_annotation_mask(self.annotation_select) # Queries with distinct_fields need ordering and when a limit is # applied we must take the slice from the ordered query. Otherwise # no need for ordering. inner_query.clear_ordering(force=False) if not inner_query.distinct: # If the inner query uses default select and it has some # aggregate annotations, then we must make sure the inner # query is grouped by the main model's primary key. However, # clearing the select clause can alter results if distinct is # used. has_existing_aggregate_annotations = any( annotation for annotation in existing_annotations if getattr(annotation, "contains_aggregate", True) ) if inner_query.default_cols and has_existing_aggregate_annotations: inner_query.group_by = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) inner_query.default_cols = False relabels = {t: "subquery" for t in inner_query.alias_map} relabels[None] = "subquery" # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. col_cnt = 0 for alias, expression in list(inner_query.annotation_select.items()): annotation_select_mask = inner_query.annotation_select_mask if expression.is_summary: expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt) outer_query.annotations[alias] = expression.relabeled_clone( relabels ) del inner_query.annotations[alias] annotation_select_mask.remove(alias) # Make sure the annotation_select wont use cached results. inner_query.set_annotation_mask(inner_query.annotation_select_mask) if ( inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask ): # In case of Model.objects[0:3].count(), there would be no # field selected in the inner query, yet we must use a subquery. # So, make sure at least one field is selected. inner_query.select = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) else: outer_query = self self.select = () self.default_cols = False self.extra = {} empty_set_result = [ expression.empty_result_set_value for expression in outer_query.annotation_select.values() ] elide_empty = not any(result is NotImplemented for result in empty_set_result) outer_query.clear_ordering(force=True) outer_query.clear_limits() outer_query.select_for_update = False outer_query.select_related = False compiler = outer_query.get_compiler(using, elide_empty=elide_empty) result = compiler.execute_sql(SINGLE) if result is None: result = empty_set_result converters = compiler.get_converters(outer_query.annotation_select.values()) result = next(compiler.apply_converters((result,), converters)) return dict(zip(outer_query.annotation_select, result)) def get_count(self, using): """ Perform a COUNT() query using the current filter constraints. """ obj = self.clone() obj.add_annotation(Count("*"), alias="__count", is_summary=True) return obj.get_aggregation(using, ["__count"])["__count"] def has_filters(self): return self.where def exists(self, using, limit=True): q = self.clone() if not (q.distinct and q.is_sliced): if q.group_by is True: q.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. q.set_group_by(allow_aliases=False) q.clear_select_clause() if q.combined_queries and q.combinator == "union": limit_combined = connections[ using ].features.supports_slicing_ordering_in_compound q.combined_queries = tuple( combined_query.exists(using, limit=limit_combined) for combined_query in q.combined_queries ) q.clear_ordering(force=True) if limit: q.set_limits(high=1) q.add_annotation(Value(1), "a") return q def has_results(self, using): q = self.exists(using) compiler = q.get_compiler(using=using) return compiler.has_results() def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"Invalid option name: {option_name!r}.") q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query()) def combine(self, rhs, connector): """ Merge the 'rhs' query into the current one (with any 'rhs' effects being applied *after* (that is, "to the right of") anything in the current query. 'rhs' is not modified during a call to this function. The 'connector' parameter describes how to connect filters from the 'rhs' query. """ if self.model != rhs.model: raise TypeError("Cannot combine queries on two different base models.") if self.is_sliced: raise TypeError("Cannot combine queries once a slice has been taken.") if self.distinct != rhs.distinct: raise TypeError("Cannot combine a unique query with a non-unique query.") if self.distinct_fields != rhs.distinct_fields: raise TypeError("Cannot combine queries with different distinct fields.") # If lhs and rhs shares the same alias prefix, it is possible to have # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up # as T4 -> T6 while combining two querysets. To prevent this, change an # alias prefix of the rhs and update current aliases accordingly, # except if the alias is the base table since it must be present in the # query on both sides. initial_alias = self.get_initial_alias() rhs.bump_prefix(self, exclude={initial_alias}) # Work out how to relabel the rhs aliases, if necessary. change_map = {} conjunction = connector == AND # Determine which existing joins can be reused. When combining the # query with AND we must recreate all joins for m2m filters. When # combining with OR we can reuse joins. The reason is that in AND # case a single row can't fulfill a condition like: # revrel__col=1 & revrel__col=2 # But, there might be two different related rows matching this # condition. In OR case a single True is enough, so single row is # enough, too. # # Note that we will be creating duplicate joins for non-m2m joins in # the AND case. The results will be correct but this creates too many # joins. This is something that could be fixed later on. reuse = set() if conjunction else set(self.alias_map) joinpromoter = JoinPromoter(connector, 2, False) joinpromoter.add_votes( j for j in self.alias_map if self.alias_map[j].join_type == INNER ) rhs_votes = set() # Now, add the joins from rhs query into the new query (skipping base # table). rhs_tables = list(rhs.alias_map)[1:] for alias in rhs_tables: join = rhs.alias_map[alias] # If the left side of the join was already relabeled, use the # updated alias. join = join.relabeled_clone(change_map) new_alias = self.join(join, reuse=reuse) if join.join_type == INNER: rhs_votes.add(new_alias) # We can't reuse the same join again in the query. If we have two # distinct joins for the same connection in rhs query, then the # combined query must have two joins, too. reuse.discard(new_alias) if alias != new_alias: change_map[alias] = new_alias if not rhs.alias_refcount[alias]: # The alias was unused in the rhs query. Unref it so that it # will be unused in the new query, too. We have to add and # unref the alias so that join promotion has information of # the join type for the unused alias. self.unref_alias(new_alias) joinpromoter.add_votes(rhs_votes) joinpromoter.update_join_types(self) # Combine subqueries aliases to ensure aliases relabelling properly # handle subqueries when combining where and select clauses. self.subq_aliases |= rhs.subq_aliases # Now relabel a copy of the rhs where-clause and add it to the current # one. w = rhs.where.clone() w.relabel_aliases(change_map) self.where.add(w, connector) # Selection columns and extra extensions are those provided by 'rhs'. if rhs.select: self.set_select([col.relabeled_clone(change_map) for col in rhs.select]) else: self.select = () if connector == OR: # It would be nice to be able to handle this, but the queries don't # really make sense (or return consistent value sets). Not worth # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( "When merging querysets using 'or', you cannot have " "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() if self.extra_select_mask is not None: extra_select_mask.update(self.extra_select_mask) if rhs.extra_select_mask is not None: extra_select_mask.update(rhs.extra_select_mask) if extra_select_mask: self.set_extra_mask(extra_select_mask) self.extra_tables += rhs.extra_tables # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. self.order_by = rhs.order_by or self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def deferred_to_data(self, target): """ Convert the self.deferred_loading data structure to an alternate data structure, describing the field that *will* be loaded. This is used to compute the columns to select from the database and also by the QuerySet class to work out which fields are being initialized on each model. Models that have all their fields included aren't mentioned in the result, only those that have field restrictions in place. The "target" parameter is the instance that is populated (in place). """ field_names, defer = self.deferred_loading if not field_names: return orig_opts = self.get_meta() seen = {} must_include = {orig_opts.concrete_model: {orig_opts.pk}} for field_name in field_names: parts = field_name.split(LOOKUP_SEP) cur_model = self.model._meta.concrete_model opts = orig_opts for name in parts[:-1]: old_model = cur_model if name in self._filtered_relations: name = self._filtered_relations[name].relation_name source = opts.get_field(name) if is_reverse_o2o(source): cur_model = source.related_model else: cur_model = source.remote_field.model cur_model = cur_model._meta.concrete_model opts = cur_model._meta # Even if we're "just passing through" this model, we must add # both the current model's pk and the related reference field # (if it's not a reverse relation) to the things we select. if not is_reverse_o2o(source): must_include[old_model].add(source) add_to_dict(must_include, cur_model, opts.pk) field = opts.get_field(parts[-1]) is_reverse_object = field.auto_created and not field.concrete model = field.related_model if is_reverse_object else field.model model = model._meta.concrete_model if model == opts.model: model = cur_model if not is_reverse_o2o(field): add_to_dict(seen, model, field) if defer: # We need to load all fields for each model, except those that # appear in "seen" (for all models that appear in "seen"). The only # slight complexity here is handling fields that exist on parent # models. workset = {} for model, values in seen.items(): for field in model._meta.local_fields: if field not in values: m = field.model._meta.concrete_model add_to_dict(workset, m, field) for model, values in must_include.items(): # If we haven't included a model in workset, we don't add the # corresponding must_include fields for that model, since an # empty set means "include all fields". That's why there's no # "else" branch here. if model in workset: workset[model].update(values) for model, fields in workset.items(): target[model] = {f.attname for f in fields} else: for model, values in must_include.items(): if model in seen: seen[model].update(values) else: # As we've passed through this model, but not explicitly # included any fields, we have to make sure it's mentioned # so that only the "must include" fields are pulled in. seen[model] = values # Now ensure that every model in the inheritance chain is mentioned # in the parent list. Again, it must be mentioned to ensure that # only "must include" fields are pulled in. for model in orig_opts.get_parent_list(): seen.setdefault(model, set()) for model, fields in seen.items(): target[model] = {f.attname for f in fields} def table_alias(self, table_name, create=False, filtered_relation=None): """ Return a table alias for the given table_name and whether this is a new alias or not. If 'create' is true, a new alias is always created. Otherwise, the most recently created alias for the table (if one exists) is reused. """ alias_list = self.table_map.get(table_name) if not create and alias_list: alias = alias_list[0] self.alias_refcount[alias] += 1 return alias, False # Create a new alias for this table. if alias_list: alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1) alias_list.append(alias) else: # The first occurrence of a table uses the table name directly. alias = ( filtered_relation.alias if filtered_relation is not None else table_name ) self.table_map[table_name] = [alias] self.alias_refcount[alias] = 1 return alias, True def ref_alias(self, alias): """Increases the reference count for this alias.""" self.alias_refcount[alias] += 1 def unref_alias(self, alias, amount=1): """Decreases the reference count for this alias.""" self.alias_refcount[alias] -= amount def promote_joins(self, aliases): """ Promote recursively the join type of given aliases and its children to an outer join. If 'unconditional' is False, only promote the join if it is nullable or the parent join is an outer join. The children promotion is done to avoid join chains that contain a LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted, then we must also promote b->c automatically, or otherwise the promotion of a->b doesn't actually change anything in the query results. """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type is None: # This is the base table (first FROM entry) - this table # isn't really joined at all in the query, so we should not # alter its join type. continue # Only the first alias (skipped above) should have None join_type assert self.alias_map[alias].join_type is not None parent_alias = self.alias_map[alias].parent_alias parent_louter = ( parent_alias and self.alias_map[parent_alias].join_type == LOUTER ) already_louter = self.alias_map[alias].join_type == LOUTER if (self.alias_map[alias].nullable or parent_louter) and not already_louter: self.alias_map[alias] = self.alias_map[alias].promote() # Join type of 'alias' changed, so re-examine all aliases that # refer to this one. aliases.extend( join for join in self.alias_map if self.alias_map[join].parent_alias == alias and join not in aliases ) def demote_joins(self, aliases): """ Change join type from LOUTER to INNER for all joins in aliases. Similarly to promote_joins(), this method must ensure no join chains containing first an outer, then an inner join are generated. If we are demoting b->c join in chain a LOUTER b LOUTER c then we must demote a->b automatically, or otherwise the demotion of b->c doesn't actually change anything in the query results. . """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type == LOUTER: self.alias_map[alias] = self.alias_map[alias].demote() parent_alias = self.alias_map[alias].parent_alias if self.alias_map[parent_alias].join_type == INNER: aliases.append(parent_alias) def reset_refcounts(self, to_counts): """ Reset reference counts for aliases so that they match the value passed in `to_counts`. """ for alias, cur_refcount in self.alias_refcount.copy().items(): unref_amount = cur_refcount - to_counts.get(alias, 0) self.unref_alias(alias, unref_amount) def change_aliases(self, change_map): """ Change the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause. """ # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. assert set(change_map).isdisjoint(change_map.values()) # 1. Update references in "select" (normal columns plus aliases), # "group by" and "where". self.where.relabel_aliases(change_map) if isinstance(self.group_by, tuple): self.group_by = tuple( [col.relabeled_clone(change_map) for col in self.group_by] ) self.select = tuple([col.relabeled_clone(change_map) for col in self.select]) self.annotations = self.annotations and { key: col.relabeled_clone(change_map) for key, col in self.annotations.items() } # 2. Rename the alias in the internal table/alias datastructures. for old_alias, new_alias in change_map.items(): if old_alias not in self.alias_map: continue alias_data = self.alias_map[old_alias].relabeled_clone(change_map) self.alias_map[new_alias] = alias_data self.alias_refcount[new_alias] = self.alias_refcount[old_alias] del self.alias_refcount[old_alias] del self.alias_map[old_alias] table_aliases = self.table_map[alias_data.table_name] for pos, alias in enumerate(table_aliases): if alias == old_alias: table_aliases[pos] = new_alias break self.external_aliases = { # Table is aliased or it's being changed and thus is aliased. change_map.get(alias, alias): (aliased or alias in change_map) for alias, aliased in self.external_aliases.items() } def bump_prefix(self, other_query, exclude=None): """ Change the alias prefix to the next letter in the alphabet in a way that the other query's aliases and this query's aliases will not conflict. Even tables that previously had no alias will get an alias after this call. To prevent changing aliases use the exclude parameter. """ def prefix_gen(): """ Generate a sequence of characters in alphabetical order: -> 'A', 'B', 'C', ... When the alphabet is finished, the sequence will continue with the Cartesian product: -> 'AA', 'AB', 'AC', ... """ alphabet = ascii_uppercase prefix = chr(ord(self.alias_prefix) + 1) yield prefix for n in count(1): seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet for s in product(seq, repeat=n): yield "".join(s) prefix = None if self.alias_prefix != other_query.alias_prefix: # No clashes between self and outer query should be possible. return # Explicitly avoid infinite loop. The constant divider is based on how # much depth recursive subquery references add to the stack. This value # might need to be adjusted when adding or removing function calls from # the code path in charge of performing these operations. local_recursion_limit = sys.getrecursionlimit() // 16 for pos, prefix in enumerate(prefix_gen()): if prefix not in self.subq_aliases: self.alias_prefix = prefix break if pos > local_recursion_limit: raise RecursionError( "Maximum recursion depth exceeded: too many subqueries." ) self.subq_aliases = self.subq_aliases.union([self.alias_prefix]) other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases) if exclude is None: exclude = {} self.change_aliases( { alias: "%s%d" % (self.alias_prefix, pos) for pos, alias in enumerate(self.alias_map) if alias not in exclude } ) def get_initial_alias(self): """ Return the first alias for this query, after increasing its reference count. """ if self.alias_map: alias = self.base_table self.ref_alias(alias) elif self.model: alias = self.join(self.base_table_class(self.get_meta().db_table, None)) else: alias = None return alias def count_active_tables(self): """ Return the number of tables in this query with a non-zero reference count. After execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method. """ return len([1 for count in self.alias_refcount.values() if count]) def join(self, join, reuse=None, reuse_with_filtered_relation=False): """ Return an alias for the 'join', either reusing an existing alias for that join or creating a new one. 'join' is either a base_table_class or join_class. The 'reuse' parameter can be either None which means all joins are reusable, or it can be a set containing the aliases that can be reused. The 'reuse_with_filtered_relation' parameter is used when computing FilteredRelation instances. A join is always created as LOUTER if the lhs alias is LOUTER to make sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new joins are created as LOUTER if the join is nullable. """ if reuse_with_filtered_relation and reuse: reuse_aliases = [ a for a, j in self.alias_map.items() if a in reuse and j.equals(join) ] else: reuse_aliases = [ a for a, j in self.alias_map.items() if (reuse is None or a in reuse) and j == join ] if reuse_aliases: if join.table_alias in reuse_aliases: reuse_alias = join.table_alias else: # Reuse the most recent alias of the joined table # (a many-to-many relation may be joined multiple times). reuse_alias = reuse_aliases[-1] self.ref_alias(reuse_alias) return reuse_alias # No reuse is possible, so we need a new alias. alias, _ = self.table_alias( join.table_name, create=True, filtered_relation=join.filtered_relation ) if join.join_type: if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable: join_type = LOUTER else: join_type = INNER join.join_type = join_type join.table_alias = alias self.alias_map[alias] = join return alias def join_parent_model(self, opts, model, alias, seen): """ Make sure the given 'model' is joined in the query. If 'model' isn't a parent of 'opts' or if it is None this method is a no-op. The 'alias' is the root alias for starting the join, 'seen' is a dict of model -> alias of existing joins. It must also contain a mapping of None -> some alias. This will be returned in the no-op case. """ if model in seen: return seen[model] chain = opts.get_base_chain(model) if not chain: return alias curr_opts = opts for int_model in chain: if int_model in seen: curr_opts = int_model._meta alias = seen[int_model] continue # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not curr_opts.parents[int_model]: curr_opts = int_model._meta continue link_field = curr_opts.get_ancestor_link(int_model) join_info = self.setup_joins([link_field.name], curr_opts, alias) curr_opts = int_model._meta alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) def add_annotation(self, annotation, alias, is_summary=False, select=True): """Add a single annotation expression to the Query.""" self.check_alias(alias) annotation = annotation.resolve_expression( self, allow_joins=True, reuse=None, summarize=is_summary ) if select: self.append_annotation_mask([alias]) else: self.set_annotation_mask(set(self.annotation_select).difference({alias})) self.annotations[alias] = annotation def resolve_expression(self, query, *args, **kwargs): clone = self.clone() # Subqueries need to use a different set of aliases than the outer query. clone.bump_prefix(query) clone.subquery = True clone.where.resolve_expression(query, *args, **kwargs) # Resolve combined queries. if clone.combinator: clone.combined_queries = tuple( [ combined_query.resolve_expression(query, *args, **kwargs) for combined_query in clone.combined_queries ] ) for key, value in clone.annotations.items(): resolved = value.resolve_expression(query, *args, **kwargs) if hasattr(resolved, "external_aliases"): resolved.external_aliases.update(clone.external_aliases) clone.annotations[key] = resolved # Outer query's aliases are considered external. for alias, table in query.alias_map.items(): clone.external_aliases[alias] = ( isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias ) or ( isinstance(table, BaseTable) and table.table_name != table.table_alias ) return clone def get_external_cols(self): exprs = chain(self.annotations.values(), self.where.children) return [ col for col in self._gen_cols(exprs, include_external=True) if col.alias in self.external_aliases ] def get_group_by_cols(self, alias=None): if alias: return [Ref(alias, self)] external_cols = self.get_external_cols() if any(col.possibly_multivalued for col in external_cols): return [self] return external_cols def as_sql(self, compiler, connection): # Some backends (e.g. Oracle) raise an error when a subquery contains # unnecessary ORDER BY clause. if ( self.subquery and not connection.features.ignores_unnecessary_order_by_in_subqueries ): self.clear_ordering(force=False) for query in self.combined_queries: query.clear_ordering(force=False) sql, params = self.get_compiler(connection=connection).as_sql() if self.subquery: sql = "(%s)" % sql return sql, params def resolve_lookup_value(self, value, can_reuse, allow_joins): if hasattr(value, "resolve_expression"): value = value.resolve_expression( self, reuse=can_reuse, allow_joins=allow_joins, ) elif isinstance(value, (list, tuple)): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( self.resolve_lookup_value(sub_value, can_reuse, allow_joins) for sub_value in value ) type_ = type(value) if hasattr(type_, "_make"): # namedtuple return type_(*values) return type_(values) return value def solve_lookup_type(self, lookup): """ Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains'). """ lookup_splitted = lookup.split(LOOKUP_SEP) if self.annotations: expression, expression_lookups = refs_expression( lookup_splitted, self.annotations ) if expression: return expression_lookups, (), expression _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)] if len(lookup_parts) > 1 and not field_parts: raise FieldError( 'Invalid lookup "%s" for model %s".' % (lookup, self.get_meta().model.__name__) ) return lookup_parts, field_parts, False def check_query_object_type(self, value, opts, field): """ Check whether the object passed while querying is of the correct type. If not, raise a ValueError specifying the wrong object. """ if hasattr(value, "_meta"): if not check_rel_lookup_compatibility(value._meta.model, opts, field): raise ValueError( 'Cannot query "%s": Must be "%s" instance.' % (value, opts.object_name) ) def check_related_objects(self, field, value, opts): """Check the type of object passed to query relations.""" if field.is_relation: # Check that the field and the queryset use the same model in a # query like .filter(author=Author.objects.all()). For example, the # opts would be Author's (from the author field) and value.model # would be Author.objects.all() queryset's .model (Author also). # The field is the related field on the lhs side. if ( isinstance(value, Query) and not value.has_select_fields and not check_rel_lookup_compatibility(value.model, opts, field) ): raise ValueError( 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' % (value.model._meta.object_name, opts.object_name) ) elif hasattr(value, "_meta"): self.check_query_object_type(value, opts, field) elif hasattr(value, "__iter__"): for v in value: self.check_query_object_type(v, opts, field) def check_filterable(self, expression): """Raise an error if expression cannot be used in a WHERE clause.""" if hasattr(expression, "resolve_expression") and not getattr( expression, "filterable", True ): raise NotSupportedError( expression.__class__.__name__ + " is disallowed in the filter " "clause." ) if hasattr(expression, "get_source_expressions"): for expr in expression.get_source_expressions(): self.check_filterable(expr) def build_lookup(self, lookups, lhs, rhs): """ Try to extract transforms and lookup from given lhs. The lhs value is something that works like SQLExpression. The rhs value is what the lookup is going to compare against. The lookups is a list of names to extract using get_lookup() and get_transform(). """ # __exact is the default lookup if one isn't given. *transforms, lookup_name = lookups or ["exact"] for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: if lhs.field.is_relation: raise FieldError( "Related Field got invalid lookup: {}".format(lookup_name) ) # A lookup wasn't found. Try to interpret the name as a transform # and do an Exact lookup against it. lhs = self.try_transform(lhs, lookup_name) lookup_name = "exact" lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: return lookup = lookup_class(lhs, rhs) # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value unless the lookup supports it. if lookup.rhs is None and not lookup.can_use_none_as_rhs: if lookup_name not in ("exact", "iexact"): raise ValueError("Cannot use None as a query value") return lhs.get_lookup("isnull")(lhs, True) # For Oracle '' is equivalent to null. The check must be done at this # stage because join promotion can't be done in the compiler. Using # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here. # A similar thing is done in is_nullable(), too. if ( lookup_name == "exact" and lookup.rhs == "" and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ): return lhs.get_lookup("isnull")(lhs, True) return lookup def try_transform(self, lhs, name): """ Helper method for build_lookup(). Try to fetch and initialize a transform for name parameter from lhs. """ transform_class = lhs.get_transform(name) if transform_class: return transform_class(lhs) else: output_field = lhs.output_field.__class__ suggested_lookups = difflib.get_close_matches( name, output_field.get_lookups() ) if suggested_lookups: suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups) else: suggestion = "." raise FieldError( "Unsupported lookup '%s' for %s or join on the field not " "permitted%s" % (name, output_field.__name__, suggestion) ) def build_filter( self, filter_expr, branch_negated=False, current_negated=False, can_reuse=None, allow_joins=True, split_subq=True, reuse_with_filtered_relation=False, check_filterable=True, ): """ Build a WhereNode for a single filter clause but don't add it to this Query. Query.add_q() will then add this filter to the where Node. The 'branch_negated' tells us if the current branch contains any negations. This will be used to determine if subqueries are needed. The 'current_negated' is used to determine if the current filter is negated or not and this will be used to determine if IS NULL filtering is needed. The difference between current_negated and branch_negated is that branch_negated is set on first negation, but current_negated is flipped for each negation. Note that add_filter will not do any negating itself, that is done upper in the code by add_q(). The 'can_reuse' is a set of reusable joins for multijoins. If 'reuse_with_filtered_relation' is True, then only joins in can_reuse will be reused. The method will create a filter clause that can be added to the current query. However, if the filter isn't added to the query then the caller is responsible for unreffing the joins used. """ if isinstance(filter_expr, dict): raise FieldError("Cannot parse keyword query as dict") if isinstance(filter_expr, Q): return self._add_q( filter_expr, branch_negated=branch_negated, current_negated=current_negated, used_aliases=can_reuse, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, ) if hasattr(filter_expr, "resolve_expression"): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression(self, allow_joins=allow_joins) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) return WhereNode([condition], connector=AND), [] arg, value = filter_expr if not arg: raise FieldError("Cannot parse keyword query %r" % arg) lookups, parts, reffed_expression = self.solve_lookup_type(arg) if check_filterable: self.check_filterable(reffed_expression) if not allow_joins and len(parts) > 1: raise FieldError("Joined field references are not permitted in this query") pre_joins = self.alias_refcount.copy() value = self.resolve_lookup_value(value, can_reuse, allow_joins) used_joins = { k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0) } if check_filterable: self.check_filterable(value) if reffed_expression: condition = self.build_lookup(lookups, reffed_expression, value) return WhereNode([condition], connector=AND), [] opts = self.get_meta() alias = self.get_initial_alias() allow_many = not branch_negated or not split_subq try: join_info = self.setup_joins( parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many, reuse_with_filtered_relation=reuse_with_filtered_relation, ) # Prevent iterator from being consumed by check_related_objects() if isinstance(value, Iterator): value = list(value) self.check_related_objects(join_info.final_field, value, join_info.opts) # split_exclude() needs to know which joins were generated for the # lookup parts self._lookup_joins = join_info.joins except MultiJoin as e: return self.split_exclude(filter_expr, can_reuse, e.names_with_path) # Update used_joins before trimming since they are reused to determine # which joins could be later promoted to INNER. used_joins.update(join_info.joins) targets, alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if can_reuse is not None: can_reuse.update(join_list) if join_info.final_field.is_relation: # No support for transforms for relational fields num_lookups = len(lookups) if num_lookups > 1: raise FieldError( "Related Field got invalid lookup: {}".format(lookups[0]) ) if len(targets) == 1: col = self._get_col(targets[0], join_info.final_field, alias) else: col = MultiColSource( alias, targets, join_info.targets, join_info.final_field ) else: col = self._get_col(targets[0], join_info.final_field, alias) condition = self.build_lookup(lookups, col, value) lookup_type = condition.lookup_name clause = WhereNode([condition], connector=AND) require_outer = ( lookup_type == "isnull" and condition.rhs is True and not current_negated ) if ( current_negated and (lookup_type != "isnull" or condition.rhs is False) and condition.rhs is not None ): require_outer = True if lookup_type != "isnull": # The condition added here will be SQL like this: # NOT (col IS NOT NULL), where the first NOT is added in # upper layers of code. The reason for addition is that if col # is null, then col != someval will result in SQL "unknown" # which isn't the same as in Python. The Python None handling # is wanted, and it can be gotten by # (col IS NULL OR col != someval) # <=> # NOT (col IS NOT NULL AND col = someval). if ( self.is_nullable(targets[0]) or self.alias_map[join_list[-1]].join_type == LOUTER ): lookup_class = targets[0].get_lookup("isnull") col = self._get_col(targets[0], join_info.targets[0], alias) clause.add(lookup_class(col, False), AND) # If someval is a nullable column, someval IS NOT NULL is # added. if isinstance(value, Col) and self.is_nullable(value.target): lookup_class = value.target.get_lookup("isnull") clause.add(lookup_class(value, False), AND) return clause, used_joins if not require_outer else () def add_filter(self, filter_lhs, filter_rhs): self.add_q(Q((filter_lhs, filter_rhs))) def add_q(self, q_object): """ A preprocessor for the internal _add_q(). Responsible for doing final join promotion. """ # For join promotion this case is doing an AND for the added q_object # and existing conditions. So, any existing inner join forces the join # type to remain inner. Existing outer joins can however be demoted. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if # rel_a doesn't produce any rows, then the whole condition must fail. # So, demotion is OK. existing_inner = { a for a in self.alias_map if self.alias_map[a].join_type == INNER } clause, _ = self._add_q(q_object, self.used_aliases) if clause: self.where.add(clause, AND) self.demote_joins(existing_inner) def build_where(self, filter_expr): return self.build_filter(filter_expr, allow_joins=False)[0] def clear_where(self): self.where = WhereNode() def _add_q( self, q_object, used_aliases, branch_negated=False, current_negated=False, allow_joins=True, split_subq=True, check_filterable=True, ): """Add a Q-object to the current filter.""" connector = q_object.connector current_negated = current_negated ^ q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) joinpromoter = JoinPromoter( q_object.connector, len(q_object.children), current_negated ) for child in q_object.children: child_clause, needed_inner = self.build_filter( child, can_reuse=used_aliases, branch_negated=branch_negated, current_negated=current_negated, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, ) joinpromoter.add_votes(needed_inner) if child_clause: target_clause.add(child_clause, connector) needed_inner = joinpromoter.update_join_types(self) return target_clause, needed_inner def build_filtered_relation_q( self, q_object, reuse, branch_negated=False, current_negated=False ): """Add a FilteredRelation object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) for child in q_object.children: if isinstance(child, Node): child_clause = self.build_filtered_relation_q( child, reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, ) else: child_clause, _ = self.build_filter( child, can_reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, allow_joins=True, split_subq=False, reuse_with_filtered_relation=True, ) target_clause.add(child_clause, connector) return target_clause def add_filtered_relation(self, filtered_relation, alias): filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( filtered_relation.relation_name ) if relation_lookup_parts: raise ValueError( "FilteredRelation's relation_name cannot contain lookups " "(got %r)." % filtered_relation.relation_name ) for lookup in chain(lookups): lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup) shift = 2 if not lookup_parts else 1 lookup_field_path = lookup_field_parts[:-shift] for idx, lookup_field_part in enumerate(lookup_field_path): if len(relation_field_parts) > idx: if relation_field_parts[idx] != lookup_field_part: raise ValueError( "FilteredRelation's condition doesn't support " "relations outside the %r (got %r)." % (filtered_relation.relation_name, lookup) ) else: raise ValueError( "FilteredRelation's condition doesn't support nested " "relations deeper than the relation_name (got %r for " "%r)." % (lookup, filtered_relation.relation_name) ) self._filtered_relations[filtered_relation.alias] = filtered_relation def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): """ Walk the list of names and turns them into PathInfo tuples. A single name in 'names' can generate multiple PathInfos (m2m, for example). 'names' is the path of names to travel, 'opts' is the model Options we start the name resolving from, 'allow_many' is as for setup_joins(). If fail_on_missing is set to True, then a name that can't be resolved will generate a FieldError. Return a list of PathInfo tuples. In addition return the final field (the last used join field) and target (which is a field guaranteed to contain the same value as the final field). Finally, return those names that weren't found (which are likely transforms and the final lookup). """ path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == "pk": name = opts.pk.name field = None filtered_relation = None try: if opts is None: raise FieldDoesNotExist field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field elif name in self._filtered_relations and pos == 0: filtered_relation = self._filtered_relations[name] if LOOKUP_SEP in filtered_relation.relation_name: parts = filtered_relation.relation_name.split(LOOKUP_SEP) filtered_relation_path, field, _, _ = self.names_to_path( parts, opts, allow_many, fail_on_missing, ) path.extend(filtered_relation_path[:-1]) else: field = opts.get_field(filtered_relation.relation_name) if field is not None: # Fields that contain one-to-many relations with a generic # model (like a GenericForeignKey) cannot generate reverse # relations and therefore cannot be used for reverse querying. if field.is_relation and not field.related_model: raise FieldError( "Field %r does not generate an automatic reverse " "relation and therefore cannot be used for reverse " "querying. If it is a GenericForeignKey, consider " "adding a GenericRelation." % name ) try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break # Check if we need any joins for concrete inheritance cases (the # field lives in parent, but we are currently in one of its # children) if opts is not None and model is not opts.model: path_to_parent = opts.get_path_to_parent(model) if path_to_parent: path.extend(path_to_parent) cur_names_with_path[1].extend(path_to_parent) opts = path_to_parent[-1].to_opts if hasattr(field, "path_infos"): if filtered_relation: pathinfos = field.get_path_info(filtered_relation) else: pathinfos = field.path_infos if not allow_many: for inner_pos, p in enumerate(pathinfos): if p.m2m: cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1]) names_with_path.append(cur_names_with_path) raise MultiJoin(pos + 1, names_with_path) last = pathinfos[-1] path.extend(pathinfos) final_field = last.join_field opts = last.to_opts targets = last.target_fields cur_names_with_path[1].extend(pathinfos) names_with_path.append(cur_names_with_path) else: # Local non-relational field. final_field = field targets = (field,) if fail_on_missing and pos + 1 != len(names): raise FieldError( "Cannot resolve keyword %r into field. Join on '%s'" " not permitted." % (names[pos + 1], name) ) break return path, final_field, targets, names[pos + 1 :] def setup_joins( self, names, opts, alias, can_reuse=None, allow_many=True, reuse_with_filtered_relation=False, ): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are starting from), 'alias' is the alias for the table to start the joining from. The 'can_reuse' defines the reverse foreign key joins we can reuse. It can be None in which case all joins are reusable or a set of aliases that can be reused. Note that non-reverse foreign keys are always reusable when using setup_joins(). The 'reuse_with_filtered_relation' can be used to force 'can_reuse' parameter and force the relation on the given connections. If 'allow_many' is False, then any reverse foreign key seen will generate a MultiJoin exception. Return the final field involved in the joins, the target field (used for any 'where' constraint), the final 'opts' value, the joins, the field path traveled to generate the joins, and a transform function that takes a field and alias and is equivalent to `field.get_col(alias)` in the simple case but wraps field transforms if they were included in names. The target field is the field containing the concrete value. Final field can be something different, for example foreign key pointing to that value. Final field is needed for example in some value conversions (convert 'obj' in fk__id=obj to pk val using the foreign key field for example). """ joins = [alias] # The transform can't be applied yet, as joins must be trimmed later. # To avoid making every caller of this method look up transforms # directly, compute transforms here and create a partial that converts # fields to the appropriate wrapped version. def final_transformer(field, alias): if not self.alias_cols: alias = None return field.get_col(alias) # Try resolving all the names as fields first. If there's an error, # treat trailing names as lookups until a field can be resolved. last_field_exception = None for pivot in range(len(names), 0, -1): try: path, final_field, targets, rest = self.names_to_path( names[:pivot], opts, allow_many, fail_on_missing=True, ) except FieldError as exc: if pivot == 1: # The first item cannot be a lookup, so it's safe # to raise the field error here. raise else: last_field_exception = exc else: # The transforms are the remaining items that couldn't be # resolved into fields. transforms = names[pivot:] break for name in transforms: def transform(field, alias, *, name, previous): try: wrapped = previous(field, alias) return self.try_transform(wrapped, name) except FieldError: # FieldError is raised if the transform doesn't exist. if isinstance(final_field, Field) and last_field_exception: raise last_field_exception else: raise final_transformer = functools.partial( transform, name=name, previous=final_transformer ) # Then, add the path to the query's joins. Note that we can't trim # joins at this stage - we will need the information about join type # of the trimmed joins. for join in path: if join.filtered_relation: filtered_relation = join.filtered_relation.clone() table_alias = filtered_relation.alias else: filtered_relation = None table_alias = None opts = join.to_opts if join.direct: nullable = self.is_nullable(join.join_field) else: nullable = True connection = self.join_class( opts.db_table, alias, table_alias, INNER, join.join_field, nullable, filtered_relation=filtered_relation, ) reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None alias = self.join( connection, reuse=reuse, reuse_with_filtered_relation=reuse_with_filtered_relation, ) joins.append(alias) if filtered_relation: filtered_relation.path = joins[:] return JoinInfo(final_field, targets, opts, joins, path, final_transformer) def trim_joins(self, targets, joins, path): """ The 'target' parameter is the final field being joined to, 'joins' is the full list of join aliases. The 'path' contain the PathInfos used to create the joins. Return the final target field and table alias and the new active joins. Always trim any direct join if the target column is already in the previous table. Can't trim reverse joins as it's unknown if there's anything on the other side of the join. """ joins = joins[:] for pos, info in enumerate(reversed(path)): if len(joins) == 1 or not info.direct: break if info.filtered_relation: break join_targets = {t.column for t in info.join_field.foreign_related_fields} cur_targets = {t.column for t in targets} if not cur_targets.issubset(join_targets): break targets_dict = { r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets } targets = tuple(targets_dict[t.column] for t in targets) self.unref_alias(joins.pop()) return targets, joins[-1], joins @classmethod def _gen_cols(cls, exprs, include_external=False): for expr in exprs: if isinstance(expr, Col): yield expr elif include_external and callable( getattr(expr, "get_external_cols", None) ): yield from expr.get_external_cols() elif hasattr(expr, "get_source_expressions"): yield from cls._gen_cols( expr.get_source_expressions(), include_external=include_external, ) @classmethod def _gen_col_aliases(cls, exprs): yield from (expr.alias for expr in cls._gen_cols(exprs)) def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False): annotation = self.annotations.get(name) if annotation is not None: if not allow_joins: for alias in self._gen_col_aliases([annotation]): if isinstance(self.alias_map[alias], Join): raise FieldError( "Joined field references are not permitted in this query" ) if summarize: # Summarize currently means we are doing an aggregate() query # which is executed as a wrapped subquery if any of the # aggregate() elements reference an existing annotation. In # that case we need to return a Ref to the subquery's annotation. if name not in self.annotation_select: raise FieldError( "Cannot aggregate over the '%s' alias. Use annotate() " "to promote it." % name ) return Ref(name, self.annotation_select[name]) else: return annotation else: field_list = name.split(LOOKUP_SEP) annotation = self.annotations.get(field_list[0]) if annotation is not None: for transform in field_list[1:]: annotation = self.try_transform(annotation, transform) return annotation join_info = self.setup_joins( field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse ) targets, final_alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if not allow_joins and len(join_list) > 1: raise FieldError( "Joined field references are not permitted in this query" ) if len(targets) > 1: raise FieldError( "Referencing multicolumn fields with F() objects isn't supported" ) # Verify that the last lookup in name is a field or a transform: # transform_function() raises FieldError if not. transform = join_info.transform_function(targets[0], final_alias) if reuse is not None: reuse.update(join_list) return transform def split_exclude(self, filter_expr, can_reuse, names_with_path): """ When doing an exclude against any kind of N-to-many relation, we need to use a subquery. This method constructs the nested query, given the original exclude filter (filter_expr) and the portion up to the first N-to-many relation field. For example, if the origin filter is ~Q(child__name='foo'), filter_expr is ('child__name', 'foo') and can_reuse is a set of joins usable for filters in the original query. We will turn this into equivalent of: WHERE NOT EXISTS( SELECT 1 FROM child WHERE name = 'foo' AND child.parent_id = parent.id LIMIT 1 ) """ # Generate the inner query. query = self.__class__(self.model) query._filtered_relations = self._filtered_relations filter_lhs, filter_rhs = filter_expr if isinstance(filter_rhs, OuterRef): filter_rhs = OuterRef(filter_rhs) elif isinstance(filter_rhs, F): filter_rhs = OuterRef(filter_rhs.name) query.add_filter(filter_lhs, filter_rhs) query.clear_ordering(force=True) # Try to have as simple as possible subquery -> trim leading joins from # the subquery. trimmed_prefix, contains_louter = query.trim_start(names_with_path) col = query.select[0] select_field = col.target alias = col.alias if alias in can_reuse: pk = select_field.model._meta.pk # Need to add a restriction so that outer query's filters are in effect for # the subquery, too. query.bump_prefix(self) lookup_class = select_field.get_lookup("exact") # Note that the query.select[0].alias is different from alias # due to bump_prefix above. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias)) query.where.add(lookup, AND) query.external_aliases[alias] = True lookup_class = select_field.get_lookup("exact") lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix)) query.where.add(lookup, AND) condition, needed_inner = self.build_filter(Exists(query)) if contains_louter: or_null_condition, _ = self.build_filter( ("%s__isnull" % trimmed_prefix, True), current_negated=True, branch_negated=True, can_reuse=can_reuse, ) condition.add(or_null_condition, OR) # Note that the end result will be: # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL. # This might look crazy but due to how IN works, this seems to be # correct. If the IS NOT NULL check is removed then outercol NOT # IN will return UNKNOWN. If the IS NULL check is removed, then if # outercol IS NULL we will not match the row. return condition, needed_inner def set_empty(self): self.where.add(NothingNode(), AND) for query in self.combined_queries: query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children) def set_limits(self, low=None, high=None): """ Adjust the limits on the rows retrieved. Use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, convert them to the appropriate offset and limit values. Apply any limits passed in here to the existing constraints. Add low to the current low value and clamp both to any existing high value. """ if high is not None: if self.high_mark is not None: self.high_mark = min(self.high_mark, self.low_mark + high) else: self.high_mark = self.low_mark + high if low is not None: if self.high_mark is not None: self.low_mark = min(self.high_mark, self.low_mark + low) else: self.low_mark = self.low_mark + low if self.low_mark == self.high_mark: self.set_empty() def clear_limits(self): """Clear any existing limits.""" self.low_mark, self.high_mark = 0, None @property def is_sliced(self): return self.low_mark != 0 or self.high_mark is not None def has_limit_one(self): return self.high_mark is not None and (self.high_mark - self.low_mark) == 1 def can_filter(self): """ Return True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results. """ return not self.is_sliced def clear_select_clause(self): """Remove all fields from SELECT clause.""" self.select = () self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_annotation_mask(()) def clear_select_fields(self): """ Clear the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns. """ self.select = () self.values_select = () def add_select_col(self, col, name): self.select += (col,) self.values_select += (name,) def set_select(self, cols): self.default_cols = False self.select = tuple(cols) def add_distinct_fields(self, *field_names): """ Add and resolve the given fields to the query's "distinct on" clause. """ self.distinct_fields = field_names self.distinct = True def add_fields(self, field_names, allow_m2m=True): """ Add the given (model) fields to the select set. Add the field names in the order specified. """ alias = self.get_initial_alias() opts = self.get_meta() try: cols = [] for name in field_names: # Join promotion note - we must not remove any rows here, so # if there is no existing joins, use outer join. join_info = self.setup_joins( name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m ) targets, final_alias, joins = self.trim_joins( join_info.targets, join_info.joins, join_info.path, ) for target in targets: cols.append(join_info.transform_function(target, final_alias)) if cols: self.set_select(cols) except MultiJoin: raise FieldError("Invalid field name: '%s'" % name) except FieldError: if LOOKUP_SEP in name: # For lookups spanning over relationships, show the error # from the model on which the lookup failed. raise elif name in self.annotations: raise FieldError( "Cannot select the '%s' alias. Use annotate() to promote " "it." % name ) else: names = sorted( [ *get_field_names_from_opts(opts), *self.extra, *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names)) ) def add_ordering(self, *ordering): """ Add items from the 'ordering' sequence to the query's "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix ('-' or '?') -- or OrderBy expressions. If 'ordering' is empty, clear all ordering from the query. """ errors = [] for item in ordering: if isinstance(item, str): if item == "?": continue if item.startswith("-"): item = item[1:] if item in self.annotations: continue if self.extra and item in self.extra: continue # names_to_path() validates the lookup. A descriptive # FieldError will be raise if it's not. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) elif not hasattr(item, "resolve_expression"): errors.append(item) if getattr(item, "contains_aggregate", False): raise FieldError( "Using an aggregate in order_by() without also including " "it in annotate() is not allowed: %s" % item ) if errors: raise FieldError("Invalid order_by arguments: %s" % errors) if ordering: self.order_by += ordering else: self.default_ordering = False def clear_ordering(self, force=False, clear_default=True): """ Remove any ordering settings if the current query allows it without side effects, set 'force' to True to clear the ordering regardless. If 'clear_default' is True, there will be no ordering in the resulting query (not even the model's default). """ if not force and ( self.is_sliced or self.distinct_fields or self.select_for_update ): return self.order_by = () self.extra_order_by = () if clear_default: self.default_ordering = False def set_group_by(self, allow_aliases=True): """ Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made automatically. """ # Column names from JOINs to check collisions with aliases. if allow_aliases: column_names = set() seen_models = set() for join in list(self.alias_map.values())[1:]: # Skip base table. model = join.join_field.related_model if model not in seen_models: column_names.update( {field.column for field in model._meta.local_concrete_fields} ) seen_models.add(model) group_by = list(self.select) if self.annotation_select: for alias, annotation in self.annotation_select.items(): if not allow_aliases or alias in column_names: alias = None group_by_cols = annotation.get_group_by_cols(alias=alias) group_by.extend(group_by_cols) self.group_by = tuple(group_by) def add_select_related(self, fields): """ Set up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True). """ if isinstance(self.select_related, bool): field_dict = {} else: field_dict = self.select_related for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict def add_extra(self, select, select_params, where, params, tables, order_by): """ Add data to the various extra_* attributes for user-created additions to the query. """ if select: # We need to pair any placeholder markers in the 'select' # dictionary with their parameters in 'select_params' so that # subsequent updates to the select dictionary also adjust the # parameters appropriately. select_pairs = {} if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s") while pos != -1: if pos == 0 or entry[pos - 1] != "%": entry_params.append(next(param_iter)) pos = entry.find("%s", pos + 2) select_pairs[name] = (entry, entry_params) self.extra.update(select_pairs) if where or params: self.where.add(ExtraWhere(where, params), AND) if tables: self.extra_tables += tuple(tables) if order_by: self.extra_order_by = order_by def clear_deferred_loading(self): """Remove any fields from the deferred loading set.""" self.deferred_loading = (frozenset(), True) def add_deferred_loading(self, field_names): """ Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. Add the new field names to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading). """ # Fields on related models are stored in the literal double-underscore # format, so that we can use a set datastructure. We do the foo__bar # splitting and handling when computing the SQL column names (as part of # get_columns()). existing, defer = self.deferred_loading if defer: # Add to existing deferred names. self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. if new_existing := existing.difference(field_names): self.deferred_loading = new_existing, False else: self.clear_deferred_loading() if new_only := set(field_names).difference(existing): self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """ Add the given list of model field names to the set of fields to retrieve when the SQL is executed ("immediate loading" fields). The field names replace any existing immediate loading field names. If there are field names already specified for deferred loading, remove those names from the new field_names before storing the new names for immediate loading. (That is, immediate loading overrides any existing immediate values, but respects existing deferrals.) """ existing, defer = self.deferred_loading field_names = set(field_names) if "pk" in field_names: field_names.remove("pk") field_names.add(self.get_meta().pk.name) if defer: # Remove any existing deferred names from the current set before # setting the new names. self.deferred_loading = field_names.difference(existing), False else: # Replace any existing "immediate load" field names. self.deferred_loading = frozenset(field_names), False def set_annotation_mask(self, names): """Set the mask of annotations that will be returned by the SELECT.""" if names is None: self.annotation_select_mask = None else: self.annotation_select_mask = set(names) self._annotation_select_cache = None def append_annotation_mask(self, names): if self.annotation_select_mask is not None: self.set_annotation_mask(self.annotation_select_mask.union(names)) def set_extra_mask(self, names): """ Set the mask of extra select items that will be returned by SELECT. Don't remove them from the Query since they might be used later. """ if names is None: self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None def set_values(self, fields): self.select_related = False self.clear_deferred_loading() self.clear_select_fields() if fields: field_names = [] extra_names = [] annotation_names = [] if not self.extra and not self.annotations: # Shortcut - if there are no extra or annotations, then # the values() clause must be just field names. field_names = list(fields) else: self.default_cols = False for f in fields: if f in self.extra_select: extra_names.append(f) elif f in self.annotation_select: annotation_names.append(f) else: field_names.append(f) self.set_extra_mask(extra_names) self.set_annotation_mask(annotation_names) selected = frozenset(field_names + extra_names + annotation_names) else: field_names = [f.attname for f in self.model._meta.concrete_fields] selected = frozenset(field_names) # Selected annotations must be known before setting the GROUP BY # clause. if self.group_by is True: self.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() elif self.group_by: # Resolve GROUP BY annotation references if they are not part of # the selected fields anymore. group_by = [] for expr in self.group_by: if isinstance(expr, Ref) and expr.refs not in selected: expr = self.annotations[expr.refs] group_by.append(expr) self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) @property def annotation_select(self): """ Return the dictionary of aggregate columns that are not masked and should be used in the SELECT clause. Cache this result for performance. """ if self._annotation_select_cache is not None: return self._annotation_select_cache elif not self.annotations: return {} elif self.annotation_select_mask is not None: self._annotation_select_cache = { k: v for k, v in self.annotations.items() if k in self.annotation_select_mask } return self._annotation_select_cache else: return self.annotations @property def extra_select(self): if self._extra_select_cache is not None: return self._extra_select_cache if not self.extra: return {} elif self.extra_select_mask is not None: self._extra_select_cache = { k: v for k, v in self.extra.items() if k in self.extra_select_mask } return self._extra_select_cache else: return self.extra def trim_start(self, names_with_path): """ Trim joins from the start of the join path. The candidates for trim are the PathInfos in names_with_path structure that are m2m joins. Also set the select column so the start matches the join. This method is meant to be used for generating the subquery joins & cols in split_exclude(). Return a lookup usable for doing outerq.filter(lookup=self) and a boolean indicating if the joins in the prefix contain a LEFT OUTER join. _""" all_paths = [] for _, paths in names_with_path: all_paths.extend(paths) contains_louter = False # Trim and operate only on tables that were generated for # the lookup part of the query. That is, avoid trimming # joins generated for F() expressions. lookup_tables = [ t for t in self.alias_map if t in self._lookup_joins or t == self.base_table ] for trimmed_paths, path in enumerate(all_paths): if path.m2m: break if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER: contains_louter = True alias = lookup_tables[trimmed_paths] self.unref_alias(alias) # The path.join_field is a Rel, lets get the other side's field join_field = path.join_field.field # Build the filter prefix. paths_in_prefix = trimmed_paths trimmed_prefix = [] for name, path in names_with_path: if paths_in_prefix - len(path) < 0: break trimmed_prefix.append(name) paths_in_prefix -= len(path) trimmed_prefix.append(join_field.foreign_related_fields[0].name) trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix) # Lets still see if we can trim the first join from the inner query # (that is, self). We can't do this for: # - LEFT JOINs because we would miss those rows that have nothing on # the outer side, # - INNER JOINs from filtered relations because we would miss their # filters. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]] if first_join.join_type != LOUTER and not first_join.filtered_relation: select_fields = [r[0] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths + 1] self.unref_alias(lookup_tables[trimmed_paths]) extra_restriction = join_field.get_extra_restriction( None, lookup_tables[trimmed_paths + 1] ) if extra_restriction: self.where.add(extra_restriction, AND) else: # TODO: It might be possible to trim more joins from the start of the # inner query if it happens to have a longer join chain containing the # values in select_fields. Lets punt this one for now. select_fields = [r[1] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths] # The found starting point is likely a join_class instead of a # base_table_class reference. But the first entry in the query's FROM # clause must not be a JOIN. for table in self.alias_map: if self.alias_refcount[table] > 0: self.alias_map[table] = self.base_table_class( self.alias_map[table].table_name, table, ) break self.set_select([f.get_col(select_alias) for f in select_fields]) return trimmed_prefix, contains_louter def is_nullable(self, field): """ Check if the given field should be treated as nullable. Some backends treat '' as null and Django treats such fields as nullable for those backends. In such situations field.null can be False even if we should treat the field as nullable. """ # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have # (nor should it have) knowledge of which connection is going to be # used. The proper fix would be to defer all decisions where # is_nullable() is needed to the compiler stage, but that is not easy # to do currently. return field.null or ( field.empty_strings_allowed and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ) def get_order_dir(field, default="ASC"): """ Return the field name and direction for an order specification. For example, '-foo' is returned as ('foo', 'DESC'). The 'default' param is used to indicate which way no prefix (or a '+' prefix) should sort. The '-' prefix always sorts the opposite way. """ dirn = ORDER_DIR[default] if field[0] == "-": return field[1:], dirn[1] return field, dirn[0] def add_to_dict(data, key, value): """ Add "value" to the set of values for "key", whether or not "key" already exists. """ if key in data: data[key].add(value) else: data[key] = {value} def is_reverse_o2o(field): """ Check if the given field is reverse-o2o. The field is expected to be some sort of relation field or related object. """ return field.is_relation and field.one_to_one and not field.concrete class JoinPromoter: """ A class to abstract away join promotion problems for complex filter conditions. """ def __init__(self, connector, num_children, negated): self.connector = connector self.negated = negated if self.negated: if connector == AND: self.effective_connector = OR else: self.effective_connector = AND else: self.effective_connector = self.connector self.num_children = num_children # Maps of table alias to how many times it is seen as required for # inner and/or outer joins. self.votes = Counter() def __repr__(self): return ( f"{self.__class__.__qualname__}(connector={self.connector!r}, " f"num_children={self.num_children!r}, negated={self.negated!r})" ) def add_votes(self, votes): """ Add single vote per item to self.votes. Parameter can be any iterable. """ self.votes.update(votes) def update_join_types(self, query): """ Change join types so that the generated query is as efficient as possible, but still correct. So, change as many joins as possible to INNER, but don't make OUTER joins INNER if that could remove results from the query. """ to_promote = set() to_demote = set() # The effective_connector is used so that NOT (a AND b) is treated # similarly to (a OR b) for join promotion. for table, votes in self.votes.items(): # We must use outer joins in OR case when the join isn't contained # in all of the joins. Otherwise the INNER JOIN itself could remove # valid results. Consider the case where a model with rel_a and # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now, # if rel_a join doesn't produce any results is null (for example # reverse foreign key or null value in direct foreign key), and # there is a matching row in rel_b with col=2, then an INNER join # to rel_a would remove a valid match from the query. So, we need # to promote any existing INNER to LOUTER (it is possible this # promotion in turn will be demoted later on). if self.effective_connector == "OR" and votes < self.num_children: to_promote.add(table) # If connector is AND and there is a filter that can match only # when there is a joinable row, then use INNER. For example, in # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL # as join output, then the col=1 or col=2 can't match (as # NULL=anything is always false). # For the OR case, if all children voted for a join to be inner, # then we can use INNER for the join. For example: # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell) # then if rel_a doesn't produce any rows, the whole condition # can't match. Hence we can safely use INNER join. if self.effective_connector == "AND" or ( self.effective_connector == "OR" and votes == self.num_children ): to_demote.add(table) # Finally, what happens in cases where we have: # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0 # Now, we first generate the OR clause, and promote joins for it # in the first if branch above. Both rel_a and rel_b are promoted # to LOUTER joins. After that we do the AND case. The OR case # voted no inner joins but the rel_a__col__gte=0 votes inner join # for rel_a. We demote it back to INNER join (in AND case a single # vote is enough). The demotion is OK, if rel_a doesn't produce # rows, then the rel_a__col__gte=0 clause can't be true, and thus # the whole clause must be false. So, it is safe to use INNER # join. # Note that in this example we could just as well have the __gte # clause and the OR clause swapped. Or we could replace the __gte # clause with an OR clause containing rel_a__col=1|rel_a__col=2, # and again we could safely demote to INNER. query.promote_joins(to_promote) query.demote_joins(to_demote) return to_demote
c2262ff1c5cb6019f83429ee855fe360fb9632ad13b3d2e58c0d76bdd71c56fe
import datetime import uuid from functools import lru_cache from django.conf import settings from django.db import DatabaseError, NotSupportedError from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import split_tzname_delta, strip_quotes, truncate_name from django.db.models import AutoField, Exists, ExpressionWrapper, Lookup from django.db.models.expressions import RawSQL from django.db.models.sql.where import WhereNode from django.utils import timezone from django.utils.encoding import force_bytes, force_str from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from .base import Database from .utils import BulkInsertMapper, InsertVar, Oracle_datetime class DatabaseOperations(BaseDatabaseOperations): # Oracle uses NUMBER(5), NUMBER(11), and NUMBER(19) for integer fields. # SmallIntegerField uses NUMBER(11) instead of NUMBER(5), which is used by # SmallAutoField, to preserve backward compatibility. integer_field_ranges = { "SmallIntegerField": (-99999999999, 99999999999), "IntegerField": (-99999999999, 99999999999), "BigIntegerField": (-9999999999999999999, 9999999999999999999), "PositiveBigIntegerField": (0, 9999999999999999999), "PositiveSmallIntegerField": (0, 99999999999), "PositiveIntegerField": (0, 99999999999), "SmallAutoField": (-99999, 99999), "AutoField": (-99999999999, 99999999999), "BigAutoField": (-9999999999999999999, 9999999999999999999), } set_operators = {**BaseDatabaseOperations.set_operators, "difference": "MINUS"} # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc. _sequence_reset_sql = """ DECLARE table_value integer; seq_value integer; seq_name user_tab_identity_cols.sequence_name%%TYPE; BEGIN BEGIN SELECT sequence_name INTO seq_name FROM user_tab_identity_cols WHERE table_name = '%(table_name)s' AND column_name = '%(column_name)s'; EXCEPTION WHEN NO_DATA_FOUND THEN seq_name := '%(no_autofield_sequence_name)s'; END; SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s; SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences WHERE sequence_name = seq_name; WHILE table_value > seq_value LOOP EXECUTE IMMEDIATE 'SELECT "'||seq_name||'".nextval FROM DUAL' INTO seq_value; END LOOP; END; /""" # Oracle doesn't support string without precision; use the max string size. cast_char_field_without_max_length = "NVARCHAR2(2000)" cast_data_types = { "AutoField": "NUMBER(11)", "BigAutoField": "NUMBER(19)", "SmallAutoField": "NUMBER(5)", "TextField": cast_char_field_without_max_length, } def cache_key_culling_sql(self): cache_key = self.quote_name("cache_key") return ( f"SELECT {cache_key} " f"FROM %s " f"ORDER BY {cache_key} OFFSET %%s ROWS FETCH FIRST 1 ROWS ONLY" ) # EXTRACT format cannot be passed in parameters. _extract_format_re = _lazy_re_compile(r"[A-Z_]+") def date_extract_sql(self, lookup_type, sql, params): extract_sql = f"TO_CHAR({sql}, %s)" extract_param = None if lookup_type == "week_day": # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday. extract_param = "D" elif lookup_type == "iso_week_day": extract_sql = f"TO_CHAR({sql} - 1, %s)" extract_param = "D" elif lookup_type == "week": # IW = ISO week number extract_param = "IW" elif lookup_type == "quarter": extract_param = "Q" elif lookup_type == "iso_year": extract_param = "IYYY" else: lookup_type = lookup_type.upper() if not self._extract_format_re.fullmatch(lookup_type): raise ValueError(f"Invalid loookup type: {lookup_type!r}") # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/EXTRACT-datetime.html return f"EXTRACT({lookup_type} FROM {sql})", params return extract_sql, (*params, extract_param) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html trunc_param = None if lookup_type in ("year", "month"): trunc_param = lookup_type.upper() elif lookup_type == "quarter": trunc_param = "Q" elif lookup_type == "week": trunc_param = "IW" else: return f"TRUNC({sql})", params return f"TRUNC({sql}, %s)", (*params, trunc_param) # Oracle crashes with "ORA-03113: end-of-file on communication channel" # if the time zone name is passed in parameter. Use interpolation instead. # https://groups.google.com/forum/#!msg/django-developers/zwQju7hbG78/9l934yelwfsJ # This regexp matches all time zone names from the zoneinfo database. _tzname_re = _lazy_re_compile(r"^[\w/:+-]+$") def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if not (settings.USE_TZ and tzname): return sql, params if not self._tzname_re.match(tzname): raise ValueError("Invalid time zone name: %s" % tzname) # Convert from connection timezone to the local time, returning # TIMESTAMP WITH TIME ZONE and cast it back to TIMESTAMP to strip the # TIME ZONE details. if self.connection.timezone_name != tzname: from_timezone_name = self.connection.timezone_name to_timezone_name = self._prepare_tzname_delta(tzname) return ( f"CAST((FROM_TZ({sql}, '{from_timezone_name}') AT TIME ZONE " f"'{to_timezone_name}') AS TIMESTAMP)", params, ) return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"TRUNC({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): # Since `TimeField` values are stored as TIMESTAMP change to the # default date and convert the field to the specified timezone. sql, params = self._convert_sql_to_tz(sql, params, tzname) convert_datetime_sql = ( f"TO_TIMESTAMP(CONCAT('1900-01-01 ', TO_CHAR({sql}, 'HH24:MI:SS.FF')), " f"'YYYY-MM-DD HH24:MI:SS.FF')" ) return ( f"CASE WHEN {sql} IS NOT NULL THEN {convert_datetime_sql} ELSE NULL END", (*params, *params), ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html trunc_param = None if lookup_type in ("year", "month"): trunc_param = lookup_type.upper() elif lookup_type == "quarter": trunc_param = "Q" elif lookup_type == "week": trunc_param = "IW" elif lookup_type == "hour": trunc_param = "HH24" elif lookup_type == "minute": trunc_param = "MI" elif lookup_type == "day": return f"TRUNC({sql})", params else: # Cast to DATE removes sub-second precision. return f"CAST({sql} AS DATE)", params return f"TRUNC({sql}, %s)", (*params, trunc_param) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): # The implementation is similar to `datetime_trunc_sql` as both # `DateTimeField` and `TimeField` are stored as TIMESTAMP where # the date part of the later is ignored. sql, params = self._convert_sql_to_tz(sql, params, tzname) trunc_param = None if lookup_type == "hour": trunc_param = "HH24" elif lookup_type == "minute": trunc_param = "MI" elif lookup_type == "second": # Cast to DATE removes sub-second precision. return f"CAST({sql} AS DATE)", params return f"TRUNC({sql}, %s)", (*params, trunc_param) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type in ["JSONField", "TextField"]: converters.append(self.convert_textfield_value) elif internal_type == "BinaryField": converters.append(self.convert_binaryfield_value) elif internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) elif internal_type == "DateTimeField": if settings.USE_TZ: converters.append(self.convert_datetimefield_value) elif internal_type == "DateField": converters.append(self.convert_datefield_value) elif internal_type == "TimeField": converters.append(self.convert_timefield_value) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) # Oracle stores empty strings as null. If the field accepts the empty # string, undo this to adhere to the Django convention of using # the empty string instead of null. if expression.output_field.empty_strings_allowed: converters.append( self.convert_empty_bytes if internal_type == "BinaryField" else self.convert_empty_string ) return converters def convert_textfield_value(self, value, expression, connection): if isinstance(value, Database.LOB): value = value.read() return value def convert_binaryfield_value(self, value, expression, connection): if isinstance(value, Database.LOB): value = force_bytes(value.read()) return value def convert_booleanfield_value(self, value, expression, connection): if value in (0, 1): value = bool(value) return value # cx_Oracle always returns datetime.datetime objects for # DATE and TIMESTAMP columns, but Django wants to see a # python datetime.date, .time, or .datetime. def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) return value def convert_datefield_value(self, value, expression, connection): if isinstance(value, Database.Timestamp): value = value.date() return value def convert_timefield_value(self, value, expression, connection): if isinstance(value, Database.Timestamp): value = value.time() return value def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value @staticmethod def convert_empty_string(value, expression, connection): return "" if value is None else value @staticmethod def convert_empty_bytes(value, expression, connection): return b"" if value is None else value def deferrable_sql(self): return " DEFERRABLE INITIALLY DEFERRED" def fetch_returned_insert_columns(self, cursor, returning_params): columns = [] for param in returning_params: value = param.get_value() if value == []: raise DatabaseError( "The database did not return a new row id. Probably " '"ORA-1403: no data found" was raised internally but was ' "hidden by the Oracle OCI library (see " "https://code.djangoproject.com/ticket/28859)." ) columns.append(value[0]) return tuple(columns) def field_cast_sql(self, db_type, internal_type): if db_type and db_type.endswith("LOB") and internal_type != "JSONField": return "DBMS_LOB.SUBSTR(%s)" else: return "%s" def no_limit_value(self): return None def limit_offset_sql(self, low_mark, high_mark): fetch, offset = self._get_limit_offset_params(low_mark, high_mark) return " ".join( sql for sql in ( ("OFFSET %d ROWS" % offset) if offset else None, ("FETCH FIRST %d ROWS ONLY" % fetch) if fetch else None, ) if sql ) def last_executed_query(self, cursor, sql, params): # https://cx-oracle.readthedocs.io/en/latest/api_manual/cursor.html#Cursor.statement # The DB API definition does not define this attribute. statement = cursor.statement # Unlike Psycopg's `query` and MySQLdb`'s `_executed`, cx_Oracle's # `statement` doesn't contain the query parameters. Substitute # parameters manually. if isinstance(params, (tuple, list)): for i, param in enumerate(reversed(params), start=1): param_num = len(params) - i statement = statement.replace( ":arg%d" % param_num, force_str(param, errors="replace") ) elif isinstance(params, dict): for key in sorted(params, key=len, reverse=True): statement = statement.replace( ":%s" % key, force_str(params[key], errors="replace") ) return statement def last_insert_id(self, cursor, table_name, pk_name): sq_name = self._get_sequence_name(cursor, strip_quotes(table_name), pk_name) cursor.execute('"%s".currval' % sq_name) return cursor.fetchone()[0] def lookup_cast(self, lookup_type, internal_type=None): if lookup_type in ("iexact", "icontains", "istartswith", "iendswith"): return "UPPER(%s)" if internal_type == "JSONField" and lookup_type == "exact": return "DBMS_LOB.SUBSTR(%s)" return "%s" def max_in_list_size(self): return 1000 def max_name_length(self): return 30 def pk_default_value(self): return "NULL" def prep_for_iexact_query(self, x): return x def process_clob(self, value): if value is None: return "" return value.read() def quote_name(self, name): # SQL92 requires delimited (quoted) names to be case-sensitive. When # not quoted, Oracle has case-insensitive behavior for identifiers, but # always defaults to uppercase. # We simplify things by making Oracle identifiers always uppercase. if not name.startswith('"') and not name.endswith('"'): name = '"%s"' % truncate_name(name, self.max_name_length()) # Oracle puts the query text into a (query % args) construct, so % signs # in names need to be escaped. The '%%' will be collapsed back to '%' at # that stage so we aren't really making the name longer here. name = name.replace("%", "%%") return name.upper() def regex_lookup(self, lookup_type): if lookup_type == "regex": match_option = "'c'" else: match_option = "'i'" return "REGEXP_LIKE(%%s, %%s, %s)" % match_option def return_insert_columns(self, fields): if not fields: return "", () field_names = [] params = [] for field in fields: field_names.append( "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) ) params.append(InsertVar(field)) return "RETURNING %s INTO %s" % ( ", ".join(field_names), ", ".join(["%s"] * len(params)), ), tuple(params) def __foreign_key_constraints(self, table_name, recursive): with self.connection.cursor() as cursor: if recursive: cursor.execute( """ SELECT user_tables.table_name, rcons.constraint_name FROM user_tables JOIN user_constraints cons ON (user_tables.table_name = cons.table_name AND cons.constraint_type = ANY('P', 'U')) LEFT JOIN user_constraints rcons ON (user_tables.table_name = rcons.table_name AND rcons.constraint_type = 'R') START WITH user_tables.table_name = UPPER(%s) CONNECT BY NOCYCLE PRIOR cons.constraint_name = rcons.r_constraint_name GROUP BY user_tables.table_name, rcons.constraint_name HAVING user_tables.table_name != UPPER(%s) ORDER BY MAX(level) DESC """, (table_name, table_name), ) else: cursor.execute( """ SELECT cons.table_name, cons.constraint_name FROM user_constraints cons WHERE cons.constraint_type = 'R' AND cons.table_name = UPPER(%s) """, (table_name,), ) return cursor.fetchall() @cached_property def _foreign_key_constraints(self): # 512 is large enough to fit the ~330 tables (as of this writing) in # Django's test suite. return lru_cache(maxsize=512)(self.__foreign_key_constraints) def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] truncated_tables = {table.upper() for table in tables} constraints = set() # Oracle's TRUNCATE CASCADE only works with ON DELETE CASCADE foreign # keys which Django doesn't define. Emulate the PostgreSQL behavior # which truncates all dependent tables by manually retrieving all # foreign key constraints and resolving dependencies. for table in tables: for foreign_table, constraint in self._foreign_key_constraints( table, recursive=allow_cascade ): if allow_cascade: truncated_tables.add(foreign_table) constraints.add((foreign_table, constraint)) sql = ( [ "%s %s %s %s %s %s %s %s;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(table)), style.SQL_KEYWORD("DISABLE"), style.SQL_KEYWORD("CONSTRAINT"), style.SQL_FIELD(self.quote_name(constraint)), style.SQL_KEYWORD("KEEP"), style.SQL_KEYWORD("INDEX"), ) for table, constraint in constraints ] + [ "%s %s %s;" % ( style.SQL_KEYWORD("TRUNCATE"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(table)), ) for table in truncated_tables ] + [ "%s %s %s %s %s %s;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(table)), style.SQL_KEYWORD("ENABLE"), style.SQL_KEYWORD("CONSTRAINT"), style.SQL_FIELD(self.quote_name(constraint)), ) for table, constraint in constraints ] ) if reset_sequences: sequences = [ sequence for sequence in self.connection.introspection.sequence_list() if sequence["table"].upper() in truncated_tables ] # Since we've just deleted all the rows, running our sequence ALTER # code will reset the sequence to 0. sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql def sequence_reset_by_name_sql(self, style, sequences): sql = [] for sequence_info in sequences: no_autofield_sequence_name = self._get_no_autofield_sequence_name( sequence_info["table"] ) table = self.quote_name(sequence_info["table"]) column = self.quote_name(sequence_info["column"] or "id") query = self._sequence_reset_sql % { "no_autofield_sequence_name": no_autofield_sequence_name, "table": table, "column": column, "table_name": strip_quotes(table), "column_name": strip_quotes(column), } sql.append(query) return sql def sequence_reset_sql(self, style, model_list): output = [] query = self._sequence_reset_sql for model in model_list: for f in model._meta.local_fields: if isinstance(f, AutoField): no_autofield_sequence_name = self._get_no_autofield_sequence_name( model._meta.db_table ) table = self.quote_name(model._meta.db_table) column = self.quote_name(f.column) output.append( query % { "no_autofield_sequence_name": no_autofield_sequence_name, "table": table, "column": column, "table_name": strip_quotes(table), "column_name": strip_quotes(column), } ) # Only one AutoField is allowed per model, so don't # continue to loop break return output def start_transaction_sql(self): return "" def tablespace_sql(self, tablespace, inline=False): if inline: return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace) else: return "TABLESPACE %s" % self.quote_name(tablespace) def adapt_datefield_value(self, value): """ Transform a date value to an object compatible with what is expected by the backend driver for date columns. The default implementation transforms the date to text, but that is not necessary for Oracle. """ return value def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. If naive datetime is passed assumes that is in UTC. Normally Django models.DateTimeField makes sure that if USE_TZ is True passed datetime is timezone aware. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # cx_Oracle doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "Oracle backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return Oracle_datetime.from_datetime(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value if isinstance(value, str): return datetime.datetime.strptime(value, "%H:%M:%S") # Oracle doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("Oracle backend does not support timezone-aware times.") return Oracle_datetime( 1900, 1, 1, value.hour, value.minute, value.second, value.microsecond ) def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): return value def combine_expression(self, connector, sub_expressions): lhs, rhs = sub_expressions if connector == "%%": return "MOD(%s)" % ",".join(sub_expressions) elif connector == "&": return "BITAND(%s)" % ",".join(sub_expressions) elif connector == "|": return "BITAND(-%(lhs)s-1,%(rhs)s)+%(lhs)s" % {"lhs": lhs, "rhs": rhs} elif connector == "<<": return "(%(lhs)s * POWER(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} elif connector == ">>": return "FLOOR(%(lhs)s / POWER(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} elif connector == "^": return "POWER(%s)" % ",".join(sub_expressions) elif connector == "#": raise NotSupportedError("Bitwise XOR is not supported in Oracle.") return super().combine_expression(connector, sub_expressions) def _get_no_autofield_sequence_name(self, table): """ Manually created sequence name to keep backward compatibility for AutoFields that aren't Oracle identity columns. """ name_length = self.max_name_length() - 3 return "%s_SQ" % truncate_name(strip_quotes(table), name_length).upper() def _get_sequence_name(self, cursor, table, pk_name): cursor.execute( """ SELECT sequence_name FROM user_tab_identity_cols WHERE table_name = UPPER(%s) AND column_name = UPPER(%s)""", [table, pk_name], ) row = cursor.fetchone() return self._get_no_autofield_sequence_name(table) if row is None else row[0] def bulk_insert_sql(self, fields, placeholder_rows): query = [] for row in placeholder_rows: select = [] for i, placeholder in enumerate(row): # A model without any fields has fields=[None]. if fields[i]: internal_type = getattr( fields[i], "target_field", fields[i] ).get_internal_type() placeholder = ( BulkInsertMapper.types.get(internal_type, "%s") % placeholder ) # Add columns aliases to the first select to avoid "ORA-00918: # column ambiguously defined" when two or more columns in the # first select have the same value. if not query: placeholder = "%s col_%s" % (placeholder, i) select.append(placeholder) query.append("SELECT %s FROM DUAL" % ", ".join(select)) # Bulk insert to tables with Oracle identity columns causes Oracle to # add sequence.nextval to it. Sequence.nextval cannot be used with the # UNION operator. To prevent incorrect SQL, move UNION to a subquery. return "SELECT * FROM (%s)" % " UNION ALL ".join(query) def subtract_temporals(self, internal_type, lhs, rhs): if internal_type == "DateField": lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) return ( "NUMTODSINTERVAL(TO_NUMBER(%s - %s), 'DAY')" % (lhs_sql, rhs_sql), params, ) return super().subtract_temporals(internal_type, lhs, rhs) def bulk_batch_size(self, fields, objs): """Oracle restricts the number of parameters in a query.""" if fields: return self.connection.features.max_query_params // len(fields) return len(objs) def conditional_expression_supported_in_where_clause(self, expression): """ Oracle supports only EXISTS(...) or filters in the WHERE clause, others must be compared with True. """ if isinstance(expression, (Exists, Lookup, WhereNode)): return True if isinstance(expression, ExpressionWrapper) and expression.conditional: return self.conditional_expression_supported_in_where_clause( expression.expression ) if isinstance(expression, RawSQL) and expression.conditional: return True return False
3c6322f341434385537fd99eb599018da3a6d93bae02a8740dc259158926e5d3
import datetime import decimal from importlib import import_module import sqlparse from django.conf import settings from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str class BaseDatabaseOperations: """ Encapsulate backend-specific differences, such as the way a backend performs ordering or calculates the ID of a recently-inserted row. """ compiler_module = "django.db.models.sql.compiler" # Integer field safe ranges by `internal_type` as documented # in docs/ref/models/fields.txt. integer_field_ranges = { "SmallIntegerField": (-32768, 32767), "IntegerField": (-2147483648, 2147483647), "BigIntegerField": (-9223372036854775808, 9223372036854775807), "PositiveBigIntegerField": (0, 9223372036854775807), "PositiveSmallIntegerField": (0, 32767), "PositiveIntegerField": (0, 2147483647), "SmallAutoField": (-32768, 32767), "AutoField": (-2147483648, 2147483647), "BigAutoField": (-9223372036854775808, 9223372036854775807), } set_operators = { "union": "UNION", "intersection": "INTERSECT", "difference": "EXCEPT", } # Mapping of Field.get_internal_type() (typically the model field's class # name) to the data type to use for the Cast() function, if different from # DatabaseWrapper.data_types. cast_data_types = {} # CharField data type if the max_length argument isn't provided. cast_char_field_without_max_length = None # Start and end points for window expressions. PRECEDING = "PRECEDING" FOLLOWING = "FOLLOWING" UNBOUNDED_PRECEDING = "UNBOUNDED " + PRECEDING UNBOUNDED_FOLLOWING = "UNBOUNDED " + FOLLOWING CURRENT_ROW = "CURRENT ROW" # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None def __init__(self, connection): self.connection = connection self._cache = None def autoinc_sql(self, table, column): """ Return any SQL needed to support auto-incrementing primary keys, or None if no SQL is necessary. This SQL is executed when a table is created. """ return None def bulk_batch_size(self, fields, objs): """ Return the maximum allowed batch size for the backend. The fields are the fields going to be inserted in the batch, the objs contains all the objects to be inserted. """ return len(objs) def format_for_duration_arithmetic(self, sql): raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a " "format_for_duration_arithmetic() method." ) def cache_key_culling_sql(self): """ Return an SQL query that retrieves the first cache key greater than the n smallest. This is used by the 'db' cache backend to determine where to start culling. """ cache_key = self.quote_name("cache_key") return f"SELECT {cache_key} FROM %s ORDER BY {cache_key} LIMIT 1 OFFSET %%s" def unification_cast_sql(self, output_field): """ Given a field instance, return the SQL that casts the result of a union to that type. The resulting string should contain a '%s' placeholder for the expression being cast. """ return "%s" def date_extract_sql(self, lookup_type, sql, params): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that extracts a value from the given date field field_name. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a date_extract_sql() " "method" ) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that truncates the given date or datetime field field_name to a date object with only the given specificity. If `tzname` is provided, the given value is truncated in a specific timezone. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a date_trunc_sql() " "method." ) def datetime_cast_date_sql(self, sql, params, tzname): """ Return the SQL to cast a datetime value to date value. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a " "datetime_cast_date_sql() method." ) def datetime_cast_time_sql(self, sql, params, tzname): """ Return the SQL to cast a datetime value to time value. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a " "datetime_cast_time_sql() method" ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that extracts a value from the given datetime field field_name. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a datetime_extract_sql() " "method" ) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that truncates the given datetime field field_name to a datetime object with only the given specificity. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() " "method" ) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): """ Given a lookup_type of 'hour', 'minute' or 'second', return the SQL that truncates the given time or datetime field field_name to a time object with only the given specificity. If `tzname` is provided, the given value is truncated in a specific timezone. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a time_trunc_sql() method" ) def time_extract_sql(self, lookup_type, sql, params): """ Given a lookup_type of 'hour', 'minute', or 'second', return the SQL that extracts a value from the given time field field_name. """ return self.date_extract_sql(lookup_type, sql, params) def deferrable_sql(self): """ Return the SQL to make a constraint "initially deferred" during a CREATE TABLE statement. """ return "" def distinct_sql(self, fields, params): """ Return an SQL DISTINCT clause which removes duplicate rows from the result set. If any fields are given, only check the given fields for duplicates. """ if fields: raise NotSupportedError( "DISTINCT ON fields is not supported by this database backend" ) else: return ["DISTINCT"], [] def fetch_returned_insert_columns(self, cursor, returning_params): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the newly created data. """ return cursor.fetchone() def field_cast_sql(self, db_type, internal_type): """ Given a column type (e.g. 'BLOB', 'VARCHAR') and an internal type (e.g. 'GenericIPAddressField'), return the SQL to cast it before using it in a WHERE statement. The resulting string should contain a '%s' placeholder for the column being searched against. """ return "%s" def force_no_ordering(self): """ Return a list used in the "ORDER BY" clause to force no ordering at all. Return an empty list to include nothing in the ordering. """ return [] def for_update_sql(self, nowait=False, skip_locked=False, of=(), no_key=False): """ Return the FOR UPDATE SQL clause to lock rows for an update operation. """ return "FOR%s UPDATE%s%s%s" % ( " NO KEY" if no_key else "", " OF %s" % ", ".join(of) if of else "", " NOWAIT" if nowait else "", " SKIP LOCKED" if skip_locked else "", ) def _get_limit_offset_params(self, low_mark, high_mark): offset = low_mark or 0 if high_mark is not None: return (high_mark - offset), offset elif offset: return self.connection.ops.no_limit_value(), offset return None, offset def limit_offset_sql(self, low_mark, high_mark): """Return LIMIT/OFFSET SQL clause.""" limit, offset = self._get_limit_offset_params(low_mark, high_mark) return " ".join( sql for sql in ( ("LIMIT %d" % limit) if limit else None, ("OFFSET %d" % offset) if offset else None, ) if sql ) def last_executed_query(self, cursor, sql, params): """ Return a string of the query last executed by the given cursor, with placeholders replaced with actual values. `sql` is the raw query containing placeholders and `params` is the sequence of parameters. These are used by default, but this method exists for database backends to provide a better implementation according to their own quoting schemes. """ # Convert params to contain string values. def to_string(s): return force_str(s, strings_only=True, errors="replace") if isinstance(params, (list, tuple)): u_params = tuple(to_string(val) for val in params) elif params is None: u_params = () else: u_params = {to_string(k): to_string(v) for k, v in params.items()} return "QUERY = %r - PARAMS = %r" % (sql, u_params) def last_insert_id(self, cursor, table_name, pk_name): """ Given a cursor object that has just performed an INSERT statement into a table that has an auto-incrementing ID, return the newly created ID. `pk_name` is the name of the primary-key column. """ return cursor.lastrowid def lookup_cast(self, lookup_type, internal_type=None): """ Return the string to use in a query when performing lookups ("contains", "like", etc.). It should contain a '%s' placeholder for the column being searched against. """ return "%s" def max_in_list_size(self): """ Return the maximum number of items that can be passed in a single 'IN' list condition, or None if the backend does not impose a limit. """ return None def max_name_length(self): """ Return the maximum length of table and column names, or None if there is no limit. """ return None def no_limit_value(self): """ Return the value to use for the LIMIT when we are wanting "LIMIT infinity". Return None if the limit clause can be omitted in this case. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a no_limit_value() method" ) def pk_default_value(self): """ Return the value to use during an INSERT statement to specify that the field should use its default value. """ return "DEFAULT" def prepare_sql_script(self, sql): """ Take an SQL script that may contain multiple lines and return a list of statements to feed to successive cursor.execute() calls. Since few databases are able to process raw SQL scripts in a single cursor.execute() call and PEP 249 doesn't talk about this use case, the default implementation is conservative. """ return [ sqlparse.format(statement, strip_comments=True) for statement in sqlparse.split(sql) if statement ] def process_clob(self, value): """ Return the value of a CLOB column, for backends that return a locator object that requires additional processing. """ return value def return_insert_columns(self, fields): """ For backends that support returning columns as part of an insert query, return the SQL and params to append to the INSERT query. The returned fragment should contain a format string to hold the appropriate column. """ pass def compiler(self, compiler_name): """ Return the SQLCompiler class corresponding to the given name, in the namespace corresponding to the `compiler_module` attribute on this backend. """ if self._cache is None: self._cache = import_module(self.compiler_module) return getattr(self._cache, compiler_name) def quote_name(self, name): """ Return a quoted version of the given table, index, or column name. Do not quote the given name if it's already been quoted. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a quote_name() method" ) def regex_lookup(self, lookup_type): """ Return the string to use in a query when performing regular expression lookups (using "regex" or "iregex"). It should contain a '%s' placeholder for the column being searched against. If the feature is not supported (or part of it is not supported), raise NotImplementedError. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations may require a regex_lookup() method" ) def savepoint_create_sql(self, sid): """ Return the SQL for starting a new savepoint. Only required if the "uses_savepoints" feature is True. The "sid" parameter is a string for the savepoint id. """ return "SAVEPOINT %s" % self.quote_name(sid) def savepoint_commit_sql(self, sid): """ Return the SQL for committing the given savepoint. """ return "RELEASE SAVEPOINT %s" % self.quote_name(sid) def savepoint_rollback_sql(self, sid): """ Return the SQL for rolling back the given savepoint. """ return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid) def set_time_zone_sql(self): """ Return the SQL that will set the connection's time zone. Return '' if the backend doesn't support time zones. """ return "" def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): """ Return a list of SQL statements required to remove all data from the given database tables (without actually removing the tables themselves). The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. If `reset_sequences` is True, the list includes SQL statements required to reset the sequences. The `allow_cascade` argument determines whether truncation may cascade to tables with foreign keys pointing the tables being truncated. PostgreSQL requires a cascade even if these tables are empty. """ raise NotImplementedError( "subclasses of BaseDatabaseOperations must provide an sql_flush() method" ) def execute_sql_flush(self, sql_list): """Execute a list of SQL statements to flush the database.""" with transaction.atomic( using=self.connection.alias, savepoint=self.connection.features.can_rollback_ddl, ): with self.connection.cursor() as cursor: for sql in sql_list: cursor.execute(sql) def sequence_reset_by_name_sql(self, style, sequences): """ Return a list of the SQL statements required to reset sequences passed in `sequences`. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. """ return [] def sequence_reset_sql(self, style, model_list): """ Return a list of the SQL statements required to reset sequences for the given models. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. """ return [] # No sequence reset required by default. def start_transaction_sql(self): """Return the SQL statement required to start a transaction.""" return "BEGIN;" def end_transaction_sql(self, success=True): """Return the SQL statement required to end a transaction.""" if not success: return "ROLLBACK;" return "COMMIT;" def tablespace_sql(self, tablespace, inline=False): """ Return the SQL that will be used in a query to define the tablespace. Return '' if the backend doesn't support tablespaces. If `inline` is True, append the SQL to a row; otherwise append it to the entire CREATE TABLE or CREATE INDEX statement. """ return "" def prep_for_like_query(self, x): """Prepare a value for use in a LIKE query.""" return str(x).replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_") # Same as prep_for_like_query(), but called for "iexact" matches, which # need not necessarily be implemented using "LIKE" in the backend. prep_for_iexact_query = prep_for_like_query def validate_autopk_value(self, value): """ Certain backends do not accept some values for "serial" fields (for example zero in MySQL). Raise a ValueError if the value is invalid, otherwise return the validated value. """ return value def adapt_unknown_value(self, value): """ Transform a value to something compatible with the backend driver. This method only depends on the type of the value. It's designed for cases where the target type isn't known, such as .raw() SQL queries. As a consequence it may not work perfectly in all circumstances. """ if isinstance(value, datetime.datetime): # must be before date return self.adapt_datetimefield_value(value) elif isinstance(value, datetime.date): return self.adapt_datefield_value(value) elif isinstance(value, datetime.time): return self.adapt_timefield_value(value) elif isinstance(value, decimal.Decimal): return self.adapt_decimalfield_value(value) else: return value def adapt_datefield_value(self, value): """ Transform a date value to an object compatible with what is expected by the backend driver for date columns. """ if value is None: return None return str(value) def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value return str(value) def adapt_timefield_value(self, value): """ Transform a time value to an object compatible with what is expected by the backend driver for time columns. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value if timezone.is_aware(value): raise ValueError("Django does not support timezone-aware times.") return str(value) def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): """ Transform a decimal.Decimal value to an object compatible with what is expected by the backend driver for decimal (numeric) columns. """ return utils.format_number(value, max_digits, decimal_places) def adapt_ipaddressfield_value(self, value): """ Transform a string representation of an IP address into the expected type for the backend driver. """ return value or None def year_lookup_bounds_for_date_field(self, value, iso_year=False): """ Return a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateField value using a year lookup. `value` is an int, containing the looked-up year. If `iso_year` is True, return bounds for ISO-8601 week-numbering years. """ if iso_year: first = datetime.date.fromisocalendar(value, 1, 1) second = datetime.date.fromisocalendar( value + 1, 1, 1 ) - datetime.timedelta(days=1) else: first = datetime.date(value, 1, 1) second = datetime.date(value, 12, 31) first = self.adapt_datefield_value(first) second = self.adapt_datefield_value(second) return [first, second] def year_lookup_bounds_for_datetime_field(self, value, iso_year=False): """ Return a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateTimeField value using a year lookup. `value` is an int, containing the looked-up year. If `iso_year` is True, return bounds for ISO-8601 week-numbering years. """ if iso_year: first = datetime.datetime.fromisocalendar(value, 1, 1) second = datetime.datetime.fromisocalendar( value + 1, 1, 1 ) - datetime.timedelta(microseconds=1) else: first = datetime.datetime(value, 1, 1) second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999) if settings.USE_TZ: tz = timezone.get_current_timezone() first = timezone.make_aware(first, tz) second = timezone.make_aware(second, tz) first = self.adapt_datetimefield_value(first) second = self.adapt_datetimefield_value(second) return [first, second] def get_db_converters(self, expression): """ Return a list of functions needed to convert field data. Some field types on some backends do not provide data in the correct format, this is the hook for converter functions. """ return [] def convert_durationfield_value(self, value, expression, connection): if value is not None: return datetime.timedelta(0, 0, value) def check_expression_support(self, expression): """ Check that the backend supports the provided expression. This is used on specific backends to rule out known expressions that have problematic or nonexistent implementations. If the expression has a known problem, the backend should raise NotSupportedError. """ pass def conditional_expression_supported_in_where_clause(self, expression): """ Return True, if the conditional expression is supported in the WHERE clause. """ return True def combine_expression(self, connector, sub_expressions): """ Combine a list of subexpressions into a single expression, using the provided connecting operator. This is required because operators can vary between backends (e.g., Oracle with %% and &) and between subexpression types (e.g., date expressions). """ conn = " %s " % connector return conn.join(sub_expressions) def combine_duration_expression(self, connector, sub_expressions): return self.combine_expression(connector, sub_expressions) def binary_placeholder_sql(self, value): """ Some backends require special syntax to insert binary content (MySQL for example uses '_binary %s'). """ return "%s" def modify_insert_params(self, placeholder, params): """ Allow modification of insert parameters. Needed for Oracle Spatial backend due to #10888. """ return params def integer_field_range(self, internal_type): """ Given an integer field internal type (e.g. 'PositiveIntegerField'), return a tuple of the (min_value, max_value) form representing the range of the column type bound to the field. """ return self.integer_field_ranges[internal_type] def subtract_temporals(self, internal_type, lhs, rhs): if self.connection.features.supports_temporal_subtraction: lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs return "(%s - %s)" % (lhs_sql, rhs_sql), (*lhs_params, *rhs_params) raise NotSupportedError( "This backend does not support %s subtraction." % internal_type ) def window_frame_start(self, start): if isinstance(start, int): if start < 0: return "%d %s" % (abs(start), self.PRECEDING) elif start == 0: return self.CURRENT_ROW elif start is None: return self.UNBOUNDED_PRECEDING raise ValueError( "start argument must be a negative integer, zero, or None, but got '%s'." % start ) def window_frame_end(self, end): if isinstance(end, int): if end == 0: return self.CURRENT_ROW elif end > 0: return "%d %s" % (end, self.FOLLOWING) elif end is None: return self.UNBOUNDED_FOLLOWING raise ValueError( "end argument must be a positive integer, zero, or None, but got '%s'." % end ) def window_frame_rows_start_end(self, start=None, end=None): """ Return SQL for start and end points in an OVER clause window frame. """ if not self.connection.features.supports_over_clause: raise NotSupportedError("This backend does not support window expressions.") return self.window_frame_start(start), self.window_frame_end(end) def window_frame_range_start_end(self, start=None, end=None): start_, end_ = self.window_frame_rows_start_end(start, end) features = self.connection.features if features.only_supports_unbounded_with_preceding_and_following and ( (start and start < 0) or (end and end > 0) ): raise NotSupportedError( "%s only supports UNBOUNDED together with PRECEDING and " "FOLLOWING." % self.connection.display_name ) return start_, end_ def explain_query_prefix(self, format=None, **options): if not self.connection.features.supports_explaining_query_execution: raise NotSupportedError( "This backend does not support explaining query execution." ) if format: supported_formats = self.connection.features.supported_explain_formats normalized_format = format.upper() if normalized_format not in supported_formats: msg = "%s is not a recognized format." % normalized_format if supported_formats: msg += " Allowed formats: %s" % ", ".join(sorted(supported_formats)) else: msg += ( f" {self.connection.display_name} does not support any formats." ) raise ValueError(msg) if options: raise ValueError("Unknown options: %s" % ", ".join(sorted(options.keys()))) return self.explain_prefix def insert_statement(self, on_conflict=None): return "INSERT INTO" def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): return ""
df942d61e0087e95eba8fad568ba2db36ca9f41bcb6bde2fb664d01c54a30870
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_pk = True related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True supports_forward_references = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True can_release_savepoints = True atomic_transactions = False can_clone_databases = True supports_temporal_subtraction = True supports_select_intersection = False supports_select_difference = False supports_slicing_ordering_in_compound = True supports_index_on_text_field = False supports_update_conflicts = True create_test_procedure_without_params_sql = """ CREATE PROCEDURE test_procedure () BEGIN DECLARE V_I INTEGER; SET V_I = 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE test_procedure (P_I INTEGER) BEGIN DECLARE V_I INTEGER; SET V_I = P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ # Neither MySQL nor MariaDB support partial indexes. supports_partial_indexes = False # COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an # indexed expression. collate_as_index_expression = True supports_order_by_nulls_modifier = False order_by_nulls_first = True supports_logical_xor = True @cached_property def minimum_database_version(self): if self.connection.mysql_is_mariadb: return (10, 4) else: return (8,) @cached_property def test_collations(self): charset = "utf8" if self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 6, ): # utf8 is an alias for utf8mb3 in MariaDB 10.6+. charset = "utf8mb3" return { "ci": f"{charset}_general_ci", "non_default": f"{charset}_esperanto_ci", "swedish_ci": f"{charset}_swedish_ci", } test_now_utc_template = "UTC_TIMESTAMP" @cached_property def django_test_skips(self): skips = { "This doesn't work on MySQL.": { "db_functions.comparison.test_greatest.GreatestTests." "test_coalesce_workaround", "db_functions.comparison.test_least.LeastTests." "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", "model_fields.test_charfield.TestCharField.test_emoji", }, "MySQL doesn't support functional indexes on a function that " "returns JSON": { "schema.tests.SchemaTests.test_func_index_json_key_transform", }, "MySQL supports multiplying and dividing DurationFields by a " "scalar value but it's not implemented (#25287).": { "expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide", }, "UPDATE ... ORDER BY syntax on MySQL/MariaDB does not support ordering by" "related fields.": { "update.tests.AdvancedTests." "test_update_ordered_by_inline_m2m_annotation", "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation", }, } if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode: skips.update( { "GROUP BY optimization does not work properly when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #31331.": { "aggregation.tests.AggregateTestCase." "test_aggregation_subquery_annotation_multivalued", "annotations.tests.NonAggregateAnnotationTestCase." "test_annotation_aggregate_with_m2o", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { "schema.tests.SchemaTests." "test_alter_not_unique_field_to_primary_key", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 12, ) < self.connection.mysql_version < (10, 5): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { "schema.tests.SchemaTests." "test_alter_pk_with_self_referential_field", }, } ) if not self.supports_explain_analyze: skips.update( { "MariaDB and MySQL >= 8.0.18 specific.": { "queries.test_explain.ExplainTests.test_mysql_analyze", }, } ) return skips @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" return self.connection.mysql_server_data["default_storage_engine"] @cached_property def allows_auto_pk_0(self): """ Autoincrement primary key can be set to 0 if it doesn't generate new autoincrement values. """ return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode @cached_property def update_can_self_select(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 3, 2, ) @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != "MyISAM" @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BinaryField": "TextField", "BooleanField": "IntegerField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", } @cached_property def can_return_columns_from_insert(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 5, 0, ) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") ) @cached_property def has_zoneinfo_database(self): return self.connection.mysql_server_data["has_zoneinfo_database"] @cached_property def is_sql_auto_is_null_enabled(self): return self.connection.mysql_server_data["sql_auto_is_null"] @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property( operator.attrgetter("supports_over_clause") ) @cached_property def supports_column_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) supports_table_check_constraints = property( operator.attrgetter("supports_column_check_constraints") ) @cached_property def can_introspect_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) @cached_property def has_select_for_update_skip_locked(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 6) return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_nowait(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_of(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 1) ) @cached_property def supports_explain_analyze(self): return self.connection.mysql_is_mariadb or self.connection.mysql_version >= ( 8, 0, 18, ) @cached_property def supported_explain_formats(self): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. formats = {"JSON", "TEXT", "TRADITIONAL"} if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 8, 0, 16, ): formats.add("TREE") return formats @cached_property def supports_transactions(self): """ All storage engines except MyISAM support transactions. """ return self._mysql_storage_engine != "MyISAM" uses_savepoints = property(operator.attrgetter("supports_transactions")) can_release_savepoints = property(operator.attrgetter("supports_transactions")) @cached_property def ignores_table_name_case(self): return self.connection.mysql_server_data["lower_case_table_names"] @cached_property def supports_default_in_lead_lag(self): # To be added in https://jira.mariadb.org/browse/MDEV-12981. return not self.connection.mysql_is_mariadb @cached_property def can_introspect_json_field(self): if self.connection.mysql_is_mariadb: return self.can_introspect_check_constraints return True @cached_property def supports_index_column_ordering(self): if self._mysql_storage_engine != "InnoDB": return False if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 8) return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self): return ( not self.connection.mysql_is_mariadb and self._mysql_storage_engine != "MyISAM" and self.connection.mysql_version >= (8, 0, 13) ) @cached_property def can_rename_index(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 5, 2) return True
679ac389c34ec93f92e2a217a34fba2dea82067df1bc6f26d44f993e84752f44
import uuid from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import split_tzname_delta from django.db.models import Exists, ExpressionWrapper, Lookup from django.db.models.constants import OnConflict from django.utils import timezone from django.utils.encoding import force_str from django.utils.regex_helper import _lazy_re_compile class DatabaseOperations(BaseDatabaseOperations): compiler_module = "django.db.backends.mysql.compiler" # MySQL stores positive fields as UNSIGNED ints. integer_field_ranges = { **BaseDatabaseOperations.integer_field_ranges, "PositiveSmallIntegerField": (0, 65535), "PositiveIntegerField": (0, 4294967295), "PositiveBigIntegerField": (0, 18446744073709551615), } cast_data_types = { "AutoField": "signed integer", "BigAutoField": "signed integer", "SmallAutoField": "signed integer", "CharField": "char(%(max_length)s)", "DecimalField": "decimal(%(max_digits)s, %(decimal_places)s)", "TextField": "char", "IntegerField": "signed integer", "BigIntegerField": "signed integer", "SmallIntegerField": "signed integer", "PositiveBigIntegerField": "unsigned integer", "PositiveIntegerField": "unsigned integer", "PositiveSmallIntegerField": "unsigned integer", "DurationField": "signed integer", } cast_char_field_without_max_length = "char" explain_prefix = "EXPLAIN" # EXTRACT format cannot be passed in parameters. _extract_format_re = _lazy_re_compile(r"[A-Z_]+") def date_extract_sql(self, lookup_type, sql, params): # https://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type == "week_day": # DAYOFWEEK() returns an integer, 1-7, Sunday=1. return f"DAYOFWEEK({sql})", params elif lookup_type == "iso_week_day": # WEEKDAY() returns an integer, 0-6, Monday=0. return f"WEEKDAY({sql}) + 1", params elif lookup_type == "week": # Override the value of default_week_format for consistency with # other database backends. # Mode 3: Monday, 1-53, with 4 or more days this year. return f"WEEK({sql}, 3)", params elif lookup_type == "iso_year": # Get the year part from the YEARWEEK function, which returns a # number as year * 100 + week. return f"TRUNCATE(YEARWEEK({sql}, 3), -2) / 100", params else: # EXTRACT returns 1-53 based on ISO-8601 for the week number. lookup_type = lookup_type.upper() if not self._extract_format_re.fullmatch(lookup_type): raise ValueError(f"Invalid loookup type: {lookup_type!r}") return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "year": "%Y-01-01", "month": "%Y-%m-01", } if lookup_type in fields: format_str = fields[lookup_type] return f"CAST(DATE_FORMAT({sql}, %s) AS DATE)", (*params, format_str) elif lookup_type == "quarter": return ( f"MAKEDATE(YEAR({sql}), 1) + " f"INTERVAL QUARTER({sql}) QUARTER - INTERVAL 1 QUARTER", (*params, *params), ) elif lookup_type == "week": return f"DATE_SUB({sql}, INTERVAL WEEKDAY({sql}) DAY)", (*params, *params) else: return f"DATE({sql})", params def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: return f"CONVERT_TZ({sql}, %s, %s)", ( *params, self.connection.timezone_name, self._prepare_tzname_delta(tzname), ) return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"DATE({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"TIME({sql})", params def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = ["year", "month", "day", "hour", "minute", "second"] format = ("%Y-", "%m", "-%d", " %H:", "%i", ":%s") format_def = ("0000-", "01", "-01", " 00:", "00", ":00") if lookup_type == "quarter": return ( f"CAST(DATE_FORMAT(MAKEDATE(YEAR({sql}), 1) + " f"INTERVAL QUARTER({sql}) QUARTER - " f"INTERVAL 1 QUARTER, %s) AS DATETIME)" ), (*params, *params, "%Y-%m-01 00:00:00") if lookup_type == "week": return ( f"CAST(DATE_FORMAT(" f"DATE_SUB({sql}, INTERVAL WEEKDAY({sql}) DAY), %s) AS DATETIME)" ), (*params, *params, "%Y-%m-%d 00:00:00") try: i = fields.index(lookup_type) + 1 except ValueError: pass else: format_str = "".join(format[:i] + format_def[i:]) return f"CAST(DATE_FORMAT({sql}, %s) AS DATETIME)", (*params, format_str) return sql, params def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "hour": "%H:00:00", "minute": "%H:%i:00", "second": "%H:%i:%s", } if lookup_type in fields: format_str = fields[lookup_type] return f"CAST(DATE_FORMAT({sql}, %s) AS TIME)", (*params, format_str) else: return f"TIME({sql})", params def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the tuple of returned data. """ return cursor.fetchall() def format_for_duration_arithmetic(self, sql): return "INTERVAL %s MICROSECOND" % sql def force_no_ordering(self): """ "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on. """ return [(None, ("NULL", [], False))] def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): return value def last_executed_query(self, cursor, sql, params): # With MySQLdb, cursor objects have an (undocumented) "_executed" # attribute where the exact query sent to the database is saved. # See MySQLdb/cursors.py in the source distribution. # MySQLdb returns string, PyMySQL bytes. return force_str(getattr(cursor, "_executed", None), errors="replace") def no_limit_value(self): # 2**64 - 1, as recommended by the MySQL documentation return 18446744073709551615 def quote_name(self, name): if name.startswith("`") and name.endswith("`"): return name # Quoting once is enough. return "`%s`" % name def return_insert_columns(self, fields): # MySQL and MariaDB < 10.5.0 don't support an INSERT...RETURNING # statement. if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] sql = ["SET FOREIGN_KEY_CHECKS = 0;"] if reset_sequences: # It's faster to TRUNCATE tables that require a sequence reset # since ALTER TABLE AUTO_INCREMENT is slower than TRUNCATE. sql.extend( "%s %s;" % ( style.SQL_KEYWORD("TRUNCATE"), style.SQL_FIELD(self.quote_name(table_name)), ) for table_name in tables ) else: # Otherwise issue a simple DELETE since it's faster than TRUNCATE # and preserves sequences. sql.extend( "%s %s %s;" % ( style.SQL_KEYWORD("DELETE"), style.SQL_KEYWORD("FROM"), style.SQL_FIELD(self.quote_name(table_name)), ) for table_name in tables ) sql.append("SET FOREIGN_KEY_CHECKS = 1;") return sql def sequence_reset_by_name_sql(self, style, sequences): return [ "%s %s %s %s = 1;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(sequence_info["table"])), style.SQL_FIELD("AUTO_INCREMENT"), ) for sequence_info in sequences ] def validate_autopk_value(self, value): # Zero in AUTO_INCREMENT field does not work without the # NO_AUTO_VALUE_ON_ZERO SQL mode. if value == 0 and not self.connection.features.allows_auto_pk_0: raise ValueError( "The database backend does not accept 0 as a value for AutoField." ) return value def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # MySQL doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "MySQL backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return str(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # MySQL doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("MySQL backend does not support timezone-aware times.") return value.isoformat(timespec="microseconds") def max_name_length(self): return 64 def pk_default_value(self): return "NULL" def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql) return "VALUES " + values_sql def combine_expression(self, connector, sub_expressions): if connector == "^": return "POW(%s)" % ",".join(sub_expressions) # Convert the result to a signed integer since MySQL's binary operators # return an unsigned integer. elif connector in ("&", "|", "<<", "#"): connector = "^" if connector == "#" else connector return "CONVERT(%s, SIGNED)" % connector.join(sub_expressions) elif connector == ">>": lhs, rhs = sub_expressions return "FLOOR(%(lhs)s / POW(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} return super().combine_expression(connector, sub_expressions) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) elif internal_type == "DateTimeField": if settings.USE_TZ: converters.append(self.convert_datetimefield_value) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) return converters def convert_booleanfield_value(self, value, expression, connection): if value in (0, 1): value = bool(value) return value def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) return value def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value def binary_placeholder_sql(self, value): return ( "_binary %s" if value is not None and not hasattr(value, "as_sql") else "%s" ) def subtract_temporals(self, internal_type, lhs, rhs): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs if internal_type == "TimeField": if self.connection.mysql_is_mariadb: # MariaDB includes the microsecond component in TIME_TO_SEC as # a decimal. MySQL returns an integer without microseconds. return ( "CAST((TIME_TO_SEC(%(lhs)s) - TIME_TO_SEC(%(rhs)s)) " "* 1000000 AS SIGNED)" ) % { "lhs": lhs_sql, "rhs": rhs_sql, }, ( *lhs_params, *rhs_params, ) return ( "((TIME_TO_SEC(%(lhs)s) * 1000000 + MICROSECOND(%(lhs)s)) -" " (TIME_TO_SEC(%(rhs)s) * 1000000 + MICROSECOND(%(rhs)s)))" ) % {"lhs": lhs_sql, "rhs": rhs_sql}, tuple(lhs_params) * 2 + tuple( rhs_params ) * 2 params = (*rhs_params, *lhs_params) return "TIMESTAMPDIFF(MICROSECOND, %s, %s)" % (rhs_sql, lhs_sql), params def explain_query_prefix(self, format=None, **options): # Alias MySQL's TRADITIONAL to TEXT for consistency with other backends. if format and format.upper() == "TEXT": format = "TRADITIONAL" elif ( not format and "TREE" in self.connection.features.supported_explain_formats ): # Use TREE by default (if supported) as it's more informative. format = "TREE" analyze = options.pop("analyze", False) prefix = super().explain_query_prefix(format, **options) if analyze and self.connection.features.supports_explain_analyze: # MariaDB uses ANALYZE instead of EXPLAIN ANALYZE. prefix = ( "ANALYZE" if self.connection.mysql_is_mariadb else prefix + " ANALYZE" ) if format and not (analyze and not self.connection.mysql_is_mariadb): # Only MariaDB supports the analyze option with formats. prefix += " FORMAT=%s" % format return prefix def regex_lookup(self, lookup_type): # REGEXP_LIKE doesn't exist in MariaDB. if self.connection.mysql_is_mariadb: if lookup_type == "regex": return "%s REGEXP BINARY %s" return "%s REGEXP %s" match_option = "c" if lookup_type == "regex" else "i" return "REGEXP_LIKE(%%s, %%s, '%s')" % match_option def insert_statement(self, on_conflict=None): if on_conflict == OnConflict.IGNORE: return "INSERT IGNORE INTO" return super().insert_statement(on_conflict=on_conflict) def lookup_cast(self, lookup_type, internal_type=None): lookup = "%s" if internal_type == "JSONField": if self.connection.mysql_is_mariadb or lookup_type in ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ): lookup = "JSON_UNQUOTE(%s)" return lookup def conditional_expression_supported_in_where_clause(self, expression): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. if isinstance(expression, (Exists, Lookup)): return True if isinstance(expression, ExpressionWrapper) and expression.conditional: return self.conditional_expression_supported_in_where_clause( expression.expression ) if getattr(expression, "conditional", False): return False return super().conditional_expression_supported_in_where_clause(expression) def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if on_conflict == OnConflict.UPDATE: conflict_suffix_sql = "ON DUPLICATE KEY UPDATE %(fields)s" # The use of VALUES() is deprecated in MySQL 8.0.20+. Instead, use # aliases for the new row and its columns available in MySQL # 8.0.19+. if not self.connection.mysql_is_mariadb: if self.connection.mysql_version >= (8, 0, 19): conflict_suffix_sql = f"AS new {conflict_suffix_sql}" field_sql = "%(field)s = new.%(field)s" else: field_sql = "%(field)s = VALUES(%(field)s)" # Use VALUE() on MariaDB. else: field_sql = "%(field)s = VALUE(%(field)s)" fields = ", ".join( [ field_sql % {"field": field} for field in map(self.quote_name, update_fields) ] ) return conflict_suffix_sql % {"fields": fields} return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
a3d5186694325049dd83bb1ac7c49ba6d91ddc878ecb8422e5cb6635732cd602
from psycopg2.extras import Inet from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import split_tzname_delta from django.db.models.constants import OnConflict class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "varchar" explain_prefix = "EXPLAIN" explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", "SETTINGS", "SUMMARY", "TIMING", "VERBOSE", "WAL", ] ) cast_data_types = { "AutoField": "integer", "BigAutoField": "bigint", "SmallAutoField": "smallint", } def unification_cast_sql(self, output_field): internal_type = output_field.get_internal_type() if internal_type in ( "GenericIPAddressField", "IPAddressField", "TimeField", "UUIDField", ): # PostgreSQL will resolve a union as type 'text' if input types are # 'unknown'. # https://www.postgresql.org/docs/current/typeconv-union-case.html # These fields cannot be implicitly cast back in the default # PostgreSQL configuration so we need to explicitly cast them. # We must also remove components of the type within brackets: # varchar(255) -> varchar. return ( "CAST(%%s AS %s)" % output_field.db_type(self.connection).split("(")[0] ) return "%s" def date_extract_sql(self, lookup_type, sql, params): # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT extract_sql = f"EXTRACT(%s FROM {sql})" extract_param = lookup_type if lookup_type == "week_day": # For consistency across backends, we return Sunday=1, Saturday=7. extract_sql = f"EXTRACT(%s FROM {sql}) + 1" extract_param = "dow" elif lookup_type == "iso_week_day": extract_param = "isodow" elif lookup_type == "iso_year": extract_param = "isoyear" return extract_sql, (extract_param, *params) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC return f"DATE_TRUNC(%s, {sql})", (lookup_type, *params) def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) if offset: sign = "-" if sign == "+" else "+" return f"{tzname}{sign}{offset}" return tzname def _convert_sql_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ: tzname_param = self._prepare_tzname_delta(tzname) return f"{sql} AT TIME ZONE %s", (*params, tzname_param) return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"({sql})::date", params def datetime_cast_time_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"({sql})::time", params def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) if lookup_type == "second": # Truncate fractional seconds. return ( f"EXTRACT(%s FROM DATE_TRUNC(%s, {sql}))", ("second", "second", *params), ) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC return f"DATE_TRUNC(%s, {sql})", (lookup_type, *params) def time_extract_sql(self, lookup_type, sql, params): if lookup_type == "second": # Truncate fractional seconds. return ( f"EXTRACT(%s FROM DATE_TRUNC(%s, {sql}))", ("second", "second", *params), ) return self.date_extract_sql(lookup_type, sql, params) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"DATE_TRUNC(%s, {sql})::time", (lookup_type, *params) def deferrable_sql(self): return " DEFERRABLE INITIALLY DEFERRED" def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the tuple of returned data. """ return cursor.fetchall() def lookup_cast(self, lookup_type, internal_type=None): lookup = "%s" # Cast text lookups to text to allow things like filter(x__contains=4) if lookup_type in ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ): if internal_type in ("IPAddressField", "GenericIPAddressField"): lookup = "HOST(%s)" elif internal_type in ("CICharField", "CIEmailField", "CITextField"): lookup = "%s::citext" else: lookup = "%s::text" # Use UPPER(x) for case-insensitive lookups; it's faster. if lookup_type in ("iexact", "icontains", "istartswith", "iendswith"): lookup = "UPPER(%s)" % lookup return lookup def no_limit_value(self): return None def prepare_sql_script(self, sql): return [sql] def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name def set_time_zone_sql(self): return "SET TIME ZONE %s" def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] # Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows us # to truncate tables referenced by a foreign key in any other table. sql_parts = [ style.SQL_KEYWORD("TRUNCATE"), ", ".join(style.SQL_FIELD(self.quote_name(table)) for table in tables), ] if reset_sequences: sql_parts.append(style.SQL_KEYWORD("RESTART IDENTITY")) if allow_cascade: sql_parts.append(style.SQL_KEYWORD("CASCADE")) return ["%s;" % " ".join(sql_parts)] def sequence_reset_by_name_sql(self, style, sequences): # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements # to reset sequence indices sql = [] for sequence_info in sequences: table_name = sequence_info["table"] # 'id' will be the case if it's an m2m using an autogenerated # intermediate table (see BaseDatabaseIntrospection.sequence_list). column_name = sequence_info["column"] or "id" sql.append( "%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" % ( style.SQL_KEYWORD("SELECT"), style.SQL_TABLE(self.quote_name(table_name)), style.SQL_FIELD(column_name), ) ) return sql def tablespace_sql(self, tablespace, inline=False): if inline: return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace) else: return "TABLESPACE %s" % self.quote_name(tablespace) def sequence_reset_sql(self, style, model_list): from django.db import models output = [] qn = self.quote_name for model in model_list: # Use `coalesce` to set the sequence for each model to the max pk # value if there are records, or 1 if there are none. Set the # `is_called` property (the third argument to `setval`) to true if # there are records (as the max pk value is already in use), # otherwise set it to false. Use pg_get_serial_sequence to get the # underlying sequence name from the table name and column name. for f in model._meta.local_fields: if isinstance(f, models.AutoField): output.append( "%s setval(pg_get_serial_sequence('%s','%s'), " "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % ( style.SQL_KEYWORD("SELECT"), style.SQL_TABLE(qn(model._meta.db_table)), style.SQL_FIELD(f.column), style.SQL_FIELD(qn(f.column)), style.SQL_FIELD(qn(f.column)), style.SQL_KEYWORD("IS NOT"), style.SQL_KEYWORD("FROM"), style.SQL_TABLE(qn(model._meta.db_table)), ) ) # Only one AutoField is allowed per model, so don't bother # continuing. break return output def prep_for_iexact_query(self, x): return x def max_name_length(self): """ Return the maximum length of an identifier. The maximum length of an identifier is 63 by default, but can be changed by recompiling PostgreSQL after editing the NAMEDATALEN macro in src/include/pg_config_manual.h. This implementation returns 63, but can be overridden by a custom database backend that inherits most of its behavior from this one. """ return 63 def distinct_sql(self, fields, params): if fields: params = [param for param_list in params for param in param_list] return (["DISTINCT ON (%s)" % ", ".join(fields)], params) else: return ["DISTINCT"], [] def last_executed_query(self, cursor, sql, params): # https://www.psycopg.org/docs/cursor.html#cursor.query # The query attribute is a Psycopg extension to the DB API 2.0. if cursor.query is not None: return cursor.query.decode() return None def return_insert_columns(self, fields): if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql) return "VALUES " + values_sql def adapt_datefield_value(self, value): return value def adapt_datetimefield_value(self, value): return value def adapt_timefield_value(self, value): return value def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): return value def adapt_ipaddressfield_value(self, value): if value: return Inet(value) return None def subtract_temporals(self, internal_type, lhs, rhs): if internal_type == "DateField": lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) return "(interval '1 day' * (%s - %s))" % (lhs_sql, rhs_sql), params return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): "true" if value else "false" for name, value in options.items() } for valid_option in self.explain_options: value = options.pop(valid_option, None) if value is not None: extra[valid_option] = value prefix = super().explain_query_prefix(format, **options) if format: extra["FORMAT"] = format if extra: prefix += " (%s)" % ", ".join("%s %s" % i for i in extra.items()) return prefix def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if on_conflict == OnConflict.IGNORE: return "ON CONFLICT DO NOTHING" if on_conflict == OnConflict.UPDATE: return "ON CONFLICT(%s) DO UPDATE SET %s" % ( ", ".join(map(self.quote_name, unique_fields)), ", ".join( [ f"{field} = EXCLUDED.{field}" for field in map(self.quote_name, update_fields) ] ), ) return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
93d7c5cf7d24d07ec4e933743d4f25ee9442faee2abf12073740e40cb1b18e04
import datetime import decimal import uuid from functools import lru_cache from itertools import chain from django.conf import settings from django.core.exceptions import FieldError from django.db import DatabaseError, NotSupportedError, models from django.db.backends.base.operations import BaseDatabaseOperations from django.db.models.constants import OnConflict from django.db.models.expressions import Col from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.functional import cached_property class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "text" cast_data_types = { "DateField": "TEXT", "DateTimeField": "TEXT", } explain_prefix = "EXPLAIN QUERY PLAN" # List of datatypes to that cannot be extracted with JSON_EXTRACT() on # SQLite. Use JSON_TYPE() instead. jsonfield_datatype_values = frozenset(["null", "false", "true"]) def bulk_batch_size(self, fields, objs): """ SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of 999 variables per query. If there's only a single field to insert, the limit is 500 (SQLITE_MAX_COMPOUND_SELECT). """ if len(fields) == 1: return 500 elif len(fields) > 1: return self.connection.features.max_query_params // len(fields) else: return len(objs) def check_expression_support(self, expression): bad_fields = (models.DateField, models.DateTimeField, models.TimeField) bad_aggregates = (models.Sum, models.Avg, models.Variance, models.StdDev) if isinstance(expression, bad_aggregates): for expr in expression.get_source_expressions(): try: output_field = expr.output_field except (AttributeError, FieldError): # Not every subexpression has an output_field which is fine # to ignore. pass else: if isinstance(output_field, bad_fields): raise NotSupportedError( "You cannot use Sum, Avg, StdDev, and Variance " "aggregations on date/time fields in sqlite3 " "since date/time is saved as text." ) if ( isinstance(expression, models.Aggregate) and expression.distinct and len(expression.source_expressions) > 1 ): raise NotSupportedError( "SQLite doesn't support DISTINCT on aggregate functions " "accepting multiple arguments." ) def date_extract_sql(self, lookup_type, sql, params): """ Support EXTRACT with a user-defined function django_date_extract() that's registered in connect(). Use single quotes because this is a string and could otherwise cause a collision with a field name. """ return f"django_date_extract(%s, {sql})", (lookup_type.lower(), *params) def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the list of returned data. """ return cursor.fetchall() def format_for_duration_arithmetic(self, sql): """Do nothing since formatting is handled in the custom function.""" return sql def date_trunc_sql(self, lookup_type, sql, params, tzname=None): return f"django_date_trunc(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): return f"django_time_trunc(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def _convert_tznames_to_sql(self, tzname): if tzname and settings.USE_TZ: return tzname, self.connection.timezone_name return None, None def datetime_cast_date_sql(self, sql, params, tzname): return f"django_datetime_cast_date({sql}, %s, %s)", ( *params, *self._convert_tznames_to_sql(tzname), ) def datetime_cast_time_sql(self, sql, params, tzname): return f"django_datetime_cast_time({sql}, %s, %s)", ( *params, *self._convert_tznames_to_sql(tzname), ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): return f"django_datetime_extract(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): return f"django_datetime_trunc(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def time_extract_sql(self, lookup_type, sql, params): return f"django_time_extract(%s, {sql})", (lookup_type.lower(), *params) def pk_default_value(self): return "NULL" def _quote_params_for_last_executed_query(self, params): """ Only for last_executed_query! Don't use this to execute SQL queries! """ # This function is limited both by SQLITE_LIMIT_VARIABLE_NUMBER (the # number of parameters, default = 999) and SQLITE_MAX_COLUMN (the # number of return values, default = 2000). Since Python's sqlite3 # module doesn't expose the get_limit() C API, assume the default # limits are in effect and split the work in batches if needed. BATCH_SIZE = 999 if len(params) > BATCH_SIZE: results = () for index in range(0, len(params), BATCH_SIZE): chunk = params[index : index + BATCH_SIZE] results += self._quote_params_for_last_executed_query(chunk) return results sql = "SELECT " + ", ".join(["QUOTE(?)"] * len(params)) # Bypass Django's wrappers and use the underlying sqlite3 connection # to avoid logging this query - it would trigger infinite recursion. cursor = self.connection.connection.cursor() # Native sqlite3 cursors cannot be used as context managers. try: return cursor.execute(sql, params).fetchone() finally: cursor.close() def last_executed_query(self, cursor, sql, params): # Python substitutes parameters in Modules/_sqlite/cursor.c with: # pysqlite_statement_bind_parameters( # self->statement, parameters, allow_8bit_chars # ); # Unfortunately there is no way to reach self->statement from Python, # so we quote and substitute parameters manually. if params: if isinstance(params, (list, tuple)): params = self._quote_params_for_last_executed_query(params) else: values = tuple(params.values()) values = self._quote_params_for_last_executed_query(values) params = dict(zip(params, values)) return sql % params # For consistency with SQLiteCursorWrapper.execute(), just return sql # when there are no parameters. See #13648 and #17158. else: return sql def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name def no_limit_value(self): return -1 def __references_graph(self, table_name): query = """ WITH tables AS ( SELECT %s name UNION SELECT sqlite_master.name FROM sqlite_master JOIN tables ON (sql REGEXP %s || tables.name || %s) ) SELECT name FROM tables; """ params = ( table_name, r'(?i)\s+references\s+("|\')?', r'("|\')?\s*\(', ) with self.connection.cursor() as cursor: results = cursor.execute(query, params) return [row[0] for row in results.fetchall()] @cached_property def _references_graph(self): # 512 is large enough to fit the ~330 tables (as of this writing) in # Django's test suite. return lru_cache(maxsize=512)(self.__references_graph) def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if tables and allow_cascade: # Simulate TRUNCATE CASCADE by recursively collecting the tables # referencing the tables to be flushed. tables = set( chain.from_iterable(self._references_graph(table) for table in tables) ) sql = [ "%s %s %s;" % ( style.SQL_KEYWORD("DELETE"), style.SQL_KEYWORD("FROM"), style.SQL_FIELD(self.quote_name(table)), ) for table in tables ] if reset_sequences: sequences = [{"table": table} for table in tables] sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql def sequence_reset_by_name_sql(self, style, sequences): if not sequences: return [] return [ "%s %s %s %s = 0 %s %s %s (%s);" % ( style.SQL_KEYWORD("UPDATE"), style.SQL_TABLE(self.quote_name("sqlite_sequence")), style.SQL_KEYWORD("SET"), style.SQL_FIELD(self.quote_name("seq")), style.SQL_KEYWORD("WHERE"), style.SQL_FIELD(self.quote_name("name")), style.SQL_KEYWORD("IN"), ", ".join( ["'%s'" % sequence_info["table"] for sequence_info in sequences] ), ), ] def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "SQLite backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return str(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): raise ValueError("SQLite backend does not support timezone-aware times.") return str(value) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == "DateTimeField": converters.append(self.convert_datetimefield_value) elif internal_type == "DateField": converters.append(self.convert_datefield_value) elif internal_type == "TimeField": converters.append(self.convert_timefield_value) elif internal_type == "DecimalField": converters.append(self.get_decimalfield_converter(expression)) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) elif internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) return converters def convert_datetimefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.datetime): value = parse_datetime(value) if settings.USE_TZ and not timezone.is_aware(value): value = timezone.make_aware(value, self.connection.timezone) return value def convert_datefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.date): value = parse_date(value) return value def convert_timefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.time): value = parse_time(value) return value def get_decimalfield_converter(self, expression): # SQLite stores only 15 significant digits. Digits coming from # float inaccuracy must be removed. create_decimal = decimal.Context(prec=15).create_decimal_from_float if isinstance(expression, Col): quantize_value = decimal.Decimal(1).scaleb( -expression.output_field.decimal_places ) def converter(value, expression, connection): if value is not None: return create_decimal(value).quantize( quantize_value, context=expression.output_field.context ) else: def converter(value, expression, connection): if value is not None: return create_decimal(value) return converter def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value def convert_booleanfield_value(self, value, expression, connection): return bool(value) if value in (1, 0) else value def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join(f"({sql})" for sql in placeholder_rows_sql) return f"VALUES {values_sql}" def combine_expression(self, connector, sub_expressions): # SQLite doesn't have a ^ operator, so use the user-defined POWER # function that's registered in connect(). if connector == "^": return "POWER(%s)" % ",".join(sub_expressions) elif connector == "#": return "BITXOR(%s)" % ",".join(sub_expressions) return super().combine_expression(connector, sub_expressions) def combine_duration_expression(self, connector, sub_expressions): if connector not in ["+", "-", "*", "/"]: raise DatabaseError("Invalid connector for timedelta: %s." % connector) fn_params = ["'%s'" % connector] + sub_expressions if len(fn_params) > 3: raise ValueError("Too many params for timedelta operations.") return "django_format_dtdelta(%s)" % ", ".join(fn_params) def integer_field_range(self, internal_type): # SQLite doesn't enforce any integer constraints return (None, None) def subtract_temporals(self, internal_type, lhs, rhs): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) if internal_type == "TimeField": return "django_time_diff(%s, %s)" % (lhs_sql, rhs_sql), params return "django_timestamp_diff(%s, %s)" % (lhs_sql, rhs_sql), params def insert_statement(self, on_conflict=None): if on_conflict == OnConflict.IGNORE: return "INSERT OR IGNORE INTO" return super().insert_statement(on_conflict=on_conflict) def return_insert_columns(self, fields): # SQLite < 3.35 doesn't support an INSERT...RETURNING statement. if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if ( on_conflict == OnConflict.UPDATE and self.connection.features.supports_update_conflicts_with_target ): return "ON CONFLICT(%s) DO UPDATE SET %s" % ( ", ".join(map(self.quote_name, unique_fields)), ", ".join( [ f"{field} = EXCLUDED.{field}" for field in map(self.quote_name, update_fields) ] ), ) return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
b2e5cd3628ed3022b24897b74c2dc7c44c9330cdba17975f9b0aea6708dcc3fc
from django.core.checks import Tags, register @register(Tags.migrations) def check_migration_operations(**kwargs): from django.db.migrations.loader import MigrationLoader errors = [] loader = MigrationLoader(None, ignore_no_migrations=True) for migration in loader.disk_migrations.values(): errors.extend(migration.check()) return errors
52ce48042d8385a9af28967f71ee657b92d4ab19215c3eae3002d0c5296306a6
from itertools import chain from django.utils.inspect import func_accepts_kwargs from django.utils.itercompat import is_iterable class Tags: """ Built-in tags for internal checks. """ admin = "admin" async_support = "async_support" caches = "caches" compatibility = "compatibility" database = "database" files = "files" migrations = "migrations" models = "models" security = "security" signals = "signals" sites = "sites" staticfiles = "staticfiles" templates = "templates" translation = "translation" urls = "urls" class CheckRegistry: def __init__(self): self.registered_checks = set() self.deployment_checks = set() def register(self, check=None, *tags, **kwargs): """ Can be used as a function or a decorator. Register given function `f` labeled with given `tags`. The function should receive **kwargs and return list of Errors and Warnings. Example:: registry = CheckRegistry() @registry.register('mytag', 'anothertag') def my_check(app_configs, **kwargs): # ... perform checks and collect `errors` ... return errors # or registry.register(my_check, 'mytag', 'anothertag') """ def inner(check): if not func_accepts_kwargs(check): raise TypeError( "Check functions must accept keyword arguments (**kwargs)." ) check.tags = tags checks = ( self.deployment_checks if kwargs.get("deploy") else self.registered_checks ) checks.add(check) return check if callable(check): return inner(check) else: if check: tags += (check,) return inner def run_checks( self, app_configs=None, tags=None, include_deployment_checks=False, databases=None, ): """ Run all registered checks and return list of Errors and Warnings. """ errors = [] checks = self.get_checks(include_deployment_checks) if tags is not None: checks = [check for check in checks if not set(check.tags).isdisjoint(tags)] for check in checks: new_errors = check(app_configs=app_configs, databases=databases) if not is_iterable(new_errors): raise TypeError( "The function %r did not return a list. All functions " "registered with the checks registry must return a list." % check, ) errors.extend(new_errors) return errors def tag_exists(self, tag, include_deployment_checks=False): return tag in self.tags_available(include_deployment_checks) def tags_available(self, deployment_checks=False): return set( chain.from_iterable( check.tags for check in self.get_checks(deployment_checks) ) ) def get_checks(self, include_deployment_checks=False): checks = list(self.registered_checks) if include_deployment_checks: checks.extend(self.deployment_checks) return checks registry = CheckRegistry() register = registry.register run_checks = registry.run_checks tag_exists = registry.tag_exists
6e17a00afe8ce6542e220a5358df489c8280a2e607a78384d8c985177c4c2adf
from .messages import ( CRITICAL, DEBUG, ERROR, INFO, WARNING, CheckMessage, Critical, Debug, Error, Info, Warning, ) from .registry import Tags, register, run_checks, tag_exists # Import these to force registration of checks import django.core.checks.async_checks # NOQA isort:skip import django.core.checks.caches # NOQA isort:skip import django.core.checks.compatibility.django_4_0 # NOQA isort:skip import django.core.checks.database # NOQA isort:skip import django.core.checks.files # NOQA isort:skip import django.core.checks.migrations # NOQA isort:skip import django.core.checks.model_checks # NOQA isort:skip import django.core.checks.security.base # NOQA isort:skip import django.core.checks.security.csrf # NOQA isort:skip import django.core.checks.security.sessions # NOQA isort:skip import django.core.checks.templates # NOQA isort:skip import django.core.checks.translation # NOQA isort:skip import django.core.checks.urls # NOQA isort:skip __all__ = [ "CheckMessage", "Debug", "Info", "Warning", "Error", "Critical", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "register", "run_checks", "tag_exists", "Tags", ]
648eded7f163bb8d35a50037e8479034d792b4ae14675c78d23d066f892394e8
import keyword import re from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.models.constants import LOOKUP_SEP class Command(BaseCommand): help = ( "Introspects the database tables in the given database and outputs a Django " "model module." ) requires_system_checks = [] stealth_options = ("table_name_filter",) db_module = "django.db" def add_arguments(self, parser): parser.add_argument( "table", nargs="*", type=str, help="Selects what tables or views should be introspected.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, help=( 'Nominates a database to introspect. Defaults to using the "default" ' "database." ), ) parser.add_argument( "--include-partitions", action="store_true", help="Also output models for partition tables.", ) parser.add_argument( "--include-views", action="store_true", help="Also output models for database views.", ) def handle(self, **options): try: for line in self.handle_inspection(options): self.stdout.write(line) except NotImplementedError: raise CommandError( "Database inspection isn't supported for the currently selected " "database backend." ) def handle_inspection(self, options): connection = connections[options["database"]] # 'table_name_filter' is a stealth option table_name_filter = options.get("table_name_filter") def table2model(table_name): return re.sub(r"[^a-zA-Z0-9]", "", table_name.title()) with connection.cursor() as cursor: yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield ( "# * Make sure each ForeignKey and OneToOneField has `on_delete` set " "to the desired behavior" ) yield ( "# * Remove `managed = False` lines if you wish to allow " "Django to create, modify, and delete the table" ) yield ( "# Feel free to rename the models, but don't rename db_table values or " "field names." ) yield "from %s import models" % self.db_module known_models = [] table_info = connection.introspection.get_table_list(cursor) # Determine types of tables and/or views to be introspected. types = {"t"} if options["include_partitions"]: types.add("p") if options["include_views"]: types.add("v") for table_name in options["table"] or sorted( info.name for info in table_info if info.type in types ): if table_name_filter is not None and callable(table_name_filter): if not table_name_filter(table_name): continue try: try: relations = connection.introspection.get_relations( cursor, table_name ) except NotImplementedError: relations = {} try: constraints = connection.introspection.get_constraints( cursor, table_name ) except NotImplementedError: constraints = {} primary_key_columns = ( connection.introspection.get_primary_key_columns( cursor, table_name ) ) primary_key_column = ( primary_key_columns[0] if primary_key_columns else None ) unique_columns = [ c["columns"][0] for c in constraints.values() if c["unique"] and len(c["columns"]) == 1 ] table_description = connection.introspection.get_table_description( cursor, table_name ) except Exception as e: yield "# Unable to inspect table '%s'" % table_name yield "# The error was: %s" % e continue model_name = table2model(table_name) yield "" yield "" yield "class %s(models.Model):" % model_name known_models.append(model_name) used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields used_relations = set() # Holds foreign relations used in the table. for row in table_description: comment_notes = ( [] ) # Holds Field notes, to be displayed in a Python comment. extra_params = {} # Holds Field parameters such as 'db_column'. column_name = row.name is_relation = column_name in relations att_name, params, notes = self.normalize_col_name( column_name, used_column_names, is_relation ) extra_params.update(params) comment_notes.extend(notes) used_column_names.append(att_name) column_to_field_name[column_name] = att_name # Add primary_key and unique, if necessary. if column_name == primary_key_column: extra_params["primary_key"] = True if len(primary_key_columns) > 1: comment_notes.append( "The composite primary key (%s) found, that is not " "supported. The first column is selected." % ", ".join(primary_key_columns) ) elif column_name in unique_columns: extra_params["unique"] = True if is_relation: ref_db_column, ref_db_table = relations[column_name] if extra_params.pop("unique", False) or extra_params.get( "primary_key" ): rel_type = "OneToOneField" else: rel_type = "ForeignKey" ref_pk_column = ( connection.introspection.get_primary_key_column( cursor, ref_db_table ) ) if ref_pk_column and ref_pk_column != ref_db_column: extra_params["to_field"] = ref_db_column rel_to = ( "self" if ref_db_table == table_name else table2model(ref_db_table) ) if rel_to in known_models: field_type = "%s(%s" % (rel_type, rel_to) else: field_type = "%s('%s'" % (rel_type, rel_to) if rel_to in used_relations: extra_params["related_name"] = "%s_%s_set" % ( model_name.lower(), att_name, ) used_relations.add(rel_to) else: # Calling `get_field_type` to get the field type string and any # additional parameters and notes. field_type, field_params, field_notes = self.get_field_type( connection, table_name, row ) extra_params.update(field_params) comment_notes.extend(field_notes) field_type += "(" # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == "id" and extra_params == {"primary_key": True}: if field_type == "AutoField(": continue elif ( field_type == connection.features.introspected_field_types["AutoField"] + "(" ): comment_notes.append("AutoField?") # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row.null_ok: # If it's NULL... extra_params["blank"] = True extra_params["null"] = True field_desc = "%s = %s%s" % ( att_name, # Custom fields will have a dotted path "" if "." in field_type else "models.", field_type, ) if field_type.startswith(("ForeignKey(", "OneToOneField(")): field_desc += ", models.DO_NOTHING" if extra_params: if not field_desc.endswith("("): field_desc += ", " field_desc += ", ".join( "%s=%r" % (k, v) for k, v in extra_params.items() ) field_desc += ")" if comment_notes: field_desc += " # " + " ".join(comment_notes) yield " %s" % field_desc is_view = any( info.name == table_name and info.type == "v" for info in table_info ) is_partition = any( info.name == table_name and info.type == "p" for info in table_info ) yield from self.get_meta( table_name, constraints, column_to_field_name, is_view, is_partition ) def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.append("Field name made lowercase.") if is_relation: if new_name.endswith("_id"): new_name = new_name[:-3] else: field_params["db_column"] = col_name new_name, num_repl = re.subn(r"\W", "_", new_name) if num_repl > 0: field_notes.append("Field renamed to remove unsuitable characters.") if new_name.find(LOOKUP_SEP) >= 0: while new_name.find(LOOKUP_SEP) >= 0: new_name = new_name.replace(LOOKUP_SEP, "_") if col_name.lower().find(LOOKUP_SEP) >= 0: # Only add the comment if the double underscore was in the original name field_notes.append( "Field renamed because it contained more than one '_' in a row." ) if new_name.startswith("_"): new_name = "field%s" % new_name field_notes.append("Field renamed because it started with '_'.") if new_name.endswith("_"): new_name = "%sfield" % new_name field_notes.append("Field renamed because it ended with '_'.") if keyword.iskeyword(new_name): new_name += "_field" field_notes.append("Field renamed because it was a Python reserved word.") if new_name[0].isdigit(): new_name = "number_%s" % new_name field_notes.append( "Field renamed because it wasn't a valid Python identifier." ) if new_name in used_column_names: num = 0 while "%s_%d" % (new_name, num) in used_column_names: num += 1 new_name = "%s_%d" % (new_name, num) field_notes.append("Field renamed because of name conflict.") if col_name != new_name and field_notes: field_params["db_column"] = col_name return new_name, field_params, field_notes def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row.type_code, row) except KeyError: field_type = "TextField" field_notes.append("This field type is a guess.") # Add max_length for all CharFields. if field_type == "CharField" and row.internal_size: field_params["max_length"] = int(row.internal_size) if field_type in {"CharField", "TextField"} and row.collation: field_params["db_collation"] = row.collation if field_type == "DecimalField": if row.precision is None or row.scale is None: field_notes.append( "max_digits and decimal_places have been guessed, as this " "database handles decimal fields as float" ) field_params["max_digits"] = ( row.precision if row.precision is not None else 10 ) field_params["decimal_places"] = ( row.scale if row.scale is not None else 5 ) else: field_params["max_digits"] = row.precision field_params["decimal_places"] = row.scale return field_type, field_params, field_notes def get_meta( self, table_name, constraints, column_to_field_name, is_view, is_partition ): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ unique_together = [] has_unsupported_constraint = False for params in constraints.values(): if params["unique"]: columns = params["columns"] if None in columns: has_unsupported_constraint = True columns = [ x for x in columns if x is not None and x in column_to_field_name ] if len(columns) > 1: unique_together.append( str(tuple(column_to_field_name[c] for c in columns)) ) if is_view: managed_comment = " # Created from a view. Don't remove." elif is_partition: managed_comment = " # Created from a partition. Don't remove." else: managed_comment = "" meta = [""] if has_unsupported_constraint: meta.append(" # A unique constraint could not be introspected.") meta += [ " class Meta:", " managed = False%s" % managed_comment, " db_table = %r" % table_name, ] if unique_together: tup = "(" + ", ".join(unique_together) + ",)" meta += [" unique_together = %s" % tup] return meta
b5b0826467947421b52f241fc6f3251b925768a4bee8623b876036c5aab99b7c
"""Redis cache backend.""" import pickle import random import re from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.functional import cached_property from django.utils.module_loading import import_string class RedisSerializer: def __init__(self, protocol=None): self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol def dumps(self, obj): # Only skip pickling for integers, a int subclasses as bool should be # pickled. if type(obj) is int: return obj return pickle.dumps(obj, self.protocol) def loads(self, data): try: return int(data) except ValueError: return pickle.loads(data) class RedisCacheClient: def __init__( self, servers, serializer=None, pool_class=None, parser_class=None, **options, ): import redis self._lib = redis self._servers = servers self._pools = {} self._client = self._lib.Redis if isinstance(pool_class, str): pool_class = import_string(pool_class) self._pool_class = pool_class or self._lib.ConnectionPool if isinstance(serializer, str): serializer = import_string(serializer) if callable(serializer): serializer = serializer() self._serializer = serializer or RedisSerializer() if isinstance(parser_class, str): parser_class = import_string(parser_class) parser_class = parser_class or self._lib.connection.DefaultParser self._pool_options = {"parser_class": parser_class, **options} def _get_connection_pool_index(self, write): # Write to the first server. Read from other servers if there are more, # otherwise read from the first server. if write or len(self._servers) == 1: return 0 return random.randint(1, len(self._servers) - 1) def _get_connection_pool(self, write): index = self._get_connection_pool_index(write) if index not in self._pools: self._pools[index] = self._pool_class.from_url( self._servers[index], **self._pool_options, ) return self._pools[index] def get_client(self, key=None, *, write=False): # key is used so that the method signature remains the same and custom # cache client can be implemented which might require the key to select # the server, e.g. sharding. pool = self._get_connection_pool(write) return self._client(connection_pool=pool) def add(self, key, value, timeout): client = self.get_client(key, write=True) value = self._serializer.dumps(value) if timeout == 0: if ret := bool(client.set(key, value, nx=True)): client.delete(key) return ret else: return bool(client.set(key, value, ex=timeout, nx=True)) def get(self, key, default): client = self.get_client(key) value = client.get(key) return default if value is None else self._serializer.loads(value) def set(self, key, value, timeout): client = self.get_client(key, write=True) value = self._serializer.dumps(value) if timeout == 0: client.delete(key) else: client.set(key, value, ex=timeout) def touch(self, key, timeout): client = self.get_client(key, write=True) if timeout is None: return bool(client.persist(key)) else: return bool(client.expire(key, timeout)) def delete(self, key): client = self.get_client(key, write=True) return bool(client.delete(key)) def get_many(self, keys): client = self.get_client(None) ret = client.mget(keys) return { k: self._serializer.loads(v) for k, v in zip(keys, ret) if v is not None } def has_key(self, key): client = self.get_client(key) return bool(client.exists(key)) def incr(self, key, delta): client = self.get_client(key) if not client.exists(key): raise ValueError("Key '%s' not found." % key) return client.incr(key, delta) def set_many(self, data, timeout): client = self.get_client(None, write=True) pipeline = client.pipeline() pipeline.mset({k: self._serializer.dumps(v) for k, v in data.items()}) if timeout is not None: # Setting timeout for each key as redis does not support timeout # with mset(). for key in data: pipeline.expire(key, timeout) pipeline.execute() def delete_many(self, keys): client = self.get_client(None, write=True) client.delete(*keys) def clear(self): client = self.get_client(None, write=True) return bool(client.flushdb()) class RedisCache(BaseCache): def __init__(self, server, params): super().__init__(params) if isinstance(server, str): self._servers = re.split("[;,]", server) else: self._servers = server self._class = RedisCacheClient self._options = params.get("OPTIONS", {}) @cached_property def _cache(self): return self._class(self._servers, **self._options) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout # The key will be made persistent if None used as a timeout. # Non-positive values will cause the key to be deleted. return None if timeout is None else max(0, int(timeout)) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.get(key, default) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) self._cache.set(key, value, self.get_backend_timeout(timeout)) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.touch(key, self.get_backend_timeout(timeout)) def delete(self, key, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.delete(key) def get_many(self, keys, version=None): key_map = { self.make_and_validate_key(key, version=version): key for key in keys } ret = self._cache.get_many(key_map.keys()) return {key_map[k]: v for k, v in ret.items()} def has_key(self, key, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.has_key(key) def incr(self, key, delta=1, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.incr(key, delta) def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): if not data: return [] safe_data = {} for key, value in data.items(): key = self.make_and_validate_key(key, version=version) safe_data[key] = value self._cache.set_many(safe_data, self.get_backend_timeout(timeout)) return [] def delete_many(self, keys, version=None): if not keys: return safe_keys = [self.make_and_validate_key(key, version=version) for key in keys] self._cache.delete_many(safe_keys) def clear(self): return self._cache.clear()
5dc5659684fd0fe3531a85a1d088de31592af247abde81ece164993fb85508c6
import warnings from django.contrib.postgres.indexes import OpClass from django.core.exceptions import ValidationError from django.db import DEFAULT_DB_ALIAS, NotSupportedError from django.db.backends.ddl_references import Expressions, Statement, Table from django.db.models import BaseConstraint, Deferrable, F, Q from django.db.models.expressions import Exists, ExpressionList from django.db.models.indexes import IndexExpression from django.db.models.lookups import PostgresOperatorLookup from django.db.models.sql import Query from django.utils.deprecation import RemovedInDjango50Warning __all__ = ["ExclusionConstraint"] class ExclusionConstraintExpression(IndexExpression): template = "%(expressions)s WITH %(operator)s" class ExclusionConstraint(BaseConstraint): template = ( "CONSTRAINT %(name)s EXCLUDE USING %(index_type)s " "(%(expressions)s)%(include)s%(where)s%(deferrable)s" ) def __init__( self, *, name, expressions, index_type=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None, ): if index_type and index_type.lower() not in {"gist", "spgist"}: raise ValueError( "Exclusion constraints only support GiST or SP-GiST indexes." ) if not expressions: raise ValueError( "At least one expression is required to define an exclusion " "constraint." ) if not all( isinstance(expr, (list, tuple)) and len(expr) == 2 for expr in expressions ): raise ValueError("The expressions must be a list of 2-tuples.") if not isinstance(condition, (type(None), Q)): raise ValueError("ExclusionConstraint.condition must be a Q instance.") if condition and deferrable: raise ValueError("ExclusionConstraint with conditions cannot be deferred.") if not isinstance(deferrable, (type(None), Deferrable)): raise ValueError( "ExclusionConstraint.deferrable must be a Deferrable instance." ) if not isinstance(include, (type(None), list, tuple)): raise ValueError("ExclusionConstraint.include must be a list or tuple.") if not isinstance(opclasses, (list, tuple)): raise ValueError("ExclusionConstraint.opclasses must be a list or tuple.") if opclasses and len(expressions) != len(opclasses): raise ValueError( "ExclusionConstraint.expressions and " "ExclusionConstraint.opclasses must have the same number of " "elements." ) self.expressions = expressions self.index_type = index_type or "GIST" self.condition = condition self.deferrable = deferrable self.include = tuple(include) if include else () self.opclasses = opclasses if self.opclasses: warnings.warn( "The opclasses argument is deprecated in favor of using " "django.contrib.postgres.indexes.OpClass in " "ExclusionConstraint.expressions.", category=RemovedInDjango50Warning, stacklevel=2, ) super().__init__(name=name, violation_error_message=violation_error_message) def _get_expressions(self, schema_editor, query): expressions = [] for idx, (expression, operator) in enumerate(self.expressions): if isinstance(expression, str): expression = F(expression) try: expression = OpClass(expression, self.opclasses[idx]) except IndexError: pass expression = ExclusionConstraintExpression(expression, operator=operator) expression.set_wrapper_classes(schema_editor.connection) expressions.append(expression) return ExpressionList(*expressions).resolve_expression(query) def _get_condition_sql(self, compiler, schema_editor, query): if self.condition is None: return None where = query.build_where(self.condition) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params) def constraint_sql(self, model, schema_editor): query = Query(model, alias_cols=False) compiler = query.get_compiler(connection=schema_editor.connection) expressions = self._get_expressions(schema_editor, query) table = model._meta.db_table condition = self._get_condition_sql(compiler, schema_editor, query) include = [ model._meta.get_field(field_name).column for field_name in self.include ] return Statement( self.template, table=Table(table, schema_editor.quote_name), name=schema_editor.quote_name(self.name), index_type=self.index_type, expressions=Expressions( table, expressions, compiler, schema_editor.quote_value ), where=" WHERE (%s)" % condition if condition else "", include=schema_editor._index_include_sql(model, include), deferrable=schema_editor._deferrable_constraint_sql(self.deferrable), ) def create_sql(self, model, schema_editor): self.check_supported(schema_editor) return Statement( "ALTER TABLE %(table)s ADD %(constraint)s", table=Table(model._meta.db_table, schema_editor.quote_name), constraint=self.constraint_sql(model, schema_editor), ) def remove_sql(self, model, schema_editor): return schema_editor._delete_constraint_sql( schema_editor.sql_delete_check, model, schema_editor.quote_name(self.name), ) def check_supported(self, schema_editor): if ( self.include and self.index_type.lower() == "spgist" and not schema_editor.connection.features.supports_covering_spgist_indexes ): raise NotSupportedError( "Covering exclusion constraints using an SP-GiST index " "require PostgreSQL 14+." ) def deconstruct(self): path, args, kwargs = super().deconstruct() kwargs["expressions"] = self.expressions if self.condition is not None: kwargs["condition"] = self.condition if self.index_type.lower() != "gist": kwargs["index_type"] = self.index_type if self.deferrable: kwargs["deferrable"] = self.deferrable if self.include: kwargs["include"] = self.include if self.opclasses: kwargs["opclasses"] = self.opclasses return path, args, kwargs def __eq__(self, other): if isinstance(other, self.__class__): return ( self.name == other.name and self.index_type == other.index_type and self.expressions == other.expressions and self.condition == other.condition and self.deferrable == other.deferrable and self.include == other.include and self.opclasses == other.opclasses and self.violation_error_message == other.violation_error_message ) return super().__eq__(other) def __repr__(self): return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s>" % ( self.__class__.__qualname__, repr(self.index_type), repr(self.expressions), repr(self.name), "" if self.condition is None else " condition=%s" % self.condition, "" if self.deferrable is None else " deferrable=%r" % self.deferrable, "" if not self.include else " include=%s" % repr(self.include), "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), ) def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): queryset = model._default_manager.using(using) replacement_map = instance._get_field_value_map( meta=model._meta, exclude=exclude ) lookups = [] for idx, (expression, operator) in enumerate(self.expressions): if isinstance(expression, str): expression = F(expression) if isinstance(expression, F): if exclude and expression.name in exclude: return rhs_expression = replacement_map.get(expression.name, expression) else: rhs_expression = expression.replace_references(replacement_map) if exclude: for expr in rhs_expression.flatten(): if isinstance(expr, F) and expr.name in exclude: return # Remove OpClass because it only has sense during the constraint # creation. if isinstance(expression, OpClass): expression = expression.get_source_expressions()[0] if isinstance(rhs_expression, OpClass): rhs_expression = rhs_expression.get_source_expressions()[0] lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression) lookup.postgres_operator = operator lookups.append(lookup) queryset = queryset.filter(*lookups) model_class_pk = instance._get_pk_val(model._meta) if not instance._state.adding and model_class_pk is not None: queryset = queryset.exclude(pk=model_class_pk) if not self.condition: if queryset.exists(): raise ValidationError(self.get_violation_error_message()) else: if (self.condition & Exists(queryset.filter(self.condition))).check( replacement_map, using=using ): raise ValidationError(self.get_violation_error_message())
406d7bb701d0495e6db3e0dbe6065301e03a37d2fb9725a9d965cfd5f22788ed
import warnings from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.db.models import Exists, OuterRef, Q from django.utils.deprecation import RemovedInDjango50Warning from django.utils.inspect import func_supports_parameter UserModel = get_user_model() class BaseBackend: def authenticate(self, request, **kwargs): return None def get_user(self, user_id): return None def get_user_permissions(self, user_obj, obj=None): return set() def get_group_permissions(self, user_obj, obj=None): return set() def get_all_permissions(self, user_obj, obj=None): return { *self.get_user_permissions(user_obj, obj=obj), *self.get_group_permissions(user_obj, obj=obj), } def has_perm(self, user_obj, perm, obj=None): return perm in self.get_all_permissions(user_obj, obj=obj) class ModelBackend(BaseBackend): """ Authenticates against settings.AUTH_USER_MODEL. """ def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def user_can_authenticate(self, user): """ Reject users with is_active=False. Custom user models that don't have that attribute are allowed. """ return getattr(user, "is_active", True) def _get_user_permissions(self, user_obj): return user_obj.user_permissions.all() def _get_group_permissions(self, user_obj): user_groups_field = get_user_model()._meta.get_field("groups") user_groups_query = "group__%s" % user_groups_field.related_query_name() return Permission.objects.filter(**{user_groups_query: user_obj}) def _get_permissions(self, user_obj, obj, from_name): """ Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively. """ if not user_obj.is_active or user_obj.is_anonymous or obj is not None: return set() perm_cache_name = "_%s_perm_cache" % from_name if not hasattr(user_obj, perm_cache_name): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj) perms = perms.values_list("content_type__app_label", "codename").order_by() setattr( user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms} ) return getattr(user_obj, perm_cache_name) def get_user_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from their `user_permissions`. """ return self._get_permissions(user_obj, obj, "user") def get_group_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from the groups they belong. """ return self._get_permissions(user_obj, obj, "group") def get_all_permissions(self, user_obj, obj=None): if not user_obj.is_active or user_obj.is_anonymous or obj is not None: return set() if not hasattr(user_obj, "_perm_cache"): user_obj._perm_cache = super().get_all_permissions(user_obj) return user_obj._perm_cache def has_perm(self, user_obj, perm, obj=None): return user_obj.is_active and super().has_perm(user_obj, perm, obj=obj) def has_module_perms(self, user_obj, app_label): """ Return True if user_obj has any permissions in the given app_label. """ return user_obj.is_active and any( perm[: perm.index(".")] == app_label for perm in self.get_all_permissions(user_obj) ) def with_perm(self, perm, is_active=True, include_superusers=True, obj=None): """ Return users that have permission "perm". By default, filter out inactive users and include superusers. """ if isinstance(perm, str): try: app_label, codename = perm.split(".") except ValueError: raise ValueError( "Permission name should be in the form " "app_label.permission_codename." ) elif not isinstance(perm, Permission): raise TypeError( "The `perm` argument must be a string or a permission instance." ) if obj is not None: return UserModel._default_manager.none() permission_q = Q(group__user=OuterRef("pk")) | Q(user=OuterRef("pk")) if isinstance(perm, Permission): permission_q &= Q(pk=perm.pk) else: permission_q &= Q(codename=codename, content_type__app_label=app_label) user_q = Exists(Permission.objects.filter(permission_q)) if include_superusers: user_q |= Q(is_superuser=True) if is_active is not None: user_q &= Q(is_active=is_active) return UserModel._default_manager.filter(user_q) def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None class AllowAllUsersModelBackend(ModelBackend): def user_can_authenticate(self, user): return True class RemoteUserBackend(ModelBackend): """ This backend is to be used in conjunction with the ``RemoteUserMiddleware`` found in the middleware module of this package, and is used when the server is handling authentication outside of Django. By default, the ``authenticate`` method creates ``User`` objects for usernames that don't already exist in the database. Subclasses can disable this behavior by setting the ``create_unknown_user`` attribute to ``False``. """ # Create a User object if not already in the database? create_unknown_user = True def authenticate(self, request, remote_user): """ The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``. Return None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found in the database. """ if not remote_user: return created = False user = None username = self.clean_username(remote_user) # Note that this could be accomplished in one try-except clause, but # instead we use get_or_create when creating unknown users since it has # built-in safeguards for multiple threads. if self.create_unknown_user: user, created = UserModel._default_manager.get_or_create( **{UserModel.USERNAME_FIELD: username} ) else: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: pass # RemovedInDjango50Warning: When the deprecation ends, replace with: # user = self.configure_user(request, user, created=created) if func_supports_parameter(self.configure_user, "created"): user = self.configure_user(request, user, created=created) else: warnings.warn( f"`created=True` must be added to the signature of " f"{self.__class__.__qualname__}.configure_user().", category=RemovedInDjango50Warning, ) if created: user = self.configure_user(request, user) return user if self.user_can_authenticate(user) else None def clean_username(self, username): """ Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username. By default, return the username unchanged. """ return username def configure_user(self, request, user, created=True): """ Configure a user and return the updated user. By default, return the user unmodified. """ return user class AllowAllUsersRemoteUserBackend(RemoteUserBackend): def user_can_authenticate(self, user): return True
755468dc2b95f19a79f36da1f65e3c9c0a625f29f7942b97415defb1164a79aa
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures): empty_intersection_returns_none = False has_spatialrefsys_table = False supports_add_srs_entry = False supports_distance_geodetic = False supports_length_geodetic = False supports_area_geodetic = False supports_transform = False supports_null_geometries = False supports_num_points_poly = False unsupported_geojson_options = {"crs"} @cached_property def supports_geometry_field_unique_index(self): # Not supported in MySQL since https://dev.mysql.com/worklog/task/?id=11808 return self.connection.mysql_is_mariadb
66285c4b3c0dd1ff22a8a39828c1ee43f318e351114acc233f8e9dbc2174bfaf
from MySQLdb.constants import FIELD_TYPE from django.contrib.gis.gdal import OGRGeomType from django.db.backends.mysql.introspection import DatabaseIntrospection class MySQLIntrospection(DatabaseIntrospection): # Updating the data_types_reverse dictionary with the appropriate # type for Geometry fields. data_types_reverse = DatabaseIntrospection.data_types_reverse.copy() data_types_reverse[FIELD_TYPE.GEOMETRY] = "GeometryField" def get_geometry_type(self, table_name, description): with self.connection.cursor() as cursor: # In order to get the specific geometry type of the field, # we introspect on the table definition using `DESCRIBE`. cursor.execute("DESCRIBE %s" % self.connection.ops.quote_name(table_name)) # Increment over description info until we get to the geometry # column. for column, typ, null, key, default, extra in cursor.fetchall(): if column == description.name: # Using OGRGeomType to convert from OGC name to Django field. # MySQL does not support 3D or SRIDs, so the field params # are empty. field_type = OGRGeomType(typ).django field_params = {} break return field_type, field_params def supports_spatial_index(self, cursor, table_name): # Supported with MyISAM, Aria, or InnoDB. storage_engine = self.get_storage_engine(cursor, table_name) return storage_engine in ("MyISAM", "Aria", "InnoDB")
2bfe4d2743beb407c4e54dd969b7787fe9bb4752f0356fdc5cd362cf48dbf792
from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.adapter import WKTAdapter from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.mysql.operations import DatabaseOperations from django.utils.functional import cached_property class MySQLOperations(BaseSpatialOperations, DatabaseOperations): name = "mysql" geom_func_prefix = "ST_" Adapter = WKTAdapter @cached_property def mariadb(self): return self.connection.mysql_is_mariadb @cached_property def mysql(self): return not self.connection.mysql_is_mariadb @cached_property def select(self): return self.geom_func_prefix + "AsBinary(%s)" @cached_property def from_text(self): return self.geom_func_prefix + "GeomFromText" @cached_property def gis_operators(self): operators = { "bbcontains": SpatialOperator( func="MBRContains" ), # For consistency w/PostGIS API "bboverlaps": SpatialOperator(func="MBROverlaps"), # ... "contained": SpatialOperator(func="MBRWithin"), # ... "contains": SpatialOperator(func="ST_Contains"), "crosses": SpatialOperator(func="ST_Crosses"), "disjoint": SpatialOperator(func="ST_Disjoint"), "equals": SpatialOperator(func="ST_Equals"), "exact": SpatialOperator(func="ST_Equals"), "intersects": SpatialOperator(func="ST_Intersects"), "overlaps": SpatialOperator(func="ST_Overlaps"), "same_as": SpatialOperator(func="ST_Equals"), "touches": SpatialOperator(func="ST_Touches"), "within": SpatialOperator(func="ST_Within"), } if self.connection.mysql_is_mariadb: operators["relate"] = SpatialOperator(func="ST_Relate") return operators disallowed_aggregates = ( models.Collect, models.Extent, models.Extent3D, models.MakeLine, models.Union, ) @cached_property def unsupported_functions(self): unsupported = { "AsGML", "AsKML", "AsSVG", "Azimuth", "BoundingCircle", "ForcePolygonCW", "GeometryDistance", "LineLocatePoint", "MakeValid", "MemSize", "Perimeter", "PointOnSurface", "Reverse", "Scale", "SnapToGrid", "Transform", "Translate", } if self.connection.mysql_is_mariadb: unsupported.remove("PointOnSurface") unsupported.update({"GeoHash", "IsValid"}) return unsupported def geo_db_type(self, f): return f.geom_type def get_distance(self, f, value, lookup_type): value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError( "Only numeric values of degree units are allowed on " "geodetic distance queries." ) dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value return [dist_param] def get_geometry_converter(self, expression): read = wkb_r().read srid = expression.output_field.srid if srid == -1: srid = None geom_class = expression.output_field.geom_class def converter(value, expression, connection): if value is not None: geom = GEOSGeometryBase(read(memoryview(value)), geom_class) if srid: geom.srid = srid return geom return converter
5d96f522628d1593541193317602d85c6b385e2ae0c3c90aa061cd549bfbeb71
import logging from django.contrib.gis.db.models import GeometryField from django.db import OperationalError from django.db.backends.mysql.schema import DatabaseSchemaEditor logger = logging.getLogger("django.contrib.gis") class MySQLGISSchemaEditor(DatabaseSchemaEditor): sql_add_spatial_index = "CREATE SPATIAL INDEX %(index)s ON %(table)s(%(column)s)" sql_drop_spatial_index = "DROP INDEX %(index)s ON %(table)s" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry_sql = [] def skip_default(self, field): # Geometry fields are stored as BLOB/TEXT, for which MySQL < 8.0.13 # doesn't support defaults. if ( isinstance(field, GeometryField) and not self._supports_limited_data_type_defaults ): return True return super().skip_default(field) def quote_value(self, value): if isinstance(value, self.connection.ops.Adapter): return super().quote_value(str(value)) return super().quote_value(value) def column_sql(self, model, field, include_default=False): column_sql = super().column_sql(model, field, include_default) # MySQL doesn't support spatial indexes on NULL columns if isinstance(field, GeometryField) and field.spatial_index and not field.null: qn = self.connection.ops.quote_name db_table = model._meta.db_table self.geometry_sql.append( self.sql_add_spatial_index % { "index": qn(self._create_spatial_index_name(model, field)), "table": qn(db_table), "column": qn(field.column), } ) return column_sql def create_model(self, model): super().create_model(model) self.create_spatial_indexes() def add_field(self, model, field): super().add_field(model, field) self.create_spatial_indexes() def remove_field(self, model, field): if isinstance(field, GeometryField) and field.spatial_index: qn = self.connection.ops.quote_name sql = self.sql_drop_spatial_index % { "index": qn(self._create_spatial_index_name(model, field)), "table": qn(model._meta.db_table), } try: self.execute(sql) except OperationalError: logger.error( "Couldn't remove spatial index: %s (may be expected " "if your storage engine doesn't support them).", sql, ) super().remove_field(model, field) def _create_spatial_index_name(self, model, field): return "%s_%s_id" % (model._meta.db_table, field.column) def create_spatial_indexes(self): for sql in self.geometry_sql: try: self.execute(sql) except OperationalError: logger.error( f"Cannot create SPATIAL INDEX {sql}. Only MyISAM, Aria, and InnoDB " f"support them.", ) self.geometry_sql = []
0d2c0c7210589eddb61821d40b58f7136391f3758cd2141928275b617712610e
from django.db import migrations, models from django.db.migrations import operations from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.serializer import serializer_factory from django.test import SimpleTestCase from .models import EmptyManager, UnicodeModel class OptimizerTests(SimpleTestCase): """ Tests the migration autodetector. """ def optimize(self, operations, app_label): """ Handy shortcut for getting results + number of loops """ optimizer = MigrationOptimizer() return optimizer.optimize(operations, app_label), optimizer._iterations def serialize(self, value): return serializer_factory(value).serialize()[0] def assertOptimizesTo( self, operations, expected, exact=None, less_than=None, app_label=None ): result, iterations = self.optimize(operations, app_label or "migrations") result = [self.serialize(f) for f in result] expected = [self.serialize(f) for f in expected] self.assertEqual(expected, result) if exact is not None and iterations != exact: raise self.failureException( "Optimization did not take exactly %s iterations (it took %s)" % (exact, iterations) ) if less_than is not None and iterations >= less_than: raise self.failureException( "Optimization did not take less than %s iterations (it took %s)" % (less_than, iterations) ) def assertDoesNotOptimize(self, operations, **kwargs): self.assertOptimizesTo(operations, operations, **kwargs) def test_none_app_label(self): optimizer = MigrationOptimizer() with self.assertRaisesMessage(TypeError, "app_label must be a str"): optimizer.optimize([], None) def test_single(self): """ The optimizer does nothing on a single operation, and that it does it in just one pass. """ self.assertOptimizesTo( [migrations.DeleteModel("Foo")], [migrations.DeleteModel("Foo")], exact=1, ) def test_create_delete_model(self): """ CreateModel and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.DeleteModel("Foo"), ], [], ) def test_create_rename_model(self): """ CreateModel should absorb RenameModels. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameModel("Foo", "Bar"), ], [ migrations.CreateModel( "Bar", [("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ) ], ) def test_rename_model_self(self): """ RenameModels should absorb themselves. """ self.assertOptimizesTo( [ migrations.RenameModel("Foo", "Baa"), migrations.RenameModel("Baa", "Bar"), ], [ migrations.RenameModel("Foo", "Bar"), ], ) def test_create_alter_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelOptions( name="Foo", options={"verbose_name_plural": "Foozes"} ), ], [ migrations.CreateModel( "Foo", fields=[], options={"verbose_name_plural": "Foozes"} ), ], ) def test_create_alter_model_managers(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelManagers( name="Foo", managers=[ ("objects", models.Manager()), ("things", models.Manager()), ], ), ], [ migrations.CreateModel( "Foo", fields=[], managers=[ ("objects", models.Manager()), ("things", models.Manager()), ], ), ], ) def test_create_model_and_remove_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel( "MyModel", fields=[], options={"verbose_name": "My Model"}, ), migrations.AlterModelOptions("MyModel", options={}), ], [migrations.CreateModel("MyModel", fields=[])], ) self.assertOptimizesTo( [ migrations.CreateModel( "MyModel", fields=[], options={ "verbose_name": "My Model", "verbose_name_plural": "My Model plural", }, ), migrations.AlterModelOptions( "MyModel", options={"verbose_name": "My Model"}, ), ], [ migrations.CreateModel( "MyModel", fields=[], options={"verbose_name": "My Model"}, ), ], ) def _test_create_alter_foo_delete_model(self, alter_foo): """ CreateModel, AlterModelTable, AlterUniqueTogether/AlterIndexTogether/ AlterOrderWithRespectTo, and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.AlterModelTable("Foo", "woohoo"), alter_foo, migrations.DeleteModel("Foo"), ], [], ) def test_create_alter_unique_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterUniqueTogether("Foo", [["a", "b"]]) ) # RemovedInDjango51Warning. def test_create_alter_index_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterIndexTogether("Foo", [["a", "b"]]) ) def test_create_alter_owrt_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterOrderWithRespectTo("Foo", "a") ) def _test_alter_alter_model(self, alter_foo, alter_bar): """ Two AlterUniqueTogether/AlterIndexTogether/AlterOrderWithRespectTo should collapse into the second. """ self.assertOptimizesTo( [ alter_foo, alter_bar, ], [ alter_bar, ], ) def test_alter_alter_table_model(self): self._test_alter_alter_model( migrations.AlterModelTable("Foo", "a"), migrations.AlterModelTable("Foo", "b"), ) def test_alter_alter_unique_model(self): self._test_alter_alter_model( migrations.AlterUniqueTogether("Foo", [["a", "b"]]), migrations.AlterUniqueTogether("Foo", [["a", "c"]]), ) # RemovedInDjango51Warning. def test_alter_alter_index_model(self): self._test_alter_alter_model( migrations.AlterIndexTogether("Foo", [["a", "b"]]), migrations.AlterIndexTogether("Foo", [["a", "c"]]), ) def test_alter_alter_owrt_model(self): self._test_alter_alter_model( migrations.AlterOrderWithRespectTo("Foo", "a"), migrations.AlterOrderWithRespectTo("Foo", "b"), ) def test_optimize_through_create(self): """ We should be able to optimize away create/delete through a create or delete of a different model, but only if the create operation does not mention the model at all. """ # These should work self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel("Bar", [("size", models.IntegerField())]), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Bar"), migrations.DeleteModel("Foo"), ], [], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Foo"), migrations.DeleteModel("Bar"), ], [], ) # Operations should be optimized if the FK references a model from the # other app. self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), ], app_label="otherapp", ) # But it shouldn't work if a FK references a model with the same # app_label. self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], ) self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) # This should not work - bases should block it self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("Foo",) ), migrations.DeleteModel("Foo"), ], ) self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) # The same operations should be optimized if app_label and none of # bases belong to that app. self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), ], app_label="otherapp", ) # But it shouldn't work if some of bases belongs to the specified app. self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) self.assertOptimizesTo( [ migrations.CreateModel( "Book", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Person", [("name", models.CharField(max_length=255))] ), migrations.AddField( "book", "author", models.ForeignKey("test_app.Person", models.CASCADE), ), migrations.CreateModel( "Review", [("book", models.ForeignKey("test_app.Book", models.CASCADE))], ), migrations.CreateModel( "Reviewer", [("name", models.CharField(max_length=255))] ), migrations.AddField( "review", "reviewer", models.ForeignKey("test_app.Reviewer", models.CASCADE), ), migrations.RemoveField("book", "author"), migrations.DeleteModel("Person"), ], [ migrations.CreateModel( "Book", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Reviewer", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Review", [ ("book", models.ForeignKey("test_app.Book", models.CASCADE)), ( "reviewer", models.ForeignKey("test_app.Reviewer", models.CASCADE), ), ], ), ], app_label="test_app", ) def test_create_model_add_field(self): """ AddField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.AddField("Foo", "age", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_create_model_reordering(self): """ AddField optimizes into CreateModel if it's a FK to a model that's between them (and there's no FK in the other direction), by changing the order of the CreateModel operations. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Link", [("url", models.TextField())]), migrations.AddField( "Foo", "link", models.ForeignKey("migrations.Link", models.CASCADE) ), ], [ migrations.CreateModel("Link", [("url", models.TextField())]), migrations.CreateModel( "Foo", [ ("name", models.CharField(max_length=255)), ("link", models.ForeignKey("migrations.Link", models.CASCADE)), ], ), ], ) def test_create_model_reordering_circular_fk(self): """ CreateModel reordering behavior doesn't result in an infinite loop if there are FKs in both directions. """ self.assertOptimizesTo( [ migrations.CreateModel("Bar", [("url", models.TextField())]), migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.AddField( "Bar", "foo_fk", models.ForeignKey("migrations.Foo", models.CASCADE) ), migrations.AddField( "Foo", "bar_fk", models.ForeignKey("migrations.Bar", models.CASCADE) ), ], [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [ ("url", models.TextField()), ("foo_fk", models.ForeignKey("migrations.Foo", models.CASCADE)), ], ), migrations.AddField( "Foo", "bar_fk", models.ForeignKey("migrations.Bar", models.CASCADE) ), ], ) def test_create_model_no_reordering_for_unrelated_fk(self): """ CreateModel order remains unchanged if the later AddField operation isn't a FK between them. """ self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Link", [("url", models.TextField())]), migrations.AddField( "Other", "link", models.ForeignKey("migrations.Link", models.CASCADE), ), ], ) def test_create_model_no_reordering_of_inherited_model(self): """ A CreateModel that inherits from another isn't reordered to avoid moving it earlier than its parent CreateModel operation. """ self.assertOptimizesTo( [ migrations.CreateModel( "Other", [("foo", models.CharField(max_length=255))] ), migrations.CreateModel( "ParentModel", [("bar", models.CharField(max_length=255))] ), migrations.CreateModel( "ChildModel", [("baz", models.CharField(max_length=255))], bases=("migrations.parentmodel",), ), migrations.AddField( "Other", "fk", models.ForeignKey("migrations.ChildModel", models.CASCADE), ), ], [ migrations.CreateModel( "ParentModel", [("bar", models.CharField(max_length=255))] ), migrations.CreateModel( "ChildModel", [("baz", models.CharField(max_length=255))], bases=("migrations.parentmodel",), ), migrations.CreateModel( "Other", [ ("foo", models.CharField(max_length=255)), ( "fk", models.ForeignKey("migrations.ChildModel", models.CASCADE), ), ], ), ], ) def test_create_model_add_field_not_through_m2m_through(self): """ AddField should NOT optimize into CreateModel if it's an M2M using a through that's created between them. """ self.assertDoesNotOptimize( [ migrations.CreateModel("Employee", []), migrations.CreateModel("Employer", []), migrations.CreateModel( "Employment", [ ( "employee", models.ForeignKey("migrations.Employee", models.CASCADE), ), ( "employment", models.ForeignKey("migrations.Employer", models.CASCADE), ), ], ), migrations.AddField( "Employer", "employees", models.ManyToManyField( "migrations.Employee", through="migrations.Employment", ), ), ], ) def test_create_model_alter_field(self): """ AlterField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.AlterField("Foo", "name", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_create_model_rename_field(self): """ RenameField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameField("Foo", "name", "title"), ], [ migrations.CreateModel( name="Foo", fields=[ ("title", models.CharField(max_length=255)), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_add_field_rename_field(self): """ RenameField should optimize into AddField """ self.assertOptimizesTo( [ migrations.AddField("Foo", "name", models.CharField(max_length=255)), migrations.RenameField("Foo", "name", "title"), ], [ migrations.AddField("Foo", "title", models.CharField(max_length=255)), ], ) def test_alter_field_rename_field(self): """ RenameField should optimize to the other side of AlterField, and into itself. """ self.assertOptimizesTo( [ migrations.AlterField("Foo", "name", models.CharField(max_length=255)), migrations.RenameField("Foo", "name", "title"), migrations.RenameField("Foo", "title", "nom"), ], [ migrations.RenameField("Foo", "name", "nom"), migrations.AlterField("Foo", "nom", models.CharField(max_length=255)), ], ) def test_swapping_fields_names(self): self.assertDoesNotOptimize( [ migrations.CreateModel( "MyModel", [ ("field_a", models.IntegerField()), ("field_b", models.IntegerField()), ], ), migrations.RunPython(migrations.RunPython.noop), migrations.RenameField("MyModel", "field_a", "field_c"), migrations.RenameField("MyModel", "field_b", "field_a"), migrations.RenameField("MyModel", "field_c", "field_b"), ], ) def test_create_model_remove_field(self): """ RemoveField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RemoveField("Foo", "age"), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_add_field_alter_field(self): """ AlterField should optimize into AddField. """ self.assertOptimizesTo( [ migrations.AddField("Foo", "age", models.IntegerField()), migrations.AlterField("Foo", "age", models.FloatField(default=2.4)), ], [ migrations.AddField( "Foo", name="age", field=models.FloatField(default=2.4) ), ], ) def test_add_field_delete_field(self): """ RemoveField should cancel AddField """ self.assertOptimizesTo( [ migrations.AddField("Foo", "age", models.IntegerField()), migrations.RemoveField("Foo", "age"), ], [], ) def test_alter_field_delete_field(self): """ RemoveField should absorb AlterField """ self.assertOptimizesTo( [ migrations.AlterField("Foo", "age", models.IntegerField()), migrations.RemoveField("Foo", "age"), ], [ migrations.RemoveField("Foo", "age"), ], ) def _test_create_alter_foo_field(self, alter): """ CreateModel, AlterFooTogether/AlterOrderWithRespectTo followed by an add/alter/rename field should optimize to CreateModel with options. """ option_value = getattr(alter, alter.option_name) options = {alter.option_name: option_value} # AddField self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.AddField("Foo", "c", models.IntegerField()), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], options=options, ), ], ) # AlterField self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.AlterField("Foo", "b", models.CharField(max_length=255)), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.CharField(max_length=255)), ], options=options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.AlterField("Foo", "c", models.CharField(max_length=255)), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.CharField(max_length=255)), ], options=options, ), ], ) # RenameField if isinstance(option_value, str): renamed_options = {alter.option_name: "c"} else: renamed_options = { alter.option_name: { tuple("c" if value == "b" else value for value in item) for item in option_value } } self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "b", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("c", models.IntegerField()), ], options=renamed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "b", "x"), migrations.RenameField("Foo", "x", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("c", models.IntegerField()), ], options=renamed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "c", "d"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("d", models.IntegerField()), ], options=options, ), ], ) # RemoveField if isinstance(option_value, str): removed_options = None else: removed_options = { alter.option_name: { tuple(value for value in item if value != "b") for item in option_value } } self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RemoveField("Foo", "b"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ], options=removed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.RemoveField("Foo", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], options=options, ), ], ) def test_create_alter_unique_field(self): self._test_create_alter_foo_field( migrations.AlterUniqueTogether("Foo", [["a", "b"]]) ) # RemovedInDjango51Warning. def test_create_alter_index_field(self): self._test_create_alter_foo_field( migrations.AlterIndexTogether("Foo", [["a", "b"]]) ) def test_create_alter_owrt_field(self): self._test_create_alter_foo_field( migrations.AlterOrderWithRespectTo("Foo", "b") ) def test_optimize_through_fields(self): """ field-level through checking is working. This should manage to collapse model Foo to nonexistence, and model Bar to a single IntegerField called "width". """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.AddField("Foo", "age", models.IntegerField()), migrations.AddField("Bar", "width", models.IntegerField()), migrations.AlterField("Foo", "age", models.IntegerField()), migrations.RenameField("Bar", "size", "dimensions"), migrations.RemoveField("Foo", "age"), migrations.RenameModel("Foo", "Phou"), migrations.RemoveField("Bar", "dimensions"), migrations.RenameModel("Phou", "Fou"), migrations.DeleteModel("Fou"), ], [ migrations.CreateModel("Bar", [("width", models.IntegerField())]), ], ) def test_optimize_elidable_operation(self): elidable_operation = operations.base.Operation() elidable_operation.elidable = True self.assertOptimizesTo( [ elidable_operation, migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), elidable_operation, migrations.CreateModel("Bar", [("size", models.IntegerField())]), elidable_operation, migrations.RenameModel("Foo", "Phou"), migrations.DeleteModel("Bar"), elidable_operation, ], [ migrations.CreateModel( "Phou", [("name", models.CharField(max_length=255))] ), ], ) def test_rename_index(self): self.assertOptimizesTo( [ migrations.RenameIndex( "Pony", new_name="mid_name", old_fields=("weight", "pink") ), migrations.RenameIndex( "Pony", new_name="new_name", old_name="mid_name" ), ], [ migrations.RenameIndex( "Pony", new_name="new_name", old_fields=("weight", "pink") ), ], ) self.assertOptimizesTo( [ migrations.RenameIndex( "Pony", new_name="mid_name", old_name="old_name" ), migrations.RenameIndex( "Pony", new_name="new_name", old_name="mid_name" ), ], [migrations.RenameIndex("Pony", new_name="new_name", old_name="old_name")], ) self.assertDoesNotOptimize( [ migrations.RenameIndex( "Pony", new_name="mid_name", old_name="old_name" ), migrations.RenameIndex( "Pony", new_name="new_name", old_fields=("weight", "pink") ), ] )
4e2419edee24a7e1b68ffc4184d192e317e26f4289c860be7c15d69436a11942
from django.core.exceptions import FieldDoesNotExist from django.db import IntegrityError, connection, migrations, models, transaction from django.db.migrations.migration import Migration from django.db.migrations.operations.fields import FieldOperation from django.db.migrations.state import ModelState, ProjectState from django.db.models.functions import Abs from django.db.transaction import atomic from django.test import ( SimpleTestCase, ignore_warnings, override_settings, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext from django.utils.deprecation import RemovedInDjango51Warning from .models import FoodManager, FoodQuerySet, UnicodeModel from .test_base import OperationTestBase class Mixin: pass class OperationTests(OperationTestBase): """ Tests running the operations and making sure they do what they say they do. Each test looks at their state changing, and then their database operation - both forwards and backwards. """ def test_create_model(self): """ Tests the CreateModel operation. Most other tests use this operation as part of setup, so check failures here first. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) self.assertEqual(operation.describe(), "Create model Pony") self.assertEqual(operation.migration_name_fragment, "pony") # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["fields", "name"]) # And default manager not in set operation = migrations.CreateModel( "Foo", fields=[], managers=[("objects", models.Manager())] ) definition = operation.deconstruct() self.assertNotIn("managers", definition[2]) def test_create_model_with_duplicate_field_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value pink in CreateModel fields argument." ): migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.TextField()), ("pink", models.IntegerField(default=1)), ], ) def test_create_model_with_duplicate_base(self): message = "Found duplicate value test_crmo.pony in CreateModel bases argument." with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.Pony", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.pony", ), ) message = ( "Found duplicate value migrations.unicodemodel in CreateModel bases " "argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, UnicodeModel, ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.unicodemodel", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.UnicodeModel", ), ) message = ( "Found duplicate value <class 'django.db.models.base.Model'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( models.Model, models.Model, ), ) message = ( "Found duplicate value <class 'migrations.test_operations.Mixin'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( Mixin, Mixin, ), ) def test_create_model_with_duplicate_manager_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value objects in CreateModel managers argument.", ): migrations.CreateModel( "Pony", fields=[], managers=[ ("objects", models.Manager()), ("objects", models.Manager()), ], ) def test_create_model_with_unique_after(self): """ Tests the CreateModel operation directly followed by an AlterUniqueTogether (bug #22844 - sqlite remake issues) """ operation1 = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) operation2 = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("number", models.IntegerField(default=1)), ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)), ], ) operation3 = migrations.AlterUniqueTogether( "Rider", [ ("number", "pony"), ], ) # Test the database alteration project_state = ProjectState() self.assertTableNotExists("test_crmoua_pony") self.assertTableNotExists("test_crmoua_rider") with connection.schema_editor() as editor: new_state = project_state.clone() operation1.state_forwards("test_crmoua", new_state) operation1.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation2.state_forwards("test_crmoua", new_state) operation2.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation3.state_forwards("test_crmoua", new_state) operation3.database_forwards( "test_crmoua", editor, project_state, new_state ) self.assertTableExists("test_crmoua_pony") self.assertTableExists("test_crmoua_rider") def test_create_model_m2m(self): """ Test the creation of a model with a ManyToMany field and the auto-created "through" model. """ project_state = self.set_up_test_model("test_crmomm") operation = migrations.CreateModel( "Stable", [ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("Pony", related_name="stables")), ], ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_crmomm", new_state) # Test the database alteration self.assertTableNotExists("test_crmomm_stable_ponies") with connection.schema_editor() as editor: operation.database_forwards("test_crmomm", editor, project_state, new_state) self.assertTableExists("test_crmomm_stable") self.assertTableExists("test_crmomm_stable_ponies") self.assertColumnNotExists("test_crmomm_stable", "ponies") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_crmomm", "Pony") Stable = new_state.apps.get_model("test_crmomm", "Stable") stable = Stable.objects.create() p1 = Pony.objects.create(pink=False, weight=4.55) p2 = Pony.objects.create(pink=True, weight=5.43) stable.ponies.add(p1, p2) self.assertEqual(stable.ponies.count(), 2) stable.ponies.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmomm", editor, new_state, project_state ) self.assertTableNotExists("test_crmomm_stable") self.assertTableNotExists("test_crmomm_stable_ponies") @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_create_fk_models_to_pk_field_db_collation(self): """Creation of models with a FK to a PK with db_collation.""" collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_cfkmtopkfdbc" operations = [ migrations.CreateModel( "Pony", [ ( "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ), ], ) ] project_state = self.apply_operations(app_label, ProjectState(), operations) # ForeignKey. new_state = project_state.clone() operation = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # OneToOneField. new_state = project_state.clone() operation = migrations.CreateModel( "ShetlandPony", [ ( "pony", models.OneToOneField("Pony", models.CASCADE, primary_key=True), ), ("cuteness", models.IntegerField(default=1)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_shetlandpony", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_create_model_inheritance(self): """ Tests the CreateModel operation on a multi-table inheritance setup. """ project_state = self.set_up_test_model("test_crmoih") # Test the state alteration operation = migrations.CreateModel( "ShetlandPony", [ ( "pony_ptr", models.OneToOneField( "test_crmoih.Pony", models.CASCADE, auto_created=True, primary_key=True, to_field="id", serialize=False, ), ), ("cuteness", models.IntegerField(default=1)), ], ) new_state = project_state.clone() operation.state_forwards("test_crmoih", new_state) self.assertIn(("test_crmoih", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crmoih_shetlandpony") with connection.schema_editor() as editor: operation.database_forwards("test_crmoih", editor, project_state, new_state) self.assertTableExists("test_crmoih_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmoih", editor, new_state, project_state ) self.assertTableNotExists("test_crmoih_shetlandpony") def test_create_proxy_model(self): """ CreateModel ignores proxy models. """ project_state = self.set_up_test_model("test_crprmo") # Test the state alteration operation = migrations.CreateModel( "ProxyPony", [], options={"proxy": True}, bases=("test_crprmo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model ProxyPony") new_state = project_state.clone() operation.state_forwards("test_crprmo", new_state) self.assertIn(("test_crprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crprmo", editor, project_state, new_state) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crprmo", editor, new_state, project_state ) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"]) def test_create_unmanaged_model(self): """ CreateModel ignores unmanaged models. """ project_state = self.set_up_test_model("test_crummo") # Test the state alteration operation = migrations.CreateModel( "UnmanagedPony", [], options={"proxy": True}, bases=("test_crummo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony") new_state = project_state.clone() operation.state_forwards("test_crummo", new_state) self.assertIn(("test_crummo", "unmanagedpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crummo", editor, project_state, new_state) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crummo", editor, new_state, project_state ) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_constraint(self): where = models.Q(pink__gt=2) check_constraint = models.CheckConstraint( check=where, name="test_constraint_pony_pink_gt_2" ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [check_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)") # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2]["options"]["constraints"], [check_constraint]) @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_boolean_expression_in_check_constraint(self): app_label = "test_crmobechc" rawsql_constraint = models.CheckConstraint( check=models.expressions.RawSQL( "price < %s", (1000,), output_field=models.BooleanField() ), name=f"{app_label}_price_lt_1000_raw", ) wrapper_constraint = models.CheckConstraint( check=models.expressions.ExpressionWrapper( models.Q(price__gt=500) | models.Q(price__lt=500), output_field=models.BooleanField(), ), name=f"{app_label}_price_neq_500_wrap", ) operation = migrations.CreateModel( "Product", [ ("id", models.AutoField(primary_key=True)), ("price", models.IntegerField(null=True)), ], options={"constraints": [rawsql_constraint, wrapper_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Add table. self.assertTableNotExists(app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertTableExists(f"{app_label}_product") insert_sql = f"INSERT INTO {app_label}_product (id, price) VALUES (%d, %d)" with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (1, 1000)) cursor.execute(insert_sql % (1, 999)) with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (2, 500)) cursor.execute(insert_sql % (2, 499)) def test_create_model_with_partial_unique_constraint(self): partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [partial_unique_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # Test constraint works Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [partial_unique_constraint] ) def test_create_model_with_deferred_unique_constraint(self): deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferrable_pink_constraint", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [deferred_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [deferred_unique_constraint], ) @skipUnlessDBFeature("supports_covering_indexes") def test_create_model_with_covering_unique_constraint(self): covering_unique_constraint = models.UniqueConstraint( fields=["pink"], include=["weight"], name="test_constraint_pony_pink_covering_weight", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [covering_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [covering_unique_constraint], ) def test_create_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_cmoma") # Test the state alteration operation = migrations.CreateModel( "Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Create model Food") new_state = project_state.clone() operation.state_forwards("test_cmoma", new_state) self.assertIn(("test_cmoma", "food"), new_state.models) managers = new_state.models["test_cmoma", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) def test_delete_model(self): """ Tests the DeleteModel operation. """ project_state = self.set_up_test_model("test_dlmo") # Test the state alteration operation = migrations.DeleteModel("Pony") self.assertEqual(operation.describe(), "Delete model Pony") self.assertEqual(operation.migration_name_fragment, "delete_pony") new_state = project_state.clone() operation.state_forwards("test_dlmo", new_state) self.assertNotIn(("test_dlmo", "pony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dlmo", editor, project_state, new_state) self.assertTableNotExists("test_dlmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_dlmo", editor, new_state, project_state) self.assertTableExists("test_dlmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "DeleteModel") self.assertEqual(definition[1], []) self.assertEqual(list(definition[2]), ["name"]) def test_delete_proxy_model(self): """ Tests the DeleteModel operation ignores proxy models. """ project_state = self.set_up_test_model("test_dlprmo", proxy_model=True) # Test the state alteration operation = migrations.DeleteModel("ProxyPony") new_state = project_state.clone() operation.state_forwards("test_dlprmo", new_state) self.assertIn(("test_dlprmo", "proxypony"), project_state.models) self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") with connection.schema_editor() as editor: operation.database_forwards("test_dlprmo", editor, project_state, new_state) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlprmo", editor, new_state, project_state ) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") def test_delete_mti_model(self): project_state = self.set_up_test_model("test_dlmtimo", mti_model=True) # Test the state alteration operation = migrations.DeleteModel("ShetlandPony") new_state = project_state.clone() operation.state_forwards("test_dlmtimo", new_state) self.assertIn(("test_dlmtimo", "shetlandpony"), project_state.models) self.assertNotIn(("test_dlmtimo", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") with connection.schema_editor() as editor: operation.database_forwards( "test_dlmtimo", editor, project_state, new_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableNotExists("test_dlmtimo_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlmtimo", editor, new_state, project_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") def test_rename_model(self): """ Tests the RenameModel operation. """ project_state = self.set_up_test_model("test_rnmo", related_model=True) # Test the state alteration operation = migrations.RenameModel("Pony", "Horse") self.assertEqual(operation.describe(), "Rename model Pony to Horse") self.assertEqual(operation.migration_name_fragment, "rename_pony_horse") # Test initial state and database self.assertIn(("test_rnmo", "pony"), project_state.models) self.assertNotIn(("test_rnmo", "horse"), project_state.models) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate forwards new_state = project_state.clone() atomic_rename = connection.features.supports_atomic_references_rename new_state = self.apply_operations( "test_rnmo", new_state, [operation], atomic=atomic_rename ) # Test new state and database self.assertNotIn(("test_rnmo", "pony"), new_state.models) self.assertIn(("test_rnmo", "horse"), new_state.models) # RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( new_state.models["test_rnmo", "rider"].fields["pony"].remote_field.model, "test_rnmo.Horse", ) self.assertTableNotExists("test_rnmo_pony") self.assertTableExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate backwards original_state = self.unapply_operations( "test_rnmo", project_state, [operation], atomic=atomic_rename ) # Test original state and database self.assertIn(("test_rnmo", "pony"), original_state.models) self.assertNotIn(("test_rnmo", "horse"), original_state.models) self.assertEqual( original_state.models["test_rnmo", "rider"] .fields["pony"] .remote_field.model, "Pony", ) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RenameModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"old_name": "Pony", "new_name": "Horse"}) def test_rename_model_state_forwards(self): """ RenameModel operations shouldn't trigger the caching of rendered apps on state without prior apps. """ state = ProjectState() state.add_model(ModelState("migrations", "Foo", [])) operation = migrations.RenameModel("Foo", "Bar") operation.state_forwards("migrations", state) self.assertNotIn("apps", state.__dict__) self.assertNotIn(("migrations", "foo"), state.models) self.assertIn(("migrations", "bar"), state.models) # Now with apps cached. apps = state.apps operation = migrations.RenameModel("Bar", "Foo") operation.state_forwards("migrations", state) self.assertIs(state.apps, apps) self.assertNotIn(("migrations", "bar"), state.models) self.assertIn(("migrations", "foo"), state.models) def test_rename_model_with_self_referential_fk(self): """ Tests the RenameModel operation on model with self referential FK. """ project_state = self.set_up_test_model("test_rmwsrf", related_model=True) # Test the state alteration operation = migrations.RenameModel("Rider", "HorseRider") self.assertEqual(operation.describe(), "Rename model Rider to HorseRider") new_state = project_state.clone() operation.state_forwards("test_rmwsrf", new_state) self.assertNotIn(("test_rmwsrf", "rider"), new_state.models) self.assertIn(("test_rmwsrf", "horserider"), new_state.models) # Remember, RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( "self", new_state.models["test_rmwsrf", "horserider"] .fields["friend"] .remote_field.model, ) HorseRider = new_state.apps.get_model("test_rmwsrf", "horserider") self.assertIs( HorseRider._meta.get_field("horserider").remote_field.model, HorseRider ) # Test the database alteration self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards("test_rmwsrf", editor, project_state, new_state) self.assertTableNotExists("test_rmwsrf_rider") self.assertTableExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_horserider", "id"), ) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards( "test_rmwsrf", editor, new_state, project_state ) self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) def test_rename_model_with_superclass_fk(self): """ Tests the RenameModel operation on a model which has a superclass that has a foreign key. """ project_state = self.set_up_test_model( "test_rmwsc", related_model=True, mti_model=True ) # Test the state alteration operation = migrations.RenameModel("ShetlandPony", "LittleHorse") self.assertEqual( operation.describe(), "Rename model ShetlandPony to LittleHorse" ) new_state = project_state.clone() operation.state_forwards("test_rmwsc", new_state) self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models) self.assertIn(("test_rmwsc", "littlehorse"), new_state.models) # RenameModel shouldn't repoint the superclass's relations, only local ones self.assertEqual( project_state.models["test_rmwsc", "rider"] .fields["pony"] .remote_field.model, new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model, ) # Before running the migration we have a table for Shetland Pony, not # Little Horse. self.assertTableExists("test_rmwsc_shetlandpony") self.assertTableNotExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # and the foreign key on rider points to pony, not shetland pony self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id") ) with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: operation.database_forwards("test_rmwsc", editor, project_state, new_state) # Now we have a little horse table, not shetland pony self.assertTableNotExists("test_rmwsc_shetlandpony") self.assertTableExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # but the Foreign keys still point at pony, not little horse self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id") ) def test_rename_model_with_self_referential_m2m(self): app_label = "test_rename_model_with_self_referential_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "ReflexivePony", fields=[ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("self")), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("ReflexivePony", "ReflexivePony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "ReflexivePony2") pony = Pony.objects.create() pony.ponies.add(pony) def test_rename_model_with_m2m(self): app_label = "test_rename_model_with_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Pony", "Pony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony2") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_model_with_db_table_noop(self): app_label = "test_rmwdbtn" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], options={"db_table": "rider"}, ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameModel("Rider", "Runner") operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) def test_rename_m2m_target_model(self): app_label = "test_rename_m2m_target_model" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Rider", "Rider2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider2") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_m2m_through_model(self): app_label = "test_rename_through" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "test_rename_through.Rider", models.CASCADE ), ), ( "pony", models.ForeignKey( "test_rename_through.Pony", models.CASCADE ), ), ], ), migrations.AddField( "Pony", "riders", models.ManyToManyField( "test_rename_through.Rider", through="test_rename_through.PonyRider", ), ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider") pony = Pony.objects.create() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("PonyRider", "PonyRider2"), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider2") pony = Pony.objects.first() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) self.assertEqual(Pony.objects.count(), 1) self.assertEqual(Rider.objects.count(), 2) self.assertEqual(PonyRider.objects.count(), 2) self.assertEqual(pony.riders.count(), 2) def test_rename_m2m_model_after_rename_field(self): """RenameModel renames a many-to-many column after a RenameField.""" app_label = "test_rename_multiple" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=20)), ], ), migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "test_rename_multiple.Pony", models.CASCADE ), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), migrations.RenameField( model_name="pony", old_name="name", new_name="fancy_name" ), migrations.RenameModel(old_name="Rider", new_name="Jockey"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Jockey = project_state.apps.get_model(app_label, "Jockey") PonyRider = project_state.apps.get_model(app_label, "PonyRider") # No "no such column" error means the column was renamed correctly. pony = Pony.objects.create(fancy_name="a good name") jockey = Jockey.objects.create(pony=pony) ponyrider = PonyRider.objects.create() ponyrider.riders.add(jockey) def test_add_field(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) self.assertEqual(operation.describe(), "Add field height to Pony") self.assertEqual(operation.migration_name_fragment, "pony_height") project_state, new_state = self.make_test_state("test_adfl", operation) self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4) field = new_state.models["test_adfl", "pony"].fields["height"] self.assertEqual(field.default, 5) # Test the database alteration self.assertColumnNotExists("test_adfl_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adfl", editor, project_state, new_state) self.assertColumnExists("test_adfl_pony", "height") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adfl", editor, new_state, project_state) self.assertColumnNotExists("test_adfl_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_add_charfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adchfl") Pony = project_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adchfl", project_state, [ migrations.AddField( "Pony", "text", models.CharField(max_length=10, default="some text"), ), migrations.AddField( "Pony", "empty", models.CharField(max_length=10, default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.CharField(max_length=10, default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.CharField(max_length=10, default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_textfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adtxtfl") Pony = project_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adtxtfl", project_state, [ migrations.AddField( "Pony", "text", models.TextField(default="some text"), ), migrations.AddField( "Pony", "empty", models.TextField(default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.TextField(default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.TextField(default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_binaryfield(self): """ Tests the AddField operation on TextField/BinaryField. """ project_state = self.set_up_test_model("test_adbinfl") Pony = project_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adbinfl", project_state, [ migrations.AddField( "Pony", "blob", models.BinaryField(default=b"some text"), ), migrations.AddField( "Pony", "empty", models.BinaryField(default=b""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.BinaryField(default=b"42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.BinaryField(default=b'"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.get(pk=pony.pk) # SQLite returns buffer/memoryview, cast to bytes for checking. self.assertEqual(bytes(pony.blob), b"some text") self.assertEqual(bytes(pony.empty), b"") self.assertEqual(bytes(pony.digits), b"42") self.assertEqual(bytes(pony.quotes), b'"\'"') def test_column_name_quoting(self): """ Column names that are SQL keywords shouldn't cause problems when used in migrations (#22168). """ project_state = self.set_up_test_model("test_regr22168") operation = migrations.AddField( "Pony", "order", models.IntegerField(default=0), ) new_state = project_state.clone() operation.state_forwards("test_regr22168", new_state) with connection.schema_editor() as editor: operation.database_forwards( "test_regr22168", editor, project_state, new_state ) self.assertColumnExists("test_regr22168_pony", "order") def test_add_field_preserve_default(self): """ Tests the AddField operation's state alteration when preserve_default = False. """ project_state = self.set_up_test_model("test_adflpd") # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=4), preserve_default=False, ) new_state = project_state.clone() operation.state_forwards("test_adflpd", new_state) self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4) field = new_state.models["test_adflpd", "pony"].fields["height"] self.assertEqual(field.default, models.NOT_PROVIDED) # Test the database alteration project_state.apps.get_model("test_adflpd", "pony").objects.create( weight=4, ) self.assertColumnNotExists("test_adflpd_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adflpd", editor, project_state, new_state) self.assertColumnExists("test_adflpd_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["field", "model_name", "name", "preserve_default"] ) def test_add_field_m2m(self): """ Tests the AddField operation with a ManyToManyField. """ project_state = self.set_up_test_model("test_adflmm", second_model=True) # Test the state alteration operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies") ) new_state = project_state.clone() operation.state_forwards("test_adflmm", new_state) self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4) # Test the database alteration self.assertTableNotExists("test_adflmm_pony_stables") with connection.schema_editor() as editor: operation.database_forwards("test_adflmm", editor, project_state, new_state) self.assertTableExists("test_adflmm_pony_stables") self.assertColumnNotExists("test_adflmm_pony", "stables") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_adflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.stables.create() self.assertEqual(p.stables.count(), 1) p.stables.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adflmm", editor, new_state, project_state ) self.assertTableNotExists("test_adflmm_pony_stables") def test_alter_field_m2m(self): project_state = self.set_up_test_model("test_alflmm", second_model=True) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertFalse(Pony._meta.get_field("stables").blank) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "stables", models.ManyToManyField( to="Stable", related_name="ponies", blank=True ), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertTrue(Pony._meta.get_field("stables").blank) def test_repoint_field_m2m(self): project_state = self.set_up_test_model( "test_alflmm", second_model=True, third_model=True ) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "places", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"), ) ], ) # Ensure the new field actually works Pony = project_state.apps.get_model("test_alflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.places.create() self.assertEqual(p.places.count(), 1) p.places.all().delete() def test_remove_field_m2m(self): project_state = self.set_up_test_model("test_rmflmm", second_model=True) project_state = self.apply_operations( "test_rmflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) self.assertTableExists("test_rmflmm_pony_stables") with_field_state = project_state.clone() operations = [migrations.RemoveField("Pony", "stables")] project_state = self.apply_operations( "test_rmflmm", project_state, operations=operations ) self.assertTableNotExists("test_rmflmm_pony_stables") # And test reversal self.unapply_operations("test_rmflmm", with_field_state, operations=operations) self.assertTableExists("test_rmflmm_pony_stables") def test_remove_field_m2m_with_through(self): project_state = self.set_up_test_model("test_rmflmmwt", second_model=True) self.assertTableNotExists("test_rmflmmwt_ponystables") project_state = self.apply_operations( "test_rmflmmwt", project_state, operations=[ migrations.CreateModel( "PonyStables", fields=[ ( "pony", models.ForeignKey("test_rmflmmwt.Pony", models.CASCADE), ), ( "stable", models.ForeignKey("test_rmflmmwt.Stable", models.CASCADE), ), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField( "Stable", related_name="ponies", through="test_rmflmmwt.PonyStables", ), ), ], ) self.assertTableExists("test_rmflmmwt_ponystables") operations = [ migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables"), ] self.apply_operations("test_rmflmmwt", project_state, operations=operations) def test_remove_field(self): """ Tests the RemoveField operation. """ project_state = self.set_up_test_model("test_rmfl") # Test the state alteration operation = migrations.RemoveField("Pony", "pink") self.assertEqual(operation.describe(), "Remove field pink from Pony") self.assertEqual(operation.migration_name_fragment, "remove_pony_pink") new_state = project_state.clone() operation.state_forwards("test_rmfl", new_state) self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2) # Test the database alteration self.assertColumnExists("test_rmfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_rmfl", editor, project_state, new_state) self.assertColumnNotExists("test_rmfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmfl", editor, new_state, project_state) self.assertColumnExists("test_rmfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveField") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pink"}) def test_remove_fk(self): """ Tests the RemoveField operation on a foreign key. """ project_state = self.set_up_test_model("test_rfk", related_model=True) self.assertColumnExists("test_rfk_rider", "pony_id") operation = migrations.RemoveField("Rider", "pony") new_state = project_state.clone() operation.state_forwards("test_rfk", new_state) with connection.schema_editor() as editor: operation.database_forwards("test_rfk", editor, project_state, new_state) self.assertColumnNotExists("test_rfk_rider", "pony_id") with connection.schema_editor() as editor: operation.database_backwards("test_rfk", editor, new_state, project_state) self.assertColumnExists("test_rfk_rider", "pony_id") def test_alter_model_table(self): """ Tests the AlterModelTable operation. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony_2") self.assertEqual( operation.describe(), "Rename table for Pony to test_almota_pony_2" ) self.assertEqual(operation.migration_name_fragment, "alter_pony_table") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2", ) # Test the database alteration self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableNotExists("test_almota_pony") self.assertTableExists("test_almota_pony_2") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelTable") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "table": "test_almota_pony_2"}) def test_alter_model_table_none(self): """ Tests the AlterModelTable operation if the table name is set to None. """ operation = migrations.AlterModelTable("Pony", None) self.assertEqual(operation.describe(), "Rename table for Pony to (default)") def test_alter_model_table_noop(self): """ Tests the AlterModelTable operation if the table name is not changed. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony", ) # Test the database alteration self.assertTableExists("test_almota_pony") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableExists("test_almota_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") def test_alter_model_table_m2m(self): """ AlterModelTable should rename auto-generated M2M tables. """ app_label = "test_talflmltlm2m" pony_db_table = "pony_foo" project_state = self.set_up_test_model( app_label, second_model=True, db_table=pony_db_table ) # Add the M2M field first_state = project_state.clone() operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable") ) operation.state_forwards(app_label, first_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, first_state) original_m2m_table = "%s_%s" % (pony_db_table, "stables") new_m2m_table = "%s_%s" % (app_label, "pony_stables") self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) # Rename the Pony db_table which should also rename the m2m table. second_state = first_state.clone() operation = migrations.AlterModelTable(name="pony", table=None) operation.state_forwards(app_label, second_state) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards(app_label, editor, first_state, second_state) self.assertTableExists(new_m2m_table) self.assertTableNotExists(original_m2m_table) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards(app_label, editor, second_state, first_state) self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) def test_alter_field(self): """ Tests the AlterField operation. """ project_state = self.set_up_test_model("test_alfl") # Test the state alteration operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) self.assertEqual(operation.describe(), "Alter field pink on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_pink") new_state = project_state.clone() operation.state_forwards("test_alfl", new_state) self.assertIs( project_state.models["test_alfl", "pony"].fields["pink"].null, False ) self.assertIs(new_state.models["test_alfl", "pony"].fields["pink"].null, True) # Test the database alteration self.assertColumnNotNull("test_alfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alfl", editor, project_state, new_state) self.assertColumnNull("test_alfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_alfl", editor, new_state, project_state) self.assertColumnNotNull("test_alfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_alter_field_add_db_column_noop(self): """ AlterField operation is a noop when adding only a db_column and the column name is not changed. """ app_label = "test_afadbn" project_state = self.set_up_test_model(app_label, related_model=True) pony_table = "%s_pony" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Pony", "weight", models.FloatField(db_column="weight") ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "pony"].fields["weight"].db_column, ) self.assertEqual( new_state.models[app_label, "pony"].fields["weight"].db_column, "weight", ) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) self.assertColumnExists(pony_table, "weight") rider_table = "%s_rider" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Rider", "pony", models.ForeignKey("Pony", models.CASCADE, db_column="pony_id"), ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "rider"].fields["pony"].db_column, ) self.assertIs( new_state.models[app_label, "rider"].fields["pony"].db_column, "pony_id", ) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, new_state, project_state) self.assertColumnExists(rider_table, "pony_id") def test_alter_field_pk(self): """ The AlterField operation on primary keys (things like PostgreSQL's SERIAL weirdness). """ project_state = self.set_up_test_model("test_alflpk") # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.IntegerField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpk", new_state) self.assertIsInstance( project_state.models["test_alflpk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpk", "pony"].fields["id"], models.IntegerField, ) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alflpk", editor, project_state, new_state) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpk", editor, new_state, project_state ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_pk_fk(self): """ Tests the AlterField operation on primary keys changes any FKs pointing to it. """ project_state = self.set_up_test_model("test_alflpkfk", related_model=True) project_state = self.apply_operations( "test_alflpkfk", project_state, [ migrations.CreateModel( "Stable", fields=[ ("ponies", models.ManyToManyField("Pony")), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable"), ), ], ) # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.FloatField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpkfk", new_state) self.assertIsInstance( project_state.models["test_alflpkfk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpkfk", "pony"].fields["id"], models.FloatField, ) def assertIdTypeEqualsFkType(): with connection.cursor() as cursor: id_type, id_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony" ) if c.name == "id" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_rider" ) if c.name == "pony_id" ][0] m2m_fk_type, m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony_stables", ) if c.name == "pony_id" ][0] remote_m2m_fk_type, remote_m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_stable_ponies", ) if c.name == "pony_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_type, m2m_fk_type) self.assertEqual(id_type, remote_m2m_fk_type) self.assertEqual(id_null, fk_null) self.assertEqual(id_null, m2m_fk_null) self.assertEqual(id_null, remote_m2m_fk_null) assertIdTypeEqualsFkType() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alflpkfk", editor, project_state, new_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpkfk", editor, new_state, project_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_alter_field_pk_fk_db_collation(self): """ AlterField operation of db_collation on primary keys changes any FKs pointing to it. """ collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_alflpkfkdbc" project_state = self.apply_operations( app_label, ProjectState(), [ migrations.CreateModel( "Pony", [ ("id", models.CharField(primary_key=True, max_length=10)), ], ), migrations.CreateModel( "Rider", [ ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ), migrations.CreateModel( "Stable", [ ("ponies", models.ManyToManyField("Pony")), ], ), ], ) # State alteration. operation = migrations.AlterField( "Pony", "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Database alteration. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_pony", "id", collation) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) self.assertColumnCollation(f"{app_label}_stable_ponies", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_alter_field_pk_mti_fk(self): app_label = "test_alflpkmtifk" project_state = self.set_up_test_model(app_label, mti_model=True) project_state = self.apply_operations( app_label, project_state, [ migrations.CreateModel( "ShetlandRider", fields=[ ( "pony", models.ForeignKey( f"{app_label}.ShetlandPony", models.CASCADE ), ), ], ), ], ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) mti_id_type = _get_column_id_type(cursor, "shetlandrider", "pony_id") self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, mti_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) def test_alter_field_pk_mti_and_fk_to_base(self): app_label = "test_alflpkmtiftb" project_state = self.set_up_test_model( app_label, mti_model=True, related_model=True, ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") fk_id_type = _get_column_id_type(cursor, "rider", "pony_id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, fk_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self): app_label = "test_alflrsfkwtflttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.IntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code" ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) id_type, id_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_rider" % app_label) if c.name == "code" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_pony" % app_label) if c.name == "rider_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_null, fk_null) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change( self, ): app_label = "test_alflrsfkwtflrnttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.PositiveIntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code", related_name="+", ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) def test_alter_field_reloads_state_on_fk_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "id", models.CharField(primary_key=True, max_length=99) ), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], ) def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_with_to_field_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="slug" ), ), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "%s.Pony" % app_label, models.CASCADE, to_field="slug" ), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "slug", models.CharField(unique=True, max_length=99) ), migrations.AlterField( "Pony", "slug", models.CharField(unique=True, max_length=99) ), ], ) def test_rename_field_reloads_state_on_fk_target_changes(self): """ If RenameField doesn't reload state appropriately, the AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_rename_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameField("Rider", "id", "id2"), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], atomic=connection.features.supports_atomic_references_rename, ) @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_field(self): """ Tests the RenameField operation. """ project_state = self.set_up_test_model("test_rnfl") operation = migrations.RenameField("Pony", "pink", "blue") self.assertEqual(operation.describe(), "Rename field pink on Pony to blue") self.assertEqual(operation.migration_name_fragment, "rename_pink_pony_blue") new_state = project_state.clone() operation.state_forwards("test_rnfl", new_state) self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields) self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields) # Rename field. self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnfl", editor, project_state, new_state) self.assertColumnExists("test_rnfl_pony", "blue") self.assertColumnNotExists("test_rnfl_pony", "pink") # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_rnfl", editor, new_state, project_state) self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "old_name": "pink", "new_name": "blue"}, ) def test_rename_field_unique_together(self): project_state = self.set_up_test_model("test_rnflut", unique_together=True) operation = migrations.RenameField("Pony", "pink", "blue") new_state = project_state.clone() operation.state_forwards("test_rnflut", new_state) # unique_together has the renamed column. self.assertIn( "blue", new_state.models["test_rnflut", "pony"].options["unique_together"][0], ) self.assertNotIn( "pink", new_state.models["test_rnflut", "pony"].options["unique_together"][0], ) # Rename field. self.assertColumnExists("test_rnflut_pony", "pink") self.assertColumnNotExists("test_rnflut_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnflut", editor, project_state, new_state) self.assertColumnExists("test_rnflut_pony", "blue") self.assertColumnNotExists("test_rnflut_pony", "pink") # The unique constraint has been ported over. with connection.cursor() as cursor: cursor.execute("INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_rnflut_pony") # Reversal. with connection.schema_editor() as editor: operation.database_backwards( "test_rnflut", editor, new_state, project_state ) self.assertColumnExists("test_rnflut_pony", "pink") self.assertColumnNotExists("test_rnflut_pony", "blue") @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_field_index_together(self): project_state = self.set_up_test_model("test_rnflit", index_together=True) operation = migrations.RenameField("Pony", "pink", "blue") new_state = project_state.clone() operation.state_forwards("test_rnflit", new_state) self.assertIn("blue", new_state.models["test_rnflit", "pony"].fields) self.assertNotIn("pink", new_state.models["test_rnflit", "pony"].fields) # index_together has the renamed column. self.assertIn( "blue", new_state.models["test_rnflit", "pony"].options["index_together"][0] ) self.assertNotIn( "pink", new_state.models["test_rnflit", "pony"].options["index_together"][0] ) # Rename field. self.assertColumnExists("test_rnflit_pony", "pink") self.assertColumnNotExists("test_rnflit_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnflit", editor, project_state, new_state) self.assertColumnExists("test_rnflit_pony", "blue") self.assertColumnNotExists("test_rnflit_pony", "pink") # The index constraint has been ported over. self.assertIndexExists("test_rnflit_pony", ["weight", "blue"]) # Reversal. with connection.schema_editor() as editor: operation.database_backwards( "test_rnflit", editor, new_state, project_state ) self.assertIndexExists("test_rnflit_pony", ["weight", "pink"]) def test_rename_field_with_db_column(self): project_state = self.apply_operations( "test_rfwdbc", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(db_column="db_field")), ( "fk_field", models.ForeignKey( "Pony", models.CASCADE, db_column="db_fk_field", ), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "renamed_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn("renamed_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertNotIn("field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") new_state = project_state.clone() operation = migrations.RenameField("Pony", "fk_field", "renamed_fk_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn( "renamed_fk_field", new_state.models["test_rfwdbc", "pony"].fields ) self.assertNotIn("fk_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") def test_rename_field_case(self): project_state = self.apply_operations( "test_rfmx", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "FiElD") operation.state_forwards("test_rfmx", new_state) self.assertIn("FiElD", new_state.models["test_rfmx", "pony"].fields) self.assertColumnExists("test_rfmx_pony", "field") with connection.schema_editor() as editor: operation.database_forwards("test_rfmx", editor, project_state, new_state) self.assertColumnExists( "test_rfmx_pony", connection.introspection.identifier_converter("FiElD"), ) with connection.schema_editor() as editor: operation.database_backwards("test_rfmx", editor, new_state, project_state) self.assertColumnExists("test_rfmx_pony", "field") def test_rename_missing_field(self): state = ProjectState() state.add_model(ModelState("app", "model", [])) with self.assertRaisesMessage( FieldDoesNotExist, "app.model has no field named 'field'" ): migrations.RenameField("model", "field", "new_field").state_forwards( "app", state ) def test_rename_referenced_field_state_forward(self): state = ProjectState() state.add_model( ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ) ) state.add_model( ModelState( "app", "OtherModel", [ ("id", models.AutoField(primary_key=True)), ( "fk", models.ForeignKey("Model", models.CASCADE, to_field="field"), ), ( "fo", models.ForeignObject( "Model", models.CASCADE, from_fields=("fk",), to_fields=("field",), ), ), ], ) ) operation = migrations.RenameField("Model", "field", "renamed") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].from_fields, ["self"] ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].to_fields, ("renamed",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("fk",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) operation = migrations.RenameField("OtherModel", "fk", "renamed_fk") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"] .fields["renamed_fk"] .remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].from_fields, ("self",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].to_fields, ("renamed",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("renamed_fk",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) def test_alter_unique_together(self): """ Tests the AlterUniqueTogether operation. """ project_state = self.set_up_test_model("test_alunto") # Test the state alteration operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter unique_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_unique_together", ) new_state = project_state.clone() operation.state_forwards("test_alunto", new_state) self.assertEqual( len( project_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # Make sure we can insert duplicate rows with connection.cursor() as cursor: cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alunto", editor, project_state, new_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_alunto_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alunto", editor, new_state, project_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test flat unique_together operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight")) operation.state_forwards("test_alunto", new_state) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterUniqueTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "unique_together": {("pink", "weight")}} ) def test_alter_unique_together_remove(self): operation = migrations.AlterUniqueTogether("Pony", None) self.assertEqual( operation.describe(), "Alter unique_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_on_pk_field(self): app_label = "test_rutopkf" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[("id", models.AutoField(primary_key=True))], options={"unique_together": {("id",)}}, ), ], ) table_name = f"{app_label}_pony" pk_constraint_name = f"{table_name}_pkey" unique_together_constraint_name = f"{table_name}_id_fb61f881_uniq" self.assertConstraintExists(table_name, pk_constraint_name, value=False) self.assertConstraintExists( table_name, unique_together_constraint_name, value=False ) new_state = project_state.clone() operation = migrations.AlterUniqueTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertConstraintExists(table_name, pk_constraint_name, value=False) self.assertConstraintNotExists(table_name, unique_together_constraint_name) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_on_unique_field(self): app_label = "test_rutouf" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=30, unique=True)), ], options={"unique_together": {("name",)}}, ), ], ) table_name = f"{app_label}_pony" unique_constraint_name = f"{table_name}_name_key" unique_together_constraint_name = f"{table_name}_name_694f3b9f_uniq" self.assertConstraintExists(table_name, unique_constraint_name, value=False) self.assertConstraintExists( table_name, unique_together_constraint_name, value=False ) new_state = project_state.clone() operation = migrations.AlterUniqueTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertConstraintExists(table_name, unique_constraint_name, value=False) self.assertConstraintNotExists(table_name, unique_together_constraint_name) def test_add_index(self): """ Test the AddIndex operation. """ project_state = self.set_up_test_model("test_adin") msg = ( "Indexes passed to AddIndex operations require a name argument. " "<Index: fields=['pink']> doesn't have one." ) with self.assertRaisesMessage(ValueError, msg): migrations.AddIndex("Pony", models.Index(fields=["pink"])) index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx") operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adin_pony_pink_idx", ) new_state = project_state.clone() operation.state_forwards("test_adin", new_state) # Test the database alteration self.assertEqual( len(new_state.models["test_adin", "pony"].options["indexes"]), 1 ) self.assertIndexNotExists("test_adin_pony", ["pink"]) with connection.schema_editor() as editor: operation.database_forwards("test_adin", editor, project_state, new_state) self.assertIndexExists("test_adin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adin", editor, new_state, project_state) self.assertIndexNotExists("test_adin_pony", ["pink"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) def test_remove_index(self): """ Test the RemoveIndex operation. """ project_state = self.set_up_test_model("test_rmin", multicol_index=True) self.assertTableExists("test_rmin_pony") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) operation = migrations.RemoveIndex("Pony", "pony_test_idx") self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony") self.assertEqual( operation.migration_name_fragment, "remove_pony_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards("test_rmin", new_state) # Test the state alteration self.assertEqual( len(new_state.models["test_rmin", "pony"].options["indexes"]), 0 ) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_rmin", editor, project_state, new_state) self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmin", editor, new_state, project_state) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pony_test_idx"}) # Also test a field dropped with index - sqlite remake issue operations = [ migrations.RemoveIndex("Pony", "pony_test_idx"), migrations.RemoveField("Pony", "pink"), ] self.assertColumnExists("test_rmin_pony", "pink") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test database alteration new_state = project_state.clone() self.apply_operations("test_rmin", new_state, operations=operations) self.assertColumnNotExists("test_rmin_pony", "pink") self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal self.unapply_operations("test_rmin", project_state, operations=operations) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) def test_rename_index(self): app_label = "test_rnin" project_state = self.set_up_test_model(app_label, index=True) table_name = app_label + "_pony" self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_name="pony_pink_idx" ) self.assertEqual( operation.describe(), "Rename index pony_pink_idx on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_pink_idx_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. expected_queries = 1 if connection.features.can_rename_index else 2 with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, "pony_pink_idx") self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reversal. with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "old_name": "pony_pink_idx", "new_name": "new_pony_test_idx", }, ) def test_rename_index_arguments(self): msg = "RenameIndex.old_name and old_fields are mutually exclusive." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex( "Pony", new_name="new_idx_name", old_name="old_idx_name", old_fields=("weight", "pink"), ) msg = "RenameIndex requires one of old_name and old_fields arguments to be set." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex("Pony", new_name="new_idx_name") @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_index_unnamed_index(self): app_label = "test_rninui" project_state = self.set_up_test_model(app_label, index_together=True) table_name = app_label + "_pony" self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) self.assertEqual( operation.describe(), "Rename unnamed index for ('weight', 'pink') on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_weight_pink_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reverse is a no-op. with connection.schema_editor() as editor, self.assertNumQueries(0): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reapply, RenameIndex operation is a noop when the old and new name # match. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "new_name": "new_pony_test_idx", "old_fields": ("weight", "pink"), }, ) def test_rename_index_unknown_unnamed_index(self): app_label = "test_rninuui" project_state = self.set_up_test_model(app_label) operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) msg = "Found wrong number (0) of indexes for test_rninuui_pony(weight, pink)." with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): operation.database_forwards(app_label, editor, project_state, new_state) def test_add_index_state_forwards(self): project_state = self.set_up_test_model("test_adinsf") index = models.Index(fields=["pink"], name="test_adinsf_pony_pink_idx") old_model = project_state.apps.get_model("test_adinsf", "Pony") new_state = project_state.clone() operation = migrations.AddIndex("Pony", index) operation.state_forwards("test_adinsf", new_state) new_model = new_state.apps.get_model("test_adinsf", "Pony") self.assertIsNot(old_model, new_model) def test_remove_index_state_forwards(self): project_state = self.set_up_test_model("test_rminsf") index = models.Index(fields=["pink"], name="test_rminsf_pony_pink_idx") migrations.AddIndex("Pony", index).state_forwards("test_rminsf", project_state) old_model = project_state.apps.get_model("test_rminsf", "Pony") new_state = project_state.clone() operation = migrations.RemoveIndex("Pony", "test_rminsf_pony_pink_idx") operation.state_forwards("test_rminsf", new_state) new_model = new_state.apps.get_model("test_rminsf", "Pony") self.assertIsNot(old_model, new_model) def test_rename_index_state_forwards(self): app_label = "test_rnidsf" project_state = self.set_up_test_model(app_label, index=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_name="pony_pink_idx" ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_index_state_forwards_unnamed_index(self): app_label = "test_rnidsfui" project_state = self.set_up_test_model(app_label, index_together=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_fields=("weight", "pink") ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.index_together, tuple()) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") @skipUnlessDBFeature("supports_expression_indexes") def test_add_func_index(self): app_label = "test_addfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) index = models.Index(Abs("weight"), name=index_name) operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_addfuncin_pony_abs_idx on Abs(F(weight)) on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_addfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 1) self.assertIndexNameNotExists(table_name, index_name) # Add index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) @skipUnlessDBFeature("supports_expression_indexes") def test_remove_func_index(self): app_label = "test_rmfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[ models.Index(Abs("weight"), name=index_name), ], ) self.assertTableExists(table_name) self.assertIndexNameExists(table_name, index_name) operation = migrations.RemoveIndex("Pony", index_name) self.assertEqual( operation.describe(), "Remove index test_rmfuncin_pony_abs_idx from Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 0) # Remove index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": index_name}) @skipUnlessDBFeature("supports_expression_indexes") def test_alter_field_with_func_index(self): app_label = "test_alfuncin" index_name = f"{app_label}_pony_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[models.Index(Abs("pink"), name=index_name)], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) def test_alter_field_with_index(self): """ Test AlterField operation with an index to ensure indexes created via Meta.indexes don't get dropped with sqlite3 remake. """ project_state = self.set_up_test_model("test_alflin", index=True) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards("test_alflin", new_state) # Test the database alteration self.assertColumnNotNull("test_alflin_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alflin", editor, project_state, new_state) # Index hasn't been dropped self.assertIndexExists("test_alflin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflin", editor, new_state, project_state ) # Ensure the index is still there self.assertIndexExists("test_alflin_pony", ["pink"]) @ignore_warnings(category=RemovedInDjango51Warning) def test_alter_index_together(self): """ Tests the AlterIndexTogether operation. """ project_state = self.set_up_test_model("test_alinto") # Test the state alteration operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter index_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_index_together", ) new_state = project_state.clone() operation.state_forwards("test_alinto", new_state) self.assertEqual( len( project_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 1, ) # Make sure there's no matching index self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alinto", editor, project_state, new_state) self.assertIndexExists("test_alinto_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alinto", editor, new_state, project_state ) self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterIndexTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "index_together": {("pink", "weight")}} ) # RemovedInDjango51Warning. def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual( operation.describe(), "Alter index_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") @ignore_warnings(category=RemovedInDjango51Warning) def test_alter_index_together_remove_with_unique_together(self): app_label = "test_alintoremove_wunto" table_name = "%s_pony" % app_label project_state = self.set_up_test_model(app_label, unique_together=True) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) # Add index together. new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexExists(table_name, ["pink", "weight"]) # Remove index together. project_state = new_state new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNotExists(table_name, ["pink", "weight"]) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint") gt_check = models.Q(pink__gt=2) gt_constraint = models.CheckConstraint( check=gt_check, name="test_add_constraint_pony_pink_gt_2" ) gt_operation = migrations.AddConstraint("Pony", gt_constraint) self.assertEqual( gt_operation.describe(), "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "pony_test_add_constraint_pony_pink_gt_2", ) # Test the state alteration new_state = project_state.clone() gt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 1, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) # Add another one. lt_check = models.Q(pink__lt=100) lt_constraint = models.CheckConstraint( check=lt_check, name="test_add_constraint_pony_pink_lt_100" ) lt_operation = migrations.AddConstraint("Pony", lt_constraint) lt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 2, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 2) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_addconstraint", editor, new_state, project_state ) Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": gt_constraint} ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_percent_escaping(self): app_label = "add_constraint_string_quoting" operations = [ migrations.CreateModel( "Author", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ("surname", models.CharField(max_length=100, default="")), ("rebate", models.CharField(max_length=100)), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) # "%" generated in startswith lookup should be escaped in a way that is # considered a leading wildcard. check = models.Q(name__startswith="Albert") constraint = models.CheckConstraint(check=check, name="name_constraint") operation = migrations.AddConstraint("Author", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Artur") # Literal "%" should be escaped in a way that is not a considered a # wildcard. check = models.Q(rebate__endswith="%") constraint = models.CheckConstraint(check=check, name="rebate_constraint") operation = migrations.AddConstraint("Author", constraint) from_state = to_state to_state = from_state.clone() operation.state_forwards(app_label, to_state) Author = to_state.apps.get_model(app_label, "Author") with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Albert", rebate="10$") author = Author.objects.create(name="Albert", rebate="10%") self.assertEqual(Author.objects.get(), author) # Right-hand-side baked "%" literals should not be used for parameters # interpolation. check = ~models.Q(surname__startswith=models.F("name")) constraint = models.CheckConstraint(check=check, name="name_constraint_rhs") operation = migrations.AddConstraint("Author", constraint) from_state = to_state to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Albert", surname="Alberto") @skipUnlessDBFeature("supports_table_check_constraints") def test_add_or_constraint(self): app_label = "test_addorconstraint" constraint_name = "add_constraint_or" from_state = self.set_up_test_model(app_label) check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0) constraint = models.CheckConstraint(check=check, name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Pony = to_state.apps.get_model(app_label, "Pony") with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=2, weight=3.0) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=3, weight=1.0) Pony.objects.bulk_create( [ Pony(pink=3, weight=-1.0), Pony(pink=1, weight=-1.0), Pony(pink=3, weight=3.0), ] ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_combinable(self): app_label = "test_addconstraint_combinable" operations = [ migrations.CreateModel( "Book", fields=[ ("id", models.AutoField(primary_key=True)), ("read", models.PositiveIntegerField()), ("unread", models.PositiveIntegerField()), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) constraint = models.CheckConstraint( check=models.Q(read=(100 - models.F("unread"))), name="test_addconstraint_combinable_sum_100", ) operation = migrations.AddConstraint("Book", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Book = to_state.apps.get_model(app_label, "Book") with self.assertRaises(IntegrityError), transaction.atomic(): Book.objects.create(read=70, unread=10) Book.objects.create(read=70, unread=30) @skipUnlessDBFeature("supports_table_check_constraints") def test_remove_constraint(self): project_state = self.set_up_test_model( "test_removeconstraint", constraints=[ models.CheckConstraint( check=models.Q(pink__gt=2), name="test_remove_constraint_pony_pink_gt_2", ), models.CheckConstraint( check=models.Q(pink__lt=100), name="test_remove_constraint_pony_pink_lt_100", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_gt_2" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "remove_pony_test_remove_constraint_pony_pink_gt_2", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 1, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=1, weight=1.0).delete() with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) # Remove the other one. lt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_lt_100" ) lt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 0, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=100, weight=1.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removeconstraint", editor, new_state, project_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "name": "test_remove_constraint_pony_pink_gt_2"}, ) def test_add_partial_unique_constraint(self): project_state = self.set_up_test_model("test_addpartialuniqueconstraint") partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.AddConstraint("Pony", partial_unique_constraint) self.assertEqual( operation.describe(), "Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq " "on model Pony", ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_addpartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_addpartialuniqueconstraint", "pony"].options[ "constraints" ] ), 1, ) Pony = new_state.apps.get_model("test_addpartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_addpartialuniqueconstraint", editor, project_state, new_state ) # Test constraint works Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_addpartialuniqueconstraint", editor, new_state, project_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": partial_unique_constraint}, ) def test_remove_partial_unique_constraint(self): project_state = self.set_up_test_model( "test_removepartialuniqueconstraint", constraints=[ models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_constraint_pony_pink_for_weight_gt_5_uniq" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from " "model Pony", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removepartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_removepartialuniqueconstraint", "pony"].options[ "constraints" ] ), 0, ) Pony = new_state.apps.get_model("test_removepartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removepartialuniqueconstraint", editor, project_state, new_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) Pony.objects.create(pink=1, weight=7.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removepartialuniqueconstraint", editor, new_state, project_state ) # Test constraint works if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "test_constraint_pony_pink_for_weight_gt_5_uniq", }, ) def test_add_deferred_unique_constraint(self): app_label = "test_adddeferred_uc" project_state = self.set_up_test_model(app_label) deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_add", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.AddConstraint("Pony", deferred_unique_constraint) self.assertEqual( operation.describe(), "Create constraint deferred_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": deferred_unique_constraint}, ) def test_remove_deferred_unique_constraint(self): app_label = "test_removedeferred_uc" deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_rm", deferrable=models.Deferrable.DEFERRED, ) project_state = self.set_up_test_model( app_label, constraints=[deferred_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", deferred_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint deferred_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_deferrable_unique_constraints: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "deferred_pink_constraint_rm", }, ) def test_add_covering_unique_constraint(self): app_label = "test_addcovering_uc" project_state = self.set_up_test_model(app_label) covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_add", include=["weight"], ) operation = migrations.AddConstraint("Pony", covering_unique_constraint) self.assertEqual( operation.describe(), "Create constraint covering_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": covering_unique_constraint}, ) def test_remove_covering_unique_constraint(self): app_label = "test_removecovering_uc" covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_rm", include=["weight"], ) project_state = self.set_up_test_model( app_label, constraints=[covering_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", covering_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint covering_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_covering_indexes: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "covering_pink_constraint_rm", }, ) def test_alter_field_with_func_unique_constraint(self): app_label = "test_alfuncuc" constraint_name = f"{app_label}_pony_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint("pink", "weight", name=constraint_name) ], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) def test_add_func_unique_constraint(self): app_label = "test_adfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) constraint = models.UniqueConstraint(Abs("weight"), name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) self.assertEqual( operation.describe(), "Create constraint test_adfuncuc_pony_abs_uq on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) self.assertIndexNameNotExists(table_name, constraint_name) # Add constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) Pony = new_state.apps.get_model(app_label, "Pony") Pony.objects.create(weight=4.0) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": constraint}, ) def test_remove_func_unique_constraint(self): app_label = "test_rmfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint(Abs("weight"), name=constraint_name), ], ) self.assertTableExists(table_name) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) operation = migrations.RemoveConstraint("Pony", constraint_name) self.assertEqual( operation.describe(), "Remove constraint test_rmfuncuc_pony_abs_uq from model Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Remove constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=-4.0).delete() # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": constraint_name}) def test_alter_model_options(self): """ Tests the AlterModelOptions operation. """ project_state = self.set_up_test_model("test_almoop") # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions( "Pony", {"permissions": [("can_groom", "Can groom")]} ) self.assertEqual(operation.describe(), "Change Meta options on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_options") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 0, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 1, ) self.assertEqual( new_state.models["test_almoop", "pony"].options["permissions"][0][0], "can_groom", ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "options": {"permissions": [("can_groom", "Can groom")]}}, ) def test_alter_model_options_emptying(self): """ The AlterModelOptions operation removes keys from the dict (#23121) """ project_state = self.set_up_test_model("test_almoop", options=True) # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions("Pony", {}) self.assertEqual(operation.describe(), "Change Meta options on Pony") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 1, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 0, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "options": {}}) def test_alter_order_with_respect_to(self): """ Tests the AlterOrderWithRespectTo operation. """ project_state = self.set_up_test_model("test_alorwrtto", related_model=True) # Test the state alteration operation = migrations.AlterOrderWithRespectTo("Rider", "pony") self.assertEqual( operation.describe(), "Set order_with_respect_to on Rider to pony" ) self.assertEqual( operation.migration_name_fragment, "alter_rider_order_with_respect_to", ) new_state = project_state.clone() operation.state_forwards("test_alorwrtto", new_state) self.assertIsNone( project_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ) ) self.assertEqual( new_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ), "pony", ) # Make sure there's no matching index self.assertColumnNotExists("test_alorwrtto_rider", "_order") # Create some rows before alteration rendered_state = project_state.apps pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create( weight=50 ) rider1 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider1.friend = rider1 rider1.save() rider2 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider2.friend = rider2 rider2.save() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alorwrtto", editor, project_state, new_state ) self.assertColumnExists("test_alorwrtto_rider", "_order") # Check for correct value in rows updated_riders = new_state.apps.get_model( "test_alorwrtto", "Rider" ).objects.all() self.assertEqual(updated_riders[0]._order, 0) self.assertEqual(updated_riders[1]._order, 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alorwrtto", editor, new_state, project_state ) self.assertColumnNotExists("test_alorwrtto_rider", "_order") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterOrderWithRespectTo") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Rider", "order_with_respect_to": "pony"} ) def test_alter_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almoma") # Test the state alteration operation = migrations.AlterModelManagers( "Pony", managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Change managers on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_managers") managers = project_state.models["test_almoma", "pony"].managers self.assertEqual(managers, []) new_state = project_state.clone() operation.state_forwards("test_almoma", new_state) self.assertIn(("test_almoma", "pony"), new_state.models) managers = new_state.models["test_almoma", "pony"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) rendered_state = new_state.apps model = rendered_state.get_model("test_almoma", "pony") self.assertIsInstance(model.food_qs, models.Manager) self.assertIsInstance(model.food_mgr, FoodManager) self.assertIsInstance(model.food_mgr_kwargs, FoodManager) def test_alter_model_managers_emptying(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almomae", manager_model=True) # Test the state alteration operation = migrations.AlterModelManagers("Food", managers=[]) self.assertEqual(operation.describe(), "Change managers on Food") self.assertIn(("test_almomae", "food"), project_state.models) managers = project_state.models["test_almomae", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) new_state = project_state.clone() operation.state_forwards("test_almomae", new_state) managers = new_state.models["test_almomae", "food"].managers self.assertEqual(managers, []) def test_alter_fk(self): """ Creating and then altering an FK works correctly and deals with the pending SQL (#23091) """ project_state = self.set_up_test_model("test_alfk") # Test adding and then altering the FK in one go create_operation = migrations.CreateModel( name="Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) create_state = project_state.clone() create_operation.state_forwards("test_alfk", create_state) alter_operation = migrations.AlterField( model_name="Rider", name="pony", field=models.ForeignKey("Pony", models.CASCADE, editable=False), ) alter_state = create_state.clone() alter_operation.state_forwards("test_alfk", alter_state) with connection.schema_editor() as editor: create_operation.database_forwards( "test_alfk", editor, project_state, create_state ) alter_operation.database_forwards( "test_alfk", editor, create_state, alter_state ) def test_alter_fk_non_fk(self): """ Altering an FK to a non-FK works (#23244) """ # Test the state alteration operation = migrations.AlterField( model_name="Rider", name="pony", field=models.FloatField(), ) project_state, new_state = self.make_test_state( "test_afknfk", operation, related_model=True ) # Test the database alteration self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") with connection.schema_editor() as editor: operation.database_forwards("test_afknfk", editor, project_state, new_state) self.assertColumnExists("test_afknfk_rider", "pony") self.assertColumnNotExists("test_afknfk_rider", "pony_id") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_afknfk", editor, new_state, project_state ) self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") def test_run_sql(self): """ Tests the RunSQL operation. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( # Use a multi-line string with a comment to test splitting on # SQLite and MySQL respectively. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (1, 'i love ponies'); -- this is magic!\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (2, 'i love django');\n" "UPDATE i_love_ponies SET special_thing = 'Ponies' " "WHERE special_thing LIKE '%%ponies';" "UPDATE i_love_ponies SET special_thing = 'Django' " "WHERE special_thing LIKE '%django';", # Run delete queries to test for parameter substitution failure # reported in #23426 "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';" "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';" "DROP TABLE i_love_ponies", state_operations=[ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) ], ) self.assertEqual(operation.describe(), "Raw SQL operation") # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_runsql", new_state) self.assertEqual( len(new_state.models["test_runsql", "somethingelse"].fields), 1 ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test SQL collection with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql)) operation.database_backwards( "test_runsql", editor, project_state, new_state ) self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql)) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertTableExists("i_love_ponies") # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 2) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'" ) self.assertEqual(cursor.fetchall()[0][0], 1) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'" ) self.assertEqual(cursor.fetchall()[0][0], 1) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunSQL") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["reverse_sql", "sql", "state_operations"] ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_sql_params(self): """ #23426 - RunSQL should accept parameters. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"], ["DROP TABLE i_love_ponies"], ) param_operation = migrations.RunSQL( # forwards ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');", [ "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);", ["Ponies"], ], ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);", ( 3, "Python", ), ), ), # backwards [ "DELETE FROM i_love_ponies WHERE special_thing = 'Django';", ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None], ( "DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;", [3, "Python"], ), ], ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") new_state = project_state.clone() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) # Test parameter passing with connection.schema_editor() as editor: param_operation.database_forwards( "test_runsql", editor, project_state, new_state ) # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 3) with connection.schema_editor() as editor: param_operation.database_backwards( "test_runsql", editor, new_state, project_state ) with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") def test_run_sql_params_invalid(self): """ #23426 - RunSQL should fail when a list of statements with an incorrect number of tuples is given. """ project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() operation = migrations.RunSQL( # forwards [["INSERT INTO foo (bar) VALUES ('buz');"]], # backwards (("DELETE FROM foo WHERE bar = 'buz';", "invalid", "parameter count"),), ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"): operation.database_forwards( "test_runsql", editor, project_state, new_state ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"): operation.database_backwards( "test_runsql", editor, new_state, project_state ) def test_run_sql_noop(self): """ #24098 - Tests no-op RunSQL operations. """ operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop) with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, None, None) operation.database_backwards("test_runsql", editor, None, None) def test_run_sql_add_missing_semicolon_on_collect_sql(self): project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() tests = [ "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1);\n", "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1)\n", ] for sql in tests: with self.subTest(sql=sql): operation = migrations.RunSQL(sql, migrations.RunPython.noop) with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards( "test_runsql", editor, project_state, new_state ) collected_sql = "\n".join(editor.collected_sql) self.assertEqual(collected_sql.count(";"), 1) def test_run_python(self): """ Tests the RunPython operation """ project_state = self.set_up_test_model("test_runpython", mti_model=True) # Create the operation def inner_method(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.create(pink=1, weight=3.55) Pony.objects.create(weight=5) def inner_method_reverse(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.filter(pink=1, weight=3.55).delete() Pony.objects.filter(weight=5).delete() operation = migrations.RunPython( inner_method, reverse_code=inner_method_reverse ) self.assertEqual(operation.describe(), "Raw Python operation") # Test the state alteration does nothing new_state = project_state.clone() operation.state_forwards("test_runpython", new_state) self.assertEqual(new_state, project_state) # Test the database alteration self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) # Now test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) # Now test we can't use a string with self.assertRaisesMessage( ValueError, "RunPython must be supplied with a callable" ): migrations.RunPython("print 'ahahaha'") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code", "reverse_code"]) # Also test reversal fails, with an operation identical to above but # without reverse_code set. no_reverse_operation = migrations.RunPython(inner_method) self.assertFalse(no_reverse_operation.reversible) with connection.schema_editor() as editor: no_reverse_operation.database_forwards( "test_runpython", editor, project_state, new_state ) with self.assertRaises(NotImplementedError): no_reverse_operation.database_backwards( "test_runpython", editor, new_state, project_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) def create_ponies(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") pony1 = Pony.objects.create(pink=1, weight=3.55) self.assertIsNot(pony1.pk, None) pony2 = Pony.objects.create(weight=5) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_ponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4 ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code"]) def create_shetlandponies(models, schema_editor): ShetlandPony = models.get_model("test_runpython", "ShetlandPony") pony1 = ShetlandPony.objects.create(weight=4.0) self.assertIsNot(pony1.pk, None) pony2 = ShetlandPony.objects.create(weight=5.0) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_shetlandponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6 ) self.assertEqual( project_state.apps.get_model( "test_runpython", "ShetlandPony" ).objects.count(), 2, ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunPython(inner_method, elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_python_atomic(self): """ Tests the RunPython operation correctly handles the "atomic" keyword """ project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True) def inner_method(models, schema_editor): Pony = models.get_model("test_runpythonatomic", "Pony") Pony.objects.create(pink=1, weight=3.55) raise ValueError("Adrian hates ponies.") # Verify atomicity when applying. atomic_migration = Migration("test", "test_runpythonatomic") atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method) ] non_atomic_migration = Migration("test", "test_runpythonatomic") non_atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False) ] # If we're a fully-transactional database, both versions should rollback if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation should leave a row there else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Reset object count to zero and verify atomicity when unapplying. project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.all().delete() # On a fully-transactional database, both versions rollback. if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation leaves a row there. else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Verify deconstruction. definition = non_atomic_migration.operations[0].deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"]) def test_run_python_related_assignment(self): """ #24282 - Model changes to a FK reverse side update the model on the FK side as well. """ def inner_method(models, schema_editor): Author = models.get_model("test_authors", "Author") Book = models.get_model("test_books", "Book") author = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author) create_author = migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ("author", models.ForeignKey("test_authors.Author", models.CASCADE)), ], options={}, ) add_hometown = migrations.AddField( "Author", "hometown", models.CharField(max_length=100), ) create_old_man = migrations.RunPython(inner_method, inner_method) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_authors", new_state) create_author.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_books", new_state) create_book.database_forwards( "test_books", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: add_hometown.state_forwards("test_authors", new_state) add_hometown.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_old_man.state_forwards("test_books", new_state) create_old_man.database_forwards( "test_books", editor, project_state, new_state ) def test_model_with_bigautofield(self): """ A model with BigAutoField can be created. """ def create_data(models, schema_editor): Author = models.get_model("test_author", "Author") Book = models.get_model("test_book", "Book") author1 = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author1) Book.objects.create(id=2**33, title="A farewell to arms", author=author1) author2 = Author.objects.create(id=2**33, name="Remarque") Book.objects.create(title="All quiet on the western front", author=author2) Book.objects.create(title="Arc de Triomphe", author=author2) create_author = migrations.CreateModel( "Author", [ ("id", models.BigAutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.BigAutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ( "author", models.ForeignKey( to="test_author.Author", on_delete=models.CASCADE ), ), ], options={}, ) fill_data = migrations.RunPython(create_data) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_author", new_state) create_author.database_forwards( "test_author", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_book", new_state) create_book.database_forwards("test_book", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_data.state_forwards("fill_data", new_state) fill_data.database_forwards("fill_data", editor, project_state, new_state) def _test_autofield_foreignfield_growth( self, source_field, target_field, target_value ): """ A field may be migrated in the following ways: - AutoField to BigAutoField - SmallAutoField to AutoField - SmallAutoField to BigAutoField """ def create_initial_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog = Blog.objects.create(name="web development done right") Article.objects.create(name="Frameworks", blog=blog) Article.objects.create(name="Programming Languages", blog=blog) def create_big_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog2 = Blog.objects.create(name="Frameworks", id=target_value) Article.objects.create(name="Django", blog=blog2) Article.objects.create(id=target_value, name="Django2", blog=blog2) create_blog = migrations.CreateModel( "Blog", [ ("id", source_field(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_article = migrations.CreateModel( "Article", [ ("id", source_field(primary_key=True)), ( "blog", models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE), ), ("name", models.CharField(max_length=100)), ("data", models.TextField(default="")), ], options={}, ) fill_initial_data = migrations.RunPython( create_initial_data, create_initial_data ) fill_big_data = migrations.RunPython(create_big_data, create_big_data) grow_article_id = migrations.AlterField( "Article", "id", target_field(primary_key=True) ) grow_blog_id = migrations.AlterField( "Blog", "id", target_field(primary_key=True) ) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_blog.state_forwards("test_blog", new_state) create_blog.database_forwards("test_blog", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_article.state_forwards("test_article", new_state) create_article.database_forwards( "test_article", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_initial_data.state_forwards("fill_initial_data", new_state) fill_initial_data.database_forwards( "fill_initial_data", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_article_id.state_forwards("test_article", new_state) grow_article_id.database_forwards( "test_article", editor, project_state, new_state ) state = new_state.clone() article = state.apps.get_model("test_article.Article") self.assertIsInstance(article._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_blog_id.state_forwards("test_blog", new_state) grow_blog_id.database_forwards( "test_blog", editor, project_state, new_state ) state = new_state.clone() blog = state.apps.get_model("test_blog.Blog") self.assertIsInstance(blog._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_big_data.state_forwards("fill_big_data", new_state) fill_big_data.database_forwards( "fill_big_data", editor, project_state, new_state ) def test_autofield__bigautofield_foreignfield_growth(self): """A field may be migrated from AutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.AutoField, models.BigAutoField, 2**33, ) def test_smallfield_autofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to AutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.AutoField, 2**22, ) def test_smallfield_bigautofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.BigAutoField, 2**33, ) def test_run_python_noop(self): """ #24098 - Tests no-op RunPython operations. """ project_state = ProjectState() new_state = project_state.clone() operation = migrations.RunPython( migrations.RunPython.noop, migrations.RunPython.noop ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) operation.database_backwards( "test_runpython", editor, new_state, project_state ) def test_separate_database_and_state(self): """ Tests the SeparateDatabaseAndState operation. """ project_state = self.set_up_test_model("test_separatedatabaseandstate") # Create the operation database_operation = migrations.RunSQL( "CREATE TABLE i_love_ponies (id int, special_thing int);", "DROP TABLE i_love_ponies;", ) state_operation = migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) operation = migrations.SeparateDatabaseAndState( state_operations=[state_operation], database_operations=[database_operation] ) self.assertEqual( operation.describe(), "Custom state/database change combination" ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_separatedatabaseandstate", new_state) self.assertEqual( len( new_state.models[ "test_separatedatabaseandstate", "somethingelse" ].fields ), 1, ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_separatedatabaseandstate", editor, project_state, new_state ) self.assertTableExists("i_love_ponies") # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_separatedatabaseandstate", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "SeparateDatabaseAndState") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["database_operations", "state_operations"] ) def test_separate_database_and_state2(self): """ A complex SeparateDatabaseAndState operation: Multiple operations both for state and database. Verify the state dependencies within each list and that state ops don't affect the database. """ app_label = "test_separatedatabaseandstate2" project_state = self.set_up_test_model(app_label) # Create the operation database_operations = [ migrations.CreateModel( "ILovePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveponies"}, ), migrations.CreateModel( "ILoveMorePonies", # We use IntegerField and not AutoField because # the model is going to be deleted immediately # and with an AutoField this fails on Oracle [("id", models.IntegerField(primary_key=True))], options={"db_table": "ilovemoreponies"}, ), migrations.DeleteModel("ILoveMorePonies"), migrations.CreateModel( "ILoveEvenMorePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveevenmoreponies"}, ), ] state_operations = [ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingelse"}, ), migrations.DeleteModel("SomethingElse"), migrations.CreateModel( "SomethingCompletelyDifferent", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingcompletelydifferent"}, ), ] operation = migrations.SeparateDatabaseAndState( state_operations=state_operations, database_operations=database_operations, ) # Test the state alteration new_state = project_state.clone() operation.state_forwards(app_label, new_state) def assertModelsAndTables(after_db): # Tables and models exist, or don't, as they should: self.assertNotIn((app_label, "somethingelse"), new_state.models) self.assertEqual( len(new_state.models[app_label, "somethingcompletelydifferent"].fields), 1, ) self.assertNotIn((app_label, "iloveponiesonies"), new_state.models) self.assertNotIn((app_label, "ilovemoreponies"), new_state.models) self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models) self.assertTableNotExists("somethingelse") self.assertTableNotExists("somethingcompletelydifferent") self.assertTableNotExists("ilovemoreponies") if after_db: self.assertTableExists("iloveponies") self.assertTableExists("iloveevenmoreponies") else: self.assertTableNotExists("iloveponies") self.assertTableNotExists("iloveevenmoreponies") assertModelsAndTables(after_db=False) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertModelsAndTables(after_db=True) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertModelsAndTables(after_db=False) class SwappableOperationTests(OperationTestBase): """ Key operations ignore swappable models (we don't want to replicate all of them here, as the functionality is in a common base class anyway) """ available_apps = ["migrations"] @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_create_ignore_swapped(self): """ The CreateTable operation ignores swapped models. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], options={ "swappable": "TEST_SWAP_MODEL", }, ) # Test the state alteration (it should still be there!) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crigsw", new_state) self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crigsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crigsw", editor, project_state, new_state) self.assertTableNotExists("test_crigsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crigsw", editor, new_state, project_state ) self.assertTableNotExists("test_crigsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_delete_ignore_swapped(self): """ Tests the DeleteModel operation ignores swapped models. """ operation = migrations.DeleteModel("Pony") project_state, new_state = self.make_test_state("test_dligsw", operation) # Test the database alteration self.assertTableNotExists("test_dligsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dligsw", editor, project_state, new_state) self.assertTableNotExists("test_dligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dligsw", editor, new_state, project_state ) self.assertTableNotExists("test_dligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_add_field_ignore_swapped(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) project_state, new_state = self.make_test_state("test_adfligsw", operation) # Test the database alteration self.assertTableNotExists("test_adfligsw_pony") with connection.schema_editor() as editor: operation.database_forwards( "test_adfligsw", editor, project_state, new_state ) self.assertTableNotExists("test_adfligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adfligsw", editor, new_state, project_state ) self.assertTableNotExists("test_adfligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_indexes_ignore_swapped(self): """ Add/RemoveIndex operations ignore swapped models. """ operation = migrations.AddIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_adinigsw", operation) with connection.schema_editor() as editor: # No database queries should be run for swapped models operation.database_forwards( "test_adinigsw", editor, project_state, new_state ) operation.database_backwards( "test_adinigsw", editor, new_state, project_state ) operation = migrations.RemoveIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_rminigsw", operation) with connection.schema_editor() as editor: operation.database_forwards( "test_rminigsw", editor, project_state, new_state ) operation.database_backwards( "test_rminigsw", editor, new_state, project_state ) class TestCreateModel(SimpleTestCase): def test_references_model_mixin(self): migrations.CreateModel( "name", fields=[], bases=(Mixin, models.Model), ).references_model("other_model", "migrations") class FieldOperationTests(SimpleTestCase): def test_references_model(self): operation = FieldOperation( "MoDel", "field", models.ForeignKey("Other", models.CASCADE) ) # Model name match. self.assertIs(operation.references_model("mOdEl", "migrations"), True) # Referenced field. self.assertIs(operation.references_model("oTher", "migrations"), True) # Doesn't reference. self.assertIs(operation.references_model("Whatever", "migrations"), False) def test_references_field_by_name(self): operation = FieldOperation("MoDel", "field", models.BooleanField(default=False)) self.assertIs(operation.references_field("model", "field", "migrations"), True) def test_references_field_by_remote_field_model(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE) ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_from_fields(self): operation = FieldOperation( "Model", "field", models.fields.related.ForeignObject( "Other", models.CASCADE, ["from"], ["to"] ), ) self.assertIs(operation.references_field("Model", "from", "migrations"), True) self.assertIs(operation.references_field("Model", "to", "migrations"), False) self.assertIs(operation.references_field("Other", "from", "migrations"), False) self.assertIs(operation.references_field("Model", "to", "migrations"), False) def test_references_field_by_to_fields(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE, to_field="field"), ) self.assertIs(operation.references_field("Other", "field", "migrations"), True) self.assertIs( operation.references_field("Other", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_through(self): operation = FieldOperation( "Model", "field", models.ManyToManyField("Other", through="Through") ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_reference_field_by_through_fields(self): operation = FieldOperation( "Model", "field", models.ManyToManyField( "Other", through="Through", through_fields=("first", "second") ), ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Through", "first", "migrations"), True ) self.assertIs( operation.references_field("Through", "second", "migrations"), True )