summaryrefslogtreecommitdiff
path: root/oslo_db/tests/sqlalchemy/test_utils.py
blob: 27ed6409bb95d1a7d3b3580c8b63695c0bc1c618 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
# Copyright (c) 2013 Boris Pavlovic (boris@pavlovic.me).
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from unittest import mock
from urllib import parse

import fixtures
import sqlalchemy
from sqlalchemy.dialects import mysql
from sqlalchemy import Boolean, Index, Integer, DateTime, String
from sqlalchemy import CheckConstraint
from sqlalchemy import MetaData, Table, Column
from sqlalchemy import ForeignKey, ForeignKeyConstraint
from sqlalchemy.dialects.postgresql import psycopg2
from sqlalchemy.engine import url as sa_url
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import mapper
from sqlalchemy.orm import Session
from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import sql
from sqlalchemy.sql.expression import cast
from sqlalchemy.sql import select
from sqlalchemy.types import UserDefinedType

from oslo_db import exception
from oslo_db.sqlalchemy import models
from oslo_db.sqlalchemy import provision
from oslo_db.sqlalchemy import session
from oslo_db.sqlalchemy import utils
from oslo_db.tests import base as test_base
from oslo_db.tests.sqlalchemy import base as db_test_base

Base = declarative_base()


class TestSanitizeDbUrl(test_base.BaseTestCase):

    def test_url_with_cred(self):
        db_url = 'myproto://johndoe:secret@localhost/myschema'
        expected = 'myproto://****:****@localhost/myschema'
        actual = utils.sanitize_db_url(db_url)
        self.assertEqual(expected, actual)

    def test_url_with_no_cred(self):
        db_url = 'sqlite:///mysqlitefile'
        actual = utils.sanitize_db_url(db_url)
        self.assertEqual(db_url, actual)


class CustomType(UserDefinedType):
    """Dummy column type for testing unsupported types."""
    def get_col_spec(self):
        return "CustomType"


class FakeTable(Base):
    __tablename__ = 'fake_table'

    user_id = Column(String(50), primary_key=True)
    project_id = Column(String(50))
    snapshot_id = Column(String(50))
    updated_at = Column(DateTime, nullable=True)
    enabled = Column(Boolean, default=True)

    _expr_to_appease_mox = project_id + snapshot_id

    @hybrid_property
    def some_hybrid(self):
        raise NotImplementedError()

    @some_hybrid.expression
    def some_hybrid(cls):
        return cls._expr_to_appease_mox

    def foo(self):
        pass


class FakeTableJoinedInh(FakeTable):
    __tablename__ = 'fake_table_inh'

    id = Column(String(50), ForeignKey('fake_table.user_id'))


class FakeTableSingleInh(FakeTable):
    __mapper_args__ = {'polymorphic_identity': 'foo'}


class FakeTableWithMultipleKeys(Base):
    __tablename__ = 'fake_table_multiple_keys'

    key1 = Column(String(50), primary_key=True)
    key2 = Column(String(50), primary_key=True)
    key3 = Column(String(50))


class FakeTableWithIndexes(Base):
    __tablename__ = 'fake_table_unique_index'

    id = Column(String(50), primary_key=True)
    key1 = Column(String(50))
    key2 = Column(String(50))
    key3 = Column(String(50))

    __table_args__ = (
        Index('idx_unique', 'key1', 'key2', unique=True),
        Index('idx_unique', 'key1', 'key3', unique=False),
    )


class FakeTableClassicalyMapped(object):
    pass


fake_table = Table(
    'fake_table_classically_mapped',
    Base.metadata,
    Column('id', Integer, primary_key=True),
    Column('key', String(50))
)

mapper(FakeTableClassicalyMapped, fake_table)


class FakeModel(object):
    def __init__(self, values):
        self.values = values

    def __getattr__(self, name):
        try:
            value = self.values[name]
        except KeyError:
            raise AttributeError(name)
        return value

    def __getitem__(self, key):
        if key in self.values:
            return self.values[key]
        else:
            raise NotImplementedError()

    def __repr__(self):
        return '<FakeModel: %s>' % self.values


