o xgRi@sddlZddlZddlmZddlZddlmZddlmZm Z ddl m Z ddl m Z ddlmZddlmZGd d d ZdS) N) import_module)settings)NotSupportedError transaction)utils)timezone force_str)_lazy_re_compilec @seZdZdZdZdddddddddd Zd d d d ZiZdZdZ dZ de Z de Z dZ dZedZddZddZddZddZddZddZdd d!Zd"d#Zd$d%Zd&d'Zd(d)Zdd*d+Zd,d-Zd.d/Zd0d1Zd2d3Z d4d5Z!d6d7Z"dd:d;Z#dd?Z%d@dAZ&dBdCZ'ddDdEZ(dFdGZ)dHdIZ*dJdKZ+dLdMZ,dNdOZ-dPdQZ.dRdSZ/dTdUZ0dVdWZ1dXdYZ2dZd[Z3d\d]Z4d^d_Z5d`daZ6d8d8dbdcddZ7dedfZ8dgdhZ9didjZ:dkdlZ;ddndoZe>Z?dtduZ@dvdwZAdxdyZBdzd{ZCd|d}ZDdd~dZEddZFddZGddZHddZIddZJddZKddZLddZMddZNddZOddZPddZQddZRddZSddZTdddZUdddZVdddZWdddZXdddZYdS)BaseDatabaseOperationsz Encapsulate backend-specific differences, such as the way a backend performs ordering or calculates the ID of a recently-inserted row. zdjango.db.models.sql.compiler)i)i)l)rr)rr )rr ) SmallIntegerField IntegerFieldBigIntegerFieldPositiveBigIntegerFieldPositiveSmallIntegerFieldPositiveIntegerFieldSmallAutoField AutoField BigAutoFieldUNION INTERSECTEXCEPT)union intersection differenceN PRECEDING FOLLOWINGz UNBOUNDED z CURRENT ROWz [\w\-_()]+cCs||_d|_dSN) connection_cache)selfr!r$D/usr/lib/python3/dist-packages/django/db/backends/base/operations.py__init__;s zBaseDatabaseOperations.__init__cCdS)z 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. Nr$)r#tablecolumnr$r$r% autoinc_sql?z"BaseDatabaseOperations.autoinc_sqlcCst|S)z 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. )len)r#fieldsobjsr$r$r%bulk_batch_sizeHz&BaseDatabaseOperations.bulk_batch_sizecCr')z 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. z>SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%sr$r#r$r$r%cache_key_culling_sqlPz,BaseDatabaseOperations.cache_key_culling_sqlcCr')z 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. %sr$)r# output_fieldr$r$r%unification_cast_sqlZz+BaseDatabaseOperations.unification_cast_sqlcCtd)z Given a lookup_type of 'year', 'month', or 'day', return the SQL that extracts a value from the given date field field_name. zLsubclasses of BaseDatabaseOperations may require a date_extract_sql() methodNotImplementedErrorr# lookup_type field_namer$r$r%date_extract_sqlbz'BaseDatabaseOperations.date_extract_sqlcCr8)a. 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. zKsubclasses of BaseDatabaseOperations may require a date_trunc_sql() method.r9r#r<r=tznamer$r$r%date_trunc_sqli z%BaseDatabaseOperations.date_trunc_sqlcCr8)zH Return the SQL to cast a datetime value to date value. zSsubclasses of BaseDatabaseOperations may require a datetime_cast_date_sql() method.r9r#r=rAr$r$r%datetime_cast_date_sqltsz-BaseDatabaseOperations.datetime_cast_date_sqlcCr8)zH Return the SQL to cast a datetime value to time value. zRsubclasses of BaseDatabaseOperations may require a datetime_cast_time_sql() methodr9rDr$r$r%datetime_cast_time_sql}sz-BaseDatabaseOperations.datetime_cast_time_sqlcCr8)z 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. zPsubclasses of BaseDatabaseOperations may require a datetime_extract_sql() methodr9r@r$r$r%datetime_extract_sqlr0z+BaseDatabaseOperations.datetime_extract_sqlcCr8)z 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. zNsubclasses of BaseDatabaseOperations may require a datetime_trunc_sql() methodr9r@r$r$r%datetime_trunc_sqlr0z)BaseDatabaseOperations.datetime_trunc_sqlcCr8)a1 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. zJsubclasses of BaseDatabaseOperations may require a time_trunc_sql() methodr9r@r$r$r%time_trunc_sqlrCz%BaseDatabaseOperations.time_trunc_sqlcC |||S)z Given a lookup_type of 'hour', 'minute', or 'second', return the SQL that extracts a value from the given time field field_name. )r>r;r$r$r%time_extract_sqls z'BaseDatabaseOperations.time_extract_sqlcCr')zs Return the SQL to make a constraint "initially deferred" during a CREATE TABLE statement. r$r1r$r$r%deferrable_sqlz%BaseDatabaseOperations.deferrable_sqlcCs|rtddggfS)z 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. zd|rdnd|rdd|nd|rdnd|rdfSdfS)zX Return the FOR UPDATE SQL clause to lock rows for an update operation. zFOR%s UPDATE%s%s%sz NO KEYrLz OF %s, z NOWAITz SKIP LOCKEDjoin)r#nowait skip_lockedofno_keyr$r$r%for_update_sqls  z%BaseDatabaseOperations.for_update_sqlcCs8|pd}|dur|||fS|r|jj|fSd|fSNr)r!opsno_limit_value)r#low_mark high_markoffsetr$r$r%_get_limit_offset_paramss  z/BaseDatabaseOperations._get_limit_offset_paramscCs@|||\}}ddd|rd|nd|rd|ndfDS)zReturn LIMIT/OFFSET SQL clause. css|]}|r|VqdSr r$).0sqlr$r$r% sz:BaseDatabaseOperations.limit_offset_sql..zLIMIT %dNz OFFSET %d)rir])r#rfrglimitrhr$r$r%limit_offset_sqls   z'BaseDatabaseOperations.limit_offset_sqlcs^ddt|ttfrtfdd|D}n|durd}n fdd|D}d ||fS) a 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. cSst|dddS)NTreplace) strings_onlyerrorsr)sr$r$r% to_stringsz=BaseDatabaseOperations.last_executed_query..to_stringc3s|]}|VqdSr r$)rkvalrtr$r%rmsz=BaseDatabaseOperations.last_executed_query..Nr$csi|] \}}||qSr$r$)rkkvrvr$r% sz>BaseDatabaseOperations.last_executed_query..zQUERY = %r - PARAMS = %r) isinstancelisttupleitems)r#rSrlrPu_paramsr$rvr%last_executed_querys  z*BaseDatabaseOperations.last_executed_querycCs|jS)z 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. ) lastrowid)r#rS table_namepk_namer$r$r%last_insert_idsz%BaseDatabaseOperations.last_insert_idcCr')z 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. r4r$)r#r<rWr$r$r% lookup_castr7z"BaseDatabaseOperations.lookup_castcCr')z 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. Nr$r1r$r$r%max_in_list_sizerNz'BaseDatabaseOperations.max_in_list_sizecCr')zl Return the maximum length of table and column names, or None if there is no limit. Nr$r1r$r$r%max_name_lengthrNz&BaseDatabaseOperations.max_name_lengthcCr8)z 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. zJsubclasses of BaseDatabaseOperations may require a no_limit_value() methodr9r1r$r$r%rer?z%BaseDatabaseOperations.no_limit_valuecCr')z Return the value to use during an INSERT statement to specify that the field should use its default value. DEFAULTr$r1r$r$r%pk_default_value%rNz'BaseDatabaseOperations.pk_default_valuecCsddt|DS)ag 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. cSsg|] }|rtj|ddqS)T)strip_comments)sqlparseformat)rk statementr$r$r% 5s  z=BaseDatabaseOperations.prepare_sql_script..)rsplit)r#rlr$r$r%prepare_sql_script,s z)BaseDatabaseOperations.prepare_sql_scriptcC|S)z Return the value of a CLOB column, for backends that return a locator object that requires additional processing. r$r#valuer$r$r% process_clob:rNz#BaseDatabaseOperations.process_clobcCr')z 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. Nr$)r#r-r$r$r%return_insert_columnsAr7z,BaseDatabaseOperations.return_insert_columnscCs"|jdur t|j|_t|j|S)z Return the SQLCompiler class corresponding to the given name, in the namespace corresponding to the `compiler_module` attribute on this backend. N)r"rcompiler_modulegetattr)r# compiler_namer$r$r%compilerIs   zBaseDatabaseOperations.compilercCr8)z Return a quoted version of the given table, index, or column name. Do not quote the given name if it's already been quoted. zFsubclasses of BaseDatabaseOperations may require a quote_name() methodr9)r#namer$r$r% quote_nameSr?z!BaseDatabaseOperations.quote_namecCr8)aG 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. zHsubclasses of BaseDatabaseOperations may require a regex_lookup() methodr9)r#r<r$r$r% regex_lookupZrCz#BaseDatabaseOperations.regex_lookupcCd||S)z 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. z SAVEPOINT %srr#sidr$r$r%savepoint_create_sqlesz+BaseDatabaseOperations.savepoint_create_sqlcCr)zD Return the SQL for committing the given savepoint. zRELEASE SAVEPOINT %srrr$r$r%savepoint_commit_sqlmz+BaseDatabaseOperations.savepoint_commit_sqlcCr)zF Return the SQL for rolling back the given savepoint. zROLLBACK TO SAVEPOINT %srrr$r$r%savepoint_rollback_sqlsrz-BaseDatabaseOperations.savepoint_rollback_sqlcCr')z Return the SQL that will set the connection's time zone. Return '' if the backend doesn't support time zones. rLr$r1r$r$r%set_time_zone_sqlyr7z(BaseDatabaseOperations.set_time_zone_sql)reset_sequences allow_cascadecCr8)a 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. zGsubclasses of BaseDatabaseOperations must provide an sql_flush() methodr9)r#styletablesrrr$r$r% sql_flushsz BaseDatabaseOperations.sql_flushc Cstj|jj|jjjd0|j}|D]}||qWdn1s'wYWddSWddS1s?wYdS)z7Execute a list of SQL statements to flush the database.)using savepointN)ratomicr!aliasfeaturescan_rollback_ddlrSexecute)r#sql_listrSrlr$r$r%execute_sql_flushs  "z(BaseDatabaseOperations.execute_sql_flushcCrY)z 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. r$)r#r sequencesr$r$r%sequence_reset_by_name_sqlr3z1BaseDatabaseOperations.sequence_reset_by_name_sqlcCrY)z 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. r$)r#r model_listr$r$r%sequence_reset_sqlr3z)BaseDatabaseOperations.sequence_reset_sqlcCr')z9Return the SQL statement required to start a transaction.zBEGIN;r$r1r$r$r%start_transaction_sqlsz,BaseDatabaseOperations.start_transaction_sqlTcCs |sdSdS)z7Return the SQL statement required to end a transaction.z ROLLBACK;zCOMMIT;r$)r#successr$r$r%end_transaction_sqlsz*BaseDatabaseOperations.end_transaction_sqlcCr')a 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. rLr$)r# tablespaceinliner$r$r%tablespace_sql z%BaseDatabaseOperations.tablespace_sqlcCs t|ddddddS)z(Prepare a value for use in a LIKE query.\z\\%z\%_z\_)strrp)r#xr$r$r%prep_for_like_querys z*BaseDatabaseOperations.prep_for_like_querycCr)z 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. r$rr$r$r%validate_autopk_valuer7z,BaseDatabaseOperations.validate_autopk_valuecCs\t|tjr ||St|tjr||St|tjr!||St|tjr,| |S|S)a8 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. ) rzdatetimeadapt_datetimefield_valuedateadapt_datefield_valuetimeadapt_timefield_valuedecimalDecimaladapt_decimalfield_valuerr$r$r%adapt_unknown_values        z*BaseDatabaseOperations.adapt_unknown_valuecC|durdSt|S)z Transform a date value to an object compatible with what is expected by the backend driver for date columns. Nrrr$r$r%rz,BaseDatabaseOperations.adapt_datefield_valuecCr)z Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. Nrrr$r$r%rrz0BaseDatabaseOperations.adapt_datetimefield_valuecCs&|durdSt|rtdt|S)z Transform a time value to an object compatible with what is expected by the backend driver for time columns. Nz-Django does not support timezone-aware times.)ris_aware ValueErrorrrr$r$r%rs  z,BaseDatabaseOperations.adapt_timefield_valuecCst|||S)z Transform a decimal.Decimal value to an object compatible with what is expected by the backend driver for decimal (numeric) columns. )r format_number)r#r max_digitsdecimal_placesr$r$r%rsz/BaseDatabaseOperations.adapt_decimalfield_valuecCs|pdS)z{ Transform a string representation of an IP address into the expected type for the backend driver. Nr$rr$r$r%adapt_ipaddressfield_value r?z1BaseDatabaseOperations.adapt_ipaddressfield_valuecCs8t|dd}t|dd}||}||}||gS)z 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.  )rrr)r#rfirstsecondr$r$r%!year_lookup_bounds_for_date_fields   z8BaseDatabaseOperations.year_lookup_bounds_for_date_fieldc Csft|dd}t|dddddd}tjr%t}t||}t||}||}||}||gS)z 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. rrr;i?B)rrUSE_TZrget_current_timezone make_awarer)r#rrrtzr$r$r%%year_lookup_bounds_for_datetime_field"s    zrBrErFrGrHrIrKrMrQrUrXrZrbrirorrrrrrerrrrrrrrrrrrrrrrrrrprep_for_iexact_queryrrrrrrrrrrrrrrrrrrrrrr rrrrr$r$r$r%r s                          r )rr importlibrr django.confr django.dbrrdjango.db.backendsr django.utilsrdjango.utils.encodingr django.utils.regex_helperr r r$r$r$r%s