-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathtests.py
5339 lines (4318 loc) · 189 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding=utf-8
import datetime
import decimal
import itertools
import logging
import operator
import os
import threading
import unittest
import sys
try:
from Queue import Queue
except ImportError:
from queue import Queue
from functools import wraps
from peewee import *
from peewee import AliasMap
from peewee import DeleteQuery
from peewee import InsertQuery
from peewee import logger
from peewee import ModelQueryResultWrapper
from peewee import NaiveQueryResultWrapper
from peewee import prefetch_add_subquery
from peewee import print_
from peewee import QueryCompiler
from peewee import R
from peewee import RawQuery
from peewee import SelectQuery
from peewee import sort_models_topologically
from peewee import transaction
from peewee import UpdateQuery
class QueryLogHandler(logging.Handler):
def __init__(self, *args, **kwargs):
self.queries = []
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.queries.append(record)
if sys.version_info[0] < 3:
import codecs
ulit = lambda s: codecs.unicode_escape_decode(s)[0]
binary_construct = buffer
binary_types = buffer
else:
ulit = lambda s: s
binary_construct = lambda s: bytes(s.encode('raw_unicode_escape'))
binary_types = (bytes, memoryview)
#
# JUNK TO ALLOW TESTING OF MULTIPLE DATABASE BACKENDS
#
BACKEND = os.environ.get('PEEWEE_TEST_BACKEND', 'sqlite')
TEST_VERBOSITY = int(os.environ.get('PEEWEE_TEST_VERBOSITY') or 1)
if TEST_VERBOSITY > 1:
handler = logging.StreamHandler()
handler.setLevel(logging.ERROR)
logger.addHandler(handler)
database_params = {}
print_('TESTING USING PYTHON %s' % sys.version)
BerkeleyDatabase = None
if BACKEND in ('postgresql', 'postgres', 'pg'):
database_class = PostgresqlDatabase
database_name = 'peewee_test'
import psycopg2
elif BACKEND == 'mysql':
database_class = MySQLDatabase
database_name = 'peewee_test'
try:
import MySQLdb as mysql
except ImportError:
import pymysql as mysql
elif BACKEND == 'apsw':
from playhouse.apsw_ext import *
database_class = APSWDatabase
database_name = 'tmp.db'
database_params['timeout'] = 1000
elif BACKEND in ('berkeleydb', 'berkeley', 'bdb'):
from playhouse.berkeleydb import *
database_class = BerkeleyDatabase
database_name = 'tmp.bdb.db'
database_params['timeout'] = 1000
elif BACKEND == 'sqlcipher':
from playhouse.sqlcipher_ext import *
database_class = SqlCipherDatabase
database_name = 'tmp-snakeoilpassphrase.db'
database_params['passphrase'] = 'snakeoilpassphrase'
from pysqlcipher import dbapi2 as sqlcipher
print_('PYSQLCIPHER VERSION: %s' % sqlcipher.version)
else:
database_class = SqliteDatabase
database_name = 'tmp.db'
import sqlite3
print_('SQLITE VERSION: %s' % sqlite3.version)
#
# TEST-ONLY QUERY COMPILER USED TO CREATE "predictable" QUERIES
#
class TestAliasMap(AliasMap):
def add(self, obj, alias=None):
self._alias_map[obj] = obj._meta.db_table
class TestQueryCompiler(QueryCompiler):
alias_map_class = TestAliasMap
class TestDatabase(database_class):
compiler_class = TestQueryCompiler
field_overrides = {}
interpolation = '?'
op_overrides = {}
quote_char = '"'
def sql_error_handler(self, exception, sql, params, require_commit):
self.last_error = (sql, params)
return super(TestDatabase, self).sql_error_handler(
exception, sql, params, require_commit)
test_db = database_class(database_name, **database_params)
query_db = TestDatabase(database_name, **database_params)
compiler = query_db.compiler()
# create a compiler we can use to test that will generate increasing aliases
# this is used to test self-referential joins
normal_compiler = QueryCompiler('"', '?', {}, {})
#
# BASE MODEL CLASS
#
class TestModel(Model):
class Meta:
database = test_db
#
# MODEL CLASSES USED BY TEST CASES
#
class User(TestModel):
username = CharField()
class Meta:
db_table = 'users'
def prepared(self):
self.foo = self.username
class Blog(TestModel):
user = ForeignKeyField(User)
title = CharField(max_length=25)
content = TextField(default='')
pub_date = DateTimeField(null=True)
pk = PrimaryKeyField()
def __unicode__(self):
return '%s: %s' % (self.user.username, self.title)
def prepared(self):
self.foo = self.title
class Comment(TestModel):
blog = ForeignKeyField(Blog, related_name='comments')
comment = CharField()
class Relationship(TestModel):
from_user = ForeignKeyField(User, related_name='relationships')
to_user = ForeignKeyField(User, related_name='related_to')
class NullModel(TestModel):
char_field = CharField(null=True)
text_field = TextField(null=True)
datetime_field = DateTimeField(null=True)
int_field = IntegerField(null=True)
float_field = FloatField(null=True)
decimal_field1 = DecimalField(null=True)
decimal_field2 = DecimalField(decimal_places=2, null=True)
double_field = DoubleField(null=True)
bigint_field = BigIntegerField(null=True)
date_field = DateField(null=True)
time_field = TimeField(null=True)
boolean_field = BooleanField(null=True)
class UniqueModel(TestModel):
name = CharField(unique=True)
class OrderedModel(TestModel):
title = CharField()
created = DateTimeField(default=datetime.datetime.now)
class Meta:
order_by = ('-created',)
class Category(TestModel):
parent = ForeignKeyField('self', related_name='children', null=True)
name = CharField()
class UserCategory(TestModel):
user = ForeignKeyField(User)
category = ForeignKeyField(Category)
class NonIntModel(TestModel):
pk = CharField(primary_key=True)
data = CharField()
class NonIntRelModel(TestModel):
non_int_model = ForeignKeyField(NonIntModel, related_name='nr')
class DBUser(TestModel):
user_id = PrimaryKeyField(db_column='db_user_id')
username = CharField(db_column='db_username')
class DBBlog(TestModel):
blog_id = PrimaryKeyField(db_column='db_blog_id')
title = CharField(db_column='db_title')
user = ForeignKeyField(DBUser, db_column='db_user')
class SeqModelA(TestModel):
id = IntegerField(primary_key=True, sequence='just_testing_seq')
num = IntegerField()
class SeqModelB(TestModel):
id = IntegerField(primary_key=True, sequence='just_testing_seq')
other_num = IntegerField()
class MultiIndexModel(TestModel):
f1 = CharField()
f2 = CharField()
f3 = CharField()
class Meta:
indexes = (
(('f1', 'f2'), True),
(('f2', 'f3'), False),
)
class BlogTwo(Blog):
title = TextField()
extra_field = CharField()
class Parent(TestModel):
data = CharField()
class Child(TestModel):
parent = ForeignKeyField(Parent)
data = CharField(default='')
class Orphan(TestModel):
parent = ForeignKeyField(Parent, null=True)
data = CharField(default='')
class ChildPet(TestModel):
child = ForeignKeyField(Child)
data = CharField(default='')
class OrphanPet(TestModel):
orphan = ForeignKeyField(Orphan)
data = CharField(default='')
class CSVField(TextField):
def db_value(self, value):
if value:
return ','.join(value)
return value or ''
def python_value(self, value):
return value.split(',') if value else []
class CSVRow(TestModel):
data = CSVField()
class BlobModel(TestModel):
data = BlobField()
class Job(TestModel):
"""A job that can be queued for later execution."""
name = CharField()
class JobExecutionRecord(TestModel):
"""Record of a job having been executed."""
# the foreign key is also the primary key to enforce the
# constraint that a job can be executed once and only once
job = ForeignKeyField(Job, primary_key=True)
status = CharField()
class TestModelA(TestModel):
field = CharField(primary_key=True)
data = CharField()
class TestModelB(TestModel):
field = CharField(primary_key=True)
data = CharField()
class TestModelC(TestModel):
field = CharField(primary_key=True)
data = CharField()
class Post(TestModel):
title = CharField()
class Tag(TestModel):
tag = CharField()
class TagPostThrough(TestModel):
tag = ForeignKeyField(Tag, related_name='posts')
post = ForeignKeyField(Post, related_name='tags')
class Meta:
primary_key = CompositeKey('tag', 'post')
class Manufacturer(TestModel):
name = CharField()
class CompositeKeyModel(TestModel):
f1 = CharField()
f2 = IntegerField()
f3 = FloatField()
class Meta:
primary_key = CompositeKey('f1', 'f2')
class UserThing(TestModel):
thing = CharField()
user = ForeignKeyField(User, related_name='things')
class Meta:
primary_key = CompositeKey('thing', 'user')
class Component(TestModel):
name = CharField()
manufacturer = ForeignKeyField(Manufacturer, null=True)
class Computer(TestModel):
hard_drive = ForeignKeyField(Component, related_name='c1')
memory = ForeignKeyField(Component, related_name='c2')
processor = ForeignKeyField(Component, related_name='c3')
class CheckModel(TestModel):
value = IntegerField(constraints=[Check('value > 0')])
# Deferred foreign keys.
SnippetProxy = Proxy()
class Language(TestModel):
name = CharField()
selected_snippet = ForeignKeyField(SnippetProxy, null=True)
class Snippet(TestModel):
code = TextField()
language = ForeignKeyField(Language, related_name='snippets')
SnippetProxy.initialize(Snippet)
class _UpperField(CharField):
def python_value(self, value):
return value.upper() if value else value
class UpperUser(TestModel):
username = _UpperField()
class Meta:
db_table = User._meta.db_table
class Package(TestModel):
barcode = CharField(unique=True)
class PackageItem(TestModel):
title = CharField()
package = ForeignKeyField(
Package,
related_name='items',
to_field=Package.barcode)
MODELS = [
User,
Blog,
Comment,
Relationship,
NullModel,
UniqueModel,
OrderedModel,
Category,
UserCategory,
NonIntModel,
NonIntRelModel,
DBUser,
DBBlog,
SeqModelA,
SeqModelB,
MultiIndexModel,
BlogTwo,
Parent,
Child,
Orphan,
ChildPet,
OrphanPet,
BlobModel,
Job,
JobExecutionRecord,
TestModelA,
TestModelB,
TestModelC,
Tag,
Post,
TagPostThrough,
Language,
Snippet,
Manufacturer,
CompositeKeyModel,
UserThing,
Component,
Computer,
CheckModel,
Package,
PackageItem,
]
INT = test_db.interpolation
def drop_tables(only=None):
for model in reversed(MODELS):
if only is None or model in only:
model.drop_table(True)
def create_tables(only=None):
for model in MODELS:
if only is None or model in only:
model.create_table()
#
# BASE TEST CASE USED BY ALL TESTS
#
class BasePeeweeTestCase(unittest.TestCase):
def setUp(self):
self.qh = QueryLogHandler()
logger.setLevel(logging.DEBUG)
logger.addHandler(self.qh)
def tearDown(self):
logger.removeHandler(self.qh)
def queries(self):
return [x.msg for x in self.qh.queries]
def parse_node(self, query, expr_list, compiler=compiler):
am = compiler.calculate_alias_map(query)
return compiler.parse_node_list(expr_list, am)
def parse_query(self, query, node, compiler=compiler):
am = compiler.calculate_alias_map(query)
if node is not None:
return compiler.parse_node(node, am)
return '', []
def make_fn(fn_name, attr_name):
def inner(self, query, expected, expected_params, compiler=compiler):
fn = getattr(self, fn_name)
att = getattr(query, attr_name)
sql, params = fn(query, att, compiler=compiler)
self.assertEqual(sql, expected)
self.assertEqual(params, expected_params)
return inner
assertSelect = make_fn('parse_node', '_select')
assertWhere = make_fn('parse_query', '_where')
assertGroupBy = make_fn('parse_node', '_group_by')
assertHaving = make_fn('parse_query', '_having')
assertOrderBy = make_fn('parse_node', '_order_by')
def assertJoins(self, sq, exp_joins, compiler=compiler):
am = compiler.calculate_alias_map(sq)
clauses = compiler.generate_joins(sq._joins, sq.model_class, am)
joins = [compiler.parse_node(clause, am)[0] for clause in clauses]
self.assertEqual(sorted(joins), sorted(exp_joins))
#
# BASIC TESTS OF QUERY TYPES AND INTERNAL DATA STRUCTURES
#
class SelectTestCase(BasePeeweeTestCase):
def test_selection(self):
sq = SelectQuery(User)
self.assertSelect(sq, 'users."id", users."username"', [])
sq = SelectQuery(Blog, Blog.pk, Blog.title, Blog.user, User.username).join(User)
self.assertSelect(sq, 'blog."pk", blog."title", blog."user_id", users."username"', [])
sq = SelectQuery(User, fn.Lower(fn.Substr(User.username, 0, 1)).alias('lu'), fn.Count(Blog.pk)).join(Blog)
self.assertSelect(sq, 'Lower(Substr(users."username", ?, ?)) AS lu, Count(blog."pk")', [0, 1])
sq = SelectQuery(User, User.username, fn.Count(Blog.select().where(Blog.user == User.id)))
self.assertSelect(sq, 'users."username", Count(SELECT blog."pk" FROM "blog" AS blog WHERE (blog."user_id" = users."id"))', [])
sq = SelectQuery(Package, Package, fn.Count(PackageItem.id)).join(PackageItem)
self.assertSelect(sq, 'package."id", package."barcode", Count(packageitem."id")', [])
def test_select_distinct(self):
sq = SelectQuery(User).distinct()
self.assertEqual(
compiler.generate_select(sq),
('SELECT DISTINCT users."id", users."username" '
'FROM "users" AS users', []))
sq = sq.distinct(False)
self.assertEqual(
compiler.generate_select(sq),
('SELECT users."id", users."username" FROM "users" AS users', []))
sq = SelectQuery(User).distinct([User.username])
self.assertEqual(
compiler.generate_select(sq),
('SELECT DISTINCT ON (users."username") users."id", '
'users."username" '
'FROM "users" AS users', []))
def test_reselect(self):
sq = SelectQuery(User, User.username)
self.assertSelect(sq, 'users."username"', [])
sq2 = sq.select()
self.assertSelect(sq2, 'users."id", users."username"', [])
self.assertTrue(id(sq) != id(sq2))
sq3 = sq2.select(User.id)
self.assertSelect(sq3, 'users."id"', [])
self.assertTrue(id(sq2) != id(sq3))
def test_select_subquery(self):
subquery = SelectQuery(Child, fn.Count(Child.id)).where(Child.parent == Parent.id).group_by(Child.parent)
sq = SelectQuery(Parent, Parent, subquery.alias('count'))
sql = compiler.generate_select(sq)
self.assertEqual(sql, (
'SELECT parent."id", parent."data", ' + \
'(SELECT Count(child."id") FROM "child" AS child ' + \
'WHERE (child."parent_id" = parent."id") GROUP BY child."parent_id") ' + \
'AS count FROM "parent" AS parent', []
))
def test_select_subquery_ordering(self):
sq = Comment.select().join(Blog).where(Blog.pk == 1)
sq1 = Comment.select().where(
(Comment.id << sq) |
(Comment.comment == '*')
)
sq2 = Comment.select().where(
(Comment.comment == '*') |
(Comment.id << sq)
)
sql1, params1 = normal_compiler.generate_select(sq1)
self.assertEqual(sql1, (
'SELECT t1."id", t1."blog_id", t1."comment" FROM "comment" AS t1 '
'WHERE ((t1."id" IN ('
'SELECT t2."id" FROM "comment" AS t2 '
'INNER JOIN "blog" AS t3 ON (t2."blog_id" = t3."pk") '
'WHERE (t3."pk" = ?))) OR (t1."comment" = ?))'))
self.assertEqual(params1, [1, '*'])
sql2, params2 = normal_compiler.generate_select(sq2)
self.assertEqual(sql2, (
'SELECT t1."id", t1."blog_id", t1."comment" FROM "comment" AS t1 '
'WHERE ((t1."comment" = ?) OR (t1."id" IN ('
'SELECT t2."id" FROM "comment" AS t2 '
'INNER JOIN "blog" AS t3 ON (t2."blog_id" = t3."pk") '
'WHERE (t3."pk" = ?))))'))
self.assertEqual(params2, ['*', 1])
def test_multiple_subquery(self):
sq2 = Comment.select().where(Comment.comment == '2').join(Blog)
sq1 = Comment.select().where(
(Comment.comment == '1') &
(Comment.id << sq2)
).join(Blog)
sq = Comment.select().where(
Comment.id << sq1
)
sql, params = normal_compiler.generate_select(sq)
self.assertEqual(sql, (
'SELECT t1."id", t1."blog_id", t1."comment" '
'FROM "comment" AS t1 '
'WHERE (t1."id" IN ('
'SELECT t2."id" FROM "comment" AS t2 '
'INNER JOIN "blog" AS t3 ON (t2."blog_id" = t3."pk") '
'WHERE ((t2."comment" = ?) AND (t2."id" IN ('
'SELECT t4."id" FROM "comment" AS t4 '
'INNER JOIN "blog" AS t5 ON (t4."blog_id" = t5."pk") '
'WHERE (t4."comment" = ?)'
')))))'))
self.assertEqual(params, ['1', '2'])
def test_select_cloning(self):
ct = fn.Count(Blog.pk)
sq = SelectQuery(User, User, User.id.alias('extra_id'), ct.alias('blog_ct')).join(
Blog, JOIN_LEFT_OUTER).group_by(User).order_by(ct.desc())
sql = compiler.generate_select(sq)
self.assertEqual(sql, (
'SELECT users."id", users."username", users."id" AS extra_id, Count(blog."pk") AS blog_ct ' + \
'FROM "users" AS users LEFT OUTER JOIN "blog" AS blog ON (users."id" = blog."user_id") ' + \
'GROUP BY users."id", users."username" ' + \
'ORDER BY Count(blog."pk") DESC', []
))
self.assertEqual(User.id._alias, None)
def test_joins(self):
sq = SelectQuery(User).join(Blog)
self.assertJoins(sq, ['INNER JOIN "blog" AS blog ON (users."id" = blog."user_id")'])
sq = SelectQuery(Blog).join(User, JOIN_LEFT_OUTER)
self.assertJoins(sq, ['LEFT OUTER JOIN "users" AS users ON (blog."user_id" = users."id")'])
sq = SelectQuery(User).join(Relationship)
self.assertJoins(sq, ['INNER JOIN "relationship" AS relationship ON (users."id" = relationship."from_user_id")'])
sq = SelectQuery(User).join(Relationship, on=Relationship.to_user)
self.assertJoins(sq, ['INNER JOIN "relationship" AS relationship ON (users."id" = relationship."to_user_id")'])
sq = SelectQuery(User).join(Relationship, JOIN_LEFT_OUTER, Relationship.to_user)
self.assertJoins(sq, ['LEFT OUTER JOIN "relationship" AS relationship ON (users."id" = relationship."to_user_id")'])
sq = SelectQuery(Package).join(PackageItem)
self.assertJoins(sq, ['INNER JOIN "packageitem" AS packageitem ON (package."barcode" = packageitem."package_id")'])
sq = SelectQuery(PackageItem).join(Package)
self.assertJoins(sq, ['INNER JOIN "package" AS package ON (packageitem."package_id" = package."barcode")'])
def test_join_self_referential(self):
sq = SelectQuery(Category).join(Category)
self.assertJoins(sq, ['INNER JOIN "category" AS category ON (category."parent_id" = category."id")'])
def test_join_self_referential_alias(self):
Parent = Category.alias()
sq = SelectQuery(Category, Category, Parent).join(Parent, on=(Category.parent == Parent.id)).where(
Parent.name == 'parent name'
).order_by(Parent.name)
self.assertSelect(sq, 't1."id", t1."parent_id", t1."name", t2."id", t2."parent_id", t2."name"', [], normal_compiler)
self.assertJoins(sq, [
'INNER JOIN "category" AS t2 ON (t1."parent_id" = t2."id")',
], normal_compiler)
self.assertWhere(sq, '(t2."name" = ?)', ['parent name'], normal_compiler)
self.assertOrderBy(sq, 't2."name"', [], normal_compiler)
Grandparent = Category.alias()
sq = SelectQuery(Category, Category, Parent, Grandparent).join(
Parent, on=(Category.parent == Parent.id)
).join(
Grandparent, on=(Parent.parent == Grandparent.id)
).where(Grandparent.name == 'g1')
self.assertSelect(sq, 't1."id", t1."parent_id", t1."name", t2."id", t2."parent_id", t2."name", t3."id", t3."parent_id", t3."name"', [], normal_compiler)
self.assertJoins(sq, [
'INNER JOIN "category" AS t2 ON (t1."parent_id" = t2."id")',
'INNER JOIN "category" AS t3 ON (t2."parent_id" = t3."id")',
], normal_compiler)
self.assertWhere(sq, '(t3."name" = ?)', ['g1'], normal_compiler)
def test_join_both_sides(self):
sq = SelectQuery(Blog).join(Comment).switch(Blog).join(User)
self.assertJoins(sq, [
'INNER JOIN "comment" AS comment ON (blog."pk" = comment."blog_id")',
'INNER JOIN "users" AS users ON (blog."user_id" = users."id")',
])
sq = SelectQuery(Blog).join(User).switch(Blog).join(Comment)
self.assertJoins(sq, [
'INNER JOIN "users" AS users ON (blog."user_id" = users."id")',
'INNER JOIN "comment" AS comment ON (blog."pk" = comment."blog_id")',
])
def test_join_switching(self):
class Artist(TestModel):
pass
class Track(TestModel):
artist = ForeignKeyField(Artist)
class Release(TestModel):
artist = ForeignKeyField(Artist)
class ReleaseTrack(TestModel):
track = ForeignKeyField(Track)
release = ForeignKeyField(Release)
class Genre(TestModel):
pass
class TrackGenre(TestModel):
genre = ForeignKeyField(Genre)
track = ForeignKeyField(Track)
multiple_first = Track.select().join(ReleaseTrack).join(Release).switch(Track).join(Artist).switch(Track).join(TrackGenre).join(Genre)
self.assertSelect(multiple_first, 'track."id", track."artist_id"', [])
self.assertJoins(multiple_first, [
'INNER JOIN "artist" AS artist ON (track."artist_id" = artist."id")',
'INNER JOIN "genre" AS genre ON (trackgenre."genre_id" = genre."id")',
'INNER JOIN "release" AS release ON (releasetrack."release_id" = release."id")',
'INNER JOIN "releasetrack" AS releasetrack ON (track."id" = releasetrack."track_id")',
'INNER JOIN "trackgenre" AS trackgenre ON (track."id" = trackgenre."track_id")',
])
single_first = Track.select().join(Artist).switch(Track).join(ReleaseTrack).join(Release).switch(Track).join(TrackGenre).join(Genre)
self.assertSelect(single_first, 'track."id", track."artist_id"', [])
self.assertJoins(single_first, [
'INNER JOIN "artist" AS artist ON (track."artist_id" = artist."id")',
'INNER JOIN "genre" AS genre ON (trackgenre."genre_id" = genre."id")',
'INNER JOIN "release" AS release ON (releasetrack."release_id" = release."id")',
'INNER JOIN "releasetrack" AS releasetrack ON (track."id" = releasetrack."track_id")',
'INNER JOIN "trackgenre" AS trackgenre ON (track."id" = trackgenre."track_id")',
])
def test_joining_expr(self):
class A(TestModel):
uniq_a = CharField(primary_key=True)
class B(TestModel):
uniq_ab = CharField(primary_key=True)
uniq_b = CharField()
class C(TestModel):
uniq_bc = CharField(primary_key=True)
sq = A.select(A, B, C).join(
B, on=(A.uniq_a == B.uniq_ab)
).join(
C, on=(B.uniq_b == C.uniq_bc)
)
self.assertSelect(sq, 'a."uniq_a", b."uniq_ab", b."uniq_b", c."uniq_bc"', [])
self.assertJoins(sq, [
'INNER JOIN "b" AS b ON (a."uniq_a" = b."uniq_ab")',
'INNER JOIN "c" AS c ON (b."uniq_b" = c."uniq_bc")',
])
def test_where(self):
sq = SelectQuery(User).where(User.id < 5)
self.assertWhere(sq, '(users."id" < ?)', [5])
sq = SelectQuery(Blog).where(Blog.user << sq)
self.assertWhere(sq, '(blog."user_id" IN (SELECT users."id" FROM "users" AS users WHERE (users."id" < ?)))', [5])
p = SelectQuery(Package).where(Package.id == 2)
sq = SelectQuery(PackageItem).where(PackageItem.package << p)
self.assertWhere(sq, '(packageitem."package_id" IN (SELECT package."barcode" FROM "package" AS package WHERE (package."id" = ?)))', [2])
def test_orwhere(self):
sq = SelectQuery(User).orwhere(User.id < 5)
self.assertWhere(sq, '(users."id" < ?)', [5])
sq = sq.orwhere(User.id > 10)
self.assertWhere(sq, '((users."id" < ?) OR (users."id" > ?))', [5, 10])
def test_fix_null(self):
sq = SelectQuery(Blog).where(Blog.user == None)
self.assertWhere(sq, '(blog."user_id" IS ?)', [None])
sq = SelectQuery(Blog).where(Blog.user != None)
self.assertWhere(sq, 'NOT (blog."user_id" IS ?)', [None])
def test_where_coercion(self):
sq = SelectQuery(User).where(User.id < '5')
self.assertWhere(sq, '(users."id" < ?)', [5])
sq = SelectQuery(User).where(User.id < (User.id - '5'))
self.assertWhere(sq, '(users."id" < (users."id" - ?))', [5])
def test_where_lists(self):
sq = SelectQuery(User).where(User.username << ['u1', 'u2'])
self.assertWhere(sq, '(users."username" IN (?, ?))', ['u1', 'u2'])
sq = SelectQuery(User).where((User.username << ['u1', 'u2']) | (User.username << ['u3', 'u4']))
self.assertWhere(sq, '((users."username" IN (?, ?)) OR (users."username" IN (?, ?)))', ['u1', 'u2', 'u3', 'u4'])
def test_where_joins(self):
sq = SelectQuery(User).where(
((User.id == 1) | (User.id == 2)) &
((Blog.pk == 3) | (Blog.pk == 4))
).where(User.id == 5).join(Blog)
self.assertWhere(sq, '((((users."id" = ?) OR (users."id" = ?)) AND ((blog."pk" = ?) OR (blog."pk" = ?))) AND (users."id" = ?))', [1, 2, 3, 4, 5])
def test_where_join_non_pk_fk(self):
sq = (SelectQuery(Package)
.join(PackageItem)
.where(PackageItem.title == 'p1'))
self.assertWhere(sq, '(packageitem."title" = ?)', ['p1'])
sq = (SelectQuery(PackageItem)
.join(Package)
.where(Package.barcode == 'b1'))
self.assertWhere(sq, '(package."barcode" = ?)', ['b1'])
def test_where_functions(self):
sq = SelectQuery(User).where(fn.Lower(fn.Substr(User.username, 0, 1)) == 'a')
self.assertWhere(sq, '(Lower(Substr(users."username", ?, ?)) = ?)', [0, 1, 'a'])
def test_where_conversion(self):
sq = SelectQuery(CSVRow).where(CSVRow.data == Param(['foo', 'bar']))
self.assertWhere(sq, '(csvrow."data" = ?)', ['foo,bar'])
sq = SelectQuery(CSVRow).where(
CSVRow.data == fn.FOO(Param(['foo', 'bar'])))
self.assertWhere(sq, '(csvrow."data" = FOO(?))', ['foo,bar'])
sq = SelectQuery(CSVRow).where(
CSVRow.data == fn.FOO(Param(['foo', 'bar'])).coerce(False))
self.assertWhere(sq, '(csvrow."data" = FOO(?))', [['foo', 'bar']])
def test_where_clauses(self):
sq = SelectQuery(Blog).where(
Blog.pub_date < (fn.NOW() - SQL('INTERVAL 1 HOUR')))
self.assertWhere(sq, '(blog."pub_date" < (NOW() - INTERVAL 1 HOUR))', [])
def test_where_r(self):
sq = SelectQuery(Blog).where(Blog.pub_date < R('NOW() - INTERVAL 1 HOUR'))
self.assertWhere(sq, '(blog."pub_date" < NOW() - INTERVAL 1 HOUR)', [])
sq = SelectQuery(Blog).where(Blog.pub_date < (fn.Now() - R('INTERVAL 1 HOUR')))
self.assertWhere(sq, '(blog."pub_date" < (Now() - INTERVAL 1 HOUR))', [])
def test_where_subqueries(self):
sq = SelectQuery(User).where(User.id << User.select().where(User.username=='u1'))
self.assertWhere(sq, '(users."id" IN (SELECT users."id" FROM "users" AS users WHERE (users."username" = ?)))', ['u1'])
sq = SelectQuery(User).where(User.username << User.select(User.username).where(User.username=='u1'))
self.assertWhere(sq, '(users."username" IN (SELECT users."username" FROM "users" AS users WHERE (users."username" = ?)))', ['u1'])
sq = SelectQuery(Blog).where((Blog.pk == 3) | (Blog.user << User.select().where(User.username << ['u1', 'u2'])))
self.assertWhere(sq, '((blog."pk" = ?) OR (blog."user_id" IN (SELECT users."id" FROM "users" AS users WHERE (users."username" IN (?, ?)))))', [3, 'u1', 'u2'])
def test_where_fk(self):
sq = SelectQuery(Blog).where(Blog.user == User(id=100))
self.assertWhere(sq, '(blog."user_id" = ?)', [100])
sq = SelectQuery(Blog).where(Blog.user << [User(id=100), User(id=101)])
self.assertWhere(sq, '(blog."user_id" IN (?, ?))', [100, 101])
sq = SelectQuery(PackageItem).where(PackageItem.package == Package(barcode='b1'))
self.assertWhere(sq, '(packageitem."package_id" = ?)', ['b1'])
def test_where_negation(self):
sq = SelectQuery(Blog).where(~(Blog.title == 'foo'))
self.assertWhere(sq, 'NOT (blog."title" = ?)', ['foo'])
sq = SelectQuery(Blog).where(~((Blog.title == 'foo') | (Blog.title == 'bar')))
self.assertWhere(sq, 'NOT ((blog."title" = ?) OR (blog."title" = ?))', ['foo', 'bar'])
sq = SelectQuery(Blog).where(~((Blog.title == 'foo') & (Blog.title == 'bar')) & (Blog.title == 'baz'))
self.assertWhere(sq, '(NOT ((blog."title" = ?) AND (blog."title" = ?)) AND (blog."title" = ?))', ['foo', 'bar', 'baz'])
sq = SelectQuery(Blog).where(~((Blog.title == 'foo') & (Blog.title == 'bar')) & ((Blog.title == 'baz') & (Blog.title == 'fizz')))
self.assertWhere(sq, '(NOT ((blog."title" = ?) AND (blog."title" = ?)) AND ((blog."title" = ?) AND (blog."title" = ?)))', ['foo', 'bar', 'baz', 'fizz'])
def test_where_chaining_collapsing(self):
sq = SelectQuery(User).where(User.id == 1).where(User.id == 2).where(User.id == 3)
self.assertWhere(sq, '(((users."id" = ?) AND (users."id" = ?)) AND (users."id" = ?))', [1, 2, 3])
sq = SelectQuery(User).where((User.id == 1) & (User.id == 2)).where(User.id == 3)
self.assertWhere(sq, '(((users."id" = ?) AND (users."id" = ?)) AND (users."id" = ?))', [1, 2, 3])
sq = SelectQuery(User).where((User.id == 1) | (User.id == 2)).where(User.id == 3)
self.assertWhere(sq, '(((users."id" = ?) OR (users."id" = ?)) AND (users."id" = ?))', [1, 2, 3])
sq = SelectQuery(User).where(User.id == 1).where((User.id == 2) & (User.id == 3))
self.assertWhere(sq, '((users."id" = ?) AND ((users."id" = ?) AND (users."id" = ?)))', [1, 2, 3])
sq = SelectQuery(User).where(User.id == 1).where((User.id == 2) | (User.id == 3))
self.assertWhere(sq, '((users."id" = ?) AND ((users."id" = ?) OR (users."id" = ?)))', [1, 2, 3])
sq = SelectQuery(User).where(~(User.id == 1)).where(User.id == 2).where(~(User.id == 3))
self.assertWhere(sq, '((NOT (users."id" = ?) AND (users."id" = ?)) AND NOT (users."id" = ?))', [1, 2, 3])
def test_grouping(self):
sq = SelectQuery(User).group_by(User.id)
self.assertGroupBy(sq, 'users."id"', [])
sq = SelectQuery(User).group_by(User)
self.assertGroupBy(sq, 'users."id", users."username"', [])
def test_having(self):
sq = SelectQuery(User, fn.Count(Blog.pk)).join(Blog).group_by(User).having(
fn.Count(Blog.pk) > 2
)
self.assertHaving(sq, '(Count(blog."pk") > ?)', [2])
sq = SelectQuery(User, fn.Count(Blog.pk)).join(Blog).group_by(User).having(
(fn.Count(Blog.pk) > 10) | (fn.Count(Blog.pk) < 2)
)
self.assertHaving(sq, '((Count(blog."pk") > ?) OR (Count(blog."pk") < ?))', [10, 2])
def test_ordering(self):
sq = SelectQuery(User).join(Blog).order_by(Blog.title)
self.assertOrderBy(sq, 'blog."title"', [])
sq = SelectQuery(User).join(Blog).order_by(Blog.title.asc())
self.assertOrderBy(sq, 'blog."title" ASC', [])
sq = SelectQuery(User).join(Blog).order_by(Blog.title.desc())
self.assertOrderBy(sq, 'blog."title" DESC', [])
sq = SelectQuery(User).join(Blog).order_by(User.username.desc(), Blog.title.asc())
self.assertOrderBy(sq, 'users."username" DESC, blog."title" ASC', [])
base_sq = SelectQuery(User, User.username, fn.Count(Blog.pk).alias('count')).join(Blog).group_by(User.username)
sq = base_sq.order_by(fn.Count(Blog.pk).desc())
self.assertOrderBy(sq, 'Count(blog."pk") DESC', [])
sq = base_sq.order_by(R('count'))
self.assertOrderBy(sq, 'count', [])
sq = OrderedModel.select()
self.assertOrderBy(sq, 'orderedmodel."created" DESC', [])
sq = OrderedModel.select().order_by(OrderedModel.id.asc())
self.assertOrderBy(sq, 'orderedmodel."id" ASC', [])
sq = User.select().order_by(User.id * 5)
self.assertOrderBy(sq, '(users."id" * ?)', [5])
sql = compiler.generate_select(sq)
self.assertEqual(sql, (
'SELECT users."id", users."username" '
'FROM "users" AS users ORDER BY (users."id" * ?)',
[5]))
def test_from_subquery(self):
# e.g. annotate the number of blogs per user, then annotate the number
# of users with that number of blogs.
inner = (Blog
.select(fn.COUNT(Blog.pk).alias('blog_ct'))
.group_by(Blog.user))
blog_ct = SQL('blog_ct')
outer = (Blog
.select(blog_ct, fn.COUNT(blog_ct).alias('blog_ct_n'))
.from_(inner)
.group_by(blog_ct))
sql, params = compiler.generate_select(outer)
self.assertEqual(sql, (
'SELECT blog_ct, COUNT(blog_ct) AS blog_ct_n '
'FROM ('
'SELECT COUNT(blog."pk") AS blog_ct FROM "blog" AS blog '
'GROUP BY blog."user_id") '
'GROUP BY blog_ct'))
def test_from_multiple(self):
q = (User
.select()
.from_(User, Blog)
.where(Blog.user == User.id))
sql, params = compiler.generate_select(q)
self.assertEqual(sql, (
'SELECT users."id", users."username" '
'FROM "users" AS users, "blog" AS blog '
'WHERE (blog."user_id" = users."id")'))
q = (User
.select()
.from_(User, Blog, Comment)
.where(
(Blog.user == User.id) &
(Comment.blog == Blog.pk)))
sql, params = compiler.generate_select(q)
self.assertEqual(sql, (
'SELECT users."id", users."username" '
'FROM "users" AS users, "blog" AS blog, "comment" AS comment '
'WHERE ((blog."user_id" = users."id") AND '
'(comment."blog_id" = blog."pk"))'))
def test_paginate(self):
sq = SelectQuery(User).paginate(1, 20)
self.assertEqual(sq._limit, 20)
self.assertEqual(sq._offset, 0)
sq = SelectQuery(User).paginate(3, 30)
self.assertEqual(sq._limit, 30)
self.assertEqual(sq._offset, 60)
def test_prefetch_subquery(self):
sq = SelectQuery(User).where(User.username == 'foo')
sq2 = SelectQuery(Blog).where(Blog.title == 'bar')
sq3 = SelectQuery(Comment).where(Comment.comment == 'baz')
fixed = prefetch_add_subquery(sq, (sq2, sq3))
fixed_sql = [
('SELECT t1."id", t1."username" FROM "users" AS t1 WHERE (t1."username" = ?)', ['foo']),
('SELECT t1."pk", t1."user_id", t1."title", t1."content", t1."pub_date" FROM "blog" AS t1 WHERE ((t1."title" = ?) AND (t1."user_id" IN (SELECT t2."id" FROM "users" AS t2 WHERE (t2."username" = ?))))', ['bar', 'foo']),
('SELECT t1."id", t1."blog_id", t1."comment" FROM "comment" AS t1 WHERE ((t1."comment" = ?) AND (t1."blog_id" IN (SELECT t2."pk" FROM "blog" AS t2 WHERE ((t2."title" = ?) AND (t2."user_id" IN (SELECT t3."id" FROM "users" AS t3 WHERE (t3."username" = ?)))))))', ['baz', 'bar', 'foo']),
]
for (query, fkf), expected in zip(fixed, fixed_sql):
self.assertEqual(normal_compiler.generate_select(query), expected)
fixed = prefetch_add_subquery(sq, (Blog,))
fixed_sql = [
('SELECT t1."id", t1."username" FROM "users" AS t1 WHERE (t1."username" = ?)', ['foo']),
('SELECT t1."pk", t1."user_id", t1."title", t1."content", t1."pub_date" FROM "blog" AS t1 WHERE (t1."user_id" IN (SELECT t2."id" FROM "users" AS t2 WHERE (t2."username" = ?)))', ['foo']),
]
for (query, fkf), expected in zip(fixed, fixed_sql):
self.assertEqual(normal_compiler.generate_select(query), expected)
def test_prefetch_non_pk_fk(self):