class TestPaginateQuery(test_base.BaseTestCase):
    def setUp(self):
        super(TestPaginateQuery, self).setUp()

        self.query = mock.Mock()
        self.mock_asc = self.useFixture(
            fixtures.MockPatchObject(sqlalchemy, 'asc')).mock
        self.mock_desc = self.useFixture(
            fixtures.MockPatchObject(sqlalchemy, 'desc')).mock

        self.marker = FakeTable(user_id='user',
                                project_id='p',
                                snapshot_id='s',
                                updated_at=None)
        self.model = FakeTable

    def test_paginate_query_no_pagination_no_sort_dirs(self):
        self.query.order_by.return_value = self.query
        self.mock_asc.side_effect = [
            'asc_3', 'asc_2', 'asc_1'
        ]

        utils.paginate_query(self.query, self.model, 5,
                             ['user_id', 'project_id', 'snapshot_id'])

        self.mock_asc.assert_has_calls([
            mock.call(self.model.user_id),
            mock.call(self.model.project_id),
            mock.call(self.model.snapshot_id),
        ])
        self.query.order_by.assert_has_calls([
            mock.call('asc_3'),
            mock.call('asc_2'),
            mock.call('asc_1'),
        ])
        self.query.limit.assert_called_once_with(5)

    def test_paginate_query_no_pagination(self):
        self.query.order_by.return_value = self.query
        self.mock_asc.side_effect = ['asc']
        self.mock_desc.side_effect = ['desc']

        utils.paginate_query(self.query, self.model, 5,
                             ['user_id', 'project_id'],
                             sort_dirs=['asc', 'desc'])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.mock_desc.assert_called_once_with(self.model.project_id)
        self.query.order_by.assert_has_calls([
            mock.call('asc'),
            mock.call('desc'),
        ])
        self.query.limit.assert_called_once_with(5)

    def test_invalid_sort_key_str(self):
        self.assertEqual("Sort key supplied is invalid: None",
                         str(exception.InvalidSortKey()))
        self.assertEqual("Sort key supplied is invalid: lol",
                         str(exception.InvalidSortKey("lol")))

    def test_invalid_unicode_paramater_str(self):
        self.assertEqual(
            "Invalid Parameter: Encoding directive wasn't provided.",
            str(exception.DBInvalidUnicodeParameter()))

    def test_paginate_query_attribute_error(self):
        self.mock_asc.return_value = 'asc'

        self.assertRaises(exception.InvalidSortKey,
                          utils.paginate_query, self.query,
                          self.model, 5, ['user_id', 'non-existent key'])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.query.order_by.assert_called_once_with('asc')

    def test_paginate_query_attribute_error_invalid_sortkey(self):
        self.assertRaises(exception.InvalidSortKey,
                          utils.paginate_query, self.query,
                          self.model, 5, ['bad_user_id'])

    def test_paginate_query_attribute_error_invalid_sortkey_2(self):
        self.assertRaises(exception.InvalidSortKey,
                          utils.paginate_query, self.query,
                          self.model, 5, ['foo'])

    def test_paginate_query_attribute_error_invalid_sortkey_3(self):
        self.assertRaises(exception.InvalidSortKey,
                          utils.paginate_query, self.query,
                          self.model, 5, ['asc-nullinvalid'])

    def test_paginate_query_assertion_error(self):
        self.assertRaises(AssertionError,
                          utils.paginate_query, self.query,
                          self.model, 5, ['user_id'],
                          marker=self.marker,
                          sort_dir='asc', sort_dirs=['asc'])

    def test_paginate_query_assertion_error_2(self):
        self.assertRaises(AssertionError,
                          utils.paginate_query, self.query,
                          self.model, 5, ['user_id'],
                          marker=self.marker,
                          sort_dir=None, sort_dirs=['asc', 'desk'])

    @mock.patch.object(sqlalchemy.sql, 'and_')
    @mock.patch.object(sqlalchemy.sql, 'or_')
    def test_paginate_query(self, mock_or, mock_and):
        self.query.order_by.return_value = self.query
        self.query.filter.return_value = self.query
        self.mock_asc.return_value = 'asc_1'
        self.mock_desc.return_value = 'desc_1'
        mock_and.side_effect = ['some_crit', 'another_crit']
        mock_or.return_value = 'some_f'

        utils.paginate_query(self.query, self.model, 5,
                             ['user_id', 'project_id'],
                             marker=self.marker,
                             sort_dirs=['asc', 'desc'])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.mock_desc.assert_called_once_with(self.model.project_id)
        self.query.order_by.assert_has_calls([
            mock.call('asc_1'),
            mock.call('desc_1'),
        ])
        mock_and.assert_has_calls([
            mock.call(mock.ANY),
            mock.call(mock.ANY, mock.ANY)
        ])
        mock_or.assert_called_once_with('some_crit', 'another_crit')
        self.query.filter.assert_called_once_with('some_f')
        self.query.limit.assert_called_once_with(5)

    @mock.patch.object(sqlalchemy.sql, 'and_')
    @mock.patch.object(sqlalchemy.sql, 'or_')
    def test_paginate_query_null(self, mock_or, mock_and):
        self.query.order_by.return_value = self.query
        self.query.filter.return_value = self.query
        self.mock_desc.side_effect = [
            'asc_null_2',
            'desc_null_2',
            'desc_1',
        ]
        self.mock_asc.side_effect = [
            'asc_1'
        ]
        mock_or.side_effect = [
            'or_1',
            'or_2',
            'some_f',
        ]
        mock_and.side_effect = [
            'some_crit',
            'another_crit',
        ]

        with mock.patch.object(self.model.user_id, 'isnot') as mock_isnot, \
                mock.patch.object(self.model.user_id, 'is_') as mock_is_a, \
                mock.patch.object(self.model.project_id, 'is_') as mock_is_b:
            mock_isnot.return_value = 'asc_null_1'
            mock_is_a.side_effect = [
                'desc_null_filter_1',
                'desc_null_filter_2',
            ]
            mock_is_b.side_effect = [
                'desc_null_1',
                'asc_null_filter',
            ]

            utils.paginate_query(self.query, self.model, 5,
                                 ['user_id', 'project_id'],
                                 marker=self.marker,
                                 sort_dirs=[
                                     'asc-nullslast', 'desc-nullsfirst'])

            mock_isnot.assert_called_once_with(None)
            mock_is_a.assert_has_calls([
                mock.call(None),
                mock.call(None),
            ])
            mock_is_b.assert_has_calls([
                mock.call(None),
                mock.call(None),
            ])

        self.mock_desc.assert_has_calls([
            mock.call('asc_null_1'),
            mock.call('desc_null_1'),
            mock.call(self.model.project_id),
        ])
        self.mock_asc.assert_has_calls([
            mock.call(self.model.user_id),
        ])
        mock_or.assert_has_calls([
            mock.call(mock.ANY, 'desc_null_filter_2'),
            mock.call(mock.ANY, 'asc_null_filter'),
            mock.call('some_crit', 'another_crit'),
        ])
        mock_and.assert_has_calls([
            mock.call('or_1'),
            mock.call(mock.ANY, 'or_2'),
        ])

        self.query.order_by.assert_has_calls([
            mock.call('asc_null_2'),
            mock.call('asc_1'),
            mock.call('desc_null_2'),
            mock.call('desc_1'),
        ])
        self.query.filter.assert_called_once_with('some_f')
        self.query.limit.assert_called_once_with(5)

    @mock.patch.object(sqlalchemy.sql, 'and_')
    @mock.patch.object(sqlalchemy.sql, 'or_')
    def test_paginate_query_marker_null(self, mock_or, mock_and):

        self.mock_asc.side_effect = [
            'asc_1'
        ]
        self.mock_desc.side_effect = [
            'asc_null_2',
            'desc_null_2',
            'desc_1',
        ]
        self.query.order_by.return_value = self.query
        self.query.filter.return_value = self.query
        mock_and.return_value = 'some_crit'
        mock_or.side_effect = ['or_1', 'some_f']

        with mock.patch.object(self.model.user_id, 'isnot') as mock_isnot, \
                mock.patch.object(self.model.updated_at, 'is_') as mock_is_a, \
                mock.patch.object(self.model.user_id, 'is_') as mock_is_b:

            mock_isnot.return_value = 'asc_null_1'
            mock_is_a.return_value = 'desc_null_1'
            mock_is_b.side_effect = ['asc_null_filter_1', 'asc_null_filter_2']

            utils.paginate_query(self.query, self.model, 5,
                                 ['user_id', 'updated_at'],
                                 marker=self.marker,
                                 sort_dirs=[
                                     'asc-nullslast', 'desc-nullsfirst'])
            mock_isnot.assert_called_once_with(None)
            mock_is_a.assert_called_once_with(None)
            mock_is_b.assert_has_calls([mock.call(None), mock.call(None)])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.mock_desc.assert_has_calls([
            mock.call('asc_null_1'),
            mock.call('desc_null_1'),
            mock.call(self.model.updated_at),
        ])
        mock_and.assert_called_once_with('or_1')
        mock_or.assert_has_calls([
            mock.call(mock.ANY, 'asc_null_filter_2'),
            mock.call('some_crit'),
        ])
        self.query.order_by.assert_has_calls([
            mock.call('asc_null_2'),
            mock.call('asc_1'),
            mock.call('desc_null_2'),
            mock.call('desc_1'),
        ])
        self.query.filter.assert_called_once_with('some_f')
        self.query.limit.assert_called_once_with(5)

    @mock.patch.object(sqlalchemy.sql, 'and_')
    @mock.patch.object(sqlalchemy.sql, 'or_')
    def test_paginate_query_marker_null_with_two_primary_keys(
            self, mock_or, mock_and):
        self.mock_asc.return_value = 'asc_1'
        self.mock_desc.side_effect = [
            'asc_null_2',
            'desc_null_2',
            'desc_1',
            'desc_null_4',
            'desc_4',
        ]
        self.query.order_by.return_value = self.query
        mock_or.side_effect = [
            'or_1',
            'or_2',
            'some_f',
        ]
        mock_and.side_effect = [
            'some_crit',
            'other_crit',
        ]
        self.query.filter.return_value = self.query

        with mock.patch.object(self.model.user_id, 'isnot') as mock_isnot, \
                mock.patch.object(self.model.updated_at, 'is_') as mock_is_a, \
                mock.patch.object(self.model.user_id, 'is_') as mock_is_b, \
                mock.patch.object(self.model.project_id, 'is_') as mock_is_c:

            mock_isnot.return_value = 'asc_null_1'
            mock_is_a.return_value = 'desc_null_1'
            mock_is_b.side_effect = ['asc_null_filter_1', 'asc_null_filter_2']
            mock_is_c.side_effect = ['desc_null_3', 'desc_null_filter_3']

            utils.paginate_query(self.query, self.model, 5,
                                 ['user_id', 'updated_at', 'project_id'],
                                 marker=self.marker,
                                 sort_dirs=['asc-nullslast', 'desc-nullsfirst',
                                            'desc-nullsfirst'])

            mock_isnot.assert_called_once_with(None)
            mock_is_a.assert_called_once_with(None)
            mock_is_b.assert_has_calls([mock.call(None), mock.call(None)])
            mock_is_c.assert_has_calls([mock.call(None), mock.call(None)])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.mock_desc.assert_has_calls([
            mock.call('asc_null_1'),
            mock.call('desc_null_1'),
            mock.call(self.model.updated_at),
            mock.call('desc_null_3'),
            mock.call(self.model.project_id),
        ])
        self.query.order_by.assert_has_calls = [
            mock.call('asc_null_2'),
            mock.call('asc_1'),
            mock.call('desc_null_2'),
            mock.call('desc_1'),
            mock.call('desc_null_4'),
            mock.call('desc_4'),
        ]
        mock_or.assert_has_calls([
            mock.call(mock.ANY, 'asc_null_filter_2'),
            mock.call(mock.ANY, 'desc_null_filter_3'),
            mock.call('some_crit', 'other_crit'),
        ])
        mock_and.assert_has_calls([
            mock.call('or_1'),
            mock.call(mock.ANY, 'or_2'),
        ])
        self.query.filter.assert_called_once_with('some_f')
        self.query.limit.assert_called_once_with(5)

    def test_paginate_query_value_error(self):
        self.mock_asc.return_value = 'asc_1'
        self.query.order_by.return_value = self.query

        self.assertRaises(ValueError, utils.paginate_query,
                          self.query, self.model, 5, ['user_id', 'project_id'],
                          marker=self.marker, sort_dirs=['asc', 'mixed'])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.query.order_by.assert_called_once_with('asc_1')

    def test_paginate_on_hybrid(self):
        self.mock_asc.return_value = 'asc_1'
        self.mock_desc.return_value = 'desc_1'
        self.query.order_by.return_value = self.query

        utils.paginate_query(self.query, self.model, 5,
                             ['user_id', 'some_hybrid'],
                             sort_dirs=['asc', 'desc'])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.mock_desc.assert_called_once_with(self.model.some_hybrid)
        self.query.order_by.assert_has_calls([
            mock.call('asc_1'),
            mock.call('desc_1'),
        ])
        self.query.limit.assert_called_once_with(5)


