/bangkokhotel/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py

https://bitbucket.org/luisrodriguez/bangkokhotel · Python · 404 lines · 291 code · 42 blank · 71 comment · 60 complexity · bc5be2daac837af62d6e63d0df2f7547 MD5 · raw file

  1. """
  2. SQLite3 backend for django.
  3. Works with either the pysqlite2 module or the sqlite3 module in the
  4. standard library.
  5. """
  6. import datetime
  7. import decimal
  8. import warnings
  9. import re
  10. import sys
  11. from django.db import utils
  12. from django.db.backends import *
  13. from django.db.backends.signals import connection_created
  14. from django.db.backends.sqlite3.client import DatabaseClient
  15. from django.db.backends.sqlite3.creation import DatabaseCreation
  16. from django.db.backends.sqlite3.introspection import DatabaseIntrospection
  17. from django.utils.dateparse import parse_date, parse_datetime, parse_time
  18. from django.utils.safestring import SafeString
  19. from django.utils import timezone
  20. try:
  21. try:
  22. from pysqlite2 import dbapi2 as Database
  23. except ImportError, e1:
  24. from sqlite3 import dbapi2 as Database
  25. except ImportError, exc:
  26. from django.core.exceptions import ImproperlyConfigured
  27. raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
  28. DatabaseError = Database.DatabaseError
  29. IntegrityError = Database.IntegrityError
  30. def parse_datetime_with_timezone_support(value):
  31. dt = parse_datetime(value)
  32. # Confirm that dt is naive before overwriting its tzinfo.
  33. if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
  34. dt = dt.replace(tzinfo=timezone.utc)
  35. return dt
  36. def adapt_datetime_with_timezone_support(value):
  37. # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
  38. if settings.USE_TZ:
  39. if timezone.is_naive(value):
  40. warnings.warn(u"SQLite received a naive datetime (%s)"
  41. u" while time zone support is active." % value,
  42. RuntimeWarning)
  43. default_timezone = timezone.get_default_timezone()
  44. value = timezone.make_aware(value, default_timezone)
  45. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  46. return value.isoformat(" ")
  47. Database.register_converter("bool", lambda s: str(s) == '1')
  48. Database.register_converter("time", parse_time)
  49. Database.register_converter("date", parse_date)
  50. Database.register_converter("datetime", parse_datetime_with_timezone_support)
  51. Database.register_converter("timestamp", parse_datetime_with_timezone_support)
  52. Database.register_converter("TIMESTAMP", parse_datetime_with_timezone_support)
  53. Database.register_converter("decimal", util.typecast_decimal)
  54. Database.register_adapter(datetime.datetime, adapt_datetime_with_timezone_support)
  55. Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal)
  56. if Database.version_info >= (2, 4, 1):
  57. # Starting in 2.4.1, the str type is not accepted anymore, therefore,
  58. # we convert all str objects to Unicode
  59. # As registering a adapter for a primitive type causes a small
  60. # slow-down, this adapter is only registered for sqlite3 versions
  61. # needing it (Python 2.6 and up).
  62. Database.register_adapter(str, lambda s: s.decode('utf-8'))
  63. Database.register_adapter(SafeString, lambda s: s.decode('utf-8'))
  64. class DatabaseFeatures(BaseDatabaseFeatures):
  65. # SQLite cannot handle us only partially reading from a cursor's result set
  66. # and then writing the same rows to the database in another cursor. This
  67. # setting ensures we always read result sets fully into memory all in one
  68. # go.
  69. can_use_chunked_reads = False
  70. test_db_allows_multiple_connections = False
  71. supports_unspecified_pk = True
  72. supports_timezones = False
  73. supports_1000_query_parameters = False
  74. supports_mixed_date_datetime_comparisons = False
  75. has_bulk_insert = True
  76. can_combine_inserts_with_and_without_auto_increment_pk = False
  77. def _supports_stddev(self):
  78. """Confirm support for STDDEV and related stats functions
  79. SQLite supports STDDEV as an extension package; so
  80. connection.ops.check_aggregate_support() can't unilaterally
  81. rule out support for STDDEV. We need to manually check
  82. whether the call works.
  83. """
  84. cursor = self.connection.cursor()
  85. cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
  86. try:
  87. cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
  88. has_support = True
  89. except utils.DatabaseError:
  90. has_support = False
  91. cursor.execute('DROP TABLE STDDEV_TEST')
  92. return has_support
  93. class DatabaseOperations(BaseDatabaseOperations):
  94. def bulk_batch_size(self, fields, objs):
  95. """
  96. SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
  97. 999 variables per query.
  98. """
  99. return (999 // len(fields)) if len(fields) > 0 else len(objs)
  100. def date_extract_sql(self, lookup_type, field_name):
  101. # sqlite doesn't support extract, so we fake it with the user-defined
  102. # function django_extract that's registered in connect(). Note that
  103. # single quotes are used because this is a string (and could otherwise
  104. # cause a collision with a field name).
  105. return "django_extract('%s', %s)" % (lookup_type.lower(), field_name)
  106. def date_interval_sql(self, sql, connector, timedelta):
  107. # It would be more straightforward if we could use the sqlite strftime
  108. # function, but it does not allow for keeping six digits of fractional
  109. # second information, nor does it allow for formatting date and datetime
  110. # values differently. So instead we register our own function that
  111. # formats the datetime combined with the delta in a manner suitable
  112. # for comparisons.
  113. return u'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql,
  114. connector, timedelta.days, timedelta.seconds, timedelta.microseconds)
  115. def date_trunc_sql(self, lookup_type, field_name):
  116. # sqlite doesn't support DATE_TRUNC, so we fake it with a user-defined
  117. # function django_date_trunc that's registered in connect(). Note that
  118. # single quotes are used because this is a string (and could otherwise
  119. # cause a collision with a field name).
  120. return "django_date_trunc('%s', %s)" % (lookup_type.lower(), field_name)
  121. def drop_foreignkey_sql(self):
  122. return ""
  123. def pk_default_value(self):
  124. return "NULL"
  125. def quote_name(self, name):
  126. if name.startswith('"') and name.endswith('"'):
  127. return name # Quoting once is enough.
  128. return '"%s"' % name
  129. def no_limit_value(self):
  130. return -1
  131. def sql_flush(self, style, tables, sequences):
  132. # NB: The generated SQL below is specific to SQLite
  133. # Note: The DELETE FROM... SQL generated below works for SQLite databases
  134. # because constraints don't exist
  135. sql = ['%s %s %s;' % \
  136. (style.SQL_KEYWORD('DELETE'),
  137. style.SQL_KEYWORD('FROM'),
  138. style.SQL_FIELD(self.quote_name(table))
  139. ) for table in tables]
  140. # Note: No requirement for reset of auto-incremented indices (cf. other
  141. # sql_flush() implementations). Just return SQL at this point
  142. return sql
  143. def value_to_db_datetime(self, value):
  144. if value is None:
  145. return None
  146. # SQLite doesn't support tz-aware datetimes
  147. if timezone.is_aware(value):
  148. if settings.USE_TZ:
  149. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  150. else:
  151. raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
  152. return unicode(value)
  153. def value_to_db_time(self, value):
  154. if value is None:
  155. return None
  156. # SQLite doesn't support tz-aware datetimes
  157. if timezone.is_aware(value):
  158. raise ValueError("SQLite backend does not support timezone-aware times.")
  159. return unicode(value)
  160. def year_lookup_bounds(self, value):
  161. first = '%s-01-01'
  162. second = '%s-12-31 23:59:59.999999'
  163. return [first % value, second % value]
  164. def convert_values(self, value, field):
  165. """SQLite returns floats when it should be returning decimals,
  166. and gets dates and datetimes wrong.
  167. For consistency with other backends, coerce when required.
  168. """
  169. internal_type = field.get_internal_type()
  170. if internal_type == 'DecimalField':
  171. return util.typecast_decimal(field.format_number(value))
  172. elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
  173. return int(value)
  174. elif internal_type == 'DateField':
  175. return parse_date(value)
  176. elif internal_type == 'DateTimeField':
  177. return parse_datetime_with_timezone_support(value)
  178. elif internal_type == 'TimeField':
  179. return parse_time(value)
  180. # No field, or the field isn't known to be a decimal or integer
  181. return value
  182. def bulk_insert_sql(self, fields, num_values):
  183. res = []
  184. res.append("SELECT %s" % ", ".join(
  185. "%%s AS %s" % self.quote_name(f.column) for f in fields
  186. ))
  187. res.extend(["UNION SELECT %s" % ", ".join(["%s"] * len(fields))] * (num_values - 1))
  188. return " ".join(res)
  189. class DatabaseWrapper(BaseDatabaseWrapper):
  190. vendor = 'sqlite'
  191. # SQLite requires LIKE statements to include an ESCAPE clause if the value
  192. # being escaped has a percent or underscore in it.
  193. # See http://www.sqlite.org/lang_expr.html for an explanation.
  194. operators = {
  195. 'exact': '= %s',
  196. 'iexact': "LIKE %s ESCAPE '\\'",
  197. 'contains': "LIKE %s ESCAPE '\\'",
  198. 'icontains': "LIKE %s ESCAPE '\\'",
  199. 'regex': 'REGEXP %s',
  200. 'iregex': "REGEXP '(?i)' || %s",
  201. 'gt': '> %s',
  202. 'gte': '>= %s',
  203. 'lt': '< %s',
  204. 'lte': '<= %s',
  205. 'startswith': "LIKE %s ESCAPE '\\'",
  206. 'endswith': "LIKE %s ESCAPE '\\'",
  207. 'istartswith': "LIKE %s ESCAPE '\\'",
  208. 'iendswith': "LIKE %s ESCAPE '\\'",
  209. }
  210. def __init__(self, *args, **kwargs):
  211. super(DatabaseWrapper, self).__init__(*args, **kwargs)
  212. self.features = DatabaseFeatures(self)
  213. self.ops = DatabaseOperations(self)
  214. self.client = DatabaseClient(self)
  215. self.creation = DatabaseCreation(self)
  216. self.introspection = DatabaseIntrospection(self)
  217. self.validation = BaseDatabaseValidation(self)
  218. def _sqlite_create_connection(self):
  219. settings_dict = self.settings_dict
  220. if not settings_dict['NAME']:
  221. from django.core.exceptions import ImproperlyConfigured
  222. raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.")
  223. kwargs = {
  224. 'database': settings_dict['NAME'],
  225. 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
  226. }
  227. kwargs.update(settings_dict['OPTIONS'])
  228. # Always allow the underlying SQLite connection to be shareable
  229. # between multiple threads. The safe-guarding will be handled at a
  230. # higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
  231. # property. This is necessary as the shareability is disabled by
  232. # default in pysqlite and it cannot be changed once a connection is
  233. # opened.
  234. if 'check_same_thread' in kwargs and kwargs['check_same_thread']:
  235. warnings.warn(
  236. 'The `check_same_thread` option was provided and set to '
  237. 'True. It will be overriden with False. Use the '
  238. '`DatabaseWrapper.allow_thread_sharing` property instead '
  239. 'for controlling thread shareability.',
  240. RuntimeWarning
  241. )
  242. kwargs.update({'check_same_thread': False})
  243. self.connection = Database.connect(**kwargs)
  244. # Register extract, date_trunc, and regexp functions.
  245. self.connection.create_function("django_extract", 2, _sqlite_extract)
  246. self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc)
  247. self.connection.create_function("regexp", 2, _sqlite_regexp)
  248. self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta)
  249. connection_created.send(sender=self.__class__, connection=self)
  250. def _cursor(self):
  251. if self.connection is None:
  252. self._sqlite_create_connection()
  253. return self.connection.cursor(factory=SQLiteCursorWrapper)
  254. def check_constraints(self, table_names=None):
  255. """
  256. Checks each table name in `table_names` for rows with invalid foreign key references. This method is
  257. intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
  258. determine if rows with invalid references were entered while constraint checks were off.
  259. Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
  260. detailed information about the invalid reference in the error message.
  261. Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
  262. ALL IMMEDIATE")
  263. """
  264. cursor = self.cursor()
  265. if table_names is None:
  266. table_names = self.introspection.get_table_list(cursor)
  267. for table_name in table_names:
  268. primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
  269. if not primary_key_column_name:
  270. continue
  271. key_columns = self.introspection.get_key_columns(cursor, table_name)
  272. for column_name, referenced_table_name, referenced_column_name in key_columns:
  273. cursor.execute("""
  274. SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
  275. LEFT JOIN `%s` as REFERRED
  276. ON (REFERRING.`%s` = REFERRED.`%s`)
  277. WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
  278. % (primary_key_column_name, column_name, table_name, referenced_table_name,
  279. column_name, referenced_column_name, column_name, referenced_column_name))
  280. for bad_row in cursor.fetchall():
  281. raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
  282. "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
  283. % (table_name, bad_row[0], table_name, column_name, bad_row[1],
  284. referenced_table_name, referenced_column_name))
  285. def close(self):
  286. self.validate_thread_sharing()
  287. # If database is in memory, closing the connection destroys the
  288. # database. To prevent accidental data loss, ignore close requests on
  289. # an in-memory db.
  290. if self.settings_dict['NAME'] != ":memory:":
  291. BaseDatabaseWrapper.close(self)
  292. FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
  293. class SQLiteCursorWrapper(Database.Cursor):
  294. """
  295. Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
  296. This fixes it -- but note that if you want to use a literal "%s" in a query,
  297. you'll need to use "%%s".
  298. """
  299. def execute(self, query, params=()):
  300. query = self.convert_query(query)
  301. try:
  302. return Database.Cursor.execute(self, query, params)
  303. except Database.IntegrityError, e:
  304. raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
  305. except Database.DatabaseError, e:
  306. raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
  307. def executemany(self, query, param_list):
  308. query = self.convert_query(query)
  309. try:
  310. return Database.Cursor.executemany(self, query, param_list)
  311. except Database.IntegrityError, e:
  312. raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
  313. except Database.DatabaseError, e:
  314. raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
  315. def convert_query(self, query):
  316. return FORMAT_QMARK_REGEX.sub('?', query).replace('%%','%')
  317. def _sqlite_extract(lookup_type, dt):
  318. if dt is None:
  319. return None
  320. try:
  321. dt = util.typecast_timestamp(dt)
  322. except (ValueError, TypeError):
  323. return None
  324. if lookup_type == 'week_day':
  325. return (dt.isoweekday() % 7) + 1
  326. else:
  327. return getattr(dt, lookup_type)
  328. def _sqlite_date_trunc(lookup_type, dt):
  329. try:
  330. dt = util.typecast_timestamp(dt)
  331. except (ValueError, TypeError):
  332. return None
  333. if lookup_type == 'year':
  334. return "%i-01-01 00:00:00" % dt.year
  335. elif lookup_type == 'month':
  336. return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
  337. elif lookup_type == 'day':
  338. return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
  339. def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
  340. try:
  341. dt = util.typecast_timestamp(dt)
  342. delta = datetime.timedelta(int(days), int(secs), int(usecs))
  343. if conn.strip() == '+':
  344. dt = dt + delta
  345. else:
  346. dt = dt - delta
  347. except (ValueError, TypeError):
  348. return None
  349. # typecast_timestamp returns a date or a datetime without timezone.
  350. # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
  351. return str(dt)
  352. def _sqlite_regexp(re_pattern, re_string):
  353. try:
  354. return bool(re.search(re_pattern, re_string))
  355. except:
  356. return False