tests.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. from __future__ import unicode_literals
  2. from datetime import date
  3. import unittest
  4. from django.core.exceptions import FieldError
  5. from django.db import models
  6. from django.db import connection
  7. from django.test import TestCase
  8. from .models import Author
  9. class Div3Lookup(models.Lookup):
  10. lookup_name = 'div3'
  11. def as_sql(self, qn, connection):
  12. lhs, params = self.process_lhs(qn, connection)
  13. rhs, rhs_params = self.process_rhs(qn, connection)
  14. params.extend(rhs_params)
  15. return '(%s) %%%% 3 = %s' % (lhs, rhs), params
  16. def as_oracle(self, qn, connection):
  17. lhs, params = self.process_lhs(qn, connection)
  18. rhs, rhs_params = self.process_rhs(qn, connection)
  19. params.extend(rhs_params)
  20. return 'mod(%s, 3) = %s' % (lhs, rhs), params
  21. class Div3Transform(models.Transform):
  22. lookup_name = 'div3'
  23. def as_sql(self, qn, connection):
  24. lhs, lhs_params = qn.compile(self.lhs)
  25. return '(%s) %%%% 3' % lhs, lhs_params
  26. def as_oracle(self, qn, connection):
  27. lhs, lhs_params = qn.compile(self.lhs)
  28. return 'mod(%s, 3)' % lhs, lhs_params
  29. class Div3BilateralTransform(Div3Transform):
  30. bilateral = True
  31. class Mult3BilateralTransform(models.Transform):
  32. bilateral = True
  33. lookup_name = 'mult3'
  34. def as_sql(self, qn, connection):
  35. lhs, lhs_params = qn.compile(self.lhs)
  36. return '3 * (%s)' % lhs, lhs_params
  37. class UpperBilateralTransform(models.Transform):
  38. bilateral = True
  39. lookup_name = 'upper'
  40. def as_sql(self, qn, connection):
  41. lhs, lhs_params = qn.compile(self.lhs)
  42. return 'UPPER(%s)' % lhs, lhs_params
  43. class YearTransform(models.Transform):
  44. lookup_name = 'year'
  45. def as_sql(self, qn, connection):
  46. lhs_sql, params = qn.compile(self.lhs)
  47. return connection.ops.date_extract_sql('year', lhs_sql), params
  48. @property
  49. def output_field(self):
  50. return models.IntegerField()
  51. @YearTransform.register_lookup
  52. class YearExact(models.lookups.Lookup):
  53. lookup_name = 'exact'
  54. def as_sql(self, qn, connection):
  55. # We will need to skip the extract part, and instead go
  56. # directly with the originating field, that is self.lhs.lhs
  57. lhs_sql, lhs_params = self.process_lhs(qn, connection, self.lhs.lhs)
  58. rhs_sql, rhs_params = self.process_rhs(qn, connection)
  59. # Note that we must be careful so that we have params in the
  60. # same order as we have the parts in the SQL.
  61. params = lhs_params + rhs_params + lhs_params + rhs_params
  62. # We use PostgreSQL specific SQL here. Note that we must do the
  63. # conversions in SQL instead of in Python to support F() references.
  64. return ("%(lhs)s >= (%(rhs)s || '-01-01')::date "
  65. "AND %(lhs)s <= (%(rhs)s || '-12-31')::date" %
  66. {'lhs': lhs_sql, 'rhs': rhs_sql}, params)
  67. @YearTransform.register_lookup
  68. class YearLte(models.lookups.LessThanOrEqual):
  69. """
  70. The purpose of this lookup is to efficiently compare the year of the field.
  71. """
  72. def as_sql(self, qn, connection):
  73. # Skip the YearTransform above us (no possibility for efficient
  74. # lookup otherwise).
  75. real_lhs = self.lhs.lhs
  76. lhs_sql, params = self.process_lhs(qn, connection, real_lhs)
  77. rhs_sql, rhs_params = self.process_rhs(qn, connection)
  78. params.extend(rhs_params)
  79. # Build SQL where the integer year is concatenated with last month
  80. # and day, then convert that to date. (We try to have SQL like:
  81. # WHERE somecol <= '2013-12-31')
  82. # but also make it work if the rhs_sql is field reference.
  83. return "%s <= (%s || '-12-31')::date" % (lhs_sql, rhs_sql), params
  84. class SQLFunc(models.Lookup):
  85. def __init__(self, name, *args, **kwargs):
  86. super(SQLFunc, self).__init__(*args, **kwargs)
  87. self.name = name
  88. def as_sql(self, qn, connection):
  89. return '%s()', [self.name]
  90. @property
  91. def output_field(self):
  92. return CustomField()
  93. class SQLFuncFactory(object):
  94. def __init__(self, name):
  95. self.name = name
  96. def __call__(self, *args, **kwargs):
  97. return SQLFunc(self.name, *args, **kwargs)
  98. class CustomField(models.TextField):
  99. def get_lookup(self, lookup_name):
  100. if lookup_name.startswith('lookupfunc_'):
  101. key, name = lookup_name.split('_', 1)
  102. return SQLFuncFactory(name)
  103. return super(CustomField, self).get_lookup(lookup_name)
  104. def get_transform(self, lookup_name):
  105. if lookup_name.startswith('transformfunc_'):
  106. key, name = lookup_name.split('_', 1)
  107. return SQLFuncFactory(name)
  108. return super(CustomField, self).get_transform(lookup_name)
  109. class CustomModel(models.Model):
  110. field = CustomField()
  111. # We will register this class temporarily in the test method.
  112. class InMonth(models.lookups.Lookup):
  113. """
  114. InMonth matches if the column's month is the same as value's month.
  115. """
  116. lookup_name = 'inmonth'
  117. def as_sql(self, qn, connection):
  118. lhs, lhs_params = self.process_lhs(qn, connection)
  119. rhs, rhs_params = self.process_rhs(qn, connection)
  120. # We need to be careful so that we get the params in right
  121. # places.
  122. params = lhs_params + rhs_params + lhs_params + rhs_params
  123. return ("%s >= date_trunc('month', %s) and "
  124. "%s < date_trunc('month', %s) + interval '1 months'" %
  125. (lhs, rhs, lhs, rhs), params)
  126. class LookupTests(TestCase):
  127. def test_basic_lookup(self):
  128. a1 = Author.objects.create(name='a1', age=1)
  129. a2 = Author.objects.create(name='a2', age=2)
  130. a3 = Author.objects.create(name='a3', age=3)
  131. a4 = Author.objects.create(name='a4', age=4)
  132. models.IntegerField.register_lookup(Div3Lookup)
  133. try:
  134. self.assertQuerysetEqual(
  135. Author.objects.filter(age__div3=0),
  136. [a3], lambda x: x
  137. )
  138. self.assertQuerysetEqual(
  139. Author.objects.filter(age__div3=1).order_by('age'),
  140. [a1, a4], lambda x: x
  141. )
  142. self.assertQuerysetEqual(
  143. Author.objects.filter(age__div3=2),
  144. [a2], lambda x: x
  145. )
  146. self.assertQuerysetEqual(
  147. Author.objects.filter(age__div3=3),
  148. [], lambda x: x
  149. )
  150. finally:
  151. models.IntegerField._unregister_lookup(Div3Lookup)
  152. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific SQL used")
  153. def test_birthdate_month(self):
  154. a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16))
  155. a2 = Author.objects.create(name='a2', birthdate=date(2012, 2, 29))
  156. a3 = Author.objects.create(name='a3', birthdate=date(2012, 1, 31))
  157. a4 = Author.objects.create(name='a4', birthdate=date(2012, 3, 1))
  158. models.DateField.register_lookup(InMonth)
  159. try:
  160. self.assertQuerysetEqual(
  161. Author.objects.filter(birthdate__inmonth=date(2012, 1, 15)),
  162. [a3], lambda x: x
  163. )
  164. self.assertQuerysetEqual(
  165. Author.objects.filter(birthdate__inmonth=date(2012, 2, 1)),
  166. [a2], lambda x: x
  167. )
  168. self.assertQuerysetEqual(
  169. Author.objects.filter(birthdate__inmonth=date(1981, 2, 28)),
  170. [a1], lambda x: x
  171. )
  172. self.assertQuerysetEqual(
  173. Author.objects.filter(birthdate__inmonth=date(2012, 3, 12)),
  174. [a4], lambda x: x
  175. )
  176. self.assertQuerysetEqual(
  177. Author.objects.filter(birthdate__inmonth=date(2012, 4, 1)),
  178. [], lambda x: x
  179. )
  180. finally:
  181. models.DateField._unregister_lookup(InMonth)
  182. def test_div3_extract(self):
  183. models.IntegerField.register_lookup(Div3Transform)
  184. try:
  185. a1 = Author.objects.create(name='a1', age=1)
  186. a2 = Author.objects.create(name='a2', age=2)
  187. a3 = Author.objects.create(name='a3', age=3)
  188. a4 = Author.objects.create(name='a4', age=4)
  189. baseqs = Author.objects.order_by('name')
  190. self.assertQuerysetEqual(
  191. baseqs.filter(age__div3=2),
  192. [a2], lambda x: x)
  193. self.assertQuerysetEqual(
  194. baseqs.filter(age__div3__lte=3),
  195. [a1, a2, a3, a4], lambda x: x)
  196. self.assertQuerysetEqual(
  197. baseqs.filter(age__div3__in=[0, 2]),
  198. [a2, a3], lambda x: x)
  199. self.assertQuerysetEqual(
  200. baseqs.filter(age__div3__in=[2, 4]),
  201. [a2], lambda x: x)
  202. self.assertQuerysetEqual(
  203. baseqs.filter(age__div3__gte=3),
  204. [], lambda x: x)
  205. self.assertQuerysetEqual(
  206. baseqs.filter(age__div3__range=(1, 2)),
  207. [a1, a2, a4], lambda x: x)
  208. finally:
  209. models.IntegerField._unregister_lookup(Div3Transform)
  210. class BilateralTransformTests(TestCase):
  211. def test_bilateral_upper(self):
  212. models.CharField.register_lookup(UpperBilateralTransform)
  213. try:
  214. Author.objects.bulk_create([
  215. Author(name='Doe'),
  216. Author(name='doe'),
  217. Author(name='Foo'),
  218. ])
  219. self.assertQuerysetEqual(
  220. Author.objects.filter(name__upper='doe'),
  221. ["<Author: Doe>", "<Author: doe>"], ordered=False)
  222. finally:
  223. models.CharField._unregister_lookup(UpperBilateralTransform)
  224. def test_bilateral_inner_qs(self):
  225. models.CharField.register_lookup(UpperBilateralTransform)
  226. try:
  227. with self.assertRaises(NotImplementedError):
  228. Author.objects.filter(name__upper__in=Author.objects.values_list('name'))
  229. finally:
  230. models.CharField._unregister_lookup(UpperBilateralTransform)
  231. def test_div3_bilateral_extract(self):
  232. models.IntegerField.register_lookup(Div3BilateralTransform)
  233. try:
  234. a1 = Author.objects.create(name='a1', age=1)
  235. a2 = Author.objects.create(name='a2', age=2)
  236. a3 = Author.objects.create(name='a3', age=3)
  237. a4 = Author.objects.create(name='a4', age=4)
  238. baseqs = Author.objects.order_by('name')
  239. self.assertQuerysetEqual(
  240. baseqs.filter(age__div3=2),
  241. [a2], lambda x: x)
  242. self.assertQuerysetEqual(
  243. baseqs.filter(age__div3__lte=3),
  244. [a3], lambda x: x)
  245. self.assertQuerysetEqual(
  246. baseqs.filter(age__div3__in=[0, 2]),
  247. [a2, a3], lambda x: x)
  248. self.assertQuerysetEqual(
  249. baseqs.filter(age__div3__in=[2, 4]),
  250. [a1, a2, a4], lambda x: x)
  251. self.assertQuerysetEqual(
  252. baseqs.filter(age__div3__gte=3),
  253. [a1, a2, a3, a4], lambda x: x)
  254. self.assertQuerysetEqual(
  255. baseqs.filter(age__div3__range=(1, 2)),
  256. [a1, a2, a4], lambda x: x)
  257. finally:
  258. models.IntegerField._unregister_lookup(Div3BilateralTransform)
  259. def test_bilateral_order(self):
  260. models.IntegerField.register_lookup(Mult3BilateralTransform)
  261. models.IntegerField.register_lookup(Div3BilateralTransform)
  262. try:
  263. a1 = Author.objects.create(name='a1', age=1)
  264. a2 = Author.objects.create(name='a2', age=2)
  265. a3 = Author.objects.create(name='a3', age=3)
  266. a4 = Author.objects.create(name='a4', age=4)
  267. baseqs = Author.objects.order_by('name')
  268. self.assertQuerysetEqual(
  269. baseqs.filter(age__mult3__div3=42),
  270. # mult3__div3 always leads to 0
  271. [a1, a2, a3, a4], lambda x: x)
  272. self.assertQuerysetEqual(
  273. baseqs.filter(age__div3__mult3=42),
  274. [a3], lambda x: x)
  275. finally:
  276. models.IntegerField._unregister_lookup(Mult3BilateralTransform)
  277. models.IntegerField._unregister_lookup(Div3BilateralTransform)
  278. def test_bilateral_fexpr(self):
  279. models.IntegerField.register_lookup(Mult3BilateralTransform)
  280. try:
  281. a1 = Author.objects.create(name='a1', age=1, average_rating=3.2)
  282. a2 = Author.objects.create(name='a2', age=2, average_rating=0.5)
  283. a3 = Author.objects.create(name='a3', age=3, average_rating=1.5)
  284. a4 = Author.objects.create(name='a4', age=4)
  285. baseqs = Author.objects.order_by('name')
  286. self.assertQuerysetEqual(
  287. baseqs.filter(age__mult3=models.F('age')),
  288. [a1, a2, a3, a4], lambda x: x)
  289. self.assertQuerysetEqual(
  290. # Same as age >= average_rating
  291. baseqs.filter(age__mult3__gte=models.F('average_rating')),
  292. [a2, a3], lambda x: x)
  293. finally:
  294. models.IntegerField._unregister_lookup(Mult3BilateralTransform)
  295. class YearLteTests(TestCase):
  296. def setUp(self):
  297. models.DateField.register_lookup(YearTransform)
  298. self.a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16))
  299. self.a2 = Author.objects.create(name='a2', birthdate=date(2012, 2, 29))
  300. self.a3 = Author.objects.create(name='a3', birthdate=date(2012, 1, 31))
  301. self.a4 = Author.objects.create(name='a4', birthdate=date(2012, 3, 1))
  302. def tearDown(self):
  303. models.DateField._unregister_lookup(YearTransform)
  304. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific SQL used")
  305. def test_year_lte(self):
  306. baseqs = Author.objects.order_by('name')
  307. self.assertQuerysetEqual(
  308. baseqs.filter(birthdate__year__lte=2012),
  309. [self.a1, self.a2, self.a3, self.a4], lambda x: x)
  310. self.assertQuerysetEqual(
  311. baseqs.filter(birthdate__year=2012),
  312. [self.a2, self.a3, self.a4], lambda x: x)
  313. self.assertNotIn('BETWEEN', str(baseqs.filter(birthdate__year=2012).query))
  314. self.assertQuerysetEqual(
  315. baseqs.filter(birthdate__year__lte=2011),
  316. [self.a1], lambda x: x)
  317. # The non-optimized version works, too.
  318. self.assertQuerysetEqual(
  319. baseqs.filter(birthdate__year__lt=2012),
  320. [self.a1], lambda x: x)
  321. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific SQL used")
  322. def test_year_lte_fexpr(self):
  323. self.a2.age = 2011
  324. self.a2.save()
  325. self.a3.age = 2012
  326. self.a3.save()
  327. self.a4.age = 2013
  328. self.a4.save()
  329. baseqs = Author.objects.order_by('name')
  330. self.assertQuerysetEqual(
  331. baseqs.filter(birthdate__year__lte=models.F('age')),
  332. [self.a3, self.a4], lambda x: x)
  333. self.assertQuerysetEqual(
  334. baseqs.filter(birthdate__year__lt=models.F('age')),
  335. [self.a4], lambda x: x)
  336. def test_year_lte_sql(self):
  337. # This test will just check the generated SQL for __lte. This
  338. # doesn't require running on PostgreSQL and spots the most likely
  339. # error - not running YearLte SQL at all.
  340. baseqs = Author.objects.order_by('name')
  341. self.assertIn(
  342. '<= (2011 || ', str(baseqs.filter(birthdate__year__lte=2011).query))
  343. self.assertIn(
  344. '-12-31', str(baseqs.filter(birthdate__year__lte=2011).query))
  345. def test_postgres_year_exact(self):
  346. baseqs = Author.objects.order_by('name')
  347. self.assertIn(
  348. '= (2011 || ', str(baseqs.filter(birthdate__year=2011).query))
  349. self.assertIn(
  350. '-12-31', str(baseqs.filter(birthdate__year=2011).query))
  351. def test_custom_implementation_year_exact(self):
  352. try:
  353. # Two ways to add a customized implementation for different backends:
  354. # First is MonkeyPatch of the class.
  355. def as_custom_sql(self, qn, connection):
  356. lhs_sql, lhs_params = self.process_lhs(qn, connection, self.lhs.lhs)
  357. rhs_sql, rhs_params = self.process_rhs(qn, connection)
  358. params = lhs_params + rhs_params + lhs_params + rhs_params
  359. return ("%(lhs)s >= str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
  360. "AND %(lhs)s <= str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" %
  361. {'lhs': lhs_sql, 'rhs': rhs_sql}, params)
  362. setattr(YearExact, 'as_' + connection.vendor, as_custom_sql)
  363. self.assertIn(
  364. 'concat(',
  365. str(Author.objects.filter(birthdate__year=2012).query))
  366. finally:
  367. delattr(YearExact, 'as_' + connection.vendor)
  368. try:
  369. # The other way is to subclass the original lookup and register the subclassed
  370. # lookup instead of the original.
  371. class CustomYearExact(YearExact):
  372. # This method should be named "as_mysql" for MySQL, "as_postgresql" for postgres
  373. # and so on, but as we don't know which DB we are running on, we need to use
  374. # setattr.
  375. def as_custom_sql(self, qn, connection):
  376. lhs_sql, lhs_params = self.process_lhs(qn, connection, self.lhs.lhs)
  377. rhs_sql, rhs_params = self.process_rhs(qn, connection)
  378. params = lhs_params + rhs_params + lhs_params + rhs_params
  379. return ("%(lhs)s >= str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
  380. "AND %(lhs)s <= str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" %
  381. {'lhs': lhs_sql, 'rhs': rhs_sql}, params)
  382. setattr(CustomYearExact, 'as_' + connection.vendor, CustomYearExact.as_custom_sql)
  383. YearTransform.register_lookup(CustomYearExact)
  384. self.assertIn(
  385. 'CONCAT(',
  386. str(Author.objects.filter(birthdate__year=2012).query))
  387. finally:
  388. YearTransform._unregister_lookup(CustomYearExact)
  389. YearTransform.register_lookup(YearExact)
  390. class TrackCallsYearTransform(YearTransform):
  391. lookup_name = 'year'
  392. call_order = []
  393. def as_sql(self, qn, connection):
  394. lhs_sql, params = qn.compile(self.lhs)
  395. return connection.ops.date_extract_sql('year', lhs_sql), params
  396. @property
  397. def output_field(self):
  398. return models.IntegerField()
  399. def get_lookup(self, lookup_name):
  400. self.call_order.append('lookup')
  401. return super(TrackCallsYearTransform, self).get_lookup(lookup_name)
  402. def get_transform(self, lookup_name):
  403. self.call_order.append('transform')
  404. return super(TrackCallsYearTransform, self).get_transform(lookup_name)
  405. class LookupTransformCallOrderTests(TestCase):
  406. def test_call_order(self):
  407. models.DateField.register_lookup(TrackCallsYearTransform)
  408. try:
  409. # junk lookup - tries lookup, then transform, then fails
  410. with self.assertRaises(FieldError):
  411. Author.objects.filter(birthdate__year__junk=2012)
  412. self.assertEqual(TrackCallsYearTransform.call_order,
  413. ['lookup', 'transform'])
  414. TrackCallsYearTransform.call_order = []
  415. # junk transform - tries transform only, then fails
  416. with self.assertRaises(FieldError):
  417. Author.objects.filter(birthdate__year__junk__more_junk=2012)
  418. self.assertEqual(TrackCallsYearTransform.call_order,
  419. ['transform'])
  420. TrackCallsYearTransform.call_order = []
  421. # Just getting the year (implied __exact) - lookup only
  422. Author.objects.filter(birthdate__year=2012)
  423. self.assertEqual(TrackCallsYearTransform.call_order,
  424. ['lookup'])
  425. TrackCallsYearTransform.call_order = []
  426. # Just getting the year (explicit __exact) - lookup only
  427. Author.objects.filter(birthdate__year__exact=2012)
  428. self.assertEqual(TrackCallsYearTransform.call_order,
  429. ['lookup'])
  430. finally:
  431. models.DateField._unregister_lookup(TrackCallsYearTransform)
  432. class CustomisedMethodsTests(TestCase):
  433. def test_overridden_get_lookup(self):
  434. q = CustomModel.objects.filter(field__lookupfunc_monkeys=3)
  435. self.assertIn('monkeys()', str(q.query))
  436. def test_overridden_get_transform(self):
  437. q = CustomModel.objects.filter(field__transformfunc_banana=3)
  438. self.assertIn('banana()', str(q.query))
  439. def test_overridden_get_lookup_chain(self):
  440. q = CustomModel.objects.filter(field__transformfunc_banana__lookupfunc_elephants=3)
  441. self.assertIn('elephants()', str(q.query))
  442. def test_overridden_get_transform_chain(self):
  443. q = CustomModel.objects.filter(field__transformfunc_banana__transformfunc_pear=3)
  444. self.assertIn('pear()', str(q.query))