-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_postgresqlx.py
More file actions
1277 lines (1111 loc) · 40.3 KB
/
test_postgresqlx.py
File metadata and controls
1277 lines (1111 loc) · 40.3 KB
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
import unittest
import importlib.util
from sqllex.constants import *
from sqllex.constants.postgresql import *
from sqllex.classes import PostgreSQLx
import psycopg2
# from sqllex.debug import debug_mode
# debug_mode(True)
class TestSqllexPostgres(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.tests_counter = 0
conn = psycopg2.connect(
dbname='postgres',
user='postgres',
password='admin'
)
conn.autocommit = True
cls.admin_cur = conn.cursor()
try:
cls.admin_cur.execute("drop database test_sqllex")
except psycopg2.errors.InvalidCatalogName:
pass
try:
cls.admin_cur.execute("drop user test_sqllex")
except psycopg2.errors.UndefinedObject:
pass
@classmethod
def tearDownClass(cls) -> None:
pass
def setUp(self) -> None:
self.tests_counter += 1
self.admin_cur.execute("create user test_sqllex with password 'test_sqllex'")
self.admin_cur.execute("alter role test_sqllex set client_encoding to 'utf8'")
self.admin_cur.execute("alter role test_sqllex set default_transaction_isolation to 'read committed'")
self.admin_cur.execute("alter role test_sqllex set timezone to 'UTC'")
self.admin_cur.execute("create database test_sqllex owner test_sqllex")
self.db = PostgreSQLx(
engine=psycopg2,
dbname='test_sqllex',
user='test_sqllex',
password='test_sqllex'
)
def tearDown(self) -> None:
self.db.disconnect()
self.admin_cur.execute("drop database test_sqllex")
self.admin_cur.execute("drop user test_sqllex")
def raw_sql_get_tables_names(self):
return tuple(map(lambda ret: ret[0], self.db.execute(
"""
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE';
"""
)))
# def test_connection(self):
# """
# Testing connection with class object init
# """
#
# self.assertIsInstance(SQLite3x(db_name).connection, sqlite3.Connection)
# os.remove(db_name)
#
# db_name = f"{self.db_name}_{1}"
# self.assertIsInstance(SQLite3x(db_name, init_connection=True).connection, sqlite3.Connection)
# os.remove(db_name)
#
# db_name = f"{self.db_name}_{1}"
# self.assertIs(SQLite3x(db_name, init_connection=False).connection, None)
def test_transaction(self):
"""
Testing transactions
"""
def get_by_id(table: str, val: int):
return self.db.execute(f'SELECT * FROM {table} WHERE id={val}')
def get_user_by_id(val: int):
return get_by_id(table='"user"', val=val)
def get_car_by_id(val: int):
return get_by_id(table='car', val=val)
self.db.execute(
"""
CREATE TABLE "user" (
"id" SERIAL PRIMARY KEY,
"name" TEXT UNIQUE
);
"""
)
self.db.execute(
"""
CREATE TABLE "car" (
"id" SERIAL PRIMARY KEY,
"owner_id" INTEGER REFERENCES "user" (id),
"brand" TEXT
);
"""
)
# Transaction with auto commit
with self.db.transaction as tran:
self.db.execute(
"""INSERT INTO "user" VALUES (1, 'Alex')"""
)
self.assertEqual(get_user_by_id(1), [(1, 'Alex')])
# Transaction with auto commit for many executes
with self.db.transaction as tran:
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (22, 'Alex22')"""
)
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (23, 'Alex23')"""
)
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (24, 'Alex24')"""
)
self.assertEqual(get_user_by_id(22), [(22, 'Alex22')])
self.assertEqual(get_user_by_id(23), [(23, 'Alex23')])
self.assertEqual(get_user_by_id(24), [(24, 'Alex24')])
# Transaction with manual commit
with self.db.transaction as tran:
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (2, 'Bob')"""
)
tran.commit()
self.assertEqual(get_user_by_id(2), [(2, 'Bob')])
# Transaction with rollback
with self.db.transaction as tran:
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (3, 'Cara')"""
)
self.assertEqual(get_user_by_id(3), [(3, 'Cara')])
tran.rollback()
self.assertEqual(get_user_by_id(3), [])
# Prep
self.assertRaises(
psycopg2.errors.UniqueViolation,
self.db.execute,
"""INSERT INTO "user" (id, name) VALUES (2, 'Sam')"""
)
# Transaction with rollback
with self.db.transaction as tran:
try:
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (2, 'Sam')"""
)
except psycopg2.errors.UniqueViolation:
tran.rollback()
self.assertEqual(get_user_by_id(2), [(2, 'Bob')])
# Normal Transaction
with self.db.transaction as tran:
self.db.execute(
"""INSERT INTO "user" (id, name) VALUES (55, 'Master')"""
)
self.db.execute(
"""INSERT INTO car VALUES (55, 55, 'BMW')"""
)
self.assertEqual(get_user_by_id(55), [(55, 'Master')])
self.assertEqual(get_car_by_id(55), [(55, 55, 'BMW')])
# Prep
self.assertRaises(psycopg2.errors.ForeignKeyViolation, self.db.execute, "INSERT INTO car VALUES (9999, 9999, 'BMW')")
# Transaction with rollback
with self.db.transaction as tran:
try:
self.db.execute(
"INSERT INTO car VALUES (9999, 9999, 'BMW')"
)
except psycopg2.errors.ForeignKeyViolation:
tran.rollback()
self.assertEqual(get_car_by_id(9999), [])
def test_create_table_1(self):
"""
Testing table creating
"""
self.assertRaises(ValueError, self.db.create_table, 'test_table_1', {})
self.assertRaises(ValueError, self.db.create_table, 'test_table_2', '')
def test_create_table_basic(self):
"""
Testing table creating
"""
columns = {'id': int}
self.db.create_table(
'test_table_1',
columns
)
self.assertEqual(self.raw_sql_get_tables_names(), ('test_table_1',))
self.db.create_table(
'test_table_2',
columns
)
self.assertEqual(self.raw_sql_get_tables_names(), ('test_table_1', 'test_table_2'))
def test_create_table_all_columns(self):
"""
Testing table creating
"""
self.db.create_table(
name='test_table',
columns={
'id': [int, PRIMARY_KEY],
'user': [str, UNIQUE, NOT_NULL],
'about': [str, DEFAULT, NULL],
'status': [str, DEFAULT, "'offline'"]
}
)
self.assertEqual(self.raw_sql_get_tables_names(), ('test_table',))
self.db.create_table(
name='test_table_1',
columns={
'id': [SERIAL, PRIMARY_KEY],
'user': [str, UNIQUE, NOT_NULL],
'about': [str, DEFAULT, NULL],
'status': [str, DEFAULT, "'offline'"]
}
)
self.assertEqual(self.raw_sql_get_tables_names(), ('test_table', 'test_table_1'))
def test_create_table_inx(self):
"""
Testing if not exist kwarg
"""
columns = {'id': int}
self.db.create_table('test_table_1', columns, IF_NOT_EXIST=True)
self.db.create_table('test_table_2', columns, IF_NOT_EXIST=True)
self.db.create_table('test_table_1', columns, IF_NOT_EXIST=True)
self.assertEqual(self.raw_sql_get_tables_names(), ('test_table_1', 'test_table_2'))
self.assertRaises(psycopg2.errors.DuplicateTable, self.db.create_table, 'test_table_1', columns, IF_NOT_EXIST=False)
def test_markup(self):
"""
Markup table
"""
self.db.markup(
{
"tt_groups": {
"group_id": [PRIMARY_KEY, UNIQUE, INTEGER],
"group_name": [TEXT, NOT_NULL, DEFAULT, "'GroupName'"],
},
"tt_users": {
"user_id": [INTEGER, PRIMARY_KEY, UNIQUE],
"user_name": TEXT,
"group_id": INTEGER,
FOREIGN_KEY: {
"group_id": ["tt_groups", "group_id"]
},
}
}
)
self.assertEqual(
self.raw_sql_get_tables_names(),
('tt_groups', 'tt_users')
)
def test_drop_and_create_table(self):
"""
Create and remove table
"""
self.db.execute(
"""
CREATE TABLE "test_table" (
"id" INTEGER
);
"""
)
self.assertEqual(
self.raw_sql_get_tables_names(),
('test_table',)
)
self.db.drop('test_table')
self.assertEqual(
self.raw_sql_get_tables_names(),
tuple()
)
def test_insert(self):
"""
All kind of possible inserts without extra arguments (OR, WITH)
"""
def get_all_records():
return self.db.execute(f'SELECT * FROM "{table_name}"')
def count_all_records():
return len(get_all_records())
def count_records(step: int = None):
"""
This decorator adding counting
with every run of decorated function it increases count_records.counter at value of step
@count_records(step=1)
def func(*args, **kwargs):
return None
func()
func()
count_records.counter == 2
"""
def wrapper_(func: callable):
def wrapper(*args, **kwargs):
# one run == + step records
count_records.counter += func.step
func(*args, **kwargs)
# checking was it inserted or not
self.assertEqual(
count_all_records(),
count_records.counter,
msg=f"Incorrect records amount\n args={args}, kwargs={kwargs}"
)
func.step = step
return wrapper
if step is None:
step = 1
count_records.counter = 0
return wrapper_
@count_records(step=2) # warning - magic number!
def insert_process(*args, **kwargs):
self.db.insert(table_name, *args, **kwargs)
self.db[table_name].insert(*args, **kwargs)
@count_records(step=10) # warning - magic number!
def insert_many_process(*args, **kwargs):
self.db.insertmany(table_name, *args, **kwargs)
self.db[table_name].insertmany(*args, **kwargs)
table_name = 'test_table'
columns = ["num_c", "int_c", "real_c", 'none_c', 'blob_c', "text_c"]
data = (10.0, 1, 3.14, None, 2, 'asdf')
self.db.execute(
"""
CREATE TABLE IF NOT EXISTS "test_table" (
"num_c" NUMERIC,
"int_c" INTEGER,
"real_c" REAL,
"none_c" INT,
"blob_c" INT,
"text_c" TEXT
);
"""
)
# columns_types = (TEXT, NUMERIC, INTEGER, REAL, NONE, BLOB)
#
# self.db.markup(
# {
# table_name: dict(zip(columns, columns_types))
# }
# )
# just arg values
# 1, 2, 3
insert_process(*data)
# arg list
# [1, 2, 3]
insert_process(list(data))
# arg tuple
# (1, 2, 3)
insert_process(tuple(data))
# arg tuple
# {'col1': 1, 'col2': 2}
insert_process(dict(zip(columns, data)))
# kwargs
# col1=1, col2=2
insert_process(**dict(zip(columns, data)))
# not full tuple
# insert_process((10.0, 'asdf'))
# not full tuple
# insert_process([10.0, 'asdf'])
# insert_many args
# (1, 2), (3, 4) ...
insert_many_process(*((data,) * 5))
# insert_many one arg
# ((1, 2), (3, 4) ... )
insert_many_process((data,) * 5)
# Manually SQL script execution
all_data = get_all_records()
self.assertEqual(all_data, self.db.select(table_name))
self.assertEqual(all_data, self.db.select(table_name, ALL))
self.assertEqual(all_data, self.db.select(table_name, '*'))
self.assertEqual(all_data, self.db[table_name].select_all())
self.assertEqual(all_data, self.db[table_name].select())
self.assertEqual(all_data, self.db[table_name].select(ALL))
def test_insert_xa_and_update(self):
"""
Insert with extra args and Update
"""
def re_init_database():
self.db.execute('''
DROP TABLE IF EXISTS "salt";
''')
self.db.execute('''
DROP TABLE IF EXISTS "hashes";
''')
self.db.execute('''
CREATE TABLE IF NOT EXISTS "hashes" (
"id" SERIAL PRIMARY KEY,
"value" TEXT
);
''')
self.db.execute('''
CREATE TABLE "salt" (
"hashID" INTEGER references hashes(id),
"value" TEXT
);
''')
self.db.execute('''
INSERT INTO "hashes" (id, value) VALUES (1, '6432642426695757642'), (2, '3259279587463616469'),
(3, '4169263184167314937'), (4, '-8758758971870855856'), (5, '-2558087477551224077');
''')
self.db.execute('''
INSERT INTO salt VALUES (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5');
''')
# sqlite3.IntegrityError: UNIQUE constraint failed: hashes.id
re_init_database()
self.assertRaises(
psycopg2.errors.UniqueViolation,
self.db.insert, 'hashes', (1, 'newHash'),
)
# INSERT OR FAIL
# sqlite3.IntegrityError: UNIQUE constraint failed: hashes.id
# re_init_database()
# self.assertRaises(
# sqlite3.IntegrityError,
# self.db.insert,
# 'hashes', (1, 'newHash'), OR=FAIL
# )
# INSERT OR ABORT
# sqlite3.IntegrityError: UNIQUE constraint failed: hashes.id
# re_init_database()
# self.assertRaises(
# psycopg2.errors.UniqueViolation,
# self.db.insert,
# 'hashes', (1, 'newHash'), OR=ABORT
# )
# INSERT OR ROLLBACK
# sqlite3.IntegrityError: UNIQUE constraint failed: hashes.id
# re_init_database()
# self.assertRaises(
# psycopg2.errors.UniqueViolation,
# self.db.insert,
# 'hashes', (1, 'newHash'), OR=ROLLBACK
# )
# INSERT OR REPLACE
# re_init_database()
# self.db.insert(
# 'hashes',
# (1, 'newHash'),
# OR=REPLACE
# )
# self.assertEqual(
# [
# (1, 'newHash'),
# (2, '3259279587463616469'),
# (3, '4169263184167314937'),
# (4, '-8758758971870855856'),
# (5, '-2558087477551224077')
# ],
# self.db.execute("SELECT * FROM hashes"),
# )
# INSERT OR IGNORE
# re_init_database()
# self.db.insert(
# 'hashes',
# (1, 'newHash'),
# (2, 'anotherNewHash'),
# OR=IGNORE
# )
# self.assertEqual(
# [
# (1, '6432642426695757642'),
# (2, '3259279587463616469'),
# (3, '4169263184167314937'),
# (4, '-8758758971870855856'),
# (5, '-2558087477551224077')
# ],
# self.db.execute("SELECT * FROM hashes"),
# )
# INSERT many OR REPLACE
# re_init_database()
# self.db.insertmany(
# 'hashes',
# (
# (1, 'newHash'),
# (6, 'anotherNewHash'),
# ),
# OR=REPLACE
# )
# self.assertEqual(
# [
# (1, 'newHash'),
# (2, '3259279587463616469'),
# (3, '4169263184167314937'),
# (4, '-8758758971870855856'),
# (5, '-2558087477551224077'),
# (6, 'anotherNewHash'),
# ],
# self.db.execute("SELECT * FROM hashes"),
# )
# INSERT many OR IGNORE
# re_init_database()
# self.db.insertmany(
# 'hashes',
# (
# (1, 'newHash'),
# (6, 'anotherNewHash'),
# ),
# OR=IGNORE
# )
# self.assertEqual(
# [
# (1, '6432642426695757642'),
# (2, '3259279587463616469'),
# (3, '4169263184167314937'),
# (4, '-8758758971870855856'),
# (5, '-2558087477551224077'),
# (6, 'anotherNewHash'),
# ],
# self.db.execute("SELECT * FROM hashes")
# )
expected = [
(2, '3259279587463616469'),
(3, '4169263184167314937'),
(4, '-8758758971870855856'),
(5, '-2558087477551224077'),
(1, 'newHash'),
]
# UPDATE
re_init_database()
self.db.update(
'hashes',
SET={'value': 'newHash'},
WHERE={'id': 1}
)
self.assertEqual(
expected,
self.db.execute("SELECT * FROM hashes"),
)
# UPDATE
re_init_database()
self.db.update(
'hashes',
SET={
self.db['hashes']['value']: 'newHash'
},
WHERE={
self.db['hashes']['id']: 1
}
)
self.assertEqual(
expected,
self.db.execute("SELECT * FROM hashes"),
)
# UPDATE
re_init_database()
self.db.update(
'hashes',
SET={
self.db['hashes']['value']: 'newHash'
},
WHERE=self.db['hashes']['id'] == 1
)
self.assertEqual(
expected,
self.db.execute("SELECT * FROM hashes"),
)
# UPDATE
re_init_database()
self.db.update(
'hashes',
SET={
self.db['hashes']['value']: 'newHash'
},
WHERE=(1 < self.db['hashes']['id']) & (self.db['hashes']['id'] < 5)
)
self.assertEqual(
self.db.execute("SELECT * FROM hashes"),
[
(1, '6432642426695757642'),
(5, '-2558087477551224077'),
(2, 'newHash'),
(3, 'newHash'),
(4, 'newHash'),
]
)
# UPDATE with impossible WHERE condition
re_init_database()
self.db.update(
'hashes',
SET={
self.db['hashes']['value']: 'newHash'
},
WHERE=(self.db['hashes']['id'] > 9999)
)
self.assertEqual(
self.db.execute("SELECT * FROM hashes"),
[
(1, '6432642426695757642'),
(2, '3259279587463616469'),
(3, '4169263184167314937'),
(4, '-8758758971870855856'),
(5, '-2558087477551224077')
]
)
def test_select(self):
"""
All kind of selects (WHERE, ORDER BY, JOIN, GROUP BY)
"""
self.db.execute(
"""
CREATE TABLE IF NOT EXISTS "position" (
"id" SERIAL PRIMARY KEY,
"name" TEXT,
"description" TEXT DEFAULT NULL
);
""")
self.db.execute("""
CREATE TABLE IF NOT EXISTS "employee" (
"id" SERIAL,
"firstName" TEXT,
"surname" TEXT,
"age" INTEGER NOT NULL,
"positionID" INTEGER REFERENCES position(id)
);
""")
self.db.execute("""
CREATE TABLE IF NOT EXISTS "payments" (
"date" TEXT,
"employeeID" INTEGER,
"amount" INTEGER NOT NULL
);
""")
# self.db.markup(
# {
# 'position': {
# 'id': [INTEGER, PRIMARY_KEY, AUTOINCREMENT],
# 'name': TEXT,
# 'description': [TEXT, DEFAULT, NULL],
# },
# 'employee': {
# 'id': [INTEGER, PRIMARY_KEY, AUTOINCREMENT],
# 'firstName': TEXT,
# 'surname': TEXT,
# 'age': [INTEGER, NOT_NULL],
# 'positionID': INTEGER,
#
# FOREIGN_KEY: {
# 'positionID': ['position', 'id']
# }
# },
# 'payments': {
# 'date': [TEXT],
# 'employeeID': INTEGER,
# 'amount': [INTEGER, NOT_NULL],
#
# FOREIGN_KEY: {
# 'positionID': ['employee', 'id']
# },
# }
# }
# )
self.db.executemany(
'INSERT INTO "position" (id, name, description) VALUES (%s, %s, %s)',
(
(0, 'Assistant', 'Novice developer'),
(1, 'Junior', 'Junior developer'),
(2, 'Middle', 'Middle developer'),
(3, 'Senior', 'senior developer'),
(4, 'DevOps', 'DevOps engineer')
)
)
self.db.executemany(
'INSERT INTO "employee" ("firstName", surname, age, "positionID") VALUES (%s, %s, %s, %s)',
(
('Alis', 'A', 11, 1),
('Bob', 'B', 22, 1),
('Carl', 'C', 33, 2),
('Alis', 'B', 44, 3),
('Dexter', 'B', 55, 1),
('Elis', 'A', 22, 1),
('Frank', 'B', 33, 1),
('Georgy', 'D', 22, 2),
('FoxCpp', 'M', 22, 1),
('Ira', 'D', 22, 2)
)
)
self.db.executemany(
'INSERT INTO "payments" (date, "employeeID", amount) VALUES (%s, %s, %s)',
(
('01.01.2022', 2, 2000),
('01.01.2022', 3, 3000),
('01.01.2022', 7, 2000),
('01.02.2022', 1, 4000),
('01.02.2022', 2, 2000),
('01.02.2022', 3, 4000),
('01.02.2022', 5, 2000),
('01.02.2022', 6, 4000),
('01.02.2022', 7, 2000),
)
)
# SELECT all
expected = self.db.execute('SELECT * FROM "employee"')
self.assertEqual(
expected, self.db['employee'].select(ALL)
)
self.assertEqual(
expected, self.db['employee'].select_all()
)
# self.assertEqual(
# expected, self.db['employee'].select_all(GROUP_BY=1)
# )
# SELECT one column
expected = self.db.execute('SELECT id FROM "employee"')
self.assertEqual(
expected, self.db.select('employee', 'id')
)
self.assertEqual(
expected, self.db['employee']['id']
)
self.assertEqual(
expected, self.db['employee'].select('id')
)
self.assertEqual(
expected, self.db['employee'].select(self.db['employee']['id'])
)
self.assertEqual(
expected, self.db['employee'].select([self.db['employee']['id']])
)
self.assertEqual(
expected, self.db['employee'].select((self.db['employee']['id'],))
)
# SELECT 2 columns
expected = self.db.execute('SELECT id, "firstName" FROM "employee"')
self.assertEqual(
expected, self.db['employee'].select('id, "firstName"')
)
self.assertEqual(
expected, self.db['employee'].select(['id', '"firstName"'])
)
self.assertEqual(
expected, self.db['employee'].select(('id', '"firstName"'))
)
self.assertEqual(
expected, self.db['employee'].select(
[
self.db['employee']['id'],
self.db['employee']['firstName']
]
)
)
# SELECT 2 columns WHERE (condition)
expected = self.db.execute('SELECT id, "firstName" FROM "employee" WHERE id > 2')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
WHERE='id > 2',
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
WHERE='id > 2'
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
WHERE=(self.db['employee']['id'] > 2)
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=[self.db['employee']['id'], self.db['employee']['firstName']],
WHERE=(self.db['employee']['id'] > 2)
)
)
# SELECT 2 columns WHERE (condition) AND (condition)
expected = self.db.execute('SELECT id, "firstName" FROM "employee" WHERE (age > 11) AND ("positionID" <> 2)')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
WHERE=(self.db['employee']['age'] > 11) & (self.db['employee']['positionID'] != 2)
)
)
# SELECT 2 columns WHERE (condition) AND (condition)
expected = self.db.execute('SELECT id, "firstName" FROM "employee" WHERE (age = 11) AND ("positionID" = 2)')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
WHERE=(self.db['employee']['age'] == 11) & (self.db['employee']['positionID'] == 2)
)
)
# SELECT 2 columns WHERE (condition) OR (condition)
expected = self.db.execute('SELECT id, "firstName" FROM "employee" WHERE (age = 11) OR ("positionID" = 2)')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
WHERE=(self.db['employee']['age'] == 11) | (self.db['employee']['positionID'] == 2)
)
)
# SELECT 3 columns ORDERED BY column
expected = self.db.execute('SELECT id, "firstName", "positionID" FROM "employee" ORDER BY "positionID"')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"', '"positionID"'],
ORDER_BY='"positionID"'
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"', '"positionID"'],
ORDER_BY=3
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"', '"positionID"'],
ORDER_BY=['"positionID"']
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"', '"positionID"'],
ORDER_BY=('"positionID"',)
)
)
# SELECT 2 columns ORDERED BY column1, column2
expected = self.db.execute('SELECT id, "firstName" FROM "employee" ORDER BY "firstName", surname')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
ORDER_BY=['"firstName"', 'surname']
)
)
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
ORDER_BY=('"firstName"', 'surname')
)
)
# SELECT 2 columns ORDERED BY column ASC
expected = self.db.execute('SELECT id, "firstName" FROM "employee" ORDER BY "firstName" ASC')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
ORDER_BY='"firstName" ASC'
)
)
# SELECT 2 columns ORDERED BY column DESC
expected = self.db.execute('SELECT id, "firstName" FROM "employee" ORDER BY "firstName" DESC')
self.assertEqual(
expected,
self.db['employee'].select(
SELECT=['id', '"firstName"'],
ORDER_BY='"firstName" DESC'
)
)
# Issue #59 (fixed)
# self.assertRaises(
# sqlite3.OperationalError,
# self.db['employee'].select,
# SELECT=['id', 'firstName'],
# ORDER_BY=['firstName', 'ASC', 'surname', 'DESC']
# )
# self.assertRaises(
# sqlite3.OperationalError,
# self.db['employee'].select,