2006-05-02 09:31:56 +08:00
|
|
|
"""
|
2007-09-03 04:04:44 +08:00
|
|
|
SQLite3 backend for django.
|
|
|
|
|
2011-03-28 10:27:05 +08:00
|
|
|
Works with either the pysqlite2 module or the sqlite3 module in the
|
2009-03-20 11:57:21 +08:00
|
|
|
standard library.
|
2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
|
2011-07-13 17:35:51 +08:00
|
|
|
import datetime
|
|
|
|
import decimal
|
2011-12-16 21:40:19 +08:00
|
|
|
import warnings
|
2010-03-23 21:51:11 +08:00
|
|
|
import re
|
2010-01-29 23:45:55 +08:00
|
|
|
import sys
|
|
|
|
|
|
|
|
from django.db import utils
|
2008-08-11 20:11:25 +08:00
|
|
|
from django.db.backends import *
|
2009-03-30 07:15:58 +08:00
|
|
|
from django.db.backends.signals import connection_created
|
2008-08-11 20:11:25 +08:00
|
|
|
from django.db.backends.sqlite3.client import DatabaseClient
|
|
|
|
from django.db.backends.sqlite3.creation import DatabaseCreation
|
|
|
|
from django.db.backends.sqlite3.introspection import DatabaseIntrospection
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.dateparse import parse_date, parse_datetime, parse_time
|
2009-01-15 19:06:34 +08:00
|
|
|
from django.utils.safestring import SafeString
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.timezone import is_aware, is_naive, utc
|
2008-08-11 20:11:25 +08:00
|
|
|
|
2006-05-27 02:58:46 +08:00
|
|
|
try:
|
2006-09-25 09:53:34 +08:00
|
|
|
try:
|
|
|
|
from pysqlite2 import dbapi2 as Database
|
2009-03-20 11:57:21 +08:00
|
|
|
except ImportError, e1:
|
|
|
|
from sqlite3 import dbapi2 as Database
|
2008-09-17 15:23:17 +08:00
|
|
|
except ImportError, exc:
|
2006-05-27 02:58:46 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2011-03-28 10:27:05 +08:00
|
|
|
raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
DatabaseError = Database.DatabaseError
|
2007-04-25 18:18:56 +08:00
|
|
|
IntegrityError = Database.IntegrityError
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def parse_datetime_with_timezone_support(value):
|
|
|
|
dt = parse_datetime(value)
|
|
|
|
# Confirm that dt is naive before overwriting its tzinfo.
|
|
|
|
if dt is not None and settings.USE_TZ and is_naive(dt):
|
|
|
|
dt = dt.replace(tzinfo=utc)
|
|
|
|
return dt
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Database.register_converter("bool", lambda s: str(s) == '1')
|
2011-11-18 21:01:06 +08:00
|
|
|
Database.register_converter("time", parse_time)
|
|
|
|
Database.register_converter("date", parse_date)
|
|
|
|
Database.register_converter("datetime", parse_datetime_with_timezone_support)
|
|
|
|
Database.register_converter("timestamp", parse_datetime_with_timezone_support)
|
|
|
|
Database.register_converter("TIMESTAMP", parse_datetime_with_timezone_support)
|
2007-05-21 09:29:58 +08:00
|
|
|
Database.register_converter("decimal", util.typecast_decimal)
|
|
|
|
Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal)
|
2011-11-18 21:01:06 +08:00
|
|
|
if Database.version_info >= (2, 4, 1):
|
2008-08-10 07:59:01 +08:00
|
|
|
# Starting in 2.4.1, the str type is not accepted anymore, therefore,
|
|
|
|
# we convert all str objects to Unicode
|
|
|
|
# As registering a adapter for a primitive type causes a small
|
|
|
|
# slow-down, this adapter is only registered for sqlite3 versions
|
|
|
|
# needing it.
|
2011-11-18 21:01:06 +08:00
|
|
|
Database.register_adapter(str, lambda s: s.decode('utf-8'))
|
|
|
|
Database.register_adapter(SafeString, lambda s: s.decode('utf-8'))
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2007-08-20 10:20:33 +08:00
|
|
|
class DatabaseFeatures(BaseDatabaseFeatures):
|
2008-07-16 02:47:32 +08:00
|
|
|
# SQLite cannot handle us only partially reading from a cursor's result set
|
|
|
|
# and then writing the same rows to the database in another cursor. This
|
|
|
|
# setting ensures we always read result sets fully into memory all in one
|
|
|
|
# go.
|
|
|
|
can_use_chunked_reads = False
|
2010-10-11 20:55:17 +08:00
|
|
|
test_db_allows_multiple_connections = False
|
|
|
|
supports_unspecified_pk = True
|
2011-11-18 21:01:06 +08:00
|
|
|
supports_timezones = False
|
2010-10-19 08:14:41 +08:00
|
|
|
supports_1000_query_parameters = False
|
2010-12-22 11:34:04 +08:00
|
|
|
supports_mixed_date_datetime_comparisons = False
|
2011-09-10 03:22:28 +08:00
|
|
|
has_bulk_insert = True
|
|
|
|
can_combine_inserts_with_and_without_auto_increment_pk = True
|
2010-10-11 20:55:17 +08:00
|
|
|
|
|
|
|
def _supports_stddev(self):
|
|
|
|
"""Confirm support for STDDEV and related stats functions
|
|
|
|
|
|
|
|
SQLite supports STDDEV as an extension package; so
|
|
|
|
connection.ops.check_aggregate_support() can't unilaterally
|
|
|
|
rule out support for STDDEV. We need to manually check
|
|
|
|
whether the call works.
|
|
|
|
"""
|
|
|
|
cursor = self.connection.cursor()
|
|
|
|
cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
|
|
|
|
try:
|
|
|
|
cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
|
|
|
|
has_support = True
|
|
|
|
except utils.DatabaseError:
|
|
|
|
has_support = False
|
|
|
|
cursor.execute('DROP TABLE STDDEV_TEST')
|
|
|
|
return has_support
|
2007-08-20 10:20:33 +08:00
|
|
|
|
2007-08-20 06:29:57 +08:00
|
|
|
class DatabaseOperations(BaseDatabaseOperations):
|
2007-08-20 06:40:06 +08:00
|
|
|
def date_extract_sql(self, lookup_type, field_name):
|
|
|
|
# sqlite doesn't support extract, so we fake it with the user-defined
|
2010-02-24 23:29:25 +08:00
|
|
|
# function django_extract that's registered in connect(). Note that
|
|
|
|
# single quotes are used because this is a string (and could otherwise
|
|
|
|
# cause a collision with a field name).
|
|
|
|
return "django_extract('%s', %s)" % (lookup_type.lower(), field_name)
|
2007-08-20 06:29:57 +08:00
|
|
|
|
2010-12-22 11:34:04 +08:00
|
|
|
def date_interval_sql(self, sql, connector, timedelta):
|
|
|
|
# It would be more straightforward if we could use the sqlite strftime
|
|
|
|
# function, but it does not allow for keeping six digits of fractional
|
|
|
|
# second information, nor does it allow for formatting date and datetime
|
2011-04-05 08:19:17 +08:00
|
|
|
# values differently. So instead we register our own function that
|
|
|
|
# formats the datetime combined with the delta in a manner suitable
|
2010-12-22 11:34:04 +08:00
|
|
|
# for comparisons.
|
2011-04-05 08:19:17 +08:00
|
|
|
return u'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql,
|
2010-12-22 11:34:04 +08:00
|
|
|
connector, timedelta.days, timedelta.seconds, timedelta.microseconds)
|
|
|
|
|
2007-08-20 06:47:43 +08:00
|
|
|
def date_trunc_sql(self, lookup_type, field_name):
|
|
|
|
# sqlite doesn't support DATE_TRUNC, so we fake it with a user-defined
|
2010-02-24 23:29:25 +08:00
|
|
|
# function django_date_trunc that's registered in connect(). Note that
|
|
|
|
# single quotes are used because this is a string (and could otherwise
|
|
|
|
# cause a collision with a field name).
|
|
|
|
return "django_date_trunc('%s', %s)" % (lookup_type.lower(), field_name)
|
2007-08-20 06:47:43 +08:00
|
|
|
|
2007-08-20 07:07:34 +08:00
|
|
|
def drop_foreignkey_sql(self):
|
|
|
|
return ""
|
|
|
|
|
2007-08-20 07:59:06 +08:00
|
|
|
def pk_default_value(self):
|
2011-09-10 03:22:28 +08:00
|
|
|
return "NULL"
|
2007-08-20 07:59:06 +08:00
|
|
|
|
2007-08-20 09:03:33 +08:00
|
|
|
def quote_name(self, name):
|
|
|
|
if name.startswith('"') and name.endswith('"'):
|
|
|
|
return name # Quoting once is enough.
|
|
|
|
return '"%s"' % name
|
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def no_limit_value(self):
|
|
|
|
return -1
|
|
|
|
|
2007-08-20 08:15:53 +08:00
|
|
|
def sql_flush(self, style, tables, sequences):
|
|
|
|
# NB: The generated SQL below is specific to SQLite
|
|
|
|
# Note: The DELETE FROM... SQL generated below works for SQLite databases
|
|
|
|
# because constraints don't exist
|
|
|
|
sql = ['%s %s %s;' % \
|
|
|
|
(style.SQL_KEYWORD('DELETE'),
|
|
|
|
style.SQL_KEYWORD('FROM'),
|
2007-08-20 09:03:33 +08:00
|
|
|
style.SQL_FIELD(self.quote_name(table))
|
2007-08-20 08:15:53 +08:00
|
|
|
) for table in tables]
|
|
|
|
# Note: No requirement for reset of auto-incremented indices (cf. other
|
|
|
|
# sql_flush() implementations). Just return SQL at this point
|
|
|
|
return sql
|
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def value_to_db_datetime(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# SQLite doesn't support tz-aware datetimes
|
|
|
|
if is_aware(value):
|
|
|
|
if settings.USE_TZ:
|
|
|
|
value = value.astimezone(utc).replace(tzinfo=None)
|
|
|
|
else:
|
|
|
|
raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
|
|
|
|
|
|
|
|
return unicode(value)
|
|
|
|
|
|
|
|
def value_to_db_time(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# SQLite doesn't support tz-aware datetimes
|
|
|
|
if is_aware(value):
|
|
|
|
raise ValueError("SQLite backend does not support timezone-aware times.")
|
|
|
|
|
|
|
|
return unicode(value)
|
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
def year_lookup_bounds(self, value):
|
|
|
|
first = '%s-01-01'
|
|
|
|
second = '%s-12-31 23:59:59.999999'
|
|
|
|
return [first % value, second % value]
|
|
|
|
|
2009-01-15 19:06:34 +08:00
|
|
|
def convert_values(self, value, field):
|
|
|
|
"""SQLite returns floats when it should be returning decimals,
|
|
|
|
and gets dates and datetimes wrong.
|
|
|
|
For consistency with other backends, coerce when required.
|
|
|
|
"""
|
|
|
|
internal_type = field.get_internal_type()
|
|
|
|
if internal_type == 'DecimalField':
|
|
|
|
return util.typecast_decimal(field.format_number(value))
|
|
|
|
elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
|
|
|
|
return int(value)
|
|
|
|
elif internal_type == 'DateField':
|
2011-11-18 21:01:06 +08:00
|
|
|
return parse_date(value)
|
2009-01-15 19:06:34 +08:00
|
|
|
elif internal_type == 'DateTimeField':
|
2011-11-18 21:01:06 +08:00
|
|
|
return parse_datetime_with_timezone_support(value)
|
2009-01-15 19:06:34 +08:00
|
|
|
elif internal_type == 'TimeField':
|
2011-11-18 21:01:06 +08:00
|
|
|
return parse_time(value)
|
2009-01-15 19:06:34 +08:00
|
|
|
|
|
|
|
# No field, or the field isn't known to be a decimal or integer
|
|
|
|
return value
|
|
|
|
|
2011-09-10 03:22:28 +08:00
|
|
|
def bulk_insert_sql(self, fields, num_values):
|
|
|
|
res = []
|
|
|
|
res.append("SELECT %s" % ", ".join(
|
|
|
|
"%%s AS %s" % self.quote_name(f.column) for f in fields
|
|
|
|
))
|
|
|
|
res.extend(["UNION SELECT %s" % ", ".join(["%s"] * len(fields))] * (num_values - 1))
|
|
|
|
return " ".join(res)
|
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
class DatabaseWrapper(BaseDatabaseWrapper):
|
2010-10-11 20:55:17 +08:00
|
|
|
vendor = 'sqlite'
|
2007-08-20 11:26:55 +08:00
|
|
|
# SQLite requires LIKE statements to include an ESCAPE clause if the value
|
|
|
|
# being escaped has a percent or underscore in it.
|
|
|
|
# See http://www.sqlite.org/lang_expr.html for an explanation.
|
|
|
|
operators = {
|
|
|
|
'exact': '= %s',
|
|
|
|
'iexact': "LIKE %s ESCAPE '\\'",
|
|
|
|
'contains': "LIKE %s ESCAPE '\\'",
|
|
|
|
'icontains': "LIKE %s ESCAPE '\\'",
|
|
|
|
'regex': 'REGEXP %s',
|
|
|
|
'iregex': "REGEXP '(?i)' || %s",
|
|
|
|
'gt': '> %s',
|
|
|
|
'gte': '>= %s',
|
|
|
|
'lt': '< %s',
|
|
|
|
'lte': '<= %s',
|
|
|
|
'startswith': "LIKE %s ESCAPE '\\'",
|
|
|
|
'endswith': "LIKE %s ESCAPE '\\'",
|
|
|
|
'istartswith': "LIKE %s ESCAPE '\\'",
|
|
|
|
'iendswith': "LIKE %s ESCAPE '\\'",
|
|
|
|
}
|
|
|
|
|
2008-08-11 20:11:25 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(DatabaseWrapper, self).__init__(*args, **kwargs)
|
2008-11-16 16:48:24 +08:00
|
|
|
|
2010-10-11 20:55:17 +08:00
|
|
|
self.features = DatabaseFeatures(self)
|
2011-04-05 08:19:17 +08:00
|
|
|
self.ops = DatabaseOperations(self)
|
2009-03-11 11:39:34 +08:00
|
|
|
self.client = DatabaseClient(self)
|
2008-08-11 20:11:25 +08:00
|
|
|
self.creation = DatabaseCreation(self)
|
|
|
|
self.introspection = DatabaseIntrospection(self)
|
2009-12-22 23:18:51 +08:00
|
|
|
self.validation = BaseDatabaseValidation(self)
|
2008-08-11 20:11:25 +08:00
|
|
|
|
2009-03-11 11:39:34 +08:00
|
|
|
def _cursor(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
if self.connection is None:
|
2009-03-11 11:39:34 +08:00
|
|
|
settings_dict = self.settings_dict
|
2009-12-22 23:18:51 +08:00
|
|
|
if not settings_dict['NAME']:
|
2008-07-19 06:36:31 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2010-01-11 02:36:20 +08:00
|
|
|
raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.")
|
2006-11-07 13:17:38 +08:00
|
|
|
kwargs = {
|
2009-12-22 23:18:51 +08:00
|
|
|
'database': settings_dict['NAME'],
|
2006-11-07 13:17:38 +08:00
|
|
|
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
|
|
|
|
}
|
2009-12-22 23:18:51 +08:00
|
|
|
kwargs.update(settings_dict['OPTIONS'])
|
2011-12-16 21:40:19 +08:00
|
|
|
# Always allow the underlying SQLite connection to be shareable
|
|
|
|
# between multiple threads. The safe-guarding will be handled at a
|
|
|
|
# higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
|
|
|
|
# property. This is necessary as the shareability is disabled by
|
|
|
|
# default in pysqlite and it cannot be changed once a connection is
|
|
|
|
# opened.
|
|
|
|
if 'check_same_thread' in kwargs and kwargs['check_same_thread']:
|
|
|
|
warnings.warn(
|
|
|
|
'The `check_same_thread` option was provided and set to '
|
|
|
|
'True. It will be overriden with False. Use the '
|
|
|
|
'`DatabaseWrapper.allow_thread_sharing` property instead '
|
|
|
|
'for controlling thread shareability.',
|
|
|
|
RuntimeWarning
|
|
|
|
)
|
|
|
|
kwargs.update({'check_same_thread': False})
|
2006-11-07 13:17:38 +08:00
|
|
|
self.connection = Database.connect(**kwargs)
|
2007-06-28 02:58:10 +08:00
|
|
|
# Register extract, date_trunc, and regexp functions.
|
2006-05-02 09:31:56 +08:00
|
|
|
self.connection.create_function("django_extract", 2, _sqlite_extract)
|
|
|
|
self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc)
|
2007-06-28 02:58:10 +08:00
|
|
|
self.connection.create_function("regexp", 2, _sqlite_regexp)
|
2010-12-22 11:34:04 +08:00
|
|
|
self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta)
|
2010-08-30 21:21:18 +08:00
|
|
|
connection_created.send(sender=self.__class__, connection=self)
|
2007-08-20 05:30:57 +08:00
|
|
|
return self.connection.cursor(factory=SQLiteCursorWrapper)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2011-08-07 08:43:26 +08:00
|
|
|
def check_constraints(self, table_names=None):
|
|
|
|
"""
|
2011-08-09 01:08:35 +08:00
|
|
|
Checks each table name in `table_names` for rows with invalid foreign key references. This method is
|
2011-08-07 08:43:26 +08:00
|
|
|
intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
|
|
|
|
determine if rows with invalid references were entered while constraint checks were off.
|
|
|
|
|
|
|
|
Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
|
|
|
|
detailed information about the invalid reference in the error message.
|
|
|
|
|
|
|
|
Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
|
|
|
|
ALL IMMEDIATE")
|
|
|
|
"""
|
|
|
|
cursor = self.cursor()
|
|
|
|
if table_names is None:
|
|
|
|
table_names = self.introspection.get_table_list(cursor)
|
|
|
|
for table_name in table_names:
|
|
|
|
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
|
|
|
|
if not primary_key_column_name:
|
|
|
|
continue
|
|
|
|
key_columns = self.introspection.get_key_columns(cursor, table_name)
|
|
|
|
for column_name, referenced_table_name, referenced_column_name in key_columns:
|
|
|
|
cursor.execute("""
|
|
|
|
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
|
|
|
|
LEFT JOIN `%s` as REFERRED
|
|
|
|
ON (REFERRING.`%s` = REFERRED.`%s`)
|
|
|
|
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
|
|
|
|
% (primary_key_column_name, column_name, table_name, referenced_table_name,
|
|
|
|
column_name, referenced_column_name, column_name, referenced_column_name))
|
|
|
|
for bad_row in cursor.fetchall():
|
|
|
|
raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
|
|
|
|
"foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
|
|
|
|
% (table_name, bad_row[0], table_name, column_name, bad_row[1],
|
|
|
|
referenced_table_name, referenced_column_name))
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def close(self):
|
2011-12-17 01:02:41 +08:00
|
|
|
self.validate_thread_sharing()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
# If database is in memory, closing the connection destroys the
|
2007-08-20 05:30:57 +08:00
|
|
|
# database. To prevent accidental data loss, ignore close requests on
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
# an in-memory db.
|
2009-12-22 23:18:51 +08:00
|
|
|
if self.settings_dict['NAME'] != ":memory:":
|
2007-08-20 05:30:57 +08:00
|
|
|
BaseDatabaseWrapper.close(self)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2011-05-10 20:20:47 +08:00
|
|
|
FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
|
2010-03-23 21:51:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class SQLiteCursorWrapper(Database.Cursor):
|
|
|
|
"""
|
|
|
|
Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
|
|
|
|
This fixes it -- but note that if you want to use a literal "%s" in a query,
|
|
|
|
you'll need to use "%%s".
|
|
|
|
"""
|
|
|
|
def execute(self, query, params=()):
|
2010-03-23 21:51:11 +08:00
|
|
|
query = self.convert_query(query)
|
2010-01-29 23:45:55 +08:00
|
|
|
try:
|
|
|
|
return Database.Cursor.execute(self, query, params)
|
|
|
|
except Database.IntegrityError, e:
|
|
|
|
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
|
|
|
|
except Database.DatabaseError, e:
|
|
|
|
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def executemany(self, query, param_list):
|
2010-03-23 21:51:11 +08:00
|
|
|
query = self.convert_query(query)
|
2007-09-15 05:32:25 +08:00
|
|
|
try:
|
2010-01-29 23:45:55 +08:00
|
|
|
return Database.Cursor.executemany(self, query, param_list)
|
|
|
|
except Database.IntegrityError, e:
|
|
|
|
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
|
|
|
|
except Database.DatabaseError, e:
|
|
|
|
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2010-03-23 21:51:11 +08:00
|
|
|
def convert_query(self, query):
|
|
|
|
return FORMAT_QMARK_REGEX.sub('?', query).replace('%%','%')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def _sqlite_extract(lookup_type, dt):
|
2008-11-16 16:48:24 +08:00
|
|
|
if dt is None:
|
|
|
|
return None
|
2006-05-02 09:31:56 +08:00
|
|
|
try:
|
|
|
|
dt = util.typecast_timestamp(dt)
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
return None
|
2009-02-08 13:08:06 +08:00
|
|
|
if lookup_type == 'week_day':
|
2009-04-12 10:00:58 +08:00
|
|
|
return (dt.isoweekday() % 7) + 1
|
2009-02-08 13:08:06 +08:00
|
|
|
else:
|
2009-04-12 10:00:58 +08:00
|
|
|
return getattr(dt, lookup_type)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def _sqlite_date_trunc(lookup_type, dt):
|
|
|
|
try:
|
|
|
|
dt = util.typecast_timestamp(dt)
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
return None
|
|
|
|
if lookup_type == 'year':
|
|
|
|
return "%i-01-01 00:00:00" % dt.year
|
|
|
|
elif lookup_type == 'month':
|
|
|
|
return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
|
|
|
|
elif lookup_type == 'day':
|
|
|
|
return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
|
|
|
|
|
2010-12-22 11:34:04 +08:00
|
|
|
def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
|
|
|
|
try:
|
|
|
|
dt = util.typecast_timestamp(dt)
|
|
|
|
delta = datetime.timedelta(int(days), int(secs), int(usecs))
|
|
|
|
if conn.strip() == '+':
|
|
|
|
dt = dt + delta
|
|
|
|
else:
|
|
|
|
dt = dt - delta
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
return None
|
2011-10-14 03:23:45 +08:00
|
|
|
# typecast_timestamp returns a date or a datetime without timezone.
|
|
|
|
# It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
|
|
|
|
return str(dt)
|
2010-12-22 11:34:04 +08:00
|
|
|
|
2007-06-28 02:58:10 +08:00
|
|
|
def _sqlite_regexp(re_pattern, re_string):
|
|
|
|
try:
|
|
|
|
return bool(re.search(re_pattern, re_string))
|
|
|
|
except:
|
|
|
|
return False
|