class Test_UnstableSortingOrder(test_base.BaseTestCase):
    def test_multiple_primary_keys_stable(self):
        self.assertTrue(
            utils._stable_sorting_order(
                FakeTableWithMultipleKeys, ['key1', 'key2']))

    def test_classically_mapped_primary_keys_stable(self):
        self.assertTrue(
            utils._stable_sorting_order(FakeTableClassicalyMapped, ['id']))

    def test_multiple_primary_keys_unstable(self):
        self.assertFalse(
            utils._stable_sorting_order(
                FakeTableWithMultipleKeys, ['key1', 'key3']))

    def test_joined_inh_stable(self):
        self.assertTrue(
            utils._stable_sorting_order(FakeTableJoinedInh, ['user_id'])
        )

    def test_single_inh_stable(self):
        self.assertTrue(
            utils._stable_sorting_order(FakeTableSingleInh, ['user_id'])
        )

    def test_unknown_primary_keys_stable(self):
        self.assertIsNone(
            utils._stable_sorting_order(object, ['key1', 'key2']))

    def test_unique_index_stable(self):
        self.assertTrue(
            utils._stable_sorting_order(
                FakeTableWithIndexes, ['key1', 'key2']))

    def test_unique_index_unstable(self):
        self.assertFalse(
            utils._stable_sorting_order(
                FakeTableWithIndexes, ['key1', 'key3']))


class TestGetUniqueKeys(test_base.BaseTestCase):
    def test_multiple_primary_keys(self):
        self.assertEqual(
            [{'key1', 'key2'}],
            utils.get_unique_keys(FakeTableWithMultipleKeys))

    def test_unique_index(self):
        self.assertEqual(
            [{'id'}, {'key1', 'key2'}],
            utils.get_unique_keys(FakeTableWithIndexes))

    def test_unknown_primary_keys(self):
        self.assertIsNone(utils.get_unique_keys(object))

    def test_cache(self):

        class CacheTable(object):
            info = {}
            constraints_called = 0
            indexes_called = 0

            @property
            def constraints(self):
                self.constraints_called += 1
                return []

            @property
            def indexes(self):
                self.indexes_called += 1
                return []

        class CacheModel(object):
            pass

        table = CacheTable()
        mapper_mock = mock.Mock(mapped_table=table, local_table=table)
        mapper_mock.base_mapper = mapper_mock
        mock_inspect = mock.Mock(
            return_value=mapper_mock)
        model = CacheModel()
        self.assertNotIn('oslodb_unique_keys', CacheTable.info)
        with mock.patch("oslo_db.sqlalchemy.utils.inspect", mock_inspect):
            utils.get_unique_keys(model)

        self.assertIn('oslodb_unique_keys', CacheTable.info)
        self.assertEqual(1, table.constraints_called)
        self.assertEqual(1, table.indexes_called)

        for i in range(10):
            utils.get_unique_keys(model)

        self.assertEqual(1, table.constraints_called)
        self.assertEqual(1, table.indexes_called)


class TestPaginateQueryActualSQL(test_base.BaseTestCase):

    def test_paginate_with_boolean_sort(self):
        s = Session()
        q = s.query(FakeTable)
        q = utils.paginate_query(q, FakeTable, 5, ['enabled'],
                                 sort_dirs=['asc'],
                                 marker=FakeTable(user_id='hello',
                                                  enabled=False))
        expected_core_sql = (
            select(FakeTable).
            order_by(sqlalchemy.asc(FakeTable.enabled)).
            where(cast(FakeTable.enabled, Integer) > 0).
            limit(5)
        )

        self.assertEqual(
            str(expected_core_sql.compile()),
            str(q.statement.compile())
        )

    def test_paginate_on_hybrid_assert_stmt(self):
        s = Session()
        q = s.query(FakeTable)
        q = utils.paginate_query(
            q, FakeTable, 5,
            ['user_id', 'some_hybrid'],
            sort_dirs=['asc', 'desc'])
        expected_core_sql = (
            select(FakeTable).
            order_by(sqlalchemy.asc(FakeTable.user_id)).
            order_by(sqlalchemy.desc(FakeTable.some_hybrid)).
            limit(5)
        )

        self.assertEqual(
            str(expected_core_sql.compile()),
            str(q.statement.compile())
        )


