encapsulate backendspecific differences such as the way a backend performs ordering or calculates the id of a recentlyinserted row integer field safe ranges by internaltype as documented in docsrefmodelsfields txt mapping of field getinternaltype typically the model field s class name to the data type to use for the cast function if different from databasewrapper datatypes charfield data type if the maxlength argument isn t provided start and end points for window expressions prefix for explain queries or none explain isn t supported return any sql needed to support autoincrementing primary keys or none if no sql is necessary this sql is executed when a table is created 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 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 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 given a lookuptype of year month or day return the sql that extracts a value from the given date field fieldname given a lookuptype of year month or day return the sql that truncates the given date or datetime field fieldname to a date object with only the given specificity if tzname is provided the given value is truncated in a specific timezone return the sql to cast a datetime value to date value return the sql to cast a datetime value to time value given a lookuptype of year month day hour minute or second return the sql that extracts a value from the given datetime field fieldname given a lookuptype of year month day hour minute or second return the sql that truncates the given datetime field fieldname to a datetime object with only the given specificity given a lookuptype of hour minute or second return the sql that truncates the given time or datetime field fieldname to a time object with only the given specificity if tzname is provided the given value is truncated in a specific timezone given a lookuptype of hour minute or second return the sql that extracts a value from the given time field fieldname return the sql to make a constraint initially deferred during a create table statement 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 given a cursor object that has just performed an insert returning statement into a table return the newly created data 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 a group by clause to use with a having clause when no grouping is specified 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 the for update sql clause to lock rows for an update operation return limitoffset sql clause limit offset self getlimitoffsetparamslowmark highmark return join sql for sql in limit d limit if limit else none offset d offset if offset else none if sql def lastexecutedqueryself cursor sql params convert params to contain string values def tostrings return forcestrs stringsonlytrue errorsreplace if isinstanceparams list tuple uparams tupletostringval for val in params elif params is none uparams else uparams tostringk tostringv for k v in params items return query r params r sql uparams def lastinsertidself cursor tablename pkname return cursor lastrowid def lookupcastself lookuptype internaltypenone return s def maxinlistsizeself return none def maxnamelengthself return none def nolimitvalueself raise notimplementederror subclasses of basedatabaseoperations may require a nolimitvalue method def pkdefaultvalueself return default def preparesqlscriptself sql return sqlparse formatstatement stripcommentstrue for statement in sqlparse splitsql if statement def processclobself value return value def returninsertcolumnsself fields pass def compilerself compilername if self cache is none self cache importmoduleself compilermodule return getattrself cache compilername def quotenameself name raise notimplementederror subclasses of basedatabaseoperations may require a quotename method def regexlookupself lookuptype raise notimplementederror subclasses of basedatabaseoperations may require a regexlookup method def savepointcreatesqlself sid return savepoint s self quotenamesid def savepointcommitsqlself sid return release savepoint s self quotenamesid def savepointrollbacksqlself sid return rollback to savepoint s self quotenamesid def settimezonesqlself return def sqlflushself style tables resetsequencesfalse allowcascadefalse raise notimplementederror subclasses of basedatabaseoperations must provide an sqlflush method def executesqlflushself sqllist 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 colorstyle or nostyle in django core management color 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 colorstyle or nostyle in django core management color return the sql statement required to start a transaction return begin def endtransactionsqlself successtrue 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 prepare a value for use in a like query return strx replace replace r replace r same as prepforlikequery but called for iexact matches which need not necessarily be implemented using like in the backend prepforiexactquery prepforlikequery def validateautopkvalueself value return value def adaptunknownvalueself value if isinstancevalue datetime datetime must be before date return self adaptdatetimefieldvaluevalue elif isinstancevalue datetime date return self adaptdatefieldvaluevalue elif isinstancevalue datetime time return self adapttimefieldvaluevalue elif isinstancevalue decimal decimal return self adaptdecimalfieldvaluevalue else return value def adaptintegerfieldvalueself value internaltype return value def adaptdatefieldvalueself value if value is none return none return strvalue def adaptdatetimefieldvalueself value if value is none return none expression values are adapted by the database if hasattrvalue resolveexpression return value return strvalue def adapttimefieldvalueself value if value is none return none expression values are adapted by the database if hasattrvalue resolveexpression return value if timezone isawarevalue raise valueerrordjango does not support timezoneaware times return strvalue def adaptdecimalfieldvalueself value maxdigitsnone decimalplacesnone return utils formatnumbervalue maxdigits decimalplaces def adaptipaddressfieldvalueself value return value or none def adaptjsonvalueself value encoder return json dumpsvalue clsencoder def yearlookupboundsfordatefieldself value isoyearfalse if isoyear first datetime date fromisocalendarvalue 1 1 second datetime date fromisocalendar value 1 1 1 datetime timedeltadays1 else first datetime datevalue 1 1 second datetime datevalue 12 31 first self adaptdatefieldvaluefirst second self adaptdatefieldvaluesecond return first second def yearlookupboundsfordatetimefieldself value isoyearfalse if isoyear first datetime datetime fromisocalendarvalue 1 1 second datetime datetime fromisocalendar value 1 1 1 datetime timedeltamicroseconds1 else first datetime datetimevalue 1 1 second datetime datetimevalue 12 31 23 59 59 999999 if settings usetz tz timezone getcurrenttimezone first timezone makeawarefirst tz second timezone makeawaresecond tz first self adaptdatetimefieldvaluefirst second self adaptdatetimefieldvaluesecond return first second def getdbconvertersself expression return def convertdurationfieldvalueself value expression connection if value is not none return datetime timedelta0 0 value def checkexpressionsupportself expression pass def conditionalexpressionsupportedinwhereclauseself expression return true def combineexpressionself connector subexpressions conn s connector return conn joinsubexpressions def combinedurationexpressionself connector subexpressions return self combineexpressionconnector subexpressions def binaryplaceholdersqlself value return s def modifyinsertparamsself placeholder params return params def integerfieldrangeself internaltype return self integerfieldrangesinternaltype def subtracttemporalsself internaltype lhs rhs if self connection features supportstemporalsubtraction lhssql lhsparams lhs rhssql rhsparams rhs return s s lhssql rhssql lhsparams rhsparams raise notsupportederror this backend does not support s subtraction internaltype def windowframevalueself value if isinstancevalue int if value 0 return self currentrow elif value 0 return d s absvalue self preceding else return d s value self following def windowframerowsstartendself startnone endnone if isinstancestart int and isinstanceend int and start end raise valueerrorstart cannot be greater than end if start is not none and not isinstancestart int raise valueerror fstart argument must be an integer zero or none but got start if end is not none and not isinstanceend int raise valueerror fend argument must be an integer zero or none but got end start self windowframevaluestart or self unboundedpreceding end self windowframevalueend or self unboundedfollowing return start end def windowframerangestartendself startnone endnone if start is not none and not isinstancestart int or isinstancestart int and start 0 raise valueerror start argument must be a negative integer zero or none but got s start if end is not none and not isinstanceend int or isinstanceend int and end 0 raise valueerror end argument must be a positive integer zero or none but got s end start self windowframevaluestart or self unboundedpreceding end self windowframevalueend or self unboundedfollowing features self connection features if features onlysupportsunboundedwithprecedingandfollowing and start and start 0 or end and end 0 raise notsupportederror s only supports unbounded together with preceding and following self connection displayname return start end def explainqueryprefixself formatnone options if not self connection features supportsexplainingqueryexecution raise notsupportederror this backend does not support explaining query execution if format supportedformats self connection features supportedexplainformats normalizedformat format upper if normalizedformat not in supportedformats msg s is not a recognized format normalizedformat if supportedformats msg allowed formats s joinsortedsupportedformats else msg f self connection displayname does not support any formats raise valueerrormsg if options raise valueerrorunknown options s joinsortedoptions keys return self explainprefix def insertstatementself onconflictnone return insert into def onconflictsuffixsqlself fields onconflict updatefields uniquefields return def preparejoinonclauseself lhstable lhsfield rhstable rhsfield lhsexpr collhstable lhsfield rhsexpr colrhstable rhsfield return lhsexpr rhsexpr encapsulate backend specific differences such as the way a backend performs ordering or calculates the id of a recently inserted row integer field safe ranges by internal_type as documented in docs ref models fields txt 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 charfield data type if the max_length argument isn t provided start and end points for window expressions prefix for explain queries or none explain isn t supported 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 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 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 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 given a lookup_type of year month or day return the sql that extracts a value from the given date field field_name 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 return the sql to cast a datetime value to date value return the sql to cast a datetime value to time value 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 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 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 given a lookup_type of hour minute or second return the sql that extracts a value from the given time field field_name return the sql to make a constraint initially deferred during a create table statement 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 given a cursor object that has just performed an insert returning statement into a table return the newly created data 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 a group by clause to use with a having clause when no grouping is specified 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 the for update sql clause to lock rows for an update operation return limit offset sql clause 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 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 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 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 the maximum length of table and column names or none if there is no limit 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 return the value to use during an insert statement to specify that the field should use its default value 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 the value of a clob column for backends that return a locator object that requires additional processing 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 return the sqlcompiler class corresponding to the given name in the namespace corresponding to the compiler_module attribute on this backend return a quoted version of the given table index or column name do not quote the given name if it s already been quoted 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 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 the sql for committing the given savepoint return the sql for rolling back the given savepoint return the sql that will set the connection s time zone return if the backend doesn t support time zones 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 execute a list of sql statements to flush the database 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 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 no sequence reset required by default return the sql statement required to start a transaction return the sql statement required to end a transaction 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 prepare a value for use in a like query same as prep_for_like_query but called for iexact matches which need not necessarily be implemented using like in the backend 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 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 must be before date transform a date value to an object compatible with what is expected by the backend driver for date columns transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns expression values are adapted by the database transform a time value to an object compatible with what is expected by the backend driver for time columns expression values are adapted by the database transform a decimal decimal value to an object compatible with what is expected by the backend driver for decimal numeric columns transform a string representation of an ip address into the expected type for the backend driver 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 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 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 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 return true if the conditional expression is supported in the where clause 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 some backends require special syntax to insert binary content mysql for example uses _binary s allow modification of insert parameters needed for oracle spatial backend due to 10888 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 sql for start and end points in an over clause window frame
import datetime
import decimal
import json
import warnings
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.db.models.expressions import Col
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango60Warning
from django.utils.encoding import force_str


class BaseDatabaseOperations:
    

    compiler_module = "django.db.models.sql.compiler"

    
    
    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",
    }
    
    
    
    cast_data_types = {}
    
    cast_char_field_without_max_length = None

    
    PRECEDING = "PRECEDING"
    FOLLOWING = "FOLLOWING"
    UNBOUNDED_PRECEDING = "UNBOUNDED " + PRECEDING
    UNBOUNDED_FOLLOWING = "UNBOUNDED " + FOLLOWING
    CURRENT_ROW = "CURRENT ROW"

    
    explain_prefix = None

    def __init__(self, connection):
        self.connection = connection
        self._cache = None

    def autoinc_sql(self, table, column):
        
        return None

    def bulk_batch_size(self, fields, objs):
        
        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):
        
        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):
        
        return "%s"

    def date_extract_sql(self, lookup_type, sql, params):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a date_extract_sql() "
            "method"
        )

    def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a date_trunc_sql() "
            "method."
        )

    def datetime_cast_date_sql(self, sql, params, tzname):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a "
            "datetime_cast_date_sql() method."
        )

    def datetime_cast_time_sql(self, sql, params, tzname):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a "
            "datetime_cast_time_sql() method"
        )

    def datetime_extract_sql(self, lookup_type, sql, params, tzname):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a datetime_extract_sql() "
            "method"
        )

    def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() "
            "method"
        )

    def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a time_trunc_sql() method"
        )

    def time_extract_sql(self, lookup_type, sql, params):
        
        return self.date_extract_sql(lookup_type, sql, params)

    def deferrable_sql(self):
        
        return ""

    def distinct_sql(self, fields, params):
        
        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):
        
        return cursor.fetchone()

    def field_cast_sql(self, db_type, internal_type):
        
        warnings.warn(
            (
                "DatabaseOperations.field_cast_sql() is deprecated use "
                "DatabaseOperations.lookup_cast() instead."
            ),
            RemovedInDjango60Warning,
        )
        return "%s"

    def force_group_by(self):
        
        return []

    def force_no_ordering(self):
        
        return []

    def for_update_sql(self, nowait=False, skip_locked=False, of=(), no_key=False):
        
        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):
        
        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):
        

        
        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):
        
        return cursor.lastrowid

    def lookup_cast(self, lookup_type, internal_type=None):
        
        return "%s"

    def max_in_list_size(self):
        
        return None

    def max_name_length(self):
        
        return None

    def no_limit_value(self):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a no_limit_value() method"
        )

    def pk_default_value(self):
        
        return "DEFAULT"

    def prepare_sql_script(self, sql):
        
        return [
            sqlparse.format(statement, strip_comments=True)
            for statement in sqlparse.split(sql)
            if statement
        ]

    def process_clob(self, value):
        
        return value

    def return_insert_columns(self, fields):
        
        pass

    def compiler(self, compiler_name):
        
        if self._cache is None:
            self._cache = import_module(self.compiler_module)
        return getattr(self._cache, compiler_name)

    def quote_name(self, name):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a quote_name() method"
        )

    def regex_lookup(self, lookup_type):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations may require a regex_lookup() method"
        )

    def savepoint_create_sql(self, sid):
        
        return "SAVEPOINT %s" % self.quote_name(sid)

    def savepoint_commit_sql(self, sid):
        
        return "RELEASE SAVEPOINT %s" % self.quote_name(sid)

    def savepoint_rollback_sql(self, sid):
        
        return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid)

    def set_time_zone_sql(self):
        
        return ""

    def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
        
        raise NotImplementedError(
            "subclasses of BaseDatabaseOperations must provide an sql_flush() method"
        )

    def execute_sql_flush(self, sql_list):
        
        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 []

    def sequence_reset_sql(self, style, model_list):
        
        return []  

    def start_transaction_sql(self):
        
        return "BEGIN;"

    def end_transaction_sql(self, success=True):
        
        if not success:
            return "ROLLBACK;"
        return "COMMIT;"

    def tablespace_sql(self, tablespace, inline=False):
        
        return ""

    def prep_for_like_query(self, x):
        
        return str(x).replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_")

    
    
    prep_for_iexact_query = prep_for_like_query

    def validate_autopk_value(self, value):
        
        return value

    def adapt_unknown_value(self, value):
        
        if isinstance(value, datetime.datetime):  
            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_integerfield_value(self, value, internal_type):
        return value

    def adapt_datefield_value(self, value):
        
        if value is None:
            return None
        return str(value)

    def adapt_datetimefield_value(self, value):
        
        if value is None:
            return None
        
        if hasattr(value, "resolve_expression"):
            return value

        return str(value)

    def adapt_timefield_value(self, value):
        
        if value is None:
            return None
        
        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):
        
        return utils.format_number(value, max_digits, decimal_places)

    def adapt_ipaddressfield_value(self, value):
        
        return value or None

    def adapt_json_value(self, value, encoder):
        return json.dumps(value, cls=encoder)

    def year_lookup_bounds_for_date_field(self, value, iso_year=False):
        
        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):
        
        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 []

    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):
        
        pass

    def conditional_expression_supported_in_where_clause(self, expression):
        
        return True

    def combine_expression(self, connector, sub_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):
        
        return "%s"

    def modify_insert_params(self, placeholder, params):
        
        return params

    def integer_field_range(self, internal_type):
        
        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_value(self, value):
        if isinstance(value, int):
            if value == 0:
                return self.CURRENT_ROW
            elif value < 0:
                return "%d %s" % (abs(value), self.PRECEDING)
            else:
                return "%d %s" % (value, self.FOLLOWING)

    def window_frame_rows_start_end(self, start=None, end=None):
        
        if isinstance(start, int) and isinstance(end, int) and start > end:
            raise ValueError("start cannot be greater than end.")
        if start is not None and not isinstance(start, int):
            raise ValueError(
                f"start argument must be an integer, zero, or None, but got '{start}'."
            )
        if end is not None and not isinstance(end, int):
            raise ValueError(
                f"end argument must be an integer, zero, or None, but got '{end}'."
            )
        start_ = self.window_frame_value(start) or self.UNBOUNDED_PRECEDING
        end_ = self.window_frame_value(end) or self.UNBOUNDED_FOLLOWING
        return start_, end_

    def window_frame_range_start_end(self, start=None, end=None):
        if (start is not None and not isinstance(start, int)) or (
            isinstance(start, int) and start > 0
        ):
            raise ValueError(
                "start argument must be a negative integer, zero, or None, "
                "but got '%s'." % start
            )
        if (end is not None and not isinstance(end, int)) or (
            isinstance(end, int) and end < 0
        ):
            raise ValueError(
                "end argument must be a positive integer, zero, or None, but got '%s'."
                % end
            )
        start_ = self.window_frame_value(start) or self.UNBOUNDED_PRECEDING
        end_ = self.window_frame_value(end) or self.UNBOUNDED_FOLLOWING
        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 ""

    def prepare_join_on_clause(self, lhs_table, lhs_field, rhs_table, rhs_field):
        lhs_expr = Col(lhs_table, lhs_field)
        rhs_expr = Col(rhs_table, rhs_field)

        return lhs_expr, rhs_expr