forked from liorrozen/source-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
1022 lines (885 loc) · 32.7 KB
/
test.py
File metadata and controls
1022 lines (885 loc) · 32.7 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 mock
import unittest
import psycopg2
import postgres
from collections import OrderedDict
from postgres.source import (
Postgres,
connect,
get_incremental,
get_query,
key_strategy,
SQL_GET_KEYS,
SQL_GET_COLUMNS
)
from panoply import PanoplyException
OPTIONS = {
"logger": lambda *msgs: None, # no-op logger
}
MOCK_MAX_VALUE = 100
def mock_max_value(*args):
column = args[2]
if column:
return MOCK_MAX_VALUE
return None
def mock_table_metadata(*args):
if args[0] == SQL_GET_COLUMNS:
return [{'attname': 'id'}]
return []
class TestPostgres(unittest.TestCase):
def setUp(self):
self.source = {
"addr": "test.database.name/foobar",
"user": "test",
"password": "testpassword",
"inckey": "inckey",
"incval": "incval"
}
self.mock_recs = [
{'id': 1, 'col1': 'foo1', 'col2': 'bar1'},
{'id': 2, 'col1': 'foo2', 'col2': 'bar2'},
{'id': 3, 'col1': 'foo3', 'col2': 'bar3'}
]
def tearDown(self):
self.source = None
# fetches list of tables from database
@mock.patch("psycopg2.connect")
def test_get_tables(self, m):
"""gets the list of tables from the database"""
# Notice 'name' here is only for validation of expected result.
# It is not a field that returns in the actual query results
mock_tables = [
{'table_schema': 'dbo', 'table_name': 'testNoUnique',
'table_type': 'BASE TABLE', 'name': 'dbo.testNoUnique'},
{'table_schema': 'dbo', 'table_name': 'testNoIndex',
'table_type': 'BASE TABLE', 'name': 'dbo.testNoIndex'},
{'table_schema': 'SalesLT', 'table_name': 'Customer',
'table_type': 'BASE TABLE', 'name': 'SalesLT.Customer'},
{'table_schema': 'SalesLT', 'table_name': 'ProductModel',
'table_type': 'BASE TABLE', 'name': 'SalesLT.ProductModel'},
{'table_schema': 'mySchema', 'table_name': 'someTable',
'table_type': 'VIEW', 'name': 'mySchema.someTable (VIEW)'}
]
inst = Postgres(self.source, OPTIONS)
m.return_value.cursor.return_value.fetchall.return_value = mock_tables
tables = inst.get_tables()
self.assertEqual(len(tables), len(mock_tables))
for x in range(0, len(tables)):
mtable = mock_tables[x]
v = '{}.{}'.format(mtable["table_schema"], mtable["table_name"])
self.assertEqual(tables[x]['name'], mtable['name'])
self.assertEqual(tables[x]['value'], v)
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata',
side_effect=mock_table_metadata)
@mock.patch("psycopg2.connect")
def test_read(self, mock_connect, _, __):
"""reads a table from the database and validates that each row
has a __tablename and __schemaname column"""
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'my_schema.foo_bar'}]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = self.mock_recs
rows = inst.read()
self.assertEqual(len(rows), len(self.mock_recs))
for x in range(0, len(rows)):
self.assertEqual(rows[x]['__tablename'], 'foo_bar')
self.assertEqual(rows[x]['__schemaname'], 'my_schema')
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata',
side_effect=mock_table_metadata)
@mock.patch("psycopg2.connect")
def test_read_from_other_schema(self, mock_connect, mock_metadata, __):
inst = Postgres(self.source, OPTIONS)
inst.tables = [
{'value': 'my_schema.foo_bar'},
{'value': 'your_schema.bar_foo'}
]
cursor_return_value = mock_connect.return_value.cursor.return_value
mock_data = [self.mock_recs[:1], []] * 2
cursor_return_value.fetchall.side_effect = mock_data
expected = [
('my_schema', 'foo_bar'),
('my_schema', 'foo_bar'),
('your_schema', 'bar_foo'),
('your_schema', 'bar_foo')
]
for expected_schema, expected_table in expected:
inst.read()
_, schema, table = mock_metadata.call_args[0]
self.assertEqual(schema, expected_schema)
self.assertEqual(table, expected_table)
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata',
side_effect=mock_table_metadata)
@mock.patch("psycopg2.connect")
def test_incremental(self, mock_connect, _, __):
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'schema.foo'}]
inst.read()
q = ('DECLARE cur CURSOR FOR '
'SELECT * FROM "schema"."foo" WHERE ("inckey" >= \'incval\' '
'AND "inckey" <= \'100\') '
'ORDER BY "id","inckey"')
execute_mock = mock_connect.return_value.cursor.return_value.execute
execute_mock.assert_has_calls([mock.call(q)], True)
@mock.patch.object(Postgres, 'get_table_metadata', return_value=[])
@mock.patch("psycopg2.connect")
def test_schema_name(self, mock_connect, _):
"""Test schema name is used when queries and that both schema and table
names are wrapped in enclosing quotes"""
source = {
"addr": "test.database.name/foobar",
"user": "test",
"password": "testpassword",
"tables": [
{'value': 'schema.foo'}
]
}
inst = Postgres(source, OPTIONS)
inst.read()
q = 'DECLARE cur CURSOR FOR SELECT * FROM "schema"."foo"'
execute_mock = mock_connect.return_value.cursor.return_value.execute
execute_mock.assert_has_calls([mock.call(q)], True)
@mock.patch("psycopg2.connect")
def test_connect_auth_error(self, mock_connect):
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'schema.foo'}]
msg = 'authentication failed'
mock_connect.side_effect = psycopg2.OperationalError(msg)
with self.assertRaises(PanoplyException):
inst.get_tables()
@mock.patch("psycopg2.connect")
def test_connect_other_error(self, mock_connect):
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'schema.foo'}]
msg = 'something unexpected'
mock_connect.side_effect = psycopg2.OperationalError(msg)
with self.assertRaises(psycopg2.OperationalError):
inst.get_tables()
@mock.patch("psycopg2.connect")
def test_no_port(self, mock_connect):
source = {
"addr": "test.database.name/foobar",
"user": "test",
"password": "testpassword",
"tables": [{'value': 'schema.foo'}]
}
inst = Postgres(source, OPTIONS)
inst.read()
mock_connect.assert_called_with(
dsn="postgres://test.database.name/foobar",
user=source['user'],
password=source['password'],
connect_timeout=postgres.source.CONNECT_TIMEOUT
)
@mock.patch("psycopg2.connect")
def test_custom_port(self, mock_connect):
source = {
"addr": "test.database.name:5439/foobar",
"user": "test",
"password": "testpassword",
"tables": [{'value': 'schema.foo'}]
}
inst = Postgres(source, OPTIONS)
inst.read()
mock_connect.assert_called_with(
dsn="postgres://test.database.name:5439/foobar",
user=source['user'],
password=source['password'],
connect_timeout=postgres.source.CONNECT_TIMEOUT
)
@mock.patch("psycopg2.connect")
def test_connection_parameters(self, mock_connect):
source = {
"addr": "test.database:5439/foobar?sslmode=verify-full",
"user": "test",
"password": "testpassword",
"tables": [{'value': 'schema.foo'}]
}
inst = Postgres(source, OPTIONS)
inst.read()
mock_connect.assert_called_with(
dsn="postgres://test.database:5439/foobar?sslmode=verify-full",
user=source['user'],
password=source['password'],
connect_timeout=postgres.source.CONNECT_TIMEOUT
)
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata')
@mock.patch("postgres.source.Postgres.execute")
@mock.patch("psycopg2.connect")
def test_read_end_stream(self, mock_connect, mock_execute, mock_metadata,
_):
"""reads the entire table from the database and validates that the
stream returns None to indicate the end"""
tables = [
{'value': 'public.table1'},
{'value': 'public.table2'},
{'value': 'public.table3'},
]
mock_metadata.side_effect = [
[{'attname': 'col1'}],
[{'attname': 'col2'}],
[{'attname': 'col3'}],
]
inst = Postgres(self.source, OPTIONS)
inst.tables = tables
result_order = [
self.mock_recs,
[],
self.mock_recs,
[],
self.mock_recs,
[]
]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.side_effect = result_order
# First call to read
result = inst.read()
self.assertEqual(len(result), len(self.mock_recs))
query = mock_execute.call_args_list[0][0][0]
expected_query = 'FROM "public"."table1" ' \
'WHERE ("inckey" >= \'incval\' ' \
'AND "inckey" <= \'100\') '\
'ORDER BY "col1","inckey"'
self.assertTrue(expected_query in query)
query = mock_execute.call_args_list[1][0][0]
expected_query = 'FETCH FORWARD'
self.assertTrue(expected_query in query)
# Second call to read
result = inst.read()
self.assertEqual(result, [])
query = mock_execute.call_args_list[2][0][0]
expected_query = 'FETCH FORWARD'
self.assertTrue(expected_query in query)
# Third call to read
result = inst.read()
self.assertEqual(len(result), len(self.mock_recs))
query = mock_execute.call_args_list[3][0][0]
expected_query = 'FROM "public"."table2" ' \
'WHERE ("inckey" >= \'incval\' ' \
'AND "inckey" <= \'100\') '\
'ORDER BY "col2","inckey"'
self.assertTrue(expected_query in query)
query = mock_execute.call_args_list[4][0][0]
expected_query = 'FETCH FORWARD'
self.assertTrue(expected_query in query)
# Fourth call to read
result = inst.read()
self.assertEqual(result, [])
query = mock_execute.call_args_list[5][0][0]
expected_query = 'FETCH FORWARD'
self.assertTrue(expected_query in query)
# Fifth call to read
result = inst.read()
self.assertEqual(len(result), len(self.mock_recs))
query = mock_execute.call_args_list[6][0][0]
expected_query = 'FROM "public"."table3" ' \
'WHERE ("inckey" >= \'incval\' ' \
'AND "inckey" <= \'100\') '\
'ORDER BY "col3","inckey"'
self.assertTrue(expected_query in query)
query = mock_execute.call_args_list[7][0][0]
expected_query = 'FETCH FORWARD'
self.assertTrue(expected_query in query)
# Sixth call to read
result = inst.read()
self.assertEqual(result, [])
query = mock_execute.call_args_list[8][0][0]
expected_query = 'FETCH FORWARD'
self.assertTrue(expected_query in query)
end = inst.read()
self.assertEqual(end, None)
# Make sure that the state is reported and that the
# output data contains a key __state
@mock.patch.object(Postgres, 'get_max_value',
side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata',
side_effect=mock_table_metadata)
@mock.patch("postgres.source.Postgres.state")
@mock.patch("psycopg2.connect")
def test_reports_state(self, mock_connect, mock_state, _, __):
"""before returning a batch of data, the sources state should be
reported as well as having the state ID appended to each data object"""
inst = Postgres(self.source, OPTIONS)
table_name = 'my_schema.foo_bar'
inst.tables = [{'value': table_name}]
result_order = [self.mock_recs, []]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.side_effect = result_order
rows = inst.read()
state_id = rows[0]['__state']
state_obj = dict([
('last_index', 0),
])
msg = 'State ID is not the same in all rows!'
for row in rows:
self.assertEqual(row['__state'], state_id, msg)
# State function was called with relevant table name and row count
mock_state.assert_called_with(state_id, state_obj)
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata', return_value=[])
@mock.patch("postgres.source.Postgres.state")
@mock.patch("psycopg2.connect")
def test_no_state_for_empty_results(self, mock_connect, mock_state, _, __):
"""before returning a batch of data, the sources state should be
reported as well as having the state ID appended to each data object"""
inst = Postgres(self.source, OPTIONS)
table_name = 'my_schema.foo_bar'
inst.tables = [{'value': table_name}]
result_order = [[], []]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.side_effect = result_order
inst.read()
# State function was called with relevant table name and row count
mock_state.assert_not_called()
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata',
side_effect=mock_table_metadata)
@mock.patch("postgres.source.Postgres.execute")
@mock.patch("psycopg2.connect")
def test_recover_from_state(self, mock_connect, mock_execute, _, __):
"""continues to read a table from the saved state"""
tables = [
{'value': 'public.test1'},
{'value': 'public.test2'},
{'value': 'public.test3'},
]
last_index = 1
self.source['state'] = {
'last_index': last_index,
'max_value': 100
}
inst = Postgres(self.source, OPTIONS)
inst.tables = tables
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = [
{'id': 101},
{'id': 102},
{'id': 103}
]
inst.read()
first_query = mock_execute.call_args_list[0][0][0]
self.assertTrue("\"inckey\" >= 'incval' AND \"inckey\" <= '100'" in
first_query)
self.assertTrue('FROM "public"."test2"' in first_query)
def test_remove_state_from_source(self):
""" once extracted, the state object is removed from the source """
last_index = 3
state = {
'last_index': last_index,
}
self.source['state'] = state
inst = Postgres(self.source, OPTIONS)
self.assertEqual(inst.index, last_index)
# No state key should be inside the source definition
self.assertIsNone(inst.source.get('state', None))
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata', return_value=[])
@mock.patch("postgres.source.Postgres.execute")
@mock.patch("psycopg2.connect")
def test_batch_size(self, mock_connect, mock_execute, _, __):
customBatchSize = 42
self.source['__batchSize'] = customBatchSize
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'my_schema.foo_bar'}]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = self.mock_recs
inst.read()
second_query = mock_execute.call_args_list[1][0][0]
txt = 'FETCH FORWARD %s' % customBatchSize
self.assertTrue(second_query.startswith(txt))
def test_reset_query_on_error(self):
inst = Postgres(self.source, OPTIONS)
mock_cursor = mock.Mock()
mock_cursor.execute.side_effect = psycopg2.DatabaseError('oh noes!')
inst.cursor = mock_cursor
with self.assertRaises(psycopg2.DatabaseError):
inst.execute('SELECT 1')
# The self.loaded variable should have been reset to 0 in order to
# reset the query and start from the begining.
self.assertEqual(inst.loaded, 0)
self.assertEqual(inst.cursor, None)
@mock.patch("postgres.source.CONNECT_TIMEOUT", 0)
@mock.patch("psycopg2.connect")
def test_read_retries(self, mock_connect):
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'my_schema.foo_bar'}]
mock_connect.side_effect = psycopg2.DatabaseError('TestRetriesError')
with self.assertRaises(psycopg2.DatabaseError):
inst.read()
self.assertEqual(mock_connect.call_count, postgres.source.MAX_RETRIES)
def test_get_query_without_state_and_incremental(self):
inckey = ''
incval = ''
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
}
]
max_value = None
state = {}
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "pk1"'
self.assertEqual(result, expected)
def test_orderby_without_incremental(self):
schema = 'public'
table = 'test'
inckey = ''
incval = ''
max_value = ''
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
}
]
state = {}
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "pk1"'
self.assertEqual(result, expected)
def test_orderby_with_incremental(self):
inckey = 'pk3'
incval = ''
max_value = 10
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
{
'attname': 'pk2',
'indisunique': True,
'indisprimary': True
}
]
state = {}
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "pk1","pk2","pk3"'
self.assertEqual(result, expected)
def test_orderby_with_incremental_in_keys(self):
inckey = 'pk2'
incval = ''
max_value = ''
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
{
'attname': 'pk2',
'indisunique': True,
'indisprimary': True
}
]
state = {}
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "pk1","pk2"'
self.assertEqual(result, expected)
def test_where_without_state_and_incremental(self):
inckey = ''
incval = ''
max_value = ''
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
{
'attname': 'pk2',
'indisunique': True,
'indisprimary': True
}
]
state = {}
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "pk1","pk2"'
self.assertEqual(result, expected)
def test_where_without_state_and_with_incremental(self):
inckey = 'id'
incval = 1
max_value = 100
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
{
'attname': 'pk2',
'indisunique': True,
'indisprimary': True
}
]
state = {}
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state)
expected = 'SELECT * FROM "public"."test" ' \
'WHERE ("id" >= \'1\' AND "id" <= \'100\') ' \
'ORDER BY "pk1","pk2","id"'
self.assertEqual(result, expected)
def test_where_with_state_and_without_incremental(self):
inckey = ''
incval = ''
max_value = ''
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
{
'attname': 'pk2',
'indisunique': True,
'indisprimary': True
}
]
state = OrderedDict([
('pk1', '1'),
('pk2', '1994-09-16')
])
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ' \
'WHERE ("pk1","pk2") >= (\'1\',\'1994-09-16\') '\
'ORDER BY "pk1","pk2"'
self.assertEqual(result, expected)
def test_where_with_single_column(self):
inckey = ''
incval = ''
max_value = ''
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
]
state = OrderedDict([
('pk1', '1'),
])
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ' \
'WHERE "pk1" >= \'1\' ' \
'ORDER BY "pk1"'
self.assertEqual(result, expected)
def test_where_with_state_and_incremental(self):
inckey = 'id'
incval = 2
max_value = 100
schema = 'public'
table = 'test'
keys = [
{
'attname': 'pk1',
'indisunique': True,
'indisprimary': True
},
]
state = OrderedDict([
('pk1', '1'),
])
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ' \
'WHERE "pk1" >= \'1\' ' \
'AND ("id" >= \'2\' AND "id" <= \'100\') ' \
'ORDER BY "pk1","id"'
self.assertEqual(result, expected)
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch.object(Postgres, 'get_table_metadata')
@mock.patch("postgres.source.CONNECT_TIMEOUT", 0)
@mock.patch("psycopg2.connect")
def test_retry_with_last_values(self, mock_connect, mock_metadata, _):
mock_metadata.side_effect = lambda *args: [
{'attname': 'col1', 'indisunique': True, 'indisprimary': True},
{'attname': 'col2', 'indisunique': True, 'indisprimary': True}
]
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'my_schema.foo_bar'}]
inst.batch_size = 1
cursor_execute = mock_connect.return_value.cursor.return_value.execute
cursor_execute.side_effect = [
lambda *args: None,
lambda *args: None,
psycopg2.DatabaseError('TestRetriesError'),
lambda *args: None,
lambda *args: None,
]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = self.mock_recs
# First read no error
inst.read()
# Raise retry error
inst.read()
# Extract mock call arguments
args = mock_connect.return_value.cursor.return_value\
.execute.call_args_list
args = [r[0] for r, _ in args]
args = filter(lambda x: 'DECLARE' in x, args)
# Second DECLARATION of cursor should start from last row fetched
self.assertTrue('WHERE ("col1","col2") >= (\'foo3\',\'bar3\')' in
args[1])
@mock.patch("postgres.source.CONNECT_TIMEOUT", 0)
@mock.patch("psycopg2.connect")
def test_query_with_primary_keys(self, mock_connect):
inst = Postgres(self.source, OPTIONS)
inst.conn, inst.cursor = connect(self.source)
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = [
{'attname': 'pk1', 'indisunique': True, 'indisprimary': True},
{'attname': 'pk2', 'indisunique': True, 'indisprimary': True},
{'attname': 'pk2', 'indisunique': True, 'indisprimary': False},
]
schema = 'public'
table = 'test'
inckey = ''
incval = ''
max_value = 100
keys = inst.get_table_metadata(SQL_GET_KEYS, schema, table)
keys = key_strategy(keys)
state = None
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "pk1","pk2"'
self.assertEqual(result, expected)
@mock.patch("postgres.source.CONNECT_TIMEOUT", 0)
@mock.patch("psycopg2.connect")
def test_query_with_unique_keys(self, mock_connect):
inst = Postgres(self.source, OPTIONS)
inst.conn, inst.cursor = connect(self.source)
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = [
{
'attname': 'idx1',
'indisunique': True,
'indisprimary': False,
'indnatts': 2,
'indexrelid': 'idx12'
},
{
'attname': 'idx2',
'indisunique': True,
'indisprimary': False,
'indnatts': 2,
'indexrelid': 'idx12'
},
{
'attname': 'idx3',
'indisunique': True,
'indisprimary': False,
'indnatts': 1,
'indexrelid': 'idx3123'
},
]
schema = 'public'
table = 'test'
inckey = ''
incval = ''
max_value = ''
keys = inst.get_table_metadata(SQL_GET_KEYS, schema, table)
keys = key_strategy(keys)
state = None
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "idx1","idx2"'
self.assertEqual(result, expected)
@mock.patch("postgres.source.CONNECT_TIMEOUT", 0)
@mock.patch("psycopg2.connect")
def test_query_with_non_unique_keys(self, mock_connect):
inst = Postgres(self.source, OPTIONS)
inst.conn, inst.cursor = connect(self.source)
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.return_value = [
{
'attname': 'idx3',
'indisunique': False,
'indisprimary': False,
'indnatts': 1,
'indexrelid': 'idx3123'
},
]
schema = 'public'
table = 'test'
inckey = ''
incval = ''
max_value = 100
keys = inst.get_table_metadata(SQL_GET_KEYS, schema, table)
keys = key_strategy(keys)
state = None
result = get_query(
schema,
table,
inckey,
incval,
keys,
max_value,
state
)
expected = 'SELECT * FROM "public"."test" ORDER BY "idx3"'
self.assertEqual(result, expected)
@mock.patch.object(Postgres, 'get_max_value', side_effect=mock_max_value)
@mock.patch("postgres.source.CONNECT_TIMEOUT", 0)
@mock.patch("psycopg2.connect")
def test_query_with_no_keys(self, mock_connect, _):
inst = Postgres(self.source, OPTIONS)
inst.tables = [{'value': 'my_schema.foo_bar'}]
cursor_return_value = mock_connect.return_value.cursor.return_value
cursor_return_value.fetchall.side_effect = [
[],
[
{'attname': 'id', 'data_type': 'integer'},
{'attname': 'name', 'data_type': 'text'},
],
[],
]
cursor_execute = mock_connect.return_value.cursor.return_value.execute
cursor_execute.return_value = lambda *args: None
inst.read()
# Extract mock call arguments
args = mock_connect.return_value.cursor.return_value \
.execute.call_args_list
args = [r[0] for r, _ in args]
args = filter(lambda x: 'DECLARE' in x, args)
expected = 'DECLARE cur ' \
'CURSOR FOR SELECT * FROM "my_schema"."foo_bar" ' \
"WHERE (\"inckey\" >= 'incval' AND \"inckey\" <= '100') " \
'ORDER BY "id","inckey"'
self.assertEqual(args[0], expected)
def test_get_incremental_key_in_where(self):
where = ''
inckey = 'inckey'
incval = 1
max_value = 100
result = get_incremental(where, inckey, incval, max_value)
expected = "(\"inckey\" >= '1' AND \"inckey\" <= '100')"
self.assertEqual(result, expected)
def test_get_incremental_key_not_in_where(self):
where = "(inckey, id) >= ('1', '2)"
inckey = 'inckey'
incval = 1
max_value = 100
result = get_incremental(where, inckey, incval, max_value)
expected = "inckey <= '100'"
self.assertEqual(result, expected)
@mock.patch("postgres.source.Postgres.execute")