class TestMigrationUtils(db_test_base._DbTestCase):

    """Class for testing utils that are used in db migrations."""

    def setUp(self):
        super(TestMigrationUtils, self).setUp()
        self.meta = MetaData()
        self.conn = self.engine.connect()

        # self.conn would be better here but does not work right now
        self.addCleanup(self.meta.drop_all, self.engine)
        self.addCleanup(self.conn.close)

    def _populate_db_for_drop_duplicate_entries(self, engine, meta,
                                                table_name):
        values = [
            {'id': 11, 'a': 3, 'b': 10, 'c': 'abcdef'},
            {'id': 12, 'a': 5, 'b': 10, 'c': 'abcdef'},
            {'id': 13, 'a': 6, 'b': 10, 'c': 'abcdef'},
            {'id': 14, 'a': 7, 'b': 10, 'c': 'abcdef'},
            {'id': 21, 'a': 1, 'b': 20, 'c': 'aa'},
            {'id': 31, 'a': 1, 'b': 20, 'c': 'bb'},
            {'id': 41, 'a': 1, 'b': 30, 'c': 'aef'},
            {'id': 42, 'a': 2, 'b': 30, 'c': 'aef'},
            {'id': 43, 'a': 3, 'b': 30, 'c': 'aef'}
        ]

        test_table = Table(table_name, meta,
                           Column('id', Integer, primary_key=True,
                                  nullable=False),
                           Column('a', Integer),
                           Column('b', Integer),
                           Column('c', String(255)),
                           Column('deleted', Integer, default=0),
                           Column('deleted_at', DateTime),
                           Column('updated_at', DateTime))

        test_table.create(engine)
        with engine.connect() as conn, conn.begin():
            conn.execute(test_table.insert(), values)
        return test_table, values

    def test_drop_old_duplicate_entries_from_table(self):
        table_name = "__test_tmp_table__"

        test_table, values = self._populate_db_for_drop_duplicate_entries(
            self.engine, self.meta, table_name)
        utils.drop_old_duplicate_entries_from_table(
            self.engine, table_name, False, 'b', 'c')

        uniq_values = set()
        expected_ids = []
        for value in sorted(values, key=lambda x: x['id'], reverse=True):
            uniq_value = (('b', value['b']), ('c', value['c']))
            if uniq_value in uniq_values:
                continue
            uniq_values.add(uniq_value)
            expected_ids.append(value['id'])

        with self.engine.connect() as conn, conn.begin():
            real_ids = [
                row[0] for row in
                conn.execute(select(test_table.c.id)).fetchall()
            ]

        self.assertEqual(len(expected_ids), len(real_ids))
        for id_ in expected_ids:
            self.assertIn(id_, real_ids)

    def test_drop_dup_entries_in_file_conn(self):
        table_name = "__test_tmp_table__"
        tmp_db_file = self.create_tempfiles([['name', '']], ext='.sql')[0]
        in_file_engine = session.EngineFacade(
            'sqlite:///%s' % tmp_db_file).get_engine()
        meta = MetaData()
        test_table, values = self._populate_db_for_drop_duplicate_entries(
            in_file_engine, meta, table_name)
        utils.drop_old_duplicate_entries_from_table(
            in_file_engine, table_name, False, 'b', 'c')

    def test_drop_old_duplicate_entries_from_table_soft_delete(self):
        table_name = "__test_tmp_table__"

        table, values = self._populate_db_for_drop_duplicate_entries(
            self.engine, self.meta, table_name)
        utils.drop_old_duplicate_entries_from_table(self.engine, table_name,
                                                    True, 'b', 'c')
        uniq_values = set()
        expected_values = []
        soft_deleted_values = []

        for value in sorted(values, key=lambda x: x['id'], reverse=True):
            uniq_value = (('b', value['b']), ('c', value['c']))
            if uniq_value in uniq_values:
                soft_deleted_values.append(value)
                continue
            uniq_values.add(uniq_value)
            expected_values.append(value)

        base_select = table.select()

        with self.engine.connect() as conn, conn.begin():
            rows_select = base_select.where(table.c.deleted != table.c.id)
            row_ids = [
                row.id for row in conn.execute(rows_select).fetchall()
            ]
            self.assertEqual(len(expected_values), len(row_ids))
            for value in expected_values:
                self.assertIn(value['id'], row_ids)

            deleted_rows_select = base_select.where(
                table.c.deleted == table.c.id)
            deleted_rows_ids = [
                row.id for row in
                conn.execute(deleted_rows_select).fetchall()
            ]
        self.assertEqual(len(values) - len(row_ids),
                         len(deleted_rows_ids))
        for value in soft_deleted_values:
            self.assertIn(value['id'], deleted_rows_ids)

    def test_change_deleted_column_type_does_not_drop_index(self):
        table_name = 'abc'

        indexes = {
            'idx_a_deleted': ['a', 'deleted'],
            'idx_b_deleted': ['b', 'deleted'],
            'idx_a': ['a']
        }

        index_instances = [Index(name, *columns)
                           for name, columns in indexes.items()]

        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('a', String(255)),
                      Column('b', String(255)),
                      Column('deleted', Boolean),
                      *index_instances)
        table.create(self.engine)
        utils.change_deleted_column_type_to_id_type(self.engine, table_name)
        utils.change_deleted_column_type_to_boolean(self.engine, table_name)

        insp = sqlalchemy.inspect(self.engine)
        real_indexes = insp.get_indexes(table_name)
        self.assertEqual(3, len(real_indexes))
        for index in real_indexes:
            name = index['name']
            self.assertIn(name, indexes)
            self.assertEqual(set(indexes[name]),
                             set(index['column_names']))

    def test_change_deleted_column_type_to_id_type_integer(self):
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('deleted', Boolean))
        table.create(self.engine)
        utils.change_deleted_column_type_to_id_type(self.engine, table_name)

        table = utils.get_table(self.engine, table_name)
        self.assertIsInstance(table.c.deleted.type, Integer)

    def test_change_deleted_column_type_to_id_type_string(self):
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', String(255), primary_key=True),
                      Column('deleted', Boolean))
        table.create(self.engine)
        utils.change_deleted_column_type_to_id_type(self.engine, table_name)

        table = utils.get_table(self.engine, table_name)
        self.assertIsInstance(table.c.deleted.type, String)

    @db_test_base.backend_specific('sqlite')
    def test_change_deleted_column_type_to_id_type_custom(self):
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('foo', CustomType),
                      Column('deleted', Boolean))
        table.create(self.engine)

        fooColumn = Column('foo', CustomType())
        utils.change_deleted_column_type_to_id_type(self.engine, table_name,
                                                    foo=fooColumn)

        table = utils.get_table(self.engine, table_name)

        self.assertIsInstance(table.c.deleted.type, Integer)

    def test_change_deleted_column_type_to_boolean(self):
        expected_types = {'mysql': mysql.TINYINT}
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('deleted', Integer))
        table.create(self.engine)

        utils.change_deleted_column_type_to_boolean(self.engine, table_name)

        table = utils.get_table(self.engine, table_name)
        self.assertIsInstance(table.c.deleted.type,
                              expected_types.get(self.engine.name, Boolean))

    def test_change_deleted_column_type_to_boolean_with_fc(self):
        expected_types = {'mysql': mysql.TINYINT}
        table_name_1 = 'abc'
        table_name_2 = 'bcd'

        table_1 = Table(table_name_1, self.meta,
                        Column('id', Integer, primary_key=True),
                        Column('deleted', Integer))
        table_1.create(self.engine)

        table_2 = Table(table_name_2, self.meta,
                        Column('id', Integer, primary_key=True),
                        Column('foreign_id', Integer,
                               ForeignKey('%s.id' % table_name_1)),
                        Column('deleted', Integer))
        table_2.create(self.engine)

        utils.change_deleted_column_type_to_boolean(self.engine, table_name_2)

        table = utils.get_table(self.engine, table_name_2)
        self.assertIsInstance(table.c.deleted.type,
                              expected_types.get(self.engine.name, Boolean))

    @db_test_base.backend_specific('sqlite')
    def test_change_deleted_column_type_to_boolean_type_custom(self):
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('foo', CustomType),
                      Column('deleted', Integer))
        table.create(self.engine)

        fooColumn = Column('foo', CustomType())
        utils.change_deleted_column_type_to_boolean(self.engine, table_name,
                                                    foo=fooColumn)

        table = utils.get_table(self.engine, table_name)
        self.assertIsInstance(table.c.deleted.type, Boolean)

    def test_detect_boolean_deleted_constraint_detection(self):
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('deleted', Boolean(create_constraint=True)))
        ck = [
            const for const in table.constraints if
            isinstance(const, CheckConstraint)][0]

        self.assertTrue(utils._is_deleted_column_constraint(ck))

        self.assertFalse(
            utils._is_deleted_column_constraint(
                CheckConstraint("deleted > 5")
            )
        )

    @db_test_base.backend_specific('sqlite')
    def test_change_deleted_column_type_sqlite_drops_check_constraint(self):
        table_name = 'abc'
        table = Table(table_name, self.meta,
                      Column('id', Integer, primary_key=True),
                      Column('deleted', Boolean))
        table.create(self.engine)

        utils._change_deleted_column_type_to_id_type_sqlite(self.engine,
                                                            table_name)
        table = Table(table_name, self.meta, autoload_with=self.engine)
        # NOTE(I159): if the CHECK constraint has been dropped (expected
        # behavior), any integer value can be inserted, otherwise only 1 or 0.
        # NOTE(zzzeek): SQLAlchemy 1.2 Boolean type will disallow non 1/0
        # value here, 1.1 also coerces to "1/0" so use raw SQL to test the
        # constraint
        with self.engine.connect() as conn, conn.begin():
            conn.exec_driver_sql(
                "INSERT INTO abc (deleted) VALUES (?)",
                (10, ),
            )

            self.assertEqual(
                10,
                conn.scalar(sql.text("SELECT deleted FROM abc")),
            )

    def test_get_foreign_key_constraint_name(self):
        table_1 = Table('table_name_1', self.meta,
                        Column('id', Integer, primary_key=True),
                        Column('deleted', Integer))
        table_2 = Table('table_name_2', self.meta,
                        Column('id', Integer, primary_key=True),
                        Column('foreign_id', Integer),
                        ForeignKeyConstraint(['foreign_id'],
                                             ['table_name_1.id'],
                                             name='table_name_2_fk1'),
                        Column('deleted', Integer))

        self.meta.create_all(self.engine, tables=[table_1, table_2])
        fkc = utils.get_foreign_key_constraint_name(self.engine,
                                                    'table_name_2',
                                                    'foreign_id')
        self.assertEqual(fkc, 'table_name_2_fk1')

    @db_test_base.backend_specific('mysql', 'postgresql')
    def test_suspend_fk_constraints_for_col_alter(self):

        a = Table(
            'a', self.meta,
            Column('id', Integer, primary_key=True)
        )
        b = Table(
            'b', self.meta,
            Column('key', Integer),
            Column('archive_id', Integer),
            Column('aid', ForeignKey('a.id')),
            PrimaryKeyConstraint("key", "archive_id")
        )
        c = Table(
            'c', self.meta,
            Column('id', Integer, primary_key=True),
            Column('aid', ForeignKey('a.id')),
            Column('key', Integer),
            Column('archive_id', Integer),
            ForeignKeyConstraint(
                ['key', 'archive_id'], ['b.key', 'b.archive_id'],
                name="some_composite_fk")
        )
        self.meta.create_all(self.engine, tables=[a, b, c])

        def get_fk_entries():
            inspector = sqlalchemy.inspect(self.engine)
            return sorted(
                inspector.get_foreign_keys('b') +
                inspector.get_foreign_keys('c'),
                key=lambda fk: fk['referred_table']
            )

        def normalize_fk_entries(fks):
            return [{
                    'name': fk['name'],
                    'referred_columns': fk['referred_columns'],
                    'referred_table': fk['referred_table'],
                    } for fk in fks]

        existing_foreign_keys = get_fk_entries()
        self.assertEqual(
            [{'name': mock.ANY,
              'referred_columns': ['id'], 'referred_table': 'a'},
                {'name': mock.ANY,
                 'referred_columns': ['id'], 'referred_table': 'a'},
                {'name': 'some_composite_fk',
                 'referred_columns': ['key', 'archive_id'],
                 'referred_table': 'b'}],
            normalize_fk_entries(existing_foreign_keys)
        )

        with mock.patch("oslo_db.sqlalchemy.ndb.ndb_status",
                        mock.Mock(return_value=True)):
            with utils.suspend_fk_constraints_for_col_alter(
                    self.engine, 'a', 'id', referents=['b', 'c']):
                no_a_foreign_keys = get_fk_entries()
                self.assertEqual(
                    [{'name': 'some_composite_fk',
                      'referred_columns': ['key', 'archive_id'],
                      'referred_table': 'b'}],
                    normalize_fk_entries(no_a_foreign_keys)
                )

        self.assertEqual(existing_foreign_keys, get_fk_entries())

        with mock.patch("oslo_db.sqlalchemy.ndb.ndb_status",
                        mock.Mock(return_value=True)):
            with utils.suspend_fk_constraints_for_col_alter(
                    self.engine, 'b', 'archive_id', referents=['c']):
                self.assertEqual(
                    [{'name': mock.ANY,
                      'referred_columns': ['id'], 'referred_table': 'a'},
                        {'name': mock.ANY,
                         'referred_columns': ['id'], 'referred_table': 'a'}],
                    normalize_fk_entries(get_fk_entries())
                )

        self.assertEqual(existing_foreign_keys, get_fk_entries())

        with utils.suspend_fk_constraints_for_col_alter(
                self.engine, 'a', 'id', referents=['b', 'c']):
            self.assertEqual(existing_foreign_keys, get_fk_entries())

        if self.engine.name == 'mysql':
            self.engine.dialect._oslodb_enable_ndb_support = True

            self.addCleanup(
                setattr, self.engine.dialect, "_oslodb_enable_ndb_support",
                False
            )

            with utils.suspend_fk_constraints_for_col_alter(
                    self.engine, 'a', 'id', referents=['b', 'c']):
                self.assertEqual(no_a_foreign_keys, get_fk_entries())


class PostgresqlTestMigrations(TestMigrationUtils,
                               db_test_base._PostgreSQLOpportunisticTestCase):

    """Test migrations on PostgreSQL."""
    pass


class MySQLTestMigrations(TestMigrationUtils,
                          db_test_base._MySQLOpportunisticTestCase):

    """Test migrations on MySQL."""
    pass


class TestConnectionUtils(test_base.BaseTestCase):

    def setUp(self):
        super(TestConnectionUtils, self).setUp()

        self.full_credentials = {'backend': 'postgresql',
                                 'database': 'test',
                                 'user': 'dude',
                                 'passwd': 'pass'}

        self.connect_string = 'postgresql://dude:pass@localhost/test'

        # NOTE(rpodolyaka): mock the dialect parts, so that we don't depend
        # on psycopg2 (or any other DBAPI implementation) in these tests

        @classmethod
        def fake_dbapi(cls):
            return mock.MagicMock()
        patch_dbapi = mock.patch.object(psycopg2.PGDialect_psycopg2, 'dbapi',
                                        new=fake_dbapi)
        patch_dbapi.start()
        self.addCleanup(patch_dbapi.stop)

        patch_onconnect = mock.patch.object(psycopg2.PGDialect_psycopg2,
                                            'on_connect')
        patch_onconnect.start()
        self.addCleanup(patch_onconnect.stop)

    def test_ensure_backend_available(self):
        with mock.patch.object(
                sqlalchemy.engine.base.Engine, 'connect') as mock_connect:
            fake_connection = mock.Mock()
            mock_connect.return_value = fake_connection

            eng = provision.Backend._ensure_backend_available(
                self.connect_string)

            self.assertIsInstance(eng, sqlalchemy.engine.base.Engine)
            self.assertEqual(self.connect_string, str(eng.url))

            mock_connect.assert_called_once()
            fake_connection.close.assert_called_once()

    def test_ensure_backend_available_no_connection_raises(self):
        log = self.useFixture(fixtures.FakeLogger())
        err = OperationalError("Can't connect to database", None, None)
        with mock.patch.object(
                sqlalchemy.engine.base.Engine, 'connect') as mock_connect:
            mock_connect.side_effect = err

            exc = self.assertRaises(
                exception.BackendNotAvailable,
                provision.Backend._ensure_backend_available,
                self.connect_string)
            self.assertEqual(
                "Backend 'postgresql' is unavailable: "
                "Could not connect", str(exc))
            self.assertEqual(
                "The postgresql backend is unavailable: %s" % err,
                log.output.strip())

    def test_ensure_backend_available_no_dbapi_raises(self):
        log = self.useFixture(fixtures.FakeLogger())
        with mock.patch.object(sqlalchemy, 'create_engine') as mock_create:
            mock_create.side_effect = ImportError(
                "Can't import DBAPI module foobar")

            exc = self.assertRaises(
                exception.BackendNotAvailable,
                provision.Backend._ensure_backend_available,
                self.connect_string)

            mock_create.assert_called_once_with(
                sa_url.make_url(self.connect_string))

            self.assertEqual(
                "Backend 'postgresql' is unavailable: "
                "No DBAPI installed", str(exc))
            self.assertEqual(
                "The postgresql backend is unavailable: Can't import "
                "DBAPI module foobar", log.output.strip())

    def test_get_db_connection_info(self):
        conn_pieces = parse.urlparse(self.connect_string)
        self.assertEqual(('dude', 'pass', 'test', 'localhost'),
                         utils.get_db_connection_info(conn_pieces))


class MyModelSoftDeletedProjectId(declarative_base(), models.ModelBase,
                                  models.SoftDeleteMixin):
    __tablename__ = 'soft_deleted_project_id_test_model'
    id = Column(Integer, primary_key=True)
    project_id = Column(Integer)


class MyModel(declarative_base(), models.ModelBase):
    __tablename__ = 'test_model'
    id = Column(Integer, primary_key=True)


class MyModelSoftDeleted(declarative_base(), models.ModelBase,
                         models.SoftDeleteMixin):
    __tablename__ = 'soft_deleted_test_model'
    id = Column(Integer, primary_key=True)


class TestModelQuery(test_base.BaseTestCase):

    def setUp(self):
        super(TestModelQuery, self).setUp()

        self.session = mock.MagicMock()
        self.session.query.return_value = self.session.query
        self.session.query.filter.return_value = self.session.query

    def test_wrong_model(self):
        self.assertRaises(TypeError, utils.model_query,
                          FakeModel, session=self.session)

    def test_no_soft_deleted(self):
        self.assertRaises(ValueError, utils.model_query,
                          MyModel, session=self.session, deleted=True)

    def test_deleted_false(self):
        mock_query = utils.model_query(
            MyModelSoftDeleted, session=self.session, deleted=False)

        deleted_filter = mock_query.filter.call_args[0][0]
        self.assertEqual('soft_deleted_test_model.deleted = :deleted_1',
                         str(deleted_filter))
        self.assertEqual(deleted_filter.right.value,
                         MyModelSoftDeleted.__mapper__.c.deleted.default.arg)

    def test_deleted_true(self):
        mock_query = utils.model_query(
            MyModelSoftDeleted, session=self.session, deleted=True)

        deleted_filter = mock_query.filter.call_args[0][0]
        self.assertEqual(str(deleted_filter),
                         'soft_deleted_test_model.deleted != :deleted_1')
        self.assertEqual(deleted_filter.right.value,
                         MyModelSoftDeleted.__mapper__.c.deleted.default.arg)

    @mock.patch.object(utils, "_read_deleted_filter")
    def test_no_deleted_value(self, _read_deleted_filter):
        utils.model_query(MyModelSoftDeleted, session=self.session)
        self.assertEqual(0, _read_deleted_filter.call_count)

    def test_project_filter(self):
        project_id = 10

        mock_query = utils.model_query(
            MyModelSoftDeletedProjectId, session=self.session,
            project_only=True, project_id=project_id)

        deleted_filter = mock_query.filter.call_args[0][0]
        self.assertEqual(
            'soft_deleted_project_id_test_model.project_id = :project_id_1',
            str(deleted_filter))
        self.assertEqual(project_id, deleted_filter.right.value)

    def test_project_filter_wrong_model(self):
        self.assertRaises(ValueError, utils.model_query,
                          MyModelSoftDeleted, session=self.session,
                          project_id=10)

    def test_project_filter_allow_none(self):
        mock_query = utils.model_query(
            MyModelSoftDeletedProjectId,
            session=self.session, project_id=(10, None))

        self.assertEqual(
            'soft_deleted_project_id_test_model.project_id'
            ' IN (:project_id_1, NULL)',
            str(mock_query.filter.call_args[0][0])
        )

    def test_model_query_common(self):
        utils.model_query(MyModel, args=(MyModel.id,), session=self.session)
        self.session.query.assert_called_with(MyModel.id)


class TestUtils(db_test_base._DbTestCase):
    def setUp(self):
        super(TestUtils, self).setUp()
        meta = MetaData()
        self.test_table = Table(
            'test_table',
            meta,
            Column('a', Integer),
            Column('b', Integer)
        )
        self.test_table.create(self.engine)
        self.addCleanup(meta.drop_all, self.engine)

    def test_get_indexes(self):
        Index('index_a', self.test_table.c.a).create(self.engine)
        Index('index_b', self.test_table.c.b).create(self.engine)
        indexes = utils.get_indexes(self.engine, "test_table")
        indexes = [(index['name'], index['column_names']) for index in indexes]
        self.assertIn(('index_a', ['a']), indexes)
        self.assertIn(('index_b', ['b']), indexes)

    def test_index_exists(self):
        self.assertFalse(utils.index_exists(self.engine, 'test_table',
                                            'new_index'))
        Index('new_index', self.test_table.c.a).create(self.engine)
        self.assertTrue(utils.index_exists(self.engine, 'test_table',
                                           'new_index'))

    def test_index_exists_on_columns(self):
        columns = [self.test_table.c.a, self.test_table.c.b]
        Index('new_index', *columns).create(self.engine)
        self.assertTrue(utils.index_exists_on_columns(self.engine,
                                                      'test_table',
                                                      ('a', 'b')))

    def test_add_index(self):
        self.assertFalse(utils.index_exists(self.engine, 'test_table',
                                            'new_index'))
        utils.add_index(self.engine, 'test_table', 'new_index', ('a',))
        self.assertTrue(utils.index_exists(self.engine, 'test_table',
                                           'new_index'))

    def test_add_existing_index(self):
        Index('new_index', self.test_table.c.a).create(self.engine)
        self.assertRaises(ValueError, utils.add_index, self.engine,
                          'test_table', 'new_index', ('a',))

    def test_drop_index(self):
        Index('new_index', self.test_table.c.a).create(self.engine)
        utils.drop_index(self.engine, 'test_table', 'new_index')
        self.assertFalse(utils.index_exists(self.engine, 'test_table',
                         'new_index'))

    def test_drop_unexisting_index(self):
        self.assertRaises(ValueError, utils.drop_index, self.engine,
                          'test_table', 'new_index')

    @mock.patch('oslo_db.sqlalchemy.utils.drop_index')
    @mock.patch('oslo_db.sqlalchemy.utils.add_index')
    def test_change_index_columns(self, add_index, drop_index):
        utils.change_index_columns(self.engine, 'test_table', 'a_index',
                                   ('a',))
        utils.drop_index.assert_called_once_with(self.engine, 'test_table',
                                                 'a_index')
        utils.add_index.assert_called_once_with(self.engine, 'test_table',
                                                'a_index', ('a',))

    def test_column_exists(self):
        for col in ['a', 'b']:
            self.assertTrue(utils.column_exists(self.engine, 'test_table',
                                                col))
        self.assertFalse(utils.column_exists(self.engine, 'test_table',
                                             'fake_column'))


class TestUtilsMysqlOpportunistically(
        TestUtils, db_test_base._MySQLOpportunisticTestCase):
    pass


class TestUtilsPostgresqlOpportunistically(
        TestUtils, db_test_base._PostgreSQLOpportunisticTestCase):
    pass


class TestDialectFunctionDispatcher(test_base.BaseTestCase):
    def _single_fixture(self):
        callable_fn = mock.Mock()

        dispatcher = orig = utils.dispatch_for_dialect("*")(
            callable_fn.default)
        dispatcher = dispatcher.dispatch_for("sqlite")(callable_fn.sqlite)
        dispatcher = dispatcher.dispatch_for("mysql+pymysql")(
            callable_fn.mysql_pymysql)
        dispatcher = dispatcher.dispatch_for("mysql")(
            callable_fn.mysql)
        dispatcher = dispatcher.dispatch_for("postgresql")(
            callable_fn.postgresql)

        self.assertTrue(dispatcher is orig)

        return dispatcher, callable_fn

    def _multiple_fixture(self):
        callable_fn = mock.Mock()

        for targ in [
            callable_fn.default,
            callable_fn.sqlite,
            callable_fn.mysql,
            callable_fn.mysql_pymysql,
            callable_fn.postgresql,
            callable_fn.postgresql_psycopg2,
            callable_fn.pyodbc
        ]:
            targ.return_value = None

        dispatcher = orig = utils.dispatch_for_dialect("*", multiple=True)(
            callable_fn.default)
        dispatcher = dispatcher.dispatch_for("sqlite")(callable_fn.sqlite)
        dispatcher = dispatcher.dispatch_for("mysql+pymysql")(
            callable_fn.mysql_pymysql)
        dispatcher = dispatcher.dispatch_for("mysql")(
            callable_fn.mysql)
        dispatcher = dispatcher.dispatch_for("postgresql+*")(
            callable_fn.postgresql)
        dispatcher = dispatcher.dispatch_for("postgresql+psycopg2")(
            callable_fn.postgresql_psycopg2)
        dispatcher = dispatcher.dispatch_for("*+pyodbc")(
            callable_fn.pyodbc)

        self.assertTrue(dispatcher is orig)

        return dispatcher, callable_fn

    def test_single(self):

        dispatcher, callable_fn = self._single_fixture()
        dispatcher("sqlite://", 1)
        dispatcher("postgresql+psycopg2://u:p@h/t", 2)
        dispatcher("mysql+pymysql://u:p@h/t", 3)
        dispatcher("mysql://u:p@h/t", 4)
        dispatcher("mysql+mysqlconnector://u:p@h/t", 5)

        self.assertEqual(
            [
                mock.call.sqlite('sqlite://', 1),
                mock.call.postgresql("postgresql+psycopg2://u:p@h/t", 2),
                mock.call.mysql_pymysql("mysql+pymysql://u:p@h/t", 3),
                mock.call.mysql("mysql://u:p@h/t", 4),
                mock.call.mysql("mysql+mysqlconnector://u:p@h/t", 5),
            ],
            callable_fn.mock_calls)

    def test_single_kwarg(self):
        dispatcher, callable_fn = self._single_fixture()
        dispatcher("sqlite://", foo='bar')
        dispatcher("postgresql+psycopg2://u:p@h/t", 1, x='y')

        self.assertEqual(
            [
                mock.call.sqlite('sqlite://', foo='bar'),
                mock.call.postgresql(
                    "postgresql+psycopg2://u:p@h/t",
                    1, x='y'),
            ],
            callable_fn.mock_calls)

    def test_dispatch_on_target(self):
        callable_fn = mock.Mock()

        @utils.dispatch_for_dialect("*")
        def default_fn(url, x, y):
            callable_fn.default(url, x, y)

        @default_fn.dispatch_for("sqlite")
        def sqlite_fn(url, x, y):
            callable_fn.sqlite(url, x, y)
            default_fn.dispatch_on_drivername("*")(url, x, y)

        default_fn("sqlite://", 4, 5)
        self.assertEqual(
            [
                mock.call.sqlite("sqlite://", 4, 5),
                mock.call.default("sqlite://", 4, 5)
            ],
            callable_fn.mock_calls
        )

    def test_single_no_dispatcher(self):
        callable_fn = mock.Mock()

        dispatcher = utils.dispatch_for_dialect("sqlite")(callable_fn.sqlite)
        dispatcher = dispatcher.dispatch_for("mysql")(callable_fn.mysql)
        exc = self.assertRaises(
            ValueError,
            dispatcher, "postgresql://s:t@localhost/test"
        )
        self.assertEqual(
            "No default function found for driver: 'postgresql+psycopg2'",
            str(exc)
        )

    def test_multiple_no_dispatcher(self):
        callable_fn = mock.Mock()

        dispatcher = utils.dispatch_for_dialect("sqlite", multiple=True)(
            callable_fn.sqlite)
        dispatcher = dispatcher.dispatch_for("mysql")(callable_fn.mysql)
        dispatcher("postgresql://s:t@localhost/test")
        self.assertEqual(
            [], callable_fn.mock_calls
        )

    def test_multiple_no_driver(self):
        callable_fn = mock.Mock(
            default=mock.Mock(return_value=None),
            sqlite=mock.Mock(return_value=None)
        )

        dispatcher = utils.dispatch_for_dialect("*", multiple=True)(
            callable_fn.default)
        dispatcher = dispatcher.dispatch_for("sqlite")(
            callable_fn.sqlite)

        dispatcher.dispatch_on_drivername("sqlite")("foo")
        self.assertEqual(
            [mock.call.sqlite("foo"), mock.call.default("foo")],
            callable_fn.mock_calls
        )

    def test_multiple_nesting(self):
        callable_fn = mock.Mock(
            default=mock.Mock(return_value=None),
            mysql=mock.Mock(return_value=None)
        )

        dispatcher = utils.dispatch_for_dialect("*", multiple=True)(
            callable_fn.default)

        dispatcher = dispatcher.dispatch_for("mysql+mysqlconnector")(
            dispatcher.dispatch_for("mysql+mysqldb")(
                callable_fn.mysql
            )
        )

        mysqldb_url = sqlalchemy.engine.url.make_url("mysql+mysqldb://")
        mysqlconnector_url = sqlalchemy.engine.url.make_url(
            "mysql+mysqlconnector://")
        sqlite_url = sqlalchemy.engine.url.make_url("sqlite://")

        dispatcher(mysqldb_url, 1)
        dispatcher(mysqlconnector_url, 2)
        dispatcher(sqlite_url, 3)

        self.assertEqual(
            [
                mock.call.mysql(mysqldb_url, 1),
                mock.call.default(mysqldb_url, 1),
                mock.call.mysql(mysqlconnector_url, 2),
                mock.call.default(mysqlconnector_url, 2),
                mock.call.default(sqlite_url, 3)
            ],
            callable_fn.mock_calls
        )

    def test_single_retval(self):
        dispatcher, callable_fn = self._single_fixture()
        callable_fn.mysql_pymysql.return_value = 5

        self.assertEqual(
            5, dispatcher("mysql+pymysql://u:p@h/t", 3)
        )

    def test_engine(self):
        eng = sqlalchemy.create_engine("sqlite:///path/to/my/db.db")
        dispatcher, callable_fn = self._single_fixture()

        dispatcher(eng)
        self.assertEqual(
            [mock.call.sqlite(eng)],
            callable_fn.mock_calls
        )

    def test_url_pymysql(self):
        url = sqlalchemy.engine.url.make_url(
            "mysql+pymysql://scott:tiger@localhost/test")
        dispatcher, callable_fn = self._single_fixture()

        dispatcher(url, 15)
        self.assertEqual(
            [mock.call.mysql_pymysql(url, 15)],
            callable_fn.mock_calls
        )

    def test_url_mysql_generic(self):
        url = sqlalchemy.engine.url.make_url(
            "mysql://scott:tiger@localhost/test")
        dispatcher, callable_fn = self._single_fixture()

        dispatcher(url, 15)
        self.assertEqual(
            [mock.call.mysql(url, 15)],
            callable_fn.mock_calls
        )

    def test_invalid_target(self):
        dispatcher, callable_fn = self._single_fixture()

        exc = self.assertRaises(
            ValueError,
            dispatcher, 20
        )
        self.assertEqual("Invalid target type: 20", str(exc))

    def test_invalid_dispatch(self):
        callable_fn = mock.Mock()

        dispatcher = utils.dispatch_for_dialect("*")(callable_fn.default)

        exc = self.assertRaises(
            ValueError,
            dispatcher.dispatch_for("+pyodbc"), callable_fn.pyodbc
        )
        self.assertEqual(
            "Couldn't parse database[+driver]: '+pyodbc'",
            str(exc)
        )

    def test_single_only_one_target(self):
        callable_fn = mock.Mock()

        dispatcher = utils.dispatch_for_dialect("*")(callable_fn.default)
        dispatcher = dispatcher.dispatch_for("sqlite")(callable_fn.sqlite)

        exc = self.assertRaises(
            TypeError,
            dispatcher.dispatch_for("sqlite"), callable_fn.sqlite2
        )
        self.assertEqual(
            "Multiple functions for expression 'sqlite'", str(exc)
        )

    def test_multiple(self):
        dispatcher, callable_fn = self._multiple_fixture()

        dispatcher("postgresql+pyodbc://", 1)
        dispatcher("mysql+pymysql://", 2)
        dispatcher("postgresql+psycopg2://", 4)
        dispatcher("postgresql://", 5)

        # TODO(zzzeek): there is a deterministic order here, but we might
        # want to tweak it, or maybe provide options.  default first?
        # most specific first?  is *+pyodbc or postgresql+* more specific?
        self.assertEqual(
            [
                mock.call.postgresql('postgresql+pyodbc://', 1),
                mock.call.pyodbc('postgresql+pyodbc://', 1),
                mock.call.default('postgresql+pyodbc://', 1),
                mock.call.mysql_pymysql('mysql+pymysql://', 2),
                mock.call.mysql('mysql+pymysql://', 2),
                mock.call.default('mysql+pymysql://', 2),
                mock.call.postgresql_psycopg2('postgresql+psycopg2://', 4),
                mock.call.postgresql('postgresql+psycopg2://', 4),
                mock.call.default('postgresql+psycopg2://', 4),
                # note this is called because we resolve the default
                # DBAPI for the url
                mock.call.postgresql_psycopg2('postgresql://', 5),
                mock.call.postgresql('postgresql://', 5),
                mock.call.default('postgresql://', 5),
            ],
            callable_fn.mock_calls
        )

    def test_multiple_no_return_value(self):
        dispatcher, callable_fn = self._multiple_fixture()
        callable_fn.sqlite.return_value = 5

        exc = self.assertRaises(
            TypeError,
            dispatcher, "sqlite://"
        )
        self.assertEqual(
            "Return value not allowed for multiple filtered function",
            str(exc)
        )


class TestGetInnoDBTables(db_test_base._MySQLOpportunisticTestCase):

    def test_all_tables_use_innodb(self):
        with self.engine.connect() as conn, conn.begin():
            conn.execute(
                sql.text(
                    "CREATE TABLE customers "
                    "(a INT, b CHAR (20), INDEX (a)) ENGINE=InnoDB"))
        self.assertEqual([], utils.get_non_innodb_tables(self.engine))

    def test_all_tables_use_innodb_false(self):
        with self.engine.connect() as conn, conn.begin():
            conn.execute(
                sql.text("CREATE TABLE employee (i INT) ENGINE=MEMORY")
            )
        self.assertEqual(['employee'],
                         utils.get_non_innodb_tables(self.engine))

    def test_skip_tables_use_default_value(self):
        with self.engine.connect() as conn, conn.begin():
            conn.execute(
                sql.text("CREATE TABLE migrate_version (i INT) ENGINE=MEMORY")
            )
        self.assertEqual([],
                         utils.get_non_innodb_tables(self.engine))

    def test_skip_tables_use_passed_value(self):
        with self.engine.connect() as conn, conn.begin():
            conn.execute(
                sql.text("CREATE TABLE some_table (i INT) ENGINE=MEMORY"))
        self.assertEqual([],
                         utils.get_non_innodb_tables(
                             self.engine, skip_tables=('some_table',)))

    def test_skip_tables_use_empty_list(self):
        with self.engine.connect() as conn, conn.begin():
            conn.execute(
                sql.text("CREATE TABLE some_table_3 (i INT) ENGINE=MEMORY"))
        self.assertEqual(['some_table_3'],
                         utils.get_non_innodb_tables(
                         self.engine, skip_tables=()))

    def test_skip_tables_use_several_values(self):
        with self.engine.connect() as conn, conn.begin():
            conn.execute(
                sql.text("CREATE TABLE some_table_1 (i INT) ENGINE=MEMORY"))
            conn.execute(
                sql.text("CREATE TABLE some_table_2 (i INT) ENGINE=MEMORY"))
        self.assertEqual([],
                         utils.get_non_innodb_tables(
                             self.engine,
                             skip_tables=('some_table_1', 'some_table_2')))