summaryrefslogtreecommitdiff
path: root/nova/db/sqlalchemy/api.py
blob: c5711285918299904e7b8e7f7f5d78df74220f7a (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
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.

"""Implementation of SQLAlchemy backend."""

import collections
import copy
import datetime
import functools
import inspect
import sys

from oslo_db import api as oslo_db_api
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import enginefacade
from oslo_db.sqlalchemy import update_match
from oslo_db.sqlalchemy import utils as sqlalchemyutils
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
import six
from six.moves import range
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy import Boolean
from sqlalchemy.exc import NoSuchTableError
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import or_
from sqlalchemy.orm import aliased
from sqlalchemy.orm import contains_eager
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import joinedload_all
from sqlalchemy.orm import noload
from sqlalchemy.orm import subqueryload
from sqlalchemy.orm import undefer
from sqlalchemy.schema import Table
from sqlalchemy import sql
from sqlalchemy.sql.expression import asc
from sqlalchemy.sql.expression import cast
from sqlalchemy.sql.expression import desc
from sqlalchemy.sql.expression import UpdateBase
from sqlalchemy.sql import false
from sqlalchemy.sql import func
from sqlalchemy.sql import null
from sqlalchemy.sql import true

from nova import block_device
from nova.compute import task_states
from nova.compute import vm_states
import nova.conf
import nova.context
from nova.db.sqlalchemy import models
from nova import exception
from nova.i18n import _
from nova import safe_utils

profiler_sqlalchemy = importutils.try_import('osprofiler.sqlalchemy')

CONF = nova.conf.CONF


LOG = logging.getLogger(__name__)

main_context_manager = enginefacade.transaction_context()
api_context_manager = enginefacade.transaction_context()


def _get_db_conf(conf_group, connection=None):
    kw = dict(conf_group.items())
    if connection is not None:
        kw['connection'] = connection
    return kw


def _context_manager_from_context(context):
    if context:
        try:
            return context.db_connection
        except AttributeError:
            pass


def configure(conf):
    main_context_manager.configure(**_get_db_conf(conf.database))
    api_context_manager.configure(**_get_db_conf(conf.api_database))

    if profiler_sqlalchemy and CONF.profiler.enabled \
            and CONF.profiler.trace_sqlalchemy:

        main_context_manager.append_on_engine_create(
            lambda eng: profiler_sqlalchemy.add_tracing(sa, eng, "db"))
        api_context_manager.append_on_engine_create(
            lambda eng: profiler_sqlalchemy.add_tracing(sa, eng, "db"))


def create_context_manager(connection=None):
    """Create a database context manager object.

    : param connection: The database connection string
    """
    ctxt_mgr = enginefacade.transaction_context()
    ctxt_mgr.configure(**_get_db_conf(CONF.database, connection=connection))
    return ctxt_mgr


def get_context_manager(context):
    """Get a database context manager object.

    :param context: The request context that can contain a context manager
    """
    return _context_manager_from_context(context) or main_context_manager


def get_engine(use_slave=False, context=None):
    """Get a database engine object.

    :param use_slave: Whether to use the slave connection
    :param context: The request context that can contain a context manager
    """
    ctxt_mgr = get_context_manager(context)
    return ctxt_mgr.get_legacy_facade().get_engine(use_slave=use_slave)


def get_api_engine():
    return api_context_manager.get_legacy_facade().get_engine()


_SHADOW_TABLE_PREFIX = 'shadow_'
_DEFAULT_QUOTA_NAME = 'default'
PER_PROJECT_QUOTAS = ['fixed_ips', 'floating_ips', 'networks']


def get_backend():
    """The backend is this module itself."""
    return sys.modules[__name__]


def require_context(f):
    """Decorator to require *any* user or admin context.

    This does no authorization for user or project access matching, see
    :py:func:`nova.context.authorize_project_context` and
    :py:func:`nova.context.authorize_user_context`.

    The first argument to the wrapped function must be the context.

    """

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        nova.context.require_context(args[0])
        return f(*args, **kwargs)
    return wrapper


def require_instance_exists_using_uuid(f):
    """Decorator to require the specified instance to exist.

    Requires the wrapped function to use context and instance_uuid as
    their first two arguments.
    """
    @functools.wraps(f)
    def wrapper(context, instance_uuid, *args, **kwargs):
        instance_get_by_uuid(context, instance_uuid)
        return f(context, instance_uuid, *args, **kwargs)

    return wrapper


def require_aggregate_exists(f):
    """Decorator to require the specified aggregate to exist.

    Requires the wrapped function to use context and aggregate_id as
    their first two arguments.
    """

    @functools.wraps(f)
    def wrapper(context, aggregate_id, *args, **kwargs):
        aggregate_get(context, aggregate_id)
        return f(context, aggregate_id, *args, **kwargs)
    return wrapper


def select_db_reader_mode(f):
    """Decorator to select synchronous or asynchronous reader mode.

    The kwarg argument 'use_slave' defines reader mode. Asynchronous reader
    will be used if 'use_slave' is True and synchronous reader otherwise.
    If 'use_slave' is not specified default value 'False' will be used.

    Wrapped function must have a context in the arguments.
    """

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        wrapped_func = safe_utils.get_wrapped_function(f)
        keyed_args = inspect.getcallargs(wrapped_func, *args, **kwargs)

        context = keyed_args['context']
        use_slave = keyed_args.get('use_slave', False)

        if use_slave:
            reader_mode = get_context_manager(context).async
        else:
            reader_mode = get_context_manager(context).reader

        with reader_mode.using(context):
            return f(*args, **kwargs)
    return wrapper


def pick_context_manager_writer(f):
    """Decorator to use a writer db context manager.

    The db context manager will be picked from the RequestContext.

    Wrapped function must have a RequestContext in the arguments.
    """
    @functools.wraps(f)
    def wrapped(context, *args, **kwargs):
        ctxt_mgr = get_context_manager(context)
        with ctxt_mgr.writer.using(context):
            return f(context, *args, **kwargs)
    return wrapped


def pick_context_manager_reader(f):
    """Decorator to use a reader db context manager.

    The db context manager will be picked from the RequestContext.

    Wrapped function must have a RequestContext in the arguments.
    """
    @functools.wraps(f)
    def wrapped(context, *args, **kwargs):
        ctxt_mgr = get_context_manager(context)
        with ctxt_mgr.reader.using(context):
            return f(context, *args, **kwargs)
    return wrapped


def pick_context_manager_reader_allow_async(f):
    """Decorator to use a reader.allow_async db context manager.

    The db context manager will be picked from the RequestContext.

    Wrapped function must have a RequestContext in the arguments.
    """
    @functools.wraps(f)
    def wrapped(context, *args, **kwargs):
        ctxt_mgr = get_context_manager(context)
        with ctxt_mgr.reader.allow_async.using(context):
            return f(context, *args, **kwargs)
    return wrapped


def model_query(context, model,
                args=None,
                read_deleted=None,
                project_only=False):
    """Query helper that accounts for context's `read_deleted` field.

    :param context:     NovaContext of the query.
    :param model:       Model to query. Must be a subclass of ModelBase.
    :param args:        Arguments to query. If None - model is used.
    :param read_deleted: If not None, overrides context's read_deleted field.
                        Permitted values are 'no', which does not return
                        deleted values; 'only', which only returns deleted
                        values; and 'yes', which does not filter deleted
                        values.
    :param project_only: If set and context is user-type, then restrict
                        query to match the context's project_id. If set to
                        'allow_none', restriction includes project_id = None.
    """

    if read_deleted is None:
        read_deleted = context.read_deleted

    query_kwargs = {}
    if 'no' == read_deleted:
        query_kwargs['deleted'] = False
    elif 'only' == read_deleted:
        query_kwargs['deleted'] = True
    elif 'yes' == read_deleted:
        pass
    else:
        raise ValueError(_("Unrecognized read_deleted value '%s'")
                           % read_deleted)

    query = sqlalchemyutils.model_query(
        model, context.session, args, **query_kwargs)

    # We can't use oslo.db model_query's project_id here, as it doesn't allow
    # us to return both our projects and unowned projects.
    if nova.context.is_user_context(context) and project_only:
        if project_only == 'allow_none':
            query = query.\
                filter(or_(model.project_id == context.project_id,
                           model.project_id == null()))
        else:
            query = query.filter_by(project_id=context.project_id)

    return query


def convert_objects_related_datetimes(values, *datetime_keys):
    if not datetime_keys:
        datetime_keys = ('created_at', 'deleted_at', 'updated_at')

    for key in datetime_keys:
        if key in values and values[key]:
            if isinstance(values[key], six.string_types):
                try:
                    values[key] = timeutils.parse_strtime(values[key])
                except ValueError:
                    # Try alternate parsing since parse_strtime will fail
                    # with say converting '2015-05-28T19:59:38+00:00'
                    values[key] = timeutils.parse_isotime(values[key])
            # NOTE(danms): Strip UTC timezones from datetimes, since they're
            # stored that way in the database
            values[key] = values[key].replace(tzinfo=None)
    return values


###################


def constraint(**conditions):
    return Constraint(conditions)


def equal_any(*values):
    return EqualityCondition(values)


def not_equal(*values):
    return InequalityCondition(values)


class Constraint(object):

    def __init__(self, conditions):
        self.conditions = conditions

    def apply(self, model, query):
        for key, condition in self.conditions.items():
            for clause in condition.clauses(getattr(model, key)):
                query = query.filter(clause)
        return query


class EqualityCondition(object):

    def __init__(self, values):
        self.values = values

    def clauses(self, field):
        # method signature requires us to return an iterable even if for OR
        # operator this will actually be a single clause
        return [or_(*[field == value for value in self.values])]


class InequalityCondition(object):

    def __init__(self, values):
        self.values = values

    def clauses(self, field):
        return [field != value for value in self.values]


class DeleteFromSelect(UpdateBase):
    def __init__(self, table, select, column):
        self.table = table
        self.select = select
        self.column = column


# NOTE(guochbo): some versions of MySQL doesn't yet support subquery with
# 'LIMIT & IN/ALL/ANY/SOME' We need work around this with nesting select .
@compiles(DeleteFromSelect)
def visit_delete_from_select(element, compiler, **kw):
    return "DELETE FROM %s WHERE %s in (SELECT T1.%s FROM (%s) as T1)" % (
        compiler.process(element.table, asfrom=True),
        compiler.process(element.column),
        element.column.name,
        compiler.process(element.select))

###################


@pick_context_manager_writer
def service_destroy(context, service_id):
    service = service_get(context, service_id)

    model_query(context, models.Service).\
                filter_by(id=service_id).\
                soft_delete(synchronize_session=False)

    if service.binary == 'nova-compute':
        # TODO(sbauza): Remove the service_id filter in a later release
        # once we are sure that all compute nodes report the host field
        model_query(context, models.ComputeNode).\
                    filter(or_(models.ComputeNode.service_id == service_id,
                               models.ComputeNode.host == service['host'])).\
                    soft_delete(synchronize_session=False)


@pick_context_manager_reader
def service_get(context, service_id):
    query = model_query(context, models.Service).filter_by(id=service_id)

    result = query.first()
    if not result:
        raise exception.ServiceNotFound(service_id=service_id)

    return result


@pick_context_manager_reader
def service_get_by_uuid(context, service_uuid):
    query = model_query(context, models.Service).filter_by(uuid=service_uuid)

    result = query.first()
    if not result:
        raise exception.ServiceNotFound(service_id=service_uuid)

    return result


@pick_context_manager_reader_allow_async
def service_get_minimum_version(context, binaries):
    min_versions = context.session.query(
        models.Service.binary,
        func.min(models.Service.version)).\
                         filter(models.Service.binary.in_(binaries)).\
                         filter(models.Service.deleted == 0).\
                         filter(models.Service.forced_down == false()).\
                         group_by(models.Service.binary)
    return dict(min_versions)


@pick_context_manager_reader
def service_get_all(context, disabled=None):
    query = model_query(context, models.Service)

    if disabled is not None:
        query = query.filter_by(disabled=disabled)

    return query.all()


@pick_context_manager_reader
def service_get_all_by_topic(context, topic):
    return model_query(context, models.Service, read_deleted="no").\
                filter_by(disabled=False).\
                filter_by(topic=topic).\
                all()


@pick_context_manager_reader
def service_get_by_host_and_topic(context, host, topic):
    return model_query(context, models.Service, read_deleted="no").\
                filter_by(disabled=False).\
                filter_by(host=host).\
                filter_by(topic=topic).\
                first()


@pick_context_manager_reader
def service_get_all_by_binary(context, binary, include_disabled=False):
    query = model_query(context, models.Service).filter_by(binary=binary)
    if not include_disabled:
        query = query.filter_by(disabled=False)
    return query.all()


@pick_context_manager_reader
def service_get_all_computes_by_hv_type(context, hv_type,
                                        include_disabled=False):
    query = model_query(context, models.Service, read_deleted="no").\
                    filter_by(binary='nova-compute')
    if not include_disabled:
        query = query.filter_by(disabled=False)
    query = query.join(models.ComputeNode,
                       models.Service.host == models.ComputeNode.host).\
                  filter(models.ComputeNode.hypervisor_type == hv_type).\
                  distinct('host')
    return query.all()


@pick_context_manager_reader
def service_get_by_host_and_binary(context, host, binary):
    result = model_query(context, models.Service, read_deleted="no").\
                    filter_by(host=host).\
                    filter_by(binary=binary).\
                    first()

    if not result:
        raise exception.HostBinaryNotFound(host=host, binary=binary)

    return result


@pick_context_manager_reader
def service_get_all_by_host(context, host):
    return model_query(context, models.Service, read_deleted="no").\
                filter_by(host=host).\
                all()


@pick_context_manager_reader_allow_async
def service_get_by_compute_host(context, host):
    result = model_query(context, models.Service, read_deleted="no").\
                filter_by(host=host).\
                filter_by(binary='nova-compute').\
                first()

    if not result:
        raise exception.ComputeHostNotFound(host=host)

    return result


@pick_context_manager_writer
def service_create(context, values):
    service_ref = models.Service()
    service_ref.update(values)
    # We only auto-disable nova-compute services since those are the only
    # ones that can be enabled using the os-services REST API and they are
    # the only ones where being disabled means anything. It does
    # not make sense to be able to disable non-compute services like
    # nova-scheduler or nova-osapi_compute since that does nothing.
    if not CONF.enable_new_services and values.get('binary') == 'nova-compute':
        msg = _("New compute service disabled due to config option.")
        service_ref.disabled = True
        service_ref.disabled_reason = msg
    try:
        service_ref.save(context.session)
    except db_exc.DBDuplicateEntry as e:
        if 'binary' in e.columns:
            raise exception.ServiceBinaryExists(host=values.get('host'),
                        binary=values.get('binary'))
        raise exception.ServiceTopicExists(host=values.get('host'),
                        topic=values.get('topic'))
    return service_ref


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def service_update(context, service_id, values):
    service_ref = service_get(context, service_id)
    # Only servicegroup.drivers.db.DbDriver._report_state() updates
    # 'report_count', so if that value changes then store the timestamp
    # as the last time we got a state report.
    if 'report_count' in values:
        if values['report_count'] > service_ref.report_count:
            service_ref.last_seen_up = timeutils.utcnow()
    service_ref.update(values)

    return service_ref


###################


def _compute_node_select(context, filters=None, limit=None, marker=None):
    if filters is None:
        filters = {}

    cn_tbl = sa.alias(models.ComputeNode.__table__, name='cn')
    select = sa.select([cn_tbl])

    if context.read_deleted == "no":
        select = select.where(cn_tbl.c.deleted == 0)
    if "compute_id" in filters:
        select = select.where(cn_tbl.c.id == filters["compute_id"])
    if "service_id" in filters:
        select = select.where(cn_tbl.c.service_id == filters["service_id"])
    if "host" in filters:
        select = select.where(cn_tbl.c.host == filters["host"])
    if "hypervisor_hostname" in filters:
        hyp_hostname = filters["hypervisor_hostname"]
        select = select.where(cn_tbl.c.hypervisor_hostname == hyp_hostname)
    if "mapped" in filters:
        select = select.where(cn_tbl.c.mapped < filters['mapped'])
    if marker is not None:
        try:
            compute_node_get(context, marker)
        except exception.ComputeHostNotFound:
            raise exception.MarkerNotFound(marker=marker)
        select = select.where(cn_tbl.c.id > marker)
    if limit is not None:
        select = select.limit(limit)
    # Explicitly order by id, so we're not dependent on the native sort
    # order of the underlying DB.
    select = select.order_by(asc("id"))
    return select


def _compute_node_fetchall(context, filters=None, limit=None, marker=None):
    select = _compute_node_select(context, filters, limit=limit, marker=marker)
    engine = get_engine(context=context)
    conn = engine.connect()

    results = conn.execute(select).fetchall()

    # Callers expect dict-like objects, not SQLAlchemy RowProxy objects...
    results = [dict(r) for r in results]
    conn.close()
    return results


@pick_context_manager_reader
def compute_node_get(context, compute_id):
    results = _compute_node_fetchall(context, {"compute_id": compute_id})
    if not results:
        raise exception.ComputeHostNotFound(host=compute_id)
    return results[0]


@pick_context_manager_reader
def compute_node_get_model(context, compute_id):
    # TODO(edleafe): remove once the compute node resource provider migration
    # is complete, and this distinction is no longer necessary.
    result = model_query(context, models.ComputeNode).\
            filter_by(id=compute_id).\
            first()
    if not result:
        raise exception.ComputeHostNotFound(host=compute_id)
    return result


@pick_context_manager_reader
def compute_nodes_get_by_service_id(context, service_id):
    results = _compute_node_fetchall(context, {"service_id": service_id})
    if not results:
        raise exception.ServiceNotFound(service_id=service_id)
    return results


@pick_context_manager_reader
def compute_node_get_by_host_and_nodename(context, host, nodename):
    results = _compute_node_fetchall(context,
            {"host": host, "hypervisor_hostname": nodename})
    if not results:
        raise exception.ComputeHostNotFound(host=host)
    return results[0]


@pick_context_manager_reader_allow_async
def compute_node_get_all_by_host(context, host):
    results = _compute_node_fetchall(context, {"host": host})
    if not results:
        raise exception.ComputeHostNotFound(host=host)
    return results


@pick_context_manager_reader
def compute_node_get_all(context):
    return _compute_node_fetchall(context)


@pick_context_manager_reader
def compute_node_get_all_mapped_less_than(context, mapped_less_than):
    return _compute_node_fetchall(context,
                                  {'mapped': mapped_less_than})


@pick_context_manager_reader
def compute_node_get_all_by_pagination(context, limit=None, marker=None):
    return _compute_node_fetchall(context, limit=limit, marker=marker)


@pick_context_manager_reader
def compute_node_search_by_hypervisor(context, hypervisor_match):
    field = models.ComputeNode.hypervisor_hostname
    return model_query(context, models.ComputeNode).\
            filter(field.like('%%%s%%' % hypervisor_match)).\
            all()


@pick_context_manager_writer
def compute_node_create(context, values):
    """Creates a new ComputeNode and populates the capacity fields
    with the most recent data.
    """
    convert_objects_related_datetimes(values)

    compute_node_ref = models.ComputeNode()
    compute_node_ref.update(values)
    compute_node_ref.save(context.session)

    return compute_node_ref


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def compute_node_update(context, compute_id, values):
    """Updates the ComputeNode record with the most recent data."""

    compute_ref = compute_node_get_model(context, compute_id)
    # Always update this, even if there's going to be no other
    # changes in data.  This ensures that we invalidate the
    # scheduler cache of compute node data in case of races.
    values['updated_at'] = timeutils.utcnow()
    convert_objects_related_datetimes(values)
    compute_ref.update(values)

    return compute_ref


@pick_context_manager_writer
def compute_node_delete(context, compute_id):
    """Delete a ComputeNode record."""
    result = model_query(context, models.ComputeNode).\
             filter_by(id=compute_id).\
             soft_delete(synchronize_session=False)

    if not result:
        raise exception.ComputeHostNotFound(host=compute_id)


@pick_context_manager_reader
def compute_node_statistics(context):
    """Compute statistics over all compute nodes."""
    engine = get_engine(context=context)
    services_tbl = models.Service.__table__

    inner_sel = sa.alias(_compute_node_select(context), name='inner_sel')

    # TODO(sbauza): Remove the service_id filter in a later release
    # once we are sure that all compute nodes report the host field
    j = sa.join(
        inner_sel, services_tbl,
        sql.and_(
            sql.or_(
                inner_sel.c.host == services_tbl.c.host,
                inner_sel.c.service_id == services_tbl.c.id
            ),
            services_tbl.c.disabled == false(),
            services_tbl.c.binary == 'nova-compute',
            services_tbl.c.deleted == 0
        )
    )

    # NOTE(jaypipes): This COALESCE() stuff is temporary while the data
    # migration to the new resource providers inventories and allocations
    # tables is completed.
    agg_cols = [
        func.count().label('count'),
        sql.func.sum(
            inner_sel.c.vcpus
        ).label('vcpus'),
        sql.func.sum(
            inner_sel.c.memory_mb
        ).label('memory_mb'),
        sql.func.sum(
            inner_sel.c.local_gb
        ).label('local_gb'),
        sql.func.sum(
            inner_sel.c.vcpus_used
        ).label('vcpus_used'),
        sql.func.sum(
            inner_sel.c.memory_mb_used
        ).label('memory_mb_used'),
        sql.func.sum(
            inner_sel.c.local_gb_used
        ).label('local_gb_used'),
        sql.func.sum(
            inner_sel.c.free_ram_mb
        ).label('free_ram_mb'),
        sql.func.sum(
            inner_sel.c.free_disk_gb
        ).label('free_disk_gb'),
        sql.func.sum(
            inner_sel.c.current_workload
        ).label('current_workload'),
        sql.func.sum(
            inner_sel.c.running_vms
        ).label('running_vms'),
        sql.func.sum(
            inner_sel.c.disk_available_least
        ).label('disk_available_least'),
    ]
    select = sql.select(agg_cols).select_from(j)
    conn = engine.connect()

    results = conn.execute(select).fetchone()

    # Build a dict of the info--making no assumptions about result
    fields = ('count', 'vcpus', 'memory_mb', 'local_gb', 'vcpus_used',
              'memory_mb_used', 'local_gb_used', 'free_ram_mb', 'free_disk_gb',
              'current_workload', 'running_vms', 'disk_available_least')
    results = {field: int(results[idx] or 0)
               for idx, field in enumerate(fields)}
    conn.close()
    return results


###################


@pick_context_manager_writer
def certificate_create(context, values):
    certificate_ref = models.Certificate()
    for (key, value) in values.items():
        certificate_ref[key] = value
    certificate_ref.save(context.session)
    return certificate_ref


@pick_context_manager_reader
def certificate_get_all_by_project(context, project_id):
    return model_query(context, models.Certificate, read_deleted="no").\
                   filter_by(project_id=project_id).\
                   all()


@pick_context_manager_reader
def certificate_get_all_by_user(context, user_id):
    return model_query(context, models.Certificate, read_deleted="no").\
                   filter_by(user_id=user_id).\
                   all()


@pick_context_manager_reader
def certificate_get_all_by_user_and_project(context, user_id, project_id):
    return model_query(context, models.Certificate, read_deleted="no").\
                   filter_by(user_id=user_id).\
                   filter_by(project_id=project_id).\
                   all()


###################


@require_context
@pick_context_manager_reader
def floating_ip_get(context, id):
    try:
        result = model_query(context, models.FloatingIp, project_only=True).\
                     filter_by(id=id).\
                     options(joinedload_all('fixed_ip.instance')).\
                     first()

        if not result:
            raise exception.FloatingIpNotFound(id=id)
    except db_exc.DBError:
        LOG.warning("Invalid floating IP ID %s in request", id)
        raise exception.InvalidID(id=id)
    return result


@require_context
@pick_context_manager_reader
def floating_ip_get_pools(context):
    pools = []
    for result in model_query(context, models.FloatingIp,
                              (models.FloatingIp.pool,)).distinct():
        pools.append({'name': result[0]})
    return pools


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def floating_ip_allocate_address(context, project_id, pool,
                                 auto_assigned=False):
    nova.context.authorize_project_context(context, project_id)
    floating_ip_ref = model_query(context, models.FloatingIp,
                                  read_deleted="no").\
        filter_by(fixed_ip_id=None).\
        filter_by(project_id=None).\
        filter_by(pool=pool).\
        first()

    if not floating_ip_ref:
        raise exception.NoMoreFloatingIps()

    params = {'project_id': project_id, 'auto_assigned': auto_assigned}

    rows_update = model_query(context, models.FloatingIp, read_deleted="no").\
        filter_by(id=floating_ip_ref['id']).\
        filter_by(fixed_ip_id=None).\
        filter_by(project_id=None).\
        filter_by(pool=pool).\
        update(params, synchronize_session='evaluate')

    if not rows_update:
        LOG.debug('The row was updated in a concurrent transaction, '
                  'we will fetch another one')
        raise db_exc.RetryRequest(exception.FloatingIpAllocateFailed())

    return floating_ip_ref['address']


@require_context
@pick_context_manager_writer
def floating_ip_bulk_create(context, ips, want_result=True):
    try:
        tab = models.FloatingIp().__table__
        context.session.execute(tab.insert(), ips)
    except db_exc.DBDuplicateEntry as e:
        raise exception.FloatingIpExists(address=e.value)

    if want_result:
        return model_query(context, models.FloatingIp).filter(
            models.FloatingIp.address.in_(
                [ip['address'] for ip in ips])).all()


def _ip_range_splitter(ips, block_size=256):
    """Yields blocks of IPs no more than block_size elements long."""
    out = []
    count = 0
    for ip in ips:
        out.append(ip['address'])
        count += 1

        if count > block_size - 1:
            yield out
            out = []
            count = 0

    if out:
        yield out


@require_context
@pick_context_manager_writer
def floating_ip_bulk_destroy(context, ips):
    project_id_to_quota_count = collections.defaultdict(int)
    for ip_block in _ip_range_splitter(ips):
        # Find any floating IPs that were not auto_assigned and
        # thus need quota released.
        query = model_query(context, models.FloatingIp).\
            filter(models.FloatingIp.address.in_(ip_block)).\
            filter_by(auto_assigned=False)
        for row in query.all():
            # The count is negative since we release quota by
            # reserving negative quota.
            project_id_to_quota_count[row['project_id']] -= 1
        # Delete the floating IPs.
        model_query(context, models.FloatingIp).\
            filter(models.FloatingIp.address.in_(ip_block)).\
            soft_delete(synchronize_session='fetch')


@require_context
@pick_context_manager_writer
def floating_ip_create(context, values):
    floating_ip_ref = models.FloatingIp()
    floating_ip_ref.update(values)
    try:
        floating_ip_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.FloatingIpExists(address=values['address'])
    return floating_ip_ref


def _floating_ip_count_by_project(context, project_id):
    nova.context.authorize_project_context(context, project_id)
    # TODO(tr3buchet): why leave auto_assigned floating IPs out?
    return model_query(context, models.FloatingIp, read_deleted="no").\
                   filter_by(project_id=project_id).\
                   filter_by(auto_assigned=False).\
                   count()


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def floating_ip_fixed_ip_associate(context, floating_address,
                                   fixed_address, host):
    fixed_ip_ref = model_query(context, models.FixedIp).\
                     filter_by(address=fixed_address).\
                     options(joinedload('network')).\
                     first()
    if not fixed_ip_ref:
        raise exception.FixedIpNotFoundForAddress(address=fixed_address)
    rows = model_query(context, models.FloatingIp).\
                filter_by(address=floating_address).\
                filter(models.FloatingIp.project_id ==
                       context.project_id).\
                filter(or_(models.FloatingIp.fixed_ip_id ==
                           fixed_ip_ref['id'],
                           models.FloatingIp.fixed_ip_id.is_(None))).\
                update({'fixed_ip_id': fixed_ip_ref['id'], 'host': host})

    if not rows:
        raise exception.FloatingIpAssociateFailed(address=floating_address)

    return fixed_ip_ref


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def floating_ip_deallocate(context, address):
    return model_query(context, models.FloatingIp).\
        filter_by(address=address).\
        filter(and_(models.FloatingIp.project_id != null()),
                    models.FloatingIp.fixed_ip_id == null()).\
        update({'project_id': None,
                'host': None,
                'auto_assigned': False},
               synchronize_session=False)


@require_context
@pick_context_manager_writer
def floating_ip_destroy(context, address):
    model_query(context, models.FloatingIp).\
            filter_by(address=address).\
            delete()


@require_context
@pick_context_manager_writer
def floating_ip_disassociate(context, address):
    floating_ip_ref = model_query(context,
                                  models.FloatingIp).\
                        filter_by(address=address).\
                        first()
    if not floating_ip_ref:
        raise exception.FloatingIpNotFoundForAddress(address=address)

    fixed_ip_ref = model_query(context, models.FixedIp).\
        filter_by(id=floating_ip_ref['fixed_ip_id']).\
        options(joinedload('network')).\
        first()
    floating_ip_ref.fixed_ip_id = None
    floating_ip_ref.host = None

    return fixed_ip_ref


def _floating_ip_get_all(context):
    return model_query(context, models.FloatingIp, read_deleted="no")


@pick_context_manager_reader
def floating_ip_get_all(context):
    floating_ip_refs = _floating_ip_get_all(context).\
                       options(joinedload('fixed_ip')).\
                       all()
    if not floating_ip_refs:
        raise exception.NoFloatingIpsDefined()
    return floating_ip_refs


@pick_context_manager_reader
def floating_ip_get_all_by_host(context, host):
    floating_ip_refs = _floating_ip_get_all(context).\
                       filter_by(host=host).\
                       options(joinedload('fixed_ip')).\
                       all()
    if not floating_ip_refs:
        raise exception.FloatingIpNotFoundForHost(host=host)
    return floating_ip_refs


@require_context
@pick_context_manager_reader
def floating_ip_get_all_by_project(context, project_id):
    nova.context.authorize_project_context(context, project_id)
    # TODO(tr3buchet): why do we not want auto_assigned floating IPs here?
    return _floating_ip_get_all(context).\
                         filter_by(project_id=project_id).\
                         filter_by(auto_assigned=False).\
                         options(joinedload_all('fixed_ip.instance')).\
                         all()


@require_context
@pick_context_manager_reader
def floating_ip_get_by_address(context, address):
    return _floating_ip_get_by_address(context, address)


def _floating_ip_get_by_address(context, address):

    # if address string is empty explicitly set it to None
    if not address:
        address = None
    try:
        result = model_query(context, models.FloatingIp).\
                    filter_by(address=address).\
                    options(joinedload_all('fixed_ip.instance')).\
                    first()

        if not result:
            raise exception.FloatingIpNotFoundForAddress(address=address)
    except db_exc.DBError:
        msg = _("Invalid floating IP %s in request") % address
        LOG.warning(msg)
        raise exception.InvalidIpAddressError(msg)

    # If the floating IP has a project ID set, check to make sure
    # the non-admin user has access.
    if result.project_id and nova.context.is_user_context(context):
        nova.context.authorize_project_context(context, result.project_id)

    return result


@require_context
@pick_context_manager_reader
def floating_ip_get_by_fixed_address(context, fixed_address):
    return model_query(context, models.FloatingIp).\
                       outerjoin(models.FixedIp,
                                 models.FixedIp.id ==
                                 models.FloatingIp.fixed_ip_id).\
                       filter(models.FixedIp.address == fixed_address).\
                       all()


@require_context
@pick_context_manager_reader
def floating_ip_get_by_fixed_ip_id(context, fixed_ip_id):
    return model_query(context, models.FloatingIp).\
                filter_by(fixed_ip_id=fixed_ip_id).\
                all()


@require_context
@pick_context_manager_writer
def floating_ip_update(context, address, values):
    float_ip_ref = _floating_ip_get_by_address(context, address)
    float_ip_ref.update(values)
    try:
        float_ip_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.FloatingIpExists(address=values['address'])
    return float_ip_ref


###################


@require_context
@pick_context_manager_reader
def dnsdomain_get(context, fqdomain):
    return model_query(context, models.DNSDomain, read_deleted="no").\
               filter_by(domain=fqdomain).\
               with_lockmode('update').\
               first()


def _dnsdomain_get_or_create(context, fqdomain):
    domain_ref = dnsdomain_get(context, fqdomain)
    if not domain_ref:
        dns_ref = models.DNSDomain()
        dns_ref.update({'domain': fqdomain,
                        'availability_zone': None,
                        'project_id': None})
        return dns_ref

    return domain_ref


@pick_context_manager_writer
def dnsdomain_register_for_zone(context, fqdomain, zone):
    domain_ref = _dnsdomain_get_or_create(context, fqdomain)
    domain_ref.scope = 'private'
    domain_ref.availability_zone = zone
    context.session.add(domain_ref)


@pick_context_manager_writer
def dnsdomain_register_for_project(context, fqdomain, project):
    domain_ref = _dnsdomain_get_or_create(context, fqdomain)
    domain_ref.scope = 'public'
    domain_ref.project_id = project
    context.session.add(domain_ref)


@pick_context_manager_writer
def dnsdomain_unregister(context, fqdomain):
    model_query(context, models.DNSDomain).\
                 filter_by(domain=fqdomain).\
                 delete()


@pick_context_manager_reader
def dnsdomain_get_all(context):
    return model_query(context, models.DNSDomain, read_deleted="no").all()


###################


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def fixed_ip_associate(context, address, instance_uuid, network_id=None,
                       reserved=False, virtual_interface_id=None):
    """Keyword arguments:
    reserved -- should be a boolean value(True or False), exact value will be
    used to filter on the fixed IP address
    """
    if not uuidutils.is_uuid_like(instance_uuid):
        raise exception.InvalidUUID(uuid=instance_uuid)

    network_or_none = or_(models.FixedIp.network_id == network_id,
                          models.FixedIp.network_id == null())
    fixed_ip_ref = model_query(context, models.FixedIp, read_deleted="no").\
                           filter(network_or_none).\
                           filter_by(reserved=reserved).\
                           filter_by(address=address).\
                           first()

    if fixed_ip_ref is None:
        raise exception.FixedIpNotFoundForNetwork(address=address,
                                        network_uuid=network_id)
    if fixed_ip_ref.instance_uuid:
        raise exception.FixedIpAlreadyInUse(address=address,
                                            instance_uuid=instance_uuid)

    params = {'instance_uuid': instance_uuid,
              'allocated': virtual_interface_id is not None}
    if not fixed_ip_ref.network_id:
        params['network_id'] = network_id
    if virtual_interface_id:
        params['virtual_interface_id'] = virtual_interface_id

    rows_updated = model_query(context, models.FixedIp, read_deleted="no").\
                            filter_by(id=fixed_ip_ref.id).\
                            filter(network_or_none).\
                            filter_by(reserved=reserved).\
                            filter_by(address=address).\
                            update(params, synchronize_session='evaluate')

    if not rows_updated:
        LOG.debug('The row was updated in a concurrent transaction, '
                  'we will fetch another row')
        raise db_exc.RetryRequest(
            exception.FixedIpAssociateFailed(net=network_id))

    return fixed_ip_ref


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def fixed_ip_associate_pool(context, network_id, instance_uuid=None,
                            host=None, virtual_interface_id=None):
    """allocate a fixed ip out of a fixed ip network pool.

    This allocates an unallocated fixed ip out of a specified
    network. We sort by updated_at to hand out the oldest address in
    the list.

    """
    if instance_uuid and not uuidutils.is_uuid_like(instance_uuid):
        raise exception.InvalidUUID(uuid=instance_uuid)

    network_or_none = or_(models.FixedIp.network_id == network_id,
                          models.FixedIp.network_id == null())
    fixed_ip_ref = model_query(context, models.FixedIp, read_deleted="no").\
                           filter(network_or_none).\
                           filter_by(reserved=False).\
                           filter_by(instance_uuid=None).\
                           filter_by(host=None).\
                           filter_by(leased=False).\
                           order_by(asc(models.FixedIp.updated_at)).\
                           first()

    if not fixed_ip_ref:
        raise exception.NoMoreFixedIps(net=network_id)

    params = {'allocated': virtual_interface_id is not None}
    if fixed_ip_ref['network_id'] is None:
        params['network_id'] = network_id
    if instance_uuid:
        params['instance_uuid'] = instance_uuid
    if host:
        params['host'] = host
    if virtual_interface_id:
        params['virtual_interface_id'] = virtual_interface_id

    rows_updated = model_query(context, models.FixedIp, read_deleted="no").\
        filter_by(id=fixed_ip_ref['id']).\
        filter_by(network_id=fixed_ip_ref['network_id']).\
        filter_by(reserved=False).\
        filter_by(instance_uuid=None).\
        filter_by(host=None).\
        filter_by(leased=False).\
        filter_by(address=fixed_ip_ref['address']).\
        update(params, synchronize_session='evaluate')

    if not rows_updated:
        LOG.debug('The row was updated in a concurrent transaction, '
                  'we will fetch another row')
        raise db_exc.RetryRequest(
            exception.FixedIpAssociateFailed(net=network_id))

    return fixed_ip_ref


@require_context
@pick_context_manager_writer
def fixed_ip_create(context, values):
    fixed_ip_ref = models.FixedIp()
    fixed_ip_ref.update(values)
    try:
        fixed_ip_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.FixedIpExists(address=values['address'])
    return fixed_ip_ref


@require_context
@pick_context_manager_writer
def fixed_ip_bulk_create(context, ips):
    try:
        tab = models.FixedIp.__table__
        context.session.execute(tab.insert(), ips)
    except db_exc.DBDuplicateEntry as e:
        raise exception.FixedIpExists(address=e.value)


@require_context
@pick_context_manager_writer
def fixed_ip_disassociate(context, address):
    _fixed_ip_get_by_address(context, address).update(
        {'instance_uuid': None,
         'virtual_interface_id': None})


@pick_context_manager_writer
def fixed_ip_disassociate_all_by_timeout(context, host, time):
    # NOTE(vish): only update fixed ips that "belong" to this
    #             host; i.e. the network host or the instance
    #             host matches. Two queries necessary because
    #             join with update doesn't work.
    host_filter = or_(and_(models.Instance.host == host,
                           models.Network.multi_host == true()),
                      models.Network.host == host)
    result = model_query(context, models.FixedIp, (models.FixedIp.id,),
                         read_deleted="no").\
            filter(models.FixedIp.allocated == false()).\
            filter(models.FixedIp.updated_at < time).\
            join((models.Network,
                  models.Network.id == models.FixedIp.network_id)).\
            join((models.Instance,
                  models.Instance.uuid == models.FixedIp.instance_uuid)).\
            filter(host_filter).\
            all()
    fixed_ip_ids = [fip[0] for fip in result]
    if not fixed_ip_ids:
        return 0
    result = model_query(context, models.FixedIp).\
                         filter(models.FixedIp.id.in_(fixed_ip_ids)).\
                         update({'instance_uuid': None,
                                 'leased': False,
                                 'updated_at': timeutils.utcnow()},
                                synchronize_session='fetch')
    return result


@require_context
@pick_context_manager_reader
def fixed_ip_get(context, id, get_network=False):
    query = model_query(context, models.FixedIp).filter_by(id=id)
    if get_network:
        query = query.options(joinedload('network'))
    result = query.first()
    if not result:
        raise exception.FixedIpNotFound(id=id)

    # FIXME(sirp): shouldn't we just use project_only here to restrict the
    # results?
    if (nova.context.is_user_context(context) and
            result['instance_uuid'] is not None):
        instance = instance_get_by_uuid(context.elevated(read_deleted='yes'),
                                        result['instance_uuid'])
        nova.context.authorize_project_context(context, instance.project_id)

    return result


@pick_context_manager_reader
def fixed_ip_get_all(context):
    result = model_query(context, models.FixedIp, read_deleted="yes").all()
    if not result:
        raise exception.NoFixedIpsDefined()

    return result


@require_context
@pick_context_manager_reader
def fixed_ip_get_by_address(context, address, columns_to_join=None):
    return _fixed_ip_get_by_address(context, address,
                                    columns_to_join=columns_to_join)


def _fixed_ip_get_by_address(context, address, columns_to_join=None):
    if columns_to_join is None:
        columns_to_join = []

    try:
        result = model_query(context, models.FixedIp)
        for column in columns_to_join:
            result = result.options(joinedload_all(column))
        result = result.filter_by(address=address).first()
        if not result:
            raise exception.FixedIpNotFoundForAddress(address=address)
    except db_exc.DBError:
        msg = _("Invalid fixed IP Address %s in request") % address
        LOG.warning(msg)
        raise exception.FixedIpInvalid(msg)

    # NOTE(sirp): shouldn't we just use project_only here to restrict the
    # results?
    if (nova.context.is_user_context(context) and
            result['instance_uuid'] is not None):
        instance = _instance_get_by_uuid(
            context.elevated(read_deleted='yes'),
            result['instance_uuid'])
        nova.context.authorize_project_context(context,
                                               instance.project_id)
    return result


@require_context
@pick_context_manager_reader
def fixed_ip_get_by_floating_address(context, floating_address):
    return model_query(context, models.FixedIp).\
                       join(models.FloatingIp,
                            models.FloatingIp.fixed_ip_id ==
                            models.FixedIp.id).\
                       filter(models.FloatingIp.address == floating_address).\
                       first()
    # NOTE(tr3buchet) please don't invent an exception here, None is fine


@require_context
@pick_context_manager_reader
def fixed_ip_get_by_instance(context, instance_uuid):
    if not uuidutils.is_uuid_like(instance_uuid):
        raise exception.InvalidUUID(uuid=instance_uuid)

    vif_and = and_(models.VirtualInterface.id ==
                   models.FixedIp.virtual_interface_id,
                   models.VirtualInterface.deleted == 0)
    result = model_query(context, models.FixedIp, read_deleted="no").\
                 filter_by(instance_uuid=instance_uuid).\
                 outerjoin(models.VirtualInterface, vif_and).\
                 options(contains_eager("virtual_interface")).\
                 options(joinedload('network')).\
                 options(joinedload('floating_ips')).\
                 order_by(asc(models.VirtualInterface.created_at),
                          asc(models.VirtualInterface.id)).\
                 all()

    if not result:
        raise exception.FixedIpNotFoundForInstance(instance_uuid=instance_uuid)

    return result


@pick_context_manager_reader
def fixed_ip_get_by_host(context, host):
    instance_uuids = _instance_get_all_uuids_by_host(context, host)
    if not instance_uuids:
        return []

    return model_query(context, models.FixedIp).\
             filter(models.FixedIp.instance_uuid.in_(instance_uuids)).\
             all()


@require_context
@pick_context_manager_reader
def fixed_ip_get_by_network_host(context, network_id, host):
    result = model_query(context, models.FixedIp, read_deleted="no").\
                 filter_by(network_id=network_id).\
                 filter_by(host=host).\
                 first()

    if not result:
        raise exception.FixedIpNotFoundForNetworkHost(network_id=network_id,
                                                      host=host)
    return result


@require_context
@pick_context_manager_reader
def fixed_ips_by_virtual_interface(context, vif_id):
    result = model_query(context, models.FixedIp, read_deleted="no").\
                 filter_by(virtual_interface_id=vif_id).\
                 options(joinedload('network')).\
                 options(joinedload('floating_ips')).\
                 all()

    return result


@require_context
@pick_context_manager_writer
def fixed_ip_update(context, address, values):
    _fixed_ip_get_by_address(context, address).update(values)


def _fixed_ip_count_by_project(context, project_id):
    nova.context.authorize_project_context(context, project_id)
    return model_query(context, models.FixedIp, (models.FixedIp.id,),
                       read_deleted="no").\
                join((models.Instance,
                      models.Instance.uuid == models.FixedIp.instance_uuid)).\
                filter(models.Instance.project_id == project_id).\
                count()


###################


@require_context
@pick_context_manager_writer
def virtual_interface_create(context, values):
    """Create a new virtual interface record in the database.

    :param values: = dict containing column values
    """
    try:
        vif_ref = models.VirtualInterface()
        vif_ref.update(values)
        vif_ref.save(context.session)
    except db_exc.DBError:
        LOG.exception("VIF creation failed with a database error.")
        raise exception.VirtualInterfaceCreateException()

    return vif_ref


def _virtual_interface_query(context):
    return model_query(context, models.VirtualInterface, read_deleted="no")


@require_context
@pick_context_manager_writer
def virtual_interface_update(context, address, values):
    vif_ref = virtual_interface_get_by_address(context, address)
    vif_ref.update(values)
    vif_ref.save(context.session)
    return vif_ref


@require_context
@pick_context_manager_reader
def virtual_interface_get(context, vif_id):
    """Gets a virtual interface from the table.

    :param vif_id: = id of the virtual interface
    """
    vif_ref = _virtual_interface_query(context).\
                      filter_by(id=vif_id).\
                      first()
    return vif_ref


@require_context
@pick_context_manager_reader
def virtual_interface_get_by_address(context, address):
    """Gets a virtual interface from the table.

    :param address: = the address of the interface you're looking to get
    """
    try:
        vif_ref = _virtual_interface_query(context).\
                          filter_by(address=address).\
                          first()
    except db_exc.DBError:
        msg = _("Invalid virtual interface address %s in request") % address
        LOG.warning(msg)
        raise exception.InvalidIpAddressError(msg)
    return vif_ref


@require_context
@pick_context_manager_reader
def virtual_interface_get_by_uuid(context, vif_uuid):
    """Gets a virtual interface from the table.

    :param vif_uuid: the uuid of the interface you're looking to get
    """
    vif_ref = _virtual_interface_query(context).\
                      filter_by(uuid=vif_uuid).\
                      first()
    return vif_ref


@require_context
@require_instance_exists_using_uuid
@pick_context_manager_reader_allow_async
def virtual_interface_get_by_instance(context, instance_uuid):
    """Gets all virtual interfaces for instance.

    :param instance_uuid: = uuid of the instance to retrieve vifs for
    """
    vif_refs = _virtual_interface_query(context).\
                       filter_by(instance_uuid=instance_uuid).\
                       order_by(asc("created_at"), asc("id")).\
                       all()
    return vif_refs


@require_context
@pick_context_manager_reader
def virtual_interface_get_by_instance_and_network(context, instance_uuid,
                                                  network_id):
    """Gets virtual interface for instance that's associated with network."""
    vif_ref = _virtual_interface_query(context).\
                      filter_by(instance_uuid=instance_uuid).\
                      filter_by(network_id=network_id).\
                      first()
    return vif_ref


@require_context
@pick_context_manager_writer
def virtual_interface_delete_by_instance(context, instance_uuid):
    """Delete virtual interface records that are associated
    with the instance given by instance_id.

    :param instance_uuid: = uuid of instance
    """
    _virtual_interface_query(context).\
           filter_by(instance_uuid=instance_uuid).\
           soft_delete()


@require_context
@pick_context_manager_writer
def virtual_interface_delete(context, id):
    """Delete virtual interface records.

    :param id: id of the interface
    """
    _virtual_interface_query(context).\
        filter_by(id=id).\
        soft_delete()


@require_context
@pick_context_manager_reader
def virtual_interface_get_all(context):
    """Get all vifs."""
    vif_refs = _virtual_interface_query(context).all()
    return vif_refs


###################


def _metadata_refs(metadata_dict, meta_class):
    metadata_refs = []
    if metadata_dict:
        for k, v in metadata_dict.items():
            metadata_ref = meta_class()
            metadata_ref['key'] = k
            metadata_ref['value'] = v
            metadata_refs.append(metadata_ref)
    return metadata_refs


def _validate_unique_server_name(context, name):
    if not CONF.osapi_compute_unique_server_name_scope:
        return

    lowername = name.lower()
    base_query = model_query(context, models.Instance, read_deleted='no').\
            filter(func.lower(models.Instance.hostname) == lowername)

    if CONF.osapi_compute_unique_server_name_scope == 'project':
        instance_with_same_name = base_query.\
                        filter_by(project_id=context.project_id).\
                        count()

    elif CONF.osapi_compute_unique_server_name_scope == 'global':
        instance_with_same_name = base_query.count()

    else:
        return

    if instance_with_same_name > 0:
        raise exception.InstanceExists(name=lowername)


def _handle_objects_related_type_conversions(values):
    """Make sure that certain things in values (which may have come from
    an objects.instance.Instance object) are in suitable form for the
    database.
    """
    # NOTE(danms): Make sure IP addresses are passed as strings to
    # the database engine
    for key in ('access_ip_v4', 'access_ip_v6'):
        if key in values and values[key] is not None:
            values[key] = str(values[key])

    datetime_keys = ('created_at', 'deleted_at', 'updated_at',
                     'launched_at', 'terminated_at')
    convert_objects_related_datetimes(values, *datetime_keys)


def _check_instance_exists_in_project(context, instance_uuid):
    if not model_query(context, models.Instance, read_deleted="no",
                       project_only=True).filter_by(
                       uuid=instance_uuid).first():
        raise exception.InstanceNotFound(instance_id=instance_uuid)


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def instance_create(context, values):
    """Create a new Instance record in the database.

    context - request context object
    values - dict containing column values.
    """

    security_group_ensure_default(context)

    values = values.copy()
    values['metadata'] = _metadata_refs(
            values.get('metadata'), models.InstanceMetadata)

    values['system_metadata'] = _metadata_refs(
            values.get('system_metadata'), models.InstanceSystemMetadata)
    _handle_objects_related_type_conversions(values)

    instance_ref = models.Instance()
    if not values.get('uuid'):
        values['uuid'] = uuidutils.generate_uuid()
    instance_ref['info_cache'] = models.InstanceInfoCache()
    info_cache = values.pop('info_cache', None)
    if info_cache is not None:
        instance_ref['info_cache'].update(info_cache)
    security_groups = values.pop('security_groups', [])
    instance_ref['extra'] = models.InstanceExtra()
    instance_ref['extra'].update(
        {'numa_topology': None,
         'pci_requests': None,
         'vcpu_model': None,
         })
    instance_ref['extra'].update(values.pop('extra', {}))
    instance_ref.update(values)

    def _get_sec_group_models(security_groups):
        models = []
        default_group = _security_group_ensure_default(context)
        if 'default' in security_groups:
            models.append(default_group)
            # Generate a new list, so we don't modify the original
            security_groups = [x for x in security_groups if x != 'default']
        if security_groups:
            models.extend(_security_group_get_by_names(
                context, security_groups))
        return models

    if 'hostname' in values:
        _validate_unique_server_name(context, values['hostname'])
    instance_ref.security_groups = _get_sec_group_models(security_groups)
    context.session.add(instance_ref)

    # create the instance uuid to ec2_id mapping entry for instance
    ec2_instance_create(context, instance_ref['uuid'])

    # Parity with the return value of instance_get_all_by_filters_sort()
    # Obviously a newly-created instance record can't already have a fault
    # record because of the FK constraint, so this is fine.
    instance_ref.fault = None

    return instance_ref


def _instance_data_get_for_user(context, project_id, user_id):
    not_soft_deleted = or_(
        models.Instance.vm_state != vm_states.SOFT_DELETED,
        models.Instance.vm_state == null()
    )
    result = model_query(context, models.Instance, (
        func.count(models.Instance.id),
        func.sum(models.Instance.vcpus),
        func.sum(models.Instance.memory_mb))).\
        filter_by(project_id=project_id).filter(not_soft_deleted)
    if user_id:
        result = result.filter_by(user_id=user_id).first()
    else:
        result = result.first()
    # NOTE(vish): convert None to 0
    return (result[0] or 0, result[1] or 0, result[2] or 0)


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def instance_destroy(context, instance_uuid, constraint=None):
    if uuidutils.is_uuid_like(instance_uuid):
        instance_ref = _instance_get_by_uuid(context, instance_uuid)
    else:
        raise exception.InvalidUUID(instance_uuid)

    query = model_query(context, models.Instance).\
                    filter_by(uuid=instance_uuid)
    if constraint is not None:
        query = constraint.apply(models.Instance, query)
    count = query.soft_delete()
    if count == 0:
        raise exception.ConstraintNotMet()
    model_query(context, models.SecurityGroupInstanceAssociation).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceInfoCache).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceMetadata).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceFault).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceExtra).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceSystemMetadata).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceGroupMember).\
            filter_by(instance_id=instance_uuid).\
            soft_delete()
    model_query(context, models.BlockDeviceMapping).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.Migration).\
            filter_by(instance_uuid=instance_uuid).\
            soft_delete()
    model_query(context, models.InstanceIdMapping).filter_by(
        uuid=instance_uuid).soft_delete()
    # NOTE(snikitin): We can't use model_query here, because there is no
    # column 'deleted' in 'tags' or 'console_auth_tokens' tables.
    context.session.query(models.Tag).filter_by(
        resource_id=instance_uuid).delete()
    context.session.query(models.ConsoleAuthToken).filter_by(
        instance_uuid=instance_uuid).delete()
    # NOTE(cfriesen): We intentionally do not soft-delete entries in the
    # instance_actions or instance_actions_events tables because they
    # can be used by operators to find out what actions were performed on a
    # deleted instance.  Both of these tables are special-cased in
    # _archive_deleted_rows_for_table().

    return instance_ref


@require_context
@pick_context_manager_reader_allow_async
def instance_get_by_uuid(context, uuid, columns_to_join=None):
    return _instance_get_by_uuid(context, uuid,
                                 columns_to_join=columns_to_join)


def _instance_get_by_uuid(context, uuid, columns_to_join=None):
    result = _build_instance_get(context, columns_to_join=columns_to_join).\
                filter_by(uuid=uuid).\
                first()

    if not result:
        raise exception.InstanceNotFound(instance_id=uuid)

    return result


@require_context
@pick_context_manager_reader
def instance_get(context, instance_id, columns_to_join=None):
    try:
        result = _build_instance_get(context, columns_to_join=columns_to_join
                                     ).filter_by(id=instance_id).first()

        if not result:
            raise exception.InstanceNotFound(instance_id=instance_id)

        return result
    except db_exc.DBError:
        # NOTE(sdague): catch all in case the db engine chokes on the
        # id because it's too long of an int to store.
        LOG.warning("Invalid instance id %s in request", instance_id)
        raise exception.InvalidID(id=instance_id)


def _build_instance_get(context, columns_to_join=None):
    query = model_query(context, models.Instance, project_only=True).\
            options(joinedload_all('security_groups.rules')).\
            options(joinedload('info_cache'))
    if columns_to_join is None:
        columns_to_join = ['metadata', 'system_metadata']
    for column in columns_to_join:
        if column in ['info_cache', 'security_groups']:
            # Already always joined above
            continue
        if 'extra.' in column:
            query = query.options(undefer(column))
        elif column in ['metadata', 'system_metadata']:
            # NOTE(melwitt): We use subqueryload() instead of joinedload() for
            # metadata and system_metadata because of the one-to-many
            # relationship of the data. Directly joining these columns can
            # result in a large number of additional rows being queried if an
            # instance has a large number of (system_)metadata items, resulting
            # in a large data transfer. Instead, the subqueryload() will
            # perform additional queries to obtain metadata and system_metadata
            # for the instance.
            query = query.options(subqueryload(column))
        else:
            query = query.options(joinedload(column))
    # NOTE(alaski) Stop lazy loading of columns not needed.
    for col in ['metadata', 'system_metadata']:
        if col not in columns_to_join:
            query = query.options(noload(col))
    # NOTE(melwitt): We need to use order_by(<unique column>) so that the
    # additional queries emitted by subqueryload() include the same ordering as
    # used by the parent query.
    # https://docs.sqlalchemy.org/en/13/orm/loading_relationships.html#the-importance-of-ordering
    return query.order_by(models.Instance.id)


def _instances_fill_metadata(context, instances, manual_joins=None):
    """Selectively fill instances with manually-joined metadata. Note that
    instance will be converted to a dict.

    :param context: security context
    :param instances: list of instances to fill
    :param manual_joins: list of tables to manually join (can be any
                         combination of 'metadata' and 'system_metadata' or
                         None to take the default of both)
    """
    uuids = [inst['uuid'] for inst in instances]

    if manual_joins is None:
        manual_joins = ['metadata', 'system_metadata']

    meta = collections.defaultdict(list)
    if 'metadata' in manual_joins:
        for row in _instance_metadata_get_multi(context, uuids):
            meta[row['instance_uuid']].append(row)

    sys_meta = collections.defaultdict(list)
    if 'system_metadata' in manual_joins:
        for row in _instance_system_metadata_get_multi(context, uuids):
            sys_meta[row['instance_uuid']].append(row)

    pcidevs = collections.defaultdict(list)
    if 'pci_devices' in manual_joins:
        for row in _instance_pcidevs_get_multi(context, uuids):
            pcidevs[row['instance_uuid']].append(row)

    if 'fault' in manual_joins:
        faults = instance_fault_get_by_instance_uuids(context, uuids,
                                                      latest=True)
    else:
        faults = {}

    filled_instances = []
    for inst in instances:
        inst = dict(inst)
        inst['system_metadata'] = sys_meta[inst['uuid']]
        inst['metadata'] = meta[inst['uuid']]
        if 'pci_devices' in manual_joins:
            inst['pci_devices'] = pcidevs[inst['uuid']]
        inst_faults = faults.get(inst['uuid'])
        inst['fault'] = inst_faults and inst_faults[0] or None
        filled_instances.append(inst)

    return filled_instances


def _manual_join_columns(columns_to_join):
    """Separate manually joined columns from columns_to_join

    If columns_to_join contains 'metadata', 'system_metadata', 'fault', or
    'pci_devices' those columns are removed from columns_to_join and added
    to a manual_joins list to be used with the _instances_fill_metadata method.

    The columns_to_join formal parameter is copied and not modified, the return
    tuple has the modified columns_to_join list to be used with joinedload in
    a model query.

    :param:columns_to_join: List of columns to join in a model query.
    :return: tuple of (manual_joins, columns_to_join)
    """
    manual_joins = []
    columns_to_join_new = copy.copy(columns_to_join)
    for column in ('metadata', 'system_metadata', 'pci_devices', 'fault'):
        if column in columns_to_join_new:
            columns_to_join_new.remove(column)
            manual_joins.append(column)
    return manual_joins, columns_to_join_new


@require_context
@pick_context_manager_reader
def instance_get_all(context, columns_to_join=None):
    if columns_to_join is None:
        columns_to_join_new = ['info_cache', 'security_groups']
        manual_joins = ['metadata', 'system_metadata']
    else:
        manual_joins, columns_to_join_new = (
            _manual_join_columns(columns_to_join))
    query = model_query(context, models.Instance)
    for column in columns_to_join_new:
        query = query.options(joinedload(column))
    if not context.is_admin:
        # If we're not admin context, add appropriate filter..
        if context.project_id:
            query = query.filter_by(project_id=context.project_id)
        else:
            query = query.filter_by(user_id=context.user_id)
    instances = query.all()
    return _instances_fill_metadata(context, instances, manual_joins)


@require_context
@pick_context_manager_reader_allow_async
def instance_get_all_by_filters(context, filters, sort_key, sort_dir,
                                limit=None, marker=None, columns_to_join=None):
    """Return instances matching all filters sorted by the primary key.

    See instance_get_all_by_filters_sort for more information.
    """
    # Invoke the API with the multiple sort keys and directions using the
    # single sort key/direction
    return instance_get_all_by_filters_sort(context, filters, limit=limit,
                                            marker=marker,
                                            columns_to_join=columns_to_join,
                                            sort_keys=[sort_key],
                                            sort_dirs=[sort_dir])


@require_context
@pick_context_manager_reader_allow_async
def instance_get_all_by_filters_sort(context, filters, limit=None, marker=None,
                                     columns_to_join=None, sort_keys=None,
                                     sort_dirs=None):
    """Return instances that match all filters sorted by the given keys.
    Deleted instances will be returned by default, unless there's a filter that
    says otherwise.

    Depending on the name of a filter, matching for that filter is
    performed using either exact matching or as regular expression
    matching. Exact matching is applied for the following filters::

    |   ['project_id', 'user_id', 'image_ref',
    |    'vm_state', 'instance_type_id', 'uuid',
    |    'metadata', 'host', 'system_metadata']


    A third type of filter (also using exact matching), filters
    based on instance metadata tags when supplied under a special
    key named 'filter'::

    |   filters = {
    |       'filter': [
    |           {'name': 'tag-key', 'value': '<metakey>'},
    |           {'name': 'tag-value', 'value': '<metaval>'},
    |           {'name': 'tag:<metakey>', 'value': '<metaval>'}
    |       ]
    |   }

    Special keys are used to tweek the query further::

    |   'changes-since' - only return instances updated after
    |   'deleted' - only return (or exclude) deleted instances
    |   'soft_deleted' - modify behavior of 'deleted' to either
    |                    include or exclude instances whose
    |                    vm_state is SOFT_DELETED.

    A fourth type of filter (also using exact matching), filters
    based on instance tags (not metadata tags). There are two types
    of these tags:

    `tags` -- One or more strings that will be used to filter results
            in an AND expression: T1 AND T2

    `tags-any` -- One or more strings that will be used to filter results in
            an OR expression: T1 OR T2

    `not-tags` -- One or more strings that will be used to filter results in
            an NOT AND expression: NOT (T1 AND T2)

    `not-tags-any` -- One or more strings that will be used to filter results
            in an NOT OR expression: NOT (T1 OR T2)

    Tags should be represented as list::

    |    filters = {
    |        'tags': [some-tag, some-another-tag],
    |        'tags-any: [some-any-tag, some-another-any-tag],
    |        'not-tags: [some-not-tag, some-another-not-tag],
    |        'not-tags-any: [some-not-any-tag, some-another-not-any-tag]
    |    }

    """
    # NOTE(mriedem): If the limit is 0 there is no point in even going
    # to the database since nothing is going to be returned anyway.
    if limit == 0:
        return []

    sort_keys, sort_dirs = process_sort_params(sort_keys,
                                               sort_dirs,
                                               default_dir='desc')

    if columns_to_join is None:
        columns_to_join_new = ['info_cache', 'security_groups']
        manual_joins = ['metadata', 'system_metadata']
    else:
        manual_joins, columns_to_join_new = (
            _manual_join_columns(columns_to_join))

    query_prefix = context.session.query(models.Instance)
    for column in columns_to_join_new:
        if 'extra.' in column:
            query_prefix = query_prefix.options(undefer(column))
        else:
            query_prefix = query_prefix.options(joinedload(column))

    # Note: order_by is done in the sqlalchemy.utils.py paginate_query(),
    # no need to do it here as well

    # Make a copy of the filters dictionary to use going forward, as we'll
    # be modifying it and we shouldn't affect the caller's use of it.
    filters = copy.deepcopy(filters)

    if 'changes-since' in filters:
        changes_since = timeutils.normalize_time(filters['changes-since'])
        query_prefix = query_prefix.\
                            filter(models.Instance.updated_at >= changes_since)

    if 'deleted' in filters:
        # Instances can be soft or hard deleted and the query needs to
        # include or exclude both
        deleted = filters.pop('deleted')
        if deleted:
            if filters.pop('soft_deleted', True):
                delete = or_(
                    models.Instance.deleted == models.Instance.id,
                    models.Instance.vm_state == vm_states.SOFT_DELETED
                    )
                query_prefix = query_prefix.\
                    filter(delete)
            else:
                query_prefix = query_prefix.\
                    filter(models.Instance.deleted == models.Instance.id)
        else:
            query_prefix = query_prefix.\
                    filter_by(deleted=0)
            if not filters.pop('soft_deleted', False):
                # It would be better to have vm_state not be nullable
                # but until then we test it explicitly as a workaround.
                not_soft_deleted = or_(
                    models.Instance.vm_state != vm_states.SOFT_DELETED,
                    models.Instance.vm_state == null()
                    )
                query_prefix = query_prefix.filter(not_soft_deleted)

    if 'cleaned' in filters:
        cleaned = 1 if filters.pop('cleaned') else 0
        query_prefix = query_prefix.filter(models.Instance.cleaned == cleaned)

    if 'tags' in filters:
        tags = filters.pop('tags')
        # We build a JOIN ladder expression for each tag, JOIN'ing
        # the first tag to the instances table, and each subsequent
        # tag to the last JOIN'd tags table
        first_tag = tags.pop(0)
        query_prefix = query_prefix.join(models.Instance.tags)
        query_prefix = query_prefix.filter(models.Tag.tag == first_tag)

        for tag in tags:
            tag_alias = aliased(models.Tag)
            query_prefix = query_prefix.join(tag_alias,
                                             models.Instance.tags)
            query_prefix = query_prefix.filter(tag_alias.tag == tag)

    if 'tags-any' in filters:
        tags = filters.pop('tags-any')
        tag_alias = aliased(models.Tag)
        query_prefix = query_prefix.join(tag_alias, models.Instance.tags)
        query_prefix = query_prefix.filter(tag_alias.tag.in_(tags))

    if 'not-tags' in filters:
        tags = filters.pop('not-tags')
        first_tag = tags.pop(0)
        subq = query_prefix.session.query(models.Tag.resource_id)
        subq = subq.join(models.Instance.tags)
        subq = subq.filter(models.Tag.tag == first_tag)

        for tag in tags:
            tag_alias = aliased(models.Tag)
            subq = subq.join(tag_alias, models.Instance.tags)
            subq = subq.filter(tag_alias.tag == tag)

        query_prefix = query_prefix.filter(~models.Instance.uuid.in_(subq))

    if 'not-tags-any' in filters:
        tags = filters.pop('not-tags-any')
        query_prefix = query_prefix.filter(~models.Instance.tags.any(
            models.Tag.tag.in_(tags)))

    if not context.is_admin:
        # If we're not admin context, add appropriate filter..
        if context.project_id:
            filters['project_id'] = context.project_id
        else:
            filters['user_id'] = context.user_id

    # Filters for exact matches that we can do along with the SQL query...
    # For other filters that don't match this, we will do regexp matching
    exact_match_filter_names = ['project_id', 'user_id', 'image_ref',
                                'vm_state', 'instance_type_id', 'uuid',
                                'metadata', 'host', 'task_state',
                                'system_metadata']

    # Filter the query
    query_prefix = _exact_instance_filter(query_prefix,
                                filters, exact_match_filter_names)
    if query_prefix is None:
        return []
    query_prefix = _regex_instance_filter(query_prefix, filters)

    # paginate query
    if marker is not None:
        try:
            marker = _instance_get_by_uuid(
                    context.elevated(read_deleted='yes'), marker)
        except exception.InstanceNotFound:
            raise exception.MarkerNotFound(marker=marker)
    try:
        query_prefix = sqlalchemyutils.paginate_query(query_prefix,
                               models.Instance, limit,
                               sort_keys,
                               marker=marker,
                               sort_dirs=sort_dirs)
    except db_exc.InvalidSortKey:
        raise exception.InvalidSortKey()

    return _instances_fill_metadata(context, query_prefix.all(), manual_joins)


@require_context
@pick_context_manager_reader_allow_async
def instance_get_by_sort_filters(context, sort_keys, sort_dirs, values):
    """Attempt to get a single instance based on a combination of sort
    keys, directions and filter values. This is used to try to find a
    marker instance when we don't have a marker uuid.

    This returns just a uuid of the instance that matched.
    """

    model = models.Instance
    return _model_get_uuid_by_sort_filters(context, model, sort_keys,
                                           sort_dirs, values)


def _model_get_uuid_by_sort_filters(context, model, sort_keys, sort_dirs,
                                    values):
    query = context.session.query(model.uuid)

    # NOTE(danms): Below is a re-implementation of our
    # oslo_db.sqlalchemy.utils.paginate_query() utility. We can't use that
    # directly because it does not return the marker and we need it to.
    # The below is basically the same algorithm, stripped down to just what
    # we need, and augmented with the filter criteria required for us to
    # get back the instance that would correspond to our query.

    # This is our position in sort_keys,sort_dirs,values for the loop below
    key_index = 0

    # We build a list of criteria to apply to the query, which looks
    # approximately like this (assuming all ascending):
    #
    #  OR(row.key1 > val1,
    #     AND(row.key1 == val1, row.key2 > val2),
    #     AND(row.key1 == val1, row.key2 == val2, row.key3 >= val3),
    #  )
    #
    # The final key is compared with the "or equal" variant so that
    # a complete match instance is still returned.
    criteria = []

    for skey, sdir, val in zip(sort_keys, sort_dirs, values):
        # Apply ordering to our query for the key, direction we're processing
        if sdir == 'desc':
            query = query.order_by(desc(getattr(model, skey)))
        else:
            query = query.order_by(asc(getattr(model, skey)))

        # Build a list of equivalence requirements on keys we've already
        # processed through the loop. In other words, if we're adding
        # key2 > val2, make sure that key1 == val1
        crit_attrs = []
        for equal_attr in range(0, key_index):
            crit_attrs.append(
                (getattr(model, sort_keys[equal_attr]) == values[equal_attr]))

        model_attr = getattr(model, skey)
        if isinstance(model_attr.type, Boolean):
            model_attr = cast(model_attr, Integer)
            val = int(val)

        if skey == sort_keys[-1]:
            # If we are the last key, then we should use or-equal to
            # allow a complete match to be returned
            if sdir == 'asc':
                crit = (model_attr >= val)
            else:
                crit = (model_attr <= val)
        else:
            # If we're not the last key, then strict greater or less than
            # so we order strictly.
            if sdir == 'asc':
                crit = (model_attr > val)
            else:
                crit = (model_attr < val)

        # AND together all the above
        crit_attrs.append(crit)
        criteria.append(and_(*crit_attrs))
        key_index += 1

    # OR together all the ANDs
    query = query.filter(or_(*criteria))

    # We can't raise InstanceNotFound because we don't have a uuid to
    # be looking for, so just return nothing if no match.
    result = query.limit(1).first()
    if result:
        # We're querying for a single column, which means we get back a
        # tuple of one thing. Strip that out and just return the uuid
        # for our caller.
        return result[0]
    else:
        return result


def _db_connection_type(db_connection):
    """Returns a lowercase symbol for the db type.

    This is useful when we need to change what we are doing per DB
    (like handling regexes). In a CellsV2 world it probably needs to
    do something better than use the database configuration string.
    """

    db_string = db_connection.split(':')[0].split('+')[0]
    return db_string.lower()


def _safe_regex_mysql(raw_string):
    """Make regex safe to mysql.

    Certain items like '|' are interpreted raw by mysql REGEX. If you
    search for a single | then you trigger an error because it's
    expecting content on either side.

    For consistency sake we escape all '|'. This does mean we wouldn't
    support something like foo|bar to match completely different
    things, however, one can argue putting such complicated regex into
    name search probably means you are doing this wrong.
    """
    return raw_string.replace('|', '\\|')


def _get_regexp_ops(connection):
    """Return safety filter and db opts for regex."""
    regexp_op_map = {
        'postgresql': '~',
        'mysql': 'REGEXP',
        'sqlite': 'REGEXP'
    }
    regex_safe_filters = {
        'mysql': _safe_regex_mysql
    }
    db_type = _db_connection_type(connection)

    return (regex_safe_filters.get(db_type, lambda x: x),
            regexp_op_map.get(db_type, 'LIKE'))


def _regex_instance_filter(query, filters):

    """Applies regular expression filtering to an Instance query.

    Returns the updated query.

    :param query: query to apply filters to
    :param filters: dictionary of filters with regex values
    """

    model = models.Instance
    safe_regex_filter, db_regexp_op = _get_regexp_ops(CONF.database.connection)
    for filter_name in filters:
        try:
            column_attr = getattr(model, filter_name)
        except AttributeError:
            continue
        if 'property' == type(column_attr).__name__:
            continue
        filter_val = filters[filter_name]
        # Sometimes the REGEX filter value is not a string
        if not isinstance(filter_val, six.string_types):
            filter_val = str(filter_val)
        if db_regexp_op == 'LIKE':
            query = query.filter(column_attr.op(db_regexp_op)(
                                 u'%' + filter_val + u'%'))
        else:
            filter_val = safe_regex_filter(filter_val)
            query = query.filter(column_attr.op(db_regexp_op)(
                                 filter_val))
    return query


def _exact_instance_filter(query, filters, legal_keys):
    """Applies exact match filtering to an Instance query.

    Returns the updated query.  Modifies filters argument to remove
    filters consumed.

    :param query: query to apply filters to
    :param filters: dictionary of filters; values that are lists,
                    tuples, sets, or frozensets cause an 'IN' test to
                    be performed, while exact matching ('==' operator)
                    is used for other values
    :param legal_keys: list of keys to apply exact filtering to
    """

    filter_dict = {}
    model = models.Instance

    # Walk through all the keys
    for key in legal_keys:
        # Skip ones we're not filtering on
        if key not in filters:
            continue

        # OK, filtering on this key; what value do we search for?
        value = filters.pop(key)

        if key in ('metadata', 'system_metadata'):
            column_attr = getattr(model, key)
            if isinstance(value, list):
                for item in value:
                    for k, v in item.items():
                        query = query.filter(column_attr.any(key=k))
                        query = query.filter(column_attr.any(value=v))

            else:
                for k, v in value.items():
                    query = query.filter(column_attr.any(key=k))
                    query = query.filter(column_attr.any(value=v))
        elif isinstance(value, (list, tuple, set, frozenset)):
            if not value:
                return None  # empty IN-predicate; short circuit
            # Looking for values in a list; apply to query directly
            column_attr = getattr(model, key)
            query = query.filter(column_attr.in_(value))
        else:
            # OK, simple exact match; save for later
            filter_dict[key] = value

    # Apply simple exact matches
    if filter_dict:
        query = query.filter(*[getattr(models.Instance, k) == v
                               for k, v in filter_dict.items()])
    return query


def process_sort_params(sort_keys, sort_dirs,
                        default_keys=['created_at', 'id'],
                        default_dir='asc'):
    """Process the sort parameters to include default keys.

    Creates a list of sort keys and a list of sort directions. Adds the default
    keys to the end of the list if they are not already included.

    When adding the default keys to the sort keys list, the associated
    direction is:
    1) The first element in the 'sort_dirs' list (if specified), else
    2) 'default_dir' value (Note that 'asc' is the default value since this is
    the default in sqlalchemy.utils.paginate_query)

    :param sort_keys: List of sort keys to include in the processed list
    :param sort_dirs: List of sort directions to include in the processed list
    :param default_keys: List of sort keys that need to be included in the
                         processed list, they are added at the end of the list
                         if not already specified.
    :param default_dir: Sort direction associated with each of the default
                        keys that are not supplied, used when they are added
                        to the processed list
    :returns: list of sort keys, list of sort directions
    :raise exception.InvalidInput: If more sort directions than sort keys
                                   are specified or if an invalid sort
                                   direction is specified
    """
    # Determine direction to use for when adding default keys
    if sort_dirs and len(sort_dirs) != 0:
        default_dir_value = sort_dirs[0]
    else:
        default_dir_value = default_dir

    # Create list of keys (do not modify the input list)
    if sort_keys:
        result_keys = list(sort_keys)
    else:
        result_keys = []

    # If a list of directions is not provided, use the default sort direction
    # for all provided keys
    if sort_dirs:
        result_dirs = []
        # Verify sort direction
        for sort_dir in sort_dirs:
            if sort_dir not in ('asc', 'desc'):
                msg = _("Unknown sort direction, must be 'desc' or 'asc'")
                raise exception.InvalidInput(reason=msg)
            result_dirs.append(sort_dir)
    else:
        result_dirs = [default_dir_value for _sort_key in result_keys]

    # Ensure that the key and direction length match
    while len(result_dirs) < len(result_keys):
        result_dirs.append(default_dir_value)
    # Unless more direction are specified, which is an error
    if len(result_dirs) > len(result_keys):
        msg = _("Sort direction size exceeds sort key size")
        raise exception.InvalidInput(reason=msg)

    # Ensure defaults are included
    for key in default_keys:
        if key not in result_keys:
            result_keys.append(key)
            result_dirs.append(default_dir_value)

    return result_keys, result_dirs


@require_context
@pick_context_manager_reader_allow_async
def instance_get_active_by_window_joined(context, begin, end=None,
                                         project_id=None, host=None,
                                         columns_to_join=None, limit=None,
                                         marker=None):
    """Return instances and joins that were active during window."""
    query = context.session.query(models.Instance)

    if columns_to_join is None:
        columns_to_join_new = ['info_cache', 'security_groups']
        manual_joins = ['metadata', 'system_metadata']
    else:
        manual_joins, columns_to_join_new = (
            _manual_join_columns(columns_to_join))

    for column in columns_to_join_new:
        if 'extra.' in column:
            query = query.options(undefer(column))
        else:
            query = query.options(joinedload(column))

    query = query.filter(or_(models.Instance.terminated_at == null(),
                             models.Instance.terminated_at > begin))
    if end:
        query = query.filter(models.Instance.launched_at < end)
    if project_id:
        query = query.filter_by(project_id=project_id)
    if host:
        query = query.filter_by(host=host)

    if marker is not None:
        try:
            marker = _instance_get_by_uuid(
                context.elevated(read_deleted='yes'), marker)
        except exception.InstanceNotFound:
            raise exception.MarkerNotFound(marker=marker)

    query = sqlalchemyutils.paginate_query(
        query, models.Instance, limit, ['project_id', 'uuid'], marker=marker)

    return _instances_fill_metadata(context, query.all(), manual_joins)


def _instance_get_all_query(context, project_only=False, joins=None):
    if joins is None:
        joins = ['info_cache', 'security_groups']

    query = model_query(context,
                        models.Instance,
                        project_only=project_only)
    for column in joins:
        if 'extra.' in column:
            query = query.options(undefer(column))
        else:
            query = query.options(joinedload(column))
    return query


@pick_context_manager_reader_allow_async
def instance_get_all_by_host(context, host, columns_to_join=None):
    query = _instance_get_all_query(context, joins=columns_to_join)
    return _instances_fill_metadata(context,
                                    query.filter_by(host=host).all(),
                                    manual_joins=columns_to_join)


def _instance_get_all_uuids_by_host(context, host):
    """Return a list of the instance uuids on a given host.

    Returns a list of UUIDs, not Instance model objects.
    """
    uuids = []
    for tuple in model_query(context, models.Instance, (models.Instance.uuid,),
                             read_deleted="no").\
                filter_by(host=host).\
                all():
        uuids.append(tuple[0])
    return uuids


@pick_context_manager_reader
def instance_get_all_by_host_and_node(context, host, node,
                                      columns_to_join=None):
    if columns_to_join is None:
        manual_joins = []
    else:
        candidates = ['system_metadata', 'metadata']
        manual_joins = [x for x in columns_to_join if x in candidates]
        columns_to_join = list(set(columns_to_join) - set(candidates))
    return _instances_fill_metadata(context,
            _instance_get_all_query(
                context,
                joins=columns_to_join).filter_by(host=host).
                filter_by(node=node).all(), manual_joins=manual_joins)


@pick_context_manager_reader
def instance_get_all_by_host_and_not_type(context, host, type_id=None):
    return _instances_fill_metadata(context,
        _instance_get_all_query(context).filter_by(host=host).
                   filter(models.Instance.instance_type_id != type_id).all())


@pick_context_manager_reader
def instance_get_all_by_grantee_security_groups(context, group_ids):
    if not group_ids:
        return []
    return _instances_fill_metadata(context,
        _instance_get_all_query(context).
            join(models.Instance.security_groups).
            filter(models.SecurityGroup.rules.any(
                models.SecurityGroupIngressRule.group_id.in_(group_ids))).
            all())


@require_context
@pick_context_manager_reader
def instance_floating_address_get_all(context, instance_uuid):
    if not uuidutils.is_uuid_like(instance_uuid):
        raise exception.InvalidUUID(uuid=instance_uuid)

    floating_ips = model_query(context,
                               models.FloatingIp,
                               (models.FloatingIp.address,)).\
        join(models.FloatingIp.fixed_ip).\
        filter_by(instance_uuid=instance_uuid)

    return [floating_ip.address for floating_ip in floating_ips]


# NOTE(hanlind): This method can be removed as conductor RPC API moves to v2.0.
@pick_context_manager_reader
def instance_get_all_hung_in_rebooting(context, reboot_window):
    reboot_window = (timeutils.utcnow() -
                     datetime.timedelta(seconds=reboot_window))

    # NOTE(danms): this is only used in the _poll_rebooting_instances()
    # call in compute/manager, so we can avoid the metadata lookups
    # explicitly
    return _instances_fill_metadata(context,
        model_query(context, models.Instance).
            filter(models.Instance.updated_at <= reboot_window).
            filter_by(task_state=task_states.REBOOTING).all(),
        manual_joins=[])


def _retry_instance_update():
    """Wrap with oslo_db_api.wrap_db_retry, and also retry on
    UnknownInstanceUpdateConflict.
    """
    exception_checker = \
        lambda exc: isinstance(exc, (exception.UnknownInstanceUpdateConflict,))
    return oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True,
                                     exception_checker=exception_checker)


@require_context
@_retry_instance_update()
@pick_context_manager_writer
def instance_update(context, instance_uuid, values, expected=None):
    return _instance_update(context, instance_uuid, values, expected)


@require_context
@_retry_instance_update()
@pick_context_manager_writer
def instance_update_and_get_original(context, instance_uuid, values,
                                     columns_to_join=None, expected=None):
    """Set the given properties on an instance and update it. Return
    a shallow copy of the original instance reference, as well as the
    updated one.

    :param context: = request context object
    :param instance_uuid: = instance uuid
    :param values: = dict containing column values

    If "expected_task_state" exists in values, the update can only happen
    when the task state before update matches expected_task_state. Otherwise
    a UnexpectedTaskStateError is thrown.

    :returns: a tuple of the form (old_instance_ref, new_instance_ref)

    Raises NotFound if instance does not exist.
    """
    instance_ref = _instance_get_by_uuid(context, instance_uuid,
                                         columns_to_join=columns_to_join)
    return (copy.copy(instance_ref), _instance_update(
        context, instance_uuid, values, expected, original=instance_ref))


# NOTE(danms): This updates the instance's metadata list in-place and in
# the database to avoid stale data and refresh issues. It assumes the
# delete=True behavior of instance_metadata_update(...)
def _instance_metadata_update_in_place(context, instance, metadata_type, model,
                                       metadata):
    metadata = dict(metadata)
    to_delete = []
    for keyvalue in instance[metadata_type]:
        key = keyvalue['key']
        if key in metadata:
            keyvalue['value'] = metadata.pop(key)
        elif key not in metadata:
            to_delete.append(keyvalue)

    # NOTE: we have to hard_delete here otherwise we will get more than one
    # system_metadata record when we read deleted for an instance;
    # regular metadata doesn't have the same problem because we don't
    # allow reading deleted regular metadata anywhere.
    if metadata_type == 'system_metadata':
        for condemned in to_delete:
            context.session.delete(condemned)
            instance[metadata_type].remove(condemned)
    else:
        for condemned in to_delete:
            condemned.soft_delete(context.session)

    for key, value in metadata.items():
        newitem = model()
        newitem.update({'key': key, 'value': value,
                        'instance_uuid': instance['uuid']})
        context.session.add(newitem)
        instance[metadata_type].append(newitem)


def _instance_update(context, instance_uuid, values, expected, original=None):
    if not uuidutils.is_uuid_like(instance_uuid):
        raise exception.InvalidUUID(instance_uuid)

    # NOTE(mdbooth): We pop values from this dict below, so we copy it here to
    # ensure there are no side effects for the caller or if we retry the
    # function due to a db conflict.
    updates = copy.copy(values)

    if expected is None:
        expected = {}
    else:
        # Coerce all single values to singleton lists
        expected = {k: [None] if v is None else sqlalchemyutils.to_list(v)
                       for (k, v) in expected.items()}

    # Extract 'expected_' values from values dict, as these aren't actually
    # updates
    for field in ('task_state', 'vm_state'):
        expected_field = 'expected_%s' % field
        if expected_field in updates:
            value = updates.pop(expected_field, None)
            # Coerce all single values to singleton lists
            if value is None:
                expected[field] = [None]
            else:
                expected[field] = sqlalchemyutils.to_list(value)

    # Values which need to be updated separately
    metadata = updates.pop('metadata', None)
    system_metadata = updates.pop('system_metadata', None)

    _handle_objects_related_type_conversions(updates)

    # Hostname is potentially unique, but this is enforced in code rather
    # than the DB. The query below races, but the number of users of
    # osapi_compute_unique_server_name_scope is small, and a robust fix
    # will be complex. This is intentionally left as is for the moment.
    if 'hostname' in updates:
        _validate_unique_server_name(context, updates['hostname'])

    compare = models.Instance(uuid=instance_uuid, **expected)
    try:
        instance_ref = model_query(context, models.Instance,
                                   project_only=True).\
                       update_on_match(compare, 'uuid', updates)
    except update_match.NoRowsMatched:
        # Update failed. Try to find why and raise a specific error.

        # We should get here only because our expected values were not current
        # when update_on_match executed. Having failed, we now have a hint that
        # the values are out of date and should check them.

        # This code is made more complex because we are using repeatable reads.
        # If we have previously read the original instance in the current
        # transaction, reading it again will return the same data, even though
        # the above update failed because it has changed: it is not possible to
        # determine what has changed in this transaction. In this case we raise
        # UnknownInstanceUpdateConflict, which will cause the operation to be
        # retried in a new transaction.

        # Because of the above, if we have previously read the instance in the
        # current transaction it will have been passed as 'original', and there
        # is no point refreshing it. If we have not previously read the
        # instance, we can fetch it here and we will get fresh data.
        if original is None:
            original = _instance_get_by_uuid(context, instance_uuid)

        conflicts_expected = {}
        conflicts_actual = {}
        for (field, expected_values) in expected.items():
            actual = original[field]
            if actual not in expected_values:
                conflicts_expected[field] = expected_values
                conflicts_actual[field] = actual

        # Exception properties
        exc_props = {
            'instance_uuid': instance_uuid,
            'expected': conflicts_expected,
            'actual': conflicts_actual
        }

        # There was a conflict, but something (probably the MySQL read view,
        # but possibly an exceptionally unlikely second race) is preventing us
        # from seeing what it is. When we go round again we'll get a fresh
        # transaction and a fresh read view.
        if len(conflicts_actual) == 0:
            raise exception.UnknownInstanceUpdateConflict(**exc_props)

        # Task state gets special handling for convenience. We raise the
        # specific error UnexpectedDeletingTaskStateError or
        # UnexpectedTaskStateError as appropriate
        if 'task_state' in conflicts_actual:
            conflict_task_state = conflicts_actual['task_state']
            if conflict_task_state == task_states.DELETING:
                exc = exception.UnexpectedDeletingTaskStateError
            else:
                exc = exception.UnexpectedTaskStateError

        # Everything else is an InstanceUpdateConflict
        else:
            exc = exception.InstanceUpdateConflict

        raise exc(**exc_props)

    if metadata is not None:
        _instance_metadata_update_in_place(context, instance_ref,
                                           'metadata',
                                           models.InstanceMetadata,
                                           metadata)

    if system_metadata is not None:
        _instance_metadata_update_in_place(context, instance_ref,
                                           'system_metadata',
                                           models.InstanceSystemMetadata,
                                           system_metadata)

    return instance_ref


@pick_context_manager_writer
def instance_add_security_group(context, instance_uuid, security_group_id):
    """Associate the given security group with the given instance."""
    sec_group_ref = models.SecurityGroupInstanceAssociation()
    sec_group_ref.update({'instance_uuid': instance_uuid,
                          'security_group_id': security_group_id})
    sec_group_ref.save(context.session)


@require_context
@pick_context_manager_writer
def instance_remove_security_group(context, instance_uuid, security_group_id):
    """Disassociate the given security group from the given instance."""
    model_query(context, models.SecurityGroupInstanceAssociation).\
                filter_by(instance_uuid=instance_uuid).\
                filter_by(security_group_id=security_group_id).\
                soft_delete()


###################


@require_context
@pick_context_manager_reader
def instance_info_cache_get(context, instance_uuid):
    """Gets an instance info cache from the table.

    :param instance_uuid: = uuid of the info cache's instance
    """
    return model_query(context, models.InstanceInfoCache).\
                         filter_by(instance_uuid=instance_uuid).\
                         first()


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def instance_info_cache_update(context, instance_uuid, values):
    """Update an instance info cache record in the table.

    :param instance_uuid: = uuid of info cache's instance
    :param values: = dict containing column values to update
    """
    convert_objects_related_datetimes(values)

    info_cache = model_query(context, models.InstanceInfoCache).\
                     filter_by(instance_uuid=instance_uuid).\
                     first()
    needs_create = False
    if info_cache and info_cache['deleted']:
        raise exception.InstanceInfoCacheNotFound(
                instance_uuid=instance_uuid)
    elif not info_cache:
        # NOTE(tr3buchet): just in case someone blows away an instance's
        #                  cache entry, re-create it.
        values['instance_uuid'] = instance_uuid
        info_cache = models.InstanceInfoCache(**values)
        needs_create = True

    try:
        with get_context_manager(context).writer.savepoint.using(context):
            if needs_create:
                info_cache.save(context.session)
            else:
                info_cache.update(values)
    except db_exc.DBDuplicateEntry:
        # NOTE(sirp): Possible race if two greenthreads attempt to
        # recreate the instance cache entry at the same time. First one
        # wins.
        pass

    return info_cache


@require_context
@pick_context_manager_writer
def instance_info_cache_delete(context, instance_uuid):
    """Deletes an existing instance_info_cache record

    :param instance_uuid: = uuid of the instance tied to the cache record
    """
    model_query(context, models.InstanceInfoCache).\
                         filter_by(instance_uuid=instance_uuid).\
                         soft_delete()


###################


def _instance_extra_create(context, values):
    inst_extra_ref = models.InstanceExtra()
    inst_extra_ref.update(values)
    inst_extra_ref.save(context.session)
    return inst_extra_ref


@pick_context_manager_writer
def instance_extra_update_by_uuid(context, instance_uuid, values):
    rows_updated = model_query(context, models.InstanceExtra).\
        filter_by(instance_uuid=instance_uuid).\
        update(values)
    if not rows_updated:
        LOG.debug("Created instance_extra for %s", instance_uuid)
        create_values = copy.copy(values)
        create_values["instance_uuid"] = instance_uuid
        _instance_extra_create(context, create_values)
        rows_updated = 1
    return rows_updated


@pick_context_manager_reader
def instance_extra_get_by_instance_uuid(context, instance_uuid,
                                        columns=None):
    query = model_query(context, models.InstanceExtra).\
        filter_by(instance_uuid=instance_uuid)
    if columns is None:
        columns = ['numa_topology', 'pci_requests', 'flavor', 'vcpu_model',
                   'migration_context']
    for column in columns:
        query = query.options(undefer(column))
    instance_extra = query.first()
    return instance_extra


###################


@require_context
@pick_context_manager_writer
def key_pair_create(context, values):
    try:
        key_pair_ref = models.KeyPair()
        key_pair_ref.update(values)
        key_pair_ref.save(context.session)
        return key_pair_ref
    except db_exc.DBDuplicateEntry:
        raise exception.KeyPairExists(key_name=values['name'])


@require_context
@pick_context_manager_writer
def key_pair_destroy(context, user_id, name):
    result = model_query(context, models.KeyPair).\
                         filter_by(user_id=user_id).\
                         filter_by(name=name).\
                         soft_delete()
    if not result:
        raise exception.KeypairNotFound(user_id=user_id, name=name)


@require_context
@pick_context_manager_reader
def key_pair_get(context, user_id, name):
    result = model_query(context, models.KeyPair).\
                     filter_by(user_id=user_id).\
                     filter_by(name=name).\
                     first()

    if not result:
        raise exception.KeypairNotFound(user_id=user_id, name=name)

    return result


@require_context
@pick_context_manager_reader
def key_pair_get_all_by_user(context, user_id, limit=None, marker=None):
    marker_row = None
    if marker is not None:
        marker_row = model_query(context, models.KeyPair, read_deleted="no").\
            filter_by(name=marker).filter_by(user_id=user_id).first()
        if not marker_row:
            raise exception.MarkerNotFound(marker=marker)

    query = model_query(context, models.KeyPair, read_deleted="no").\
        filter_by(user_id=user_id)

    query = sqlalchemyutils.paginate_query(
        query, models.KeyPair, limit, ['name'], marker=marker_row)

    return query.all()


@require_context
@pick_context_manager_reader
def key_pair_count_by_user(context, user_id):
    return model_query(context, models.KeyPair, read_deleted="no").\
                   filter_by(user_id=user_id).\
                   count()


###################

@pick_context_manager_writer
def network_associate(context, project_id, network_id=None, force=False):
    """Associate a project with a network.

    called by project_get_networks under certain conditions
    and network manager add_network_to_project()

    only associate if the project doesn't already have a network
    or if force is True

    force solves race condition where a fresh project has multiple instance
    builds simultaneously picked up by multiple network hosts which attempt
    to associate the project with multiple networks
    force should only be used as a direct consequence of user request
    all automated requests should not use force
    """
    def network_query(project_filter, id=None):
        filter_kwargs = {'project_id': project_filter}
        if id is not None:
            filter_kwargs['id'] = id
        return model_query(context, models.Network, read_deleted="no").\
                       filter_by(**filter_kwargs).\
                       with_lockmode('update').\
                       first()

    if not force:
        # find out if project has a network
        network_ref = network_query(project_id)

    if force or not network_ref:
        # in force mode or project doesn't have a network so associate
        # with a new network

        # get new network
        network_ref = network_query(None, network_id)
        if not network_ref:
            raise exception.NoMoreNetworks()

        # associate with network
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        network_ref['project_id'] = project_id
        context.session.add(network_ref)
    return network_ref


def _network_ips_query(context, network_id):
    return model_query(context, models.FixedIp, read_deleted="no").\
                   filter_by(network_id=network_id)


@pick_context_manager_reader
def network_count_reserved_ips(context, network_id):
    return _network_ips_query(context, network_id).\
                    filter_by(reserved=True).\
                    count()


@pick_context_manager_writer
def network_create_safe(context, values):
    network_ref = models.Network()
    network_ref['uuid'] = uuidutils.generate_uuid()
    network_ref.update(values)

    try:
        network_ref.save(context.session)
        return network_ref
    except db_exc.DBDuplicateEntry:
        raise exception.DuplicateVlan(vlan=values['vlan'])


@pick_context_manager_writer
def network_delete_safe(context, network_id):
    result = model_query(context, models.FixedIp, read_deleted="no").\
                     filter_by(network_id=network_id).\
                     filter_by(allocated=True).\
                     count()
    if result != 0:
        raise exception.NetworkInUse(network_id=network_id)
    network_ref = _network_get(context, network_id=network_id)

    model_query(context, models.FixedIp, read_deleted="no").\
            filter_by(network_id=network_id).\
            soft_delete()

    context.session.delete(network_ref)


@pick_context_manager_writer
def network_disassociate(context, network_id, disassociate_host,
                         disassociate_project):
    net_update = {}
    if disassociate_project:
        net_update['project_id'] = None
    if disassociate_host:
        net_update['host'] = None
    network_update(context, network_id, net_update)


def _network_get(context, network_id, project_only='allow_none'):
    result = model_query(context, models.Network, project_only=project_only).\
                    filter_by(id=network_id).\
                    first()

    if not result:
        raise exception.NetworkNotFound(network_id=network_id)

    return result


@require_context
@pick_context_manager_reader
def network_get(context, network_id, project_only='allow_none'):
    return _network_get(context, network_id, project_only=project_only)


@require_context
@pick_context_manager_reader
def network_get_all(context, project_only):
    result = model_query(context, models.Network, read_deleted="no",
                         project_only=project_only).all()

    if not result:
        raise exception.NoNetworksFound()

    return result


@require_context
@pick_context_manager_reader
def network_get_all_by_uuids(context, network_uuids, project_only):
    result = model_query(context, models.Network, read_deleted="no",
                         project_only=project_only).\
                filter(models.Network.uuid.in_(network_uuids)).\
                all()

    if not result:
        raise exception.NoNetworksFound()

    # check if the result contains all the networks
    # we are looking for
    for network_uuid in network_uuids:
        for network in result:
            if network['uuid'] == network_uuid:
                break
        else:
            if project_only:
                raise exception.NetworkNotFoundForProject(
                      network_uuid=network_uuid, project_id=context.project_id)
            raise exception.NetworkNotFound(network_id=network_uuid)

    return result


def _get_associated_fixed_ips_query(context, network_id, host=None):
    # NOTE(vish): The ugly joins here are to solve a performance issue and
    #             should be removed once we can add and remove leases
    #             without regenerating the whole list
    vif_and = and_(models.VirtualInterface.id ==
                   models.FixedIp.virtual_interface_id,
                   models.VirtualInterface.deleted == 0)
    inst_and = and_(models.Instance.uuid == models.FixedIp.instance_uuid,
                    models.Instance.deleted == 0)
    # NOTE(vish): This subquery left joins the minimum interface id for each
    #             instance. If the join succeeds (i.e. the 11th column is not
    #             null), then the fixed ip is on the first interface.
    subq = context.session.query(
        func.min(models.VirtualInterface.id).label("id"),
        models.VirtualInterface.instance_uuid).\
        group_by(models.VirtualInterface.instance_uuid).subquery()
    subq_and = and_(subq.c.id == models.FixedIp.virtual_interface_id,
            subq.c.instance_uuid == models.VirtualInterface.instance_uuid)
    query = context.session.query(
        models.FixedIp.address,
        models.FixedIp.instance_uuid,
        models.FixedIp.network_id,
        models.FixedIp.virtual_interface_id,
        models.VirtualInterface.address,
        models.Instance.hostname,
        models.Instance.updated_at,
        models.Instance.created_at,
        models.FixedIp.allocated,
        models.FixedIp.leased,
        subq.c.id).\
        filter(models.FixedIp.deleted == 0).\
        filter(models.FixedIp.network_id == network_id).\
        join((models.VirtualInterface, vif_and)).\
        join((models.Instance, inst_and)).\
        outerjoin((subq, subq_and)).\
        filter(models.FixedIp.instance_uuid != null()).\
        filter(models.FixedIp.virtual_interface_id != null())
    if host:
        query = query.filter(models.Instance.host == host)
    return query


@pick_context_manager_reader
def network_get_associated_fixed_ips(context, network_id, host=None):
    # FIXME(sirp): since this returns fixed_ips, this would be better named
    # fixed_ip_get_all_by_network.
    query = _get_associated_fixed_ips_query(context, network_id, host)
    result = query.all()
    data = []
    for datum in result:
        cleaned = {}
        cleaned['address'] = datum[0]
        cleaned['instance_uuid'] = datum[1]
        cleaned['network_id'] = datum[2]
        cleaned['vif_id'] = datum[3]
        cleaned['vif_address'] = datum[4]
        cleaned['instance_hostname'] = datum[5]
        cleaned['instance_updated'] = datum[6]
        cleaned['instance_created'] = datum[7]
        cleaned['allocated'] = datum[8]
        cleaned['leased'] = datum[9]
        # NOTE(vish): default_route is True if this fixed ip is on the first
        #             interface its instance.
        cleaned['default_route'] = datum[10] is not None
        data.append(cleaned)
    return data


@pick_context_manager_reader
def network_in_use_on_host(context, network_id, host):
    query = _get_associated_fixed_ips_query(context, network_id, host)
    return query.count() > 0


def _network_get_query(context):
    return model_query(context, models.Network, read_deleted="no")


@pick_context_manager_reader
def network_get_by_uuid(context, uuid):
    result = _network_get_query(context).filter_by(uuid=uuid).first()

    if not result:
        raise exception.NetworkNotFoundForUUID(uuid=uuid)

    return result


@pick_context_manager_reader
def network_get_by_cidr(context, cidr):
    result = _network_get_query(context).\
                filter(or_(models.Network.cidr == cidr,
                           models.Network.cidr_v6 == cidr)).\
                first()

    if not result:
        raise exception.NetworkNotFoundForCidr(cidr=cidr)

    return result


@pick_context_manager_reader
def network_get_all_by_host(context, host):
    fixed_host_filter = or_(models.FixedIp.host == host,
            and_(models.FixedIp.instance_uuid != null(),
                 models.Instance.host == host))
    fixed_ip_query = model_query(context, models.FixedIp,
                                 (models.FixedIp.network_id,)).\
                     outerjoin((models.Instance,
                                models.Instance.uuid ==
                                models.FixedIp.instance_uuid)).\
                     filter(fixed_host_filter)
    # NOTE(vish): return networks that have host set
    #             or that have a fixed ip with host set
    #             or that have an instance with host set
    host_filter = or_(models.Network.host == host,
                      models.Network.id.in_(fixed_ip_query.subquery()))
    return _network_get_query(context).filter(host_filter).all()


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def network_set_host(context, network_id, host_id):
    network_ref = _network_get_query(context).\
        filter_by(id=network_id).\
        first()

    if not network_ref:
        raise exception.NetworkNotFound(network_id=network_id)

    if network_ref.host:
        return None

    rows_updated = _network_get_query(context).\
        filter_by(id=network_id).\
        filter_by(host=None).\
        update({'host': host_id})

    if not rows_updated:
        LOG.debug('The row was updated in a concurrent transaction, '
                  'we will fetch another row')
        raise db_exc.RetryRequest(
            exception.NetworkSetHostFailed(network_id=network_id))


@require_context
@pick_context_manager_writer
def network_update(context, network_id, values):
    network_ref = _network_get(context, network_id)
    network_ref.update(values)
    try:
        network_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.DuplicateVlan(vlan=values['vlan'])
    return network_ref


###################


@require_context
@pick_context_manager_reader
def quota_get(context, project_id, resource, user_id=None):
    model = models.ProjectUserQuota if user_id else models.Quota
    query = model_query(context, model).\
                    filter_by(project_id=project_id).\
                    filter_by(resource=resource)
    if user_id:
        query = query.filter_by(user_id=user_id)

    result = query.first()
    if not result:
        if user_id:
            raise exception.ProjectUserQuotaNotFound(project_id=project_id,
                                                     user_id=user_id)
        else:
            raise exception.ProjectQuotaNotFound(project_id=project_id)

    return result


@require_context
@pick_context_manager_reader
def quota_get_all_by_project_and_user(context, project_id, user_id):
    user_quotas = model_query(context, models.ProjectUserQuota,
                              (models.ProjectUserQuota.resource,
                               models.ProjectUserQuota.hard_limit)).\
                   filter_by(project_id=project_id).\
                   filter_by(user_id=user_id).\
                   all()

    result = {'project_id': project_id, 'user_id': user_id}
    for user_quota in user_quotas:
        result[user_quota.resource] = user_quota.hard_limit

    return result


@require_context
@pick_context_manager_reader
def quota_get_all_by_project(context, project_id):
    rows = model_query(context, models.Quota, read_deleted="no").\
                   filter_by(project_id=project_id).\
                   all()

    result = {'project_id': project_id}
    for row in rows:
        result[row.resource] = row.hard_limit

    return result


@require_context
@pick_context_manager_reader
def quota_get_all(context, project_id):
    result = model_query(context, models.ProjectUserQuota).\
                   filter_by(project_id=project_id).\
                   all()

    return result


def quota_get_per_project_resources():
    return PER_PROJECT_QUOTAS


@pick_context_manager_writer
def quota_create(context, project_id, resource, limit, user_id=None):
    per_user = user_id and resource not in PER_PROJECT_QUOTAS
    quota_ref = models.ProjectUserQuota() if per_user else models.Quota()
    if per_user:
        quota_ref.user_id = user_id
    quota_ref.project_id = project_id
    quota_ref.resource = resource
    quota_ref.hard_limit = limit
    try:
        quota_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.QuotaExists(project_id=project_id, resource=resource)
    return quota_ref


@pick_context_manager_writer
def quota_update(context, project_id, resource, limit, user_id=None):
    per_user = user_id and resource not in PER_PROJECT_QUOTAS
    model = models.ProjectUserQuota if per_user else models.Quota
    query = model_query(context, model).\
                filter_by(project_id=project_id).\
                filter_by(resource=resource)
    if per_user:
        query = query.filter_by(user_id=user_id)

    result = query.update({'hard_limit': limit})
    if not result:
        if per_user:
            raise exception.ProjectUserQuotaNotFound(project_id=project_id,
                                                     user_id=user_id)
        else:
            raise exception.ProjectQuotaNotFound(project_id=project_id)


###################


@require_context
@pick_context_manager_reader
def quota_class_get(context, class_name, resource):
    result = model_query(context, models.QuotaClass, read_deleted="no").\
                     filter_by(class_name=class_name).\
                     filter_by(resource=resource).\
                     first()

    if not result:
        raise exception.QuotaClassNotFound(class_name=class_name)

    return result


@pick_context_manager_reader
def quota_class_get_default(context):
    rows = model_query(context, models.QuotaClass, read_deleted="no").\
                   filter_by(class_name=_DEFAULT_QUOTA_NAME).\
                   all()

    result = {'class_name': _DEFAULT_QUOTA_NAME}
    for row in rows:
        result[row.resource] = row.hard_limit

    return result


@require_context
@pick_context_manager_reader
def quota_class_get_all_by_name(context, class_name):
    rows = model_query(context, models.QuotaClass, read_deleted="no").\
                   filter_by(class_name=class_name).\
                   all()

    result = {'class_name': class_name}
    for row in rows:
        result[row.resource] = row.hard_limit

    return result


@pick_context_manager_writer
def quota_class_create(context, class_name, resource, limit):
    quota_class_ref = models.QuotaClass()
    quota_class_ref.class_name = class_name
    quota_class_ref.resource = resource
    quota_class_ref.hard_limit = limit
    quota_class_ref.save(context.session)
    return quota_class_ref


@pick_context_manager_writer
def quota_class_update(context, class_name, resource, limit):
    result = model_query(context, models.QuotaClass, read_deleted="no").\
                     filter_by(class_name=class_name).\
                     filter_by(resource=resource).\
                     update({'hard_limit': limit})

    if not result:
        raise exception.QuotaClassNotFound(class_name=class_name)


###################


@pick_context_manager_writer
def quota_destroy_all_by_project_and_user(context, project_id, user_id):
    model_query(context, models.ProjectUserQuota, read_deleted="no").\
        filter_by(project_id=project_id).\
        filter_by(user_id=user_id).\
        soft_delete(synchronize_session=False)


@pick_context_manager_writer
def quota_destroy_all_by_project(context, project_id):
    model_query(context, models.Quota, read_deleted="no").\
        filter_by(project_id=project_id).\
        soft_delete(synchronize_session=False)

    model_query(context, models.ProjectUserQuota, read_deleted="no").\
        filter_by(project_id=project_id).\
        soft_delete(synchronize_session=False)


###################


def _ec2_volume_get_query(context):
    return model_query(context, models.VolumeIdMapping, read_deleted='yes')


def _ec2_snapshot_get_query(context):
    return model_query(context, models.SnapshotIdMapping, read_deleted='yes')


@require_context
@pick_context_manager_writer
def ec2_volume_create(context, volume_uuid, id=None):
    """Create ec2 compatible volume by provided uuid."""
    ec2_volume_ref = models.VolumeIdMapping()
    ec2_volume_ref.update({'uuid': volume_uuid})
    if id is not None:
        ec2_volume_ref.update({'id': id})

    ec2_volume_ref.save(context.session)

    return ec2_volume_ref


@require_context
@pick_context_manager_reader
def ec2_volume_get_by_uuid(context, volume_uuid):
    result = _ec2_volume_get_query(context).\
                    filter_by(uuid=volume_uuid).\
                    first()

    if not result:
        raise exception.VolumeNotFound(volume_id=volume_uuid)

    return result


@require_context
@pick_context_manager_reader
def ec2_volume_get_by_id(context, volume_id):
    result = _ec2_volume_get_query(context).\
                    filter_by(id=volume_id).\
                    first()

    if not result:
        raise exception.VolumeNotFound(volume_id=volume_id)

    return result


@require_context
@pick_context_manager_writer
def ec2_snapshot_create(context, snapshot_uuid, id=None):
    """Create ec2 compatible snapshot by provided uuid."""
    ec2_snapshot_ref = models.SnapshotIdMapping()
    ec2_snapshot_ref.update({'uuid': snapshot_uuid})
    if id is not None:
        ec2_snapshot_ref.update({'id': id})

    ec2_snapshot_ref.save(context.session)

    return ec2_snapshot_ref


@require_context
@pick_context_manager_reader
def ec2_snapshot_get_by_ec2_id(context, ec2_id):
    result = _ec2_snapshot_get_query(context).\
                    filter_by(id=ec2_id).\
                    first()

    if not result:
        raise exception.SnapshotNotFound(snapshot_id=ec2_id)

    return result


@require_context
@pick_context_manager_reader
def ec2_snapshot_get_by_uuid(context, snapshot_uuid):
    result = _ec2_snapshot_get_query(context).\
                    filter_by(uuid=snapshot_uuid).\
                    first()

    if not result:
        raise exception.SnapshotNotFound(snapshot_id=snapshot_uuid)

    return result


###################


def _block_device_mapping_get_query(context, columns_to_join=None):
    if columns_to_join is None:
        columns_to_join = []

    query = model_query(context, models.BlockDeviceMapping)

    for column in columns_to_join:
        query = query.options(joinedload(column))

    return query


def _scrub_empty_str_values(dct, keys_to_scrub):
    """Remove any keys found in sequence keys_to_scrub from the dict
    if they have the value ''.
    """
    for key in keys_to_scrub:
        if key in dct and dct[key] == '':
            del dct[key]


def _from_legacy_values(values, legacy, allow_updates=False):
    if legacy:
        if allow_updates and block_device.is_safe_for_update(values):
            return values
        else:
            return block_device.BlockDeviceDict.from_legacy(values)
    else:
        return values


def _set_or_validate_uuid(values):
    uuid = values.get('uuid')

    # values doesn't contain uuid, or it's blank
    if not uuid:
        values['uuid'] = uuidutils.generate_uuid()

    # values contains a uuid
    else:
        if not uuidutils.is_uuid_like(uuid):
            raise exception.InvalidUUID(uuid=uuid)


@require_context
@pick_context_manager_writer
def block_device_mapping_create(context, values, legacy=True):
    _scrub_empty_str_values(values, ['volume_size'])
    values = _from_legacy_values(values, legacy)
    convert_objects_related_datetimes(values)

    _set_or_validate_uuid(values)

    bdm_ref = models.BlockDeviceMapping()
    bdm_ref.update(values)
    bdm_ref.save(context.session)
    return bdm_ref


@require_context
@pick_context_manager_writer
def block_device_mapping_update(context, bdm_id, values, legacy=True):
    _scrub_empty_str_values(values, ['volume_size'])
    values = _from_legacy_values(values, legacy, allow_updates=True)
    convert_objects_related_datetimes(values)

    query = _block_device_mapping_get_query(context).filter_by(id=bdm_id)
    query.update(values)
    return query.first()


@pick_context_manager_writer
def block_device_mapping_update_or_create(context, values, legacy=True):
    # TODO(mdbooth): Remove this method entirely. Callers should know whether
    # they require update or create, and call the appropriate method.

    _scrub_empty_str_values(values, ['volume_size'])
    values = _from_legacy_values(values, legacy, allow_updates=True)
    convert_objects_related_datetimes(values)

    result = None
    # NOTE(xqueralt,danms): Only update a BDM when device_name or
    # uuid was provided. Prefer the uuid, if available, but fall
    # back to device_name if no uuid is provided, which can happen
    # for BDMs created before we had a uuid. We allow empty device
    # names so they will be set later by the manager.
    if 'uuid' in values:
        query = _block_device_mapping_get_query(context)
        result = query.filter_by(instance_uuid=values['instance_uuid'],
                                 uuid=values['uuid']).one_or_none()

    if not result and values['device_name']:
        query = _block_device_mapping_get_query(context)
        result = query.filter_by(instance_uuid=values['instance_uuid'],
                                 device_name=values['device_name']).first()

    if result:
        result.update(values)
    else:
        # Either the device_name or uuid doesn't exist in the database yet, or
        # neither was provided. Both cases mean creating a new BDM.
        _set_or_validate_uuid(values)
        result = models.BlockDeviceMapping(**values)
        result.save(context.session)

    # NOTE(xqueralt): Prevent from having multiple swap devices for the
    # same instance. This will delete all the existing ones.
    if block_device.new_format_is_swap(values):
        query = _block_device_mapping_get_query(context)
        query = query.filter_by(instance_uuid=values['instance_uuid'],
                                source_type='blank', guest_format='swap')
        query = query.filter(models.BlockDeviceMapping.id != result.id)
        query.soft_delete()

    return result


@require_context
@pick_context_manager_reader_allow_async
def block_device_mapping_get_all_by_instance_uuids(context, instance_uuids):
    if not instance_uuids:
        return []
    return _block_device_mapping_get_query(context).filter(
        models.BlockDeviceMapping.instance_uuid.in_(instance_uuids)).all()


@require_context
@pick_context_manager_reader_allow_async
def block_device_mapping_get_all_by_instance(context, instance_uuid):
    return _block_device_mapping_get_query(context).\
                 filter_by(instance_uuid=instance_uuid).\
                 all()


@require_context
@pick_context_manager_reader
def block_device_mapping_get_all_by_volume_id(context, volume_id,
        columns_to_join=None):
    return _block_device_mapping_get_query(context,
            columns_to_join=columns_to_join).\
                 filter_by(volume_id=volume_id).\
                 all()


@require_context
@pick_context_manager_reader
def block_device_mapping_get_by_instance_and_volume_id(context, volume_id,
                                                       instance_uuid,
                                                       columns_to_join=None):
    return _block_device_mapping_get_query(context,
            columns_to_join=columns_to_join).\
                 filter_by(volume_id=volume_id).\
                 filter_by(instance_uuid=instance_uuid).\
                 first()


@require_context
@pick_context_manager_writer
def block_device_mapping_destroy(context, bdm_id):
    _block_device_mapping_get_query(context).\
            filter_by(id=bdm_id).\
            soft_delete()


@require_context
@pick_context_manager_writer
def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid,
                                                        volume_id):
    _block_device_mapping_get_query(context).\
            filter_by(instance_uuid=instance_uuid).\
            filter_by(volume_id=volume_id).\
            soft_delete()


@require_context
@pick_context_manager_writer
def block_device_mapping_destroy_by_instance_and_device(context, instance_uuid,
                                                        device_name):
    _block_device_mapping_get_query(context).\
            filter_by(instance_uuid=instance_uuid).\
            filter_by(device_name=device_name).\
            soft_delete()


###################


@require_context
@pick_context_manager_writer
def security_group_create(context, values):
    security_group_ref = models.SecurityGroup()
    # FIXME(devcamcar): Unless I do this, rules fails with lazy load exception
    # once save() is called.  This will get cleaned up in next orm pass.
    security_group_ref.rules
    security_group_ref.update(values)
    try:
        with get_context_manager(context).writer.savepoint.using(context):
            security_group_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.SecurityGroupExists(
                project_id=values['project_id'],
                security_group_name=values['name'])
    return security_group_ref


def _security_group_get_query(context, read_deleted=None,
                              project_only=False, join_rules=True):
    query = model_query(context, models.SecurityGroup,
            read_deleted=read_deleted, project_only=project_only)
    if join_rules:
        query = query.options(joinedload_all('rules.grantee_group'))
    return query


def _security_group_get_by_names(context, group_names):
    """Get security group models for a project by a list of names.
    Raise SecurityGroupNotFoundForProject for a name not found.
    """
    query = _security_group_get_query(context, read_deleted="no",
                                      join_rules=False).\
            filter_by(project_id=context.project_id).\
            filter(models.SecurityGroup.name.in_(group_names))
    sg_models = query.all()
    if len(sg_models) == len(group_names):
        return sg_models
    # Find the first one missing and raise
    group_names_from_models = [x.name for x in sg_models]
    for group_name in group_names:
        if group_name not in group_names_from_models:
            raise exception.SecurityGroupNotFoundForProject(
                project_id=context.project_id, security_group_id=group_name)
    # Not Reached


@require_context
@pick_context_manager_reader
def security_group_get_all(context):
    return _security_group_get_query(context).all()


@require_context
@pick_context_manager_reader
def security_group_get(context, security_group_id, columns_to_join=None):
    join_rules = columns_to_join and 'rules' in columns_to_join
    if join_rules:
        columns_to_join.remove('rules')
    query = _security_group_get_query(context, project_only=True,
                                      join_rules=join_rules).\
                    filter_by(id=security_group_id)

    if columns_to_join is None:
        columns_to_join = []
    for column in columns_to_join:
        if column.startswith('instances'):
            query = query.options(joinedload_all(column))

    result = query.first()
    if not result:
        raise exception.SecurityGroupNotFound(
                security_group_id=security_group_id)

    return result


@require_context
@pick_context_manager_reader
def security_group_get_by_name(context, project_id, group_name,
                               columns_to_join=None):
    query = _security_group_get_query(context,
                                      read_deleted="no", join_rules=False).\
            filter_by(project_id=project_id).\
            filter_by(name=group_name)

    if columns_to_join is None:
        columns_to_join = ['instances', 'rules.grantee_group']

    for column in columns_to_join:
        query = query.options(joinedload_all(column))

    result = query.first()
    if not result:
        raise exception.SecurityGroupNotFoundForProject(
                project_id=project_id, security_group_id=group_name)

    return result


@require_context
@pick_context_manager_reader
def security_group_get_by_project(context, project_id):
    return _security_group_get_query(context, read_deleted="no").\
                        filter_by(project_id=project_id).\
                        all()


@require_context
@pick_context_manager_reader
def security_group_get_by_instance(context, instance_uuid):
    return _security_group_get_query(context, read_deleted="no").\
                   join(models.SecurityGroup.instances).\
                   filter_by(uuid=instance_uuid).\
                   all()


@require_context
@pick_context_manager_reader
def security_group_in_use(context, group_id):
    # Are there any instances that haven't been deleted
    # that include this group?
    inst_assoc = model_query(context,
                             models.SecurityGroupInstanceAssociation,
                             read_deleted="no").\
                    filter_by(security_group_id=group_id).\
                    all()
    for ia in inst_assoc:
        num_instances = model_query(context, models.Instance,
                                    read_deleted="no").\
                    filter_by(uuid=ia.instance_uuid).\
                    count()
        if num_instances:
            return True

    return False


@require_context
@pick_context_manager_writer
def security_group_update(context, security_group_id, values,
                          columns_to_join=None):
    query = model_query(context, models.SecurityGroup).filter_by(
        id=security_group_id)
    if columns_to_join:
        for column in columns_to_join:
            query = query.options(joinedload_all(column))
    security_group_ref = query.first()

    if not security_group_ref:
        raise exception.SecurityGroupNotFound(
                security_group_id=security_group_id)
    security_group_ref.update(values)
    name = security_group_ref['name']
    project_id = security_group_ref['project_id']
    try:
        security_group_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.SecurityGroupExists(
                project_id=project_id,
                security_group_name=name)
    return security_group_ref


def security_group_ensure_default(context):
    """Ensure default security group exists for a project_id."""

    try:
        # NOTE(rpodolyaka): create the default security group, if it doesn't
        # exist. This must be done in a separate transaction, so that
        # this one is not aborted in case a concurrent one succeeds first
        # and the unique constraint for security group names is violated
        # by a concurrent INSERT
        with get_context_manager(context).writer.independent.using(context):
            return _security_group_ensure_default(context)
    except exception.SecurityGroupExists:
        # NOTE(rpodolyaka): a concurrent transaction has succeeded first,
        # suppress the error and proceed
        return security_group_get_by_name(context, context.project_id,
                                          'default')


@pick_context_manager_writer
def _security_group_ensure_default(context):
    try:
        default_group = _security_group_get_by_names(context, ['default'])[0]
    except exception.NotFound:
        values = {'name': 'default',
                  'description': 'default',
                  'user_id': context.user_id,
                  'project_id': context.project_id}
        default_group = security_group_create(context, values)

        default_rules = _security_group_rule_get_default_query(context).all()
        for default_rule in default_rules:
            # This is suboptimal, it should be programmatic to know
            # the values of the default_rule
            rule_values = {'protocol': default_rule.protocol,
                           'from_port': default_rule.from_port,
                           'to_port': default_rule.to_port,
                           'cidr': default_rule.cidr,
                           'parent_group_id': default_group.id,
            }
            _security_group_rule_create(context, rule_values)
    return default_group


@require_context
@pick_context_manager_writer
def security_group_destroy(context, security_group_id):
    model_query(context, models.SecurityGroup).\
            filter_by(id=security_group_id).\
            soft_delete()
    model_query(context, models.SecurityGroupInstanceAssociation).\
            filter_by(security_group_id=security_group_id).\
            soft_delete()
    model_query(context, models.SecurityGroupIngressRule).\
            filter_by(group_id=security_group_id).\
            soft_delete()
    model_query(context, models.SecurityGroupIngressRule).\
            filter_by(parent_group_id=security_group_id).\
            soft_delete()


def _security_group_count_by_project_and_user(context, project_id, user_id):
    nova.context.authorize_project_context(context, project_id)
    return model_query(context, models.SecurityGroup, read_deleted="no").\
                   filter_by(project_id=project_id).\
                   filter_by(user_id=user_id).\
                   count()


###################


def _security_group_rule_create(context, values):
    security_group_rule_ref = models.SecurityGroupIngressRule()
    security_group_rule_ref.update(values)
    security_group_rule_ref.save(context.session)
    return security_group_rule_ref


def _security_group_rule_get_query(context):
    return model_query(context, models.SecurityGroupIngressRule)


@require_context
@pick_context_manager_reader
def security_group_rule_get(context, security_group_rule_id):
    result = (_security_group_rule_get_query(context).
                         filter_by(id=security_group_rule_id).
                         first())

    if not result:
        raise exception.SecurityGroupNotFoundForRule(
                                               rule_id=security_group_rule_id)

    return result


@require_context
@pick_context_manager_reader
def security_group_rule_get_by_security_group(context, security_group_id,
                                              columns_to_join=None):
    if columns_to_join is None:
        columns_to_join = ['grantee_group.instances.system_metadata',
                           'grantee_group.instances.info_cache']
    query = (_security_group_rule_get_query(context).
             filter_by(parent_group_id=security_group_id))
    for column in columns_to_join:
        query = query.options(joinedload_all(column))
    return query.all()


@require_context
@pick_context_manager_reader
def security_group_rule_get_by_instance(context, instance_uuid):
    return (_security_group_rule_get_query(context).
            join('parent_group', 'instances').
            filter_by(uuid=instance_uuid).
            options(joinedload('grantee_group')).
            all())


@require_context
@pick_context_manager_writer
def security_group_rule_create(context, values):
    return _security_group_rule_create(context, values)


@require_context
@pick_context_manager_writer
def security_group_rule_destroy(context, security_group_rule_id):
    count = (_security_group_rule_get_query(context).
                    filter_by(id=security_group_rule_id).
                    soft_delete())
    if count == 0:
        raise exception.SecurityGroupNotFoundForRule(
                                            rule_id=security_group_rule_id)


@require_context
@pick_context_manager_reader
def security_group_rule_count_by_group(context, security_group_id):
    return (model_query(context, models.SecurityGroupIngressRule,
                   read_deleted="no").
                   filter_by(parent_group_id=security_group_id).
                   count())


###################


def _security_group_rule_get_default_query(context):
    return model_query(context, models.SecurityGroupIngressDefaultRule)


@require_context
@pick_context_manager_reader
def security_group_default_rule_get(context, security_group_rule_default_id):
    result = _security_group_rule_get_default_query(context).\
                        filter_by(id=security_group_rule_default_id).\
                        first()

    if not result:
        raise exception.SecurityGroupDefaultRuleNotFound(
                                        rule_id=security_group_rule_default_id)

    return result


@pick_context_manager_writer
def security_group_default_rule_destroy(context,
                                        security_group_rule_default_id):
    count = _security_group_rule_get_default_query(context).\
                        filter_by(id=security_group_rule_default_id).\
                        soft_delete()
    if count == 0:
        raise exception.SecurityGroupDefaultRuleNotFound(
                                    rule_id=security_group_rule_default_id)


@pick_context_manager_writer
def security_group_default_rule_create(context, values):
    security_group_default_rule_ref = models.SecurityGroupIngressDefaultRule()
    security_group_default_rule_ref.update(values)
    security_group_default_rule_ref.save(context.session)
    return security_group_default_rule_ref


@require_context
@pick_context_manager_reader
def security_group_default_rule_list(context):
    return _security_group_rule_get_default_query(context).all()


###################


@pick_context_manager_writer
def provider_fw_rule_create(context, rule):
    fw_rule_ref = models.ProviderFirewallRule()
    fw_rule_ref.update(rule)
    fw_rule_ref.save(context.session)
    return fw_rule_ref


@pick_context_manager_reader
def provider_fw_rule_get_all(context):
    return model_query(context, models.ProviderFirewallRule).all()


@pick_context_manager_writer
def provider_fw_rule_destroy(context, rule_id):
    context.session.query(models.ProviderFirewallRule).\
        filter_by(id=rule_id).\
        soft_delete()


###################


@require_context
@pick_context_manager_writer
def project_get_networks(context, project_id, associate=True):
    # NOTE(tr3buchet): as before this function will associate
    # a project with a network if it doesn't have one and
    # associate is true
    result = model_query(context, models.Network, read_deleted="no").\
                     filter_by(project_id=project_id).\
                     all()

    if not result:
        if not associate:
            return []

        return [network_associate(context, project_id)]

    return result


###################


@pick_context_manager_writer
def migration_create(context, values):
    migration = models.Migration()
    migration.update(values)
    migration.save(context.session)
    return migration


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def migration_update(context, id, values):
    migration = migration_get(context, id)
    migration.update(values)

    return migration


@pick_context_manager_reader
def migration_get(context, id):
    result = model_query(context, models.Migration, read_deleted="yes").\
                     filter_by(id=id).\
                     first()

    if not result:
        raise exception.MigrationNotFound(migration_id=id)

    return result


@pick_context_manager_reader
def migration_get_by_uuid(context, migration_uuid):
    result = model_query(context, models.Migration, read_deleted="yes").\
                     filter_by(uuid=migration_uuid).\
                     first()

    if not result:
        raise exception.MigrationNotFound(migration_id=migration_uuid)

    return result


@pick_context_manager_reader
def migration_get_by_id_and_instance(context, id, instance_uuid):
    result = model_query(context, models.Migration).\
                     filter_by(id=id).\
                     filter_by(instance_uuid=instance_uuid).\
                     first()

    if not result:
        raise exception.MigrationNotFoundForInstance(migration_id=id,
                                                     instance_id=instance_uuid)

    return result


@pick_context_manager_reader
def migration_get_by_instance_and_status(context, instance_uuid, status):
    result = model_query(context, models.Migration, read_deleted="yes").\
                     filter_by(instance_uuid=instance_uuid).\
                     filter_by(status=status).\
                     first()

    if not result:
        raise exception.MigrationNotFoundByStatus(instance_id=instance_uuid,
                                                  status=status)

    return result


@pick_context_manager_reader_allow_async
def migration_get_unconfirmed_by_dest_compute(context, confirm_window,
                                              dest_compute):
    confirm_window = (timeutils.utcnow() -
                      datetime.timedelta(seconds=confirm_window))

    return model_query(context, models.Migration, read_deleted="yes").\
             filter(models.Migration.updated_at <= confirm_window).\
             filter_by(status="finished").\
             filter_by(dest_compute=dest_compute).\
             all()


@pick_context_manager_reader
def migration_get_in_progress_by_host_and_node(context, host, node):
    # TODO(mriedem): Tracking what various code flows set for
    # migration status is nutty, since it happens all over the place
    # and several of the statuses are redundant (done and completed).
    # We need to define these in an enum somewhere and just update
    # that one central place that defines what "in progress" means.
    # NOTE(mriedem): The 'finished' status is not in this list because
    # 'finished' means a resize is finished on the destination host
    # and the instance is in VERIFY_RESIZE state, so the end state
    # for a resize is actually 'confirmed' or 'reverted'.
    return model_query(context, models.Migration).\
            filter(or_(and_(models.Migration.source_compute == host,
                            models.Migration.source_node == node),
                       and_(models.Migration.dest_compute == host,
                            models.Migration.dest_node == node))).\
            filter(~models.Migration.status.in_(['accepted', 'confirmed',
                                                 'reverted', 'error',
                                                 'failed', 'completed',
                                                 'cancelled', 'done'])).\
            options(joinedload_all('instance.system_metadata')).\
            all()


@pick_context_manager_reader
def migration_get_in_progress_by_instance(context, instance_uuid,
                                          migration_type=None):
    # TODO(Shaohe Feng) we should share the in-progress list.
    # TODO(Shaohe Feng) will also summarize all status to a new
    # MigrationStatus class.
    query = model_query(context, models.Migration).\
            filter_by(instance_uuid=instance_uuid).\
            filter(models.Migration.status.in_(['queued', 'preparing',
                                                'running',
                                                'post-migrating']))
    if migration_type:
        query = query.filter(models.Migration.migration_type == migration_type)

    return query.all()


@pick_context_manager_reader
def migration_get_all_by_filters(context, filters,
                                 sort_keys=None, sort_dirs=None,
                                 limit=None, marker=None):
    if limit == 0:
        return []

    query = model_query(context, models.Migration)
    if "uuid" in filters:
        # The uuid filter is here for the MigrationLister and multi-cell
        # paging support in the compute API.
        uuid = filters["uuid"]
        uuid = [uuid] if isinstance(uuid, six.string_types) else uuid
        query = query.filter(models.Migration.uuid.in_(uuid))
    if 'changes-since' in filters:
        changes_since = timeutils.normalize_time(filters['changes-since'])
        query = query. \
            filter(models.Migration.updated_at >= changes_since)
    if "status" in filters:
        status = filters["status"]
        status = [status] if isinstance(status, six.string_types) else status
        query = query.filter(models.Migration.status.in_(status))
    if "host" in filters:
        host = filters["host"]
        query = query.filter(or_(models.Migration.source_compute == host,
                                 models.Migration.dest_compute == host))
    elif "source_compute" in filters:
        host = filters['source_compute']
        query = query.filter(models.Migration.source_compute == host)
    if "migration_type" in filters:
        migtype = filters["migration_type"]
        query = query.filter(models.Migration.migration_type == migtype)
    if "hidden" in filters:
        hidden = filters["hidden"]
        query = query.filter(models.Migration.hidden == hidden)
    if "instance_uuid" in filters:
        instance_uuid = filters["instance_uuid"]
        query = query.filter(models.Migration.instance_uuid == instance_uuid)
    if marker:
        try:
            marker = migration_get_by_uuid(context, marker)
        except exception.MigrationNotFound:
            raise exception.MarkerNotFound(marker=marker)
    if limit or marker or sort_keys or sort_dirs:
        # Default sort by desc(['created_at', 'id'])
        sort_keys, sort_dirs = process_sort_params(sort_keys, sort_dirs,
                                                   default_dir='desc')
        return sqlalchemyutils.paginate_query(query,
                                              models.Migration,
                                              limit=limit,
                                              sort_keys=sort_keys,
                                              marker=marker,
                                              sort_dirs=sort_dirs).all()
    else:
        return query.all()


@require_context
@pick_context_manager_reader_allow_async
def migration_get_by_sort_filters(context, sort_keys, sort_dirs, values):
    """Attempt to get a single migration based on a combination of sort
    keys, directions and filter values. This is used to try to find a
    marker migration when we don't have a marker uuid.

    This returns just a uuid of the migration that matched.
    """
    model = models.Migration
    return _model_get_uuid_by_sort_filters(context, model, sort_keys,
                                           sort_dirs, values)


@pick_context_manager_writer
def migration_migrate_to_uuid(context, count):
    # Avoid circular import
    from nova import objects

    db_migrations = model_query(context, models.Migration).filter_by(
        uuid=None).limit(count).all()

    done = 0
    for db_migration in db_migrations:
        mig = objects.Migration(context)
        mig._from_db_object(context, mig, db_migration)
        done += 1

    # We don't have any situation where we can (detectably) not
    # migrate a thing, so report anything that matched as "completed".
    return done, done


##################


@pick_context_manager_writer
def console_pool_create(context, values):
    pool = models.ConsolePool()
    pool.update(values)
    try:
        pool.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.ConsolePoolExists(
            host=values["host"],
            console_type=values["console_type"],
            compute_host=values["compute_host"],
        )
    return pool


@pick_context_manager_reader
def console_pool_get_by_host_type(context, compute_host, host,
                                  console_type):

    result = model_query(context, models.ConsolePool, read_deleted="no").\
                   filter_by(host=host).\
                   filter_by(console_type=console_type).\
                   filter_by(compute_host=compute_host).\
                   options(joinedload('consoles')).\
                   first()

    if not result:
        raise exception.ConsolePoolNotFoundForHostType(
                host=host, console_type=console_type,
                compute_host=compute_host)

    return result


@pick_context_manager_reader
def console_pool_get_all_by_host_type(context, host, console_type):
    return model_query(context, models.ConsolePool, read_deleted="no").\
                   filter_by(host=host).\
                   filter_by(console_type=console_type).\
                   options(joinedload('consoles')).\
                   all()


##################


@pick_context_manager_writer
def console_create(context, values):
    console = models.Console()
    console.update(values)
    console.save(context.session)
    return console


@pick_context_manager_writer
def console_delete(context, console_id):
    # NOTE(mdragon): consoles are meant to be transient.
    context.session.query(models.Console).\
        filter_by(id=console_id).\
        delete()


@pick_context_manager_reader
def console_get_by_pool_instance(context, pool_id, instance_uuid):
    result = model_query(context, models.Console, read_deleted="yes").\
                   filter_by(pool_id=pool_id).\
                   filter_by(instance_uuid=instance_uuid).\
                   options(joinedload('pool')).\
                   first()

    if not result:
        raise exception.ConsoleNotFoundInPoolForInstance(
                pool_id=pool_id, instance_uuid=instance_uuid)

    return result


@pick_context_manager_reader
def console_get_all_by_instance(context, instance_uuid, columns_to_join=None):
    query = model_query(context, models.Console, read_deleted="yes").\
                filter_by(instance_uuid=instance_uuid)
    if columns_to_join:
        for column in columns_to_join:
            query = query.options(joinedload(column))
    return query.all()


@pick_context_manager_reader
def console_get(context, console_id, instance_uuid=None):
    query = model_query(context, models.Console, read_deleted="yes").\
                    filter_by(id=console_id).\
                    options(joinedload('pool'))

    if instance_uuid is not None:
        query = query.filter_by(instance_uuid=instance_uuid)

    result = query.first()

    if not result:
        if instance_uuid:
            raise exception.ConsoleNotFoundForInstance(
                    instance_uuid=instance_uuid)
        else:
            raise exception.ConsoleNotFound(console_id=console_id)

    return result


##################


@pick_context_manager_writer
def flavor_create(context, values, projects=None):
    """Create a new instance type. In order to pass in extra specs,
    the values dict should contain a 'extra_specs' key/value pair:

    {'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}}

    """
    specs = values.get('extra_specs')
    specs_refs = []
    if specs:
        for k, v in specs.items():
            specs_ref = models.InstanceTypeExtraSpecs()
            specs_ref['key'] = k
            specs_ref['value'] = v
            specs_refs.append(specs_ref)

    values['extra_specs'] = specs_refs
    instance_type_ref = models.InstanceTypes()
    instance_type_ref.update(values)

    if projects is None:
        projects = []

    try:
        instance_type_ref.save(context.session)
    except db_exc.DBDuplicateEntry as e:
        if 'flavorid' in e.columns:
            raise exception.FlavorIdExists(flavor_id=values['flavorid'])
        raise exception.FlavorExists(name=values['name'])
    except Exception as e:
        raise db_exc.DBError(e)
    for project in set(projects):
        access_ref = models.InstanceTypeProjects()
        access_ref.update({"instance_type_id": instance_type_ref.id,
                           "project_id": project})
        access_ref.save(context.session)

    return _dict_with_extra_specs(instance_type_ref)


def _dict_with_extra_specs(inst_type_query):
    """Takes an instance or instance type query returned
    by sqlalchemy and returns it as a dictionary, converting the
    extra_specs entry from a list of dicts:

    'extra_specs' : [{'key': 'k1', 'value': 'v1', ...}, ...]

    to a single dict:

    'extra_specs' : {'k1': 'v1'}

    """
    inst_type_dict = dict(inst_type_query)
    extra_specs = {x['key']: x['value']
                   for x in inst_type_query['extra_specs']}
    inst_type_dict['extra_specs'] = extra_specs
    return inst_type_dict


def _flavor_get_query(context, read_deleted=None):
    query = model_query(context, models.InstanceTypes,
                       read_deleted=read_deleted).\
                       options(joinedload('extra_specs'))
    if not context.is_admin:
        the_filter = [models.InstanceTypes.is_public == true()]
        the_filter.extend([
            models.InstanceTypes.projects.any(project_id=context.project_id)
        ])
        query = query.filter(or_(*the_filter))
    return query


@require_context
@pick_context_manager_reader
def flavor_get_all(context, inactive=False, filters=None,
                   sort_key='flavorid', sort_dir='asc', limit=None,
                   marker=None):
    """Returns all flavors.
    """
    filters = filters or {}

    # FIXME(sirp): now that we have the `disabled` field for flavors, we
    # should probably remove the use of `deleted` to mark inactive. `deleted`
    # should mean truly deleted, e.g. we can safely purge the record out of the
    # database.
    read_deleted = "yes" if inactive else "no"

    query = _flavor_get_query(context, read_deleted=read_deleted)

    if 'min_memory_mb' in filters:
        query = query.filter(
                models.InstanceTypes.memory_mb >= filters['min_memory_mb'])

    if 'min_root_gb' in filters:
        query = query.filter(
                models.InstanceTypes.root_gb >= filters['min_root_gb'])

    if 'disabled' in filters:
        query = query.filter(
                models.InstanceTypes.disabled == filters['disabled'])

    if 'is_public' in filters and filters['is_public'] is not None:
        the_filter = [models.InstanceTypes.is_public == filters['is_public']]
        if filters['is_public'] and context.project_id is not None:
            the_filter.extend([
                models.InstanceTypes.projects.any(
                    project_id=context.project_id, deleted=0)
            ])
        if len(the_filter) > 1:
            query = query.filter(or_(*the_filter))
        else:
            query = query.filter(the_filter[0])

    marker_row = None
    if marker is not None:
        marker_row = _flavor_get_query(context, read_deleted=read_deleted).\
                    filter_by(flavorid=marker).\
                    first()
        if not marker_row:
            raise exception.MarkerNotFound(marker=marker)

    query = sqlalchemyutils.paginate_query(query, models.InstanceTypes, limit,
                                           [sort_key, 'id'],
                                           marker=marker_row,
                                           sort_dir=sort_dir)

    inst_types = query.all()

    return [_dict_with_extra_specs(i) for i in inst_types]


def _flavor_get_id_from_flavor_query(context, flavor_id):
    return model_query(context, models.InstanceTypes,
                       (models.InstanceTypes.id,),
                       read_deleted="no").\
                filter_by(flavorid=flavor_id)


def _flavor_get_id_from_flavor(context, flavor_id):
    result = _flavor_get_id_from_flavor_query(context, flavor_id).first()
    if not result:
        raise exception.FlavorNotFound(flavor_id=flavor_id)
    return result[0]


@require_context
@pick_context_manager_reader
def flavor_get(context, id):
    """Returns a dict describing specific flavor."""
    result = _flavor_get_query(context).\
                        filter_by(id=id).\
                        first()
    if not result:
        raise exception.FlavorNotFound(flavor_id=id)
    return _dict_with_extra_specs(result)


@require_context
@pick_context_manager_reader
def flavor_get_by_name(context, name):
    """Returns a dict describing specific flavor."""
    result = _flavor_get_query(context).\
                        filter_by(name=name).\
                        first()
    if not result:
        raise exception.FlavorNotFoundByName(flavor_name=name)
    return _dict_with_extra_specs(result)


@require_context
@pick_context_manager_reader
def flavor_get_by_flavor_id(context, flavor_id, read_deleted):
    """Returns a dict describing specific flavor_id."""
    result = _flavor_get_query(context, read_deleted=read_deleted).\
                        filter_by(flavorid=flavor_id).\
                        order_by(asc(models.InstanceTypes.deleted),
                                 asc(models.InstanceTypes.id)).\
                        first()
    if not result:
        raise exception.FlavorNotFound(flavor_id=flavor_id)
    return _dict_with_extra_specs(result)


@pick_context_manager_writer
def flavor_destroy(context, flavor_id):
    """Marks specific flavor as deleted."""
    ref = model_query(context, models.InstanceTypes, read_deleted="no").\
                filter_by(flavorid=flavor_id).\
                first()
    if not ref:
        raise exception.FlavorNotFound(flavor_id=flavor_id)

    ref.soft_delete(context.session)
    model_query(context, models.InstanceTypeExtraSpecs, read_deleted="no").\
            filter_by(instance_type_id=ref['id']).\
            soft_delete()
    model_query(context, models.InstanceTypeProjects, read_deleted="no").\
            filter_by(instance_type_id=ref['id']).\
            soft_delete()


def _flavor_access_query(context):
    return model_query(context, models.InstanceTypeProjects, read_deleted="no")


@pick_context_manager_reader
def flavor_access_get_by_flavor_id(context, flavor_id):
    """Get flavor access list by flavor id."""
    instance_type_id_subq = _flavor_get_id_from_flavor_query(context,
                                                             flavor_id)
    access_refs = _flavor_access_query(context).\
                        filter_by(instance_type_id=instance_type_id_subq).\
                        all()
    return access_refs


@pick_context_manager_writer
def flavor_access_add(context, flavor_id, project_id):
    """Add given tenant to the flavor access list."""
    instance_type_id = _flavor_get_id_from_flavor(context, flavor_id)

    access_ref = models.InstanceTypeProjects()
    access_ref.update({"instance_type_id": instance_type_id,
                       "project_id": project_id})
    try:
        access_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.FlavorAccessExists(flavor_id=flavor_id,
                                            project_id=project_id)
    return access_ref


@pick_context_manager_writer
def flavor_access_remove(context, flavor_id, project_id):
    """Remove given tenant from the flavor access list."""
    instance_type_id = _flavor_get_id_from_flavor(context, flavor_id)

    count = _flavor_access_query(context).\
                    filter_by(instance_type_id=instance_type_id).\
                    filter_by(project_id=project_id).\
                    soft_delete(synchronize_session=False)
    if count == 0:
        raise exception.FlavorAccessNotFound(flavor_id=flavor_id,
                                             project_id=project_id)


def _flavor_extra_specs_get_query(context, flavor_id):
    instance_type_id_subq = _flavor_get_id_from_flavor_query(context,
                                                             flavor_id)

    return model_query(context, models.InstanceTypeExtraSpecs,
                       read_deleted="no").\
                filter_by(instance_type_id=instance_type_id_subq)


@require_context
@pick_context_manager_reader
def flavor_extra_specs_get(context, flavor_id):
    rows = _flavor_extra_specs_get_query(context, flavor_id).all()
    return {row['key']: row['value'] for row in rows}


@require_context
@pick_context_manager_writer
def flavor_extra_specs_delete(context, flavor_id, key):
    result = _flavor_extra_specs_get_query(context, flavor_id).\
                     filter(models.InstanceTypeExtraSpecs.key == key).\
                     soft_delete(synchronize_session=False)
    # did not find the extra spec
    if result == 0:
        raise exception.FlavorExtraSpecsNotFound(
                extra_specs_key=key, flavor_id=flavor_id)


@require_context
@pick_context_manager_writer
def flavor_extra_specs_update_or_create(context, flavor_id, specs,
                                               max_retries=10):
    for attempt in range(max_retries):
        try:
            instance_type_id = _flavor_get_id_from_flavor(context, flavor_id)

            spec_refs = model_query(context, models.InstanceTypeExtraSpecs,
                                    read_deleted="no").\
              filter_by(instance_type_id=instance_type_id).\
              filter(models.InstanceTypeExtraSpecs.key.in_(specs.keys())).\
              all()

            existing_keys = set()
            for spec_ref in spec_refs:
                key = spec_ref["key"]
                existing_keys.add(key)
                with get_context_manager(context).writer.savepoint.using(
                        context):
                    spec_ref.update({"value": specs[key]})

            for key, value in specs.items():
                if key in existing_keys:
                    continue
                spec_ref = models.InstanceTypeExtraSpecs()
                with get_context_manager(context).writer.savepoint.using(
                        context):
                    spec_ref.update({"key": key, "value": value,
                                     "instance_type_id": instance_type_id})
                    context.session.add(spec_ref)

            return specs
        except db_exc.DBDuplicateEntry:
            # a concurrent transaction has been committed,
            # try again unless this was the last attempt
            if attempt == max_retries - 1:
                raise exception.FlavorExtraSpecUpdateCreateFailed(
                                    id=flavor_id, retries=max_retries)


####################


@pick_context_manager_writer
def cell_create(context, values):
    cell = models.Cell()
    cell.update(values)
    try:
        cell.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.CellExists(name=values['name'])
    return cell


def _cell_get_by_name_query(context, cell_name):
    return model_query(context, models.Cell).filter_by(name=cell_name)


@pick_context_manager_writer
def cell_update(context, cell_name, values):
    cell_query = _cell_get_by_name_query(context, cell_name)
    if not cell_query.update(values):
        raise exception.CellNotFound(cell_name=cell_name)
    cell = cell_query.first()
    return cell


@pick_context_manager_writer
def cell_delete(context, cell_name):
    return _cell_get_by_name_query(context, cell_name).soft_delete()


@pick_context_manager_reader
def cell_get(context, cell_name):
    result = _cell_get_by_name_query(context, cell_name).first()
    if not result:
        raise exception.CellNotFound(cell_name=cell_name)
    return result


@pick_context_manager_reader
def cell_get_all(context):
    return model_query(context, models.Cell, read_deleted="no").all()


########################
# User-provided metadata

def _instance_metadata_get_multi(context, instance_uuids):
    if not instance_uuids:
        return []
    return model_query(context, models.InstanceMetadata).filter(
        models.InstanceMetadata.instance_uuid.in_(instance_uuids))


def _instance_metadata_get_query(context, instance_uuid):
    return model_query(context, models.InstanceMetadata, read_deleted="no").\
                    filter_by(instance_uuid=instance_uuid)


@require_context
@pick_context_manager_reader
def instance_metadata_get(context, instance_uuid):
    rows = _instance_metadata_get_query(context, instance_uuid).all()
    return {row['key']: row['value'] for row in rows}


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def instance_metadata_delete(context, instance_uuid, key):
    _instance_metadata_get_query(context, instance_uuid).\
        filter_by(key=key).\
        soft_delete()


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def instance_metadata_update(context, instance_uuid, metadata, delete):
    all_keys = metadata.keys()
    if delete:
        _instance_metadata_get_query(context, instance_uuid).\
            filter(~models.InstanceMetadata.key.in_(all_keys)).\
            soft_delete(synchronize_session=False)

    already_existing_keys = []
    meta_refs = _instance_metadata_get_query(context, instance_uuid).\
        filter(models.InstanceMetadata.key.in_(all_keys)).\
        all()

    for meta_ref in meta_refs:
        already_existing_keys.append(meta_ref.key)
        meta_ref.update({"value": metadata[meta_ref.key]})

    new_keys = set(all_keys) - set(already_existing_keys)
    for key in new_keys:
        meta_ref = models.InstanceMetadata()
        meta_ref.update({"key": key, "value": metadata[key],
                         "instance_uuid": instance_uuid})
        context.session.add(meta_ref)

    return metadata


#######################
# System-owned metadata


def _instance_system_metadata_get_multi(context, instance_uuids):
    if not instance_uuids:
        return []
    return model_query(context, models.InstanceSystemMetadata,
                       read_deleted='yes').filter(
        models.InstanceSystemMetadata.instance_uuid.in_(instance_uuids))


def _instance_system_metadata_get_query(context, instance_uuid):
    return model_query(context, models.InstanceSystemMetadata).\
                    filter_by(instance_uuid=instance_uuid)


@require_context
@pick_context_manager_reader
def instance_system_metadata_get(context, instance_uuid):
    rows = _instance_system_metadata_get_query(context, instance_uuid).all()
    return {row['key']: row['value'] for row in rows}


@require_context
@pick_context_manager_writer
def instance_system_metadata_update(context, instance_uuid, metadata, delete):
    all_keys = metadata.keys()
    if delete:
        _instance_system_metadata_get_query(context, instance_uuid).\
            filter(~models.InstanceSystemMetadata.key.in_(all_keys)).\
            soft_delete(synchronize_session=False)

    already_existing_keys = []
    meta_refs = _instance_system_metadata_get_query(context, instance_uuid).\
        filter(models.InstanceSystemMetadata.key.in_(all_keys)).\
        all()

    for meta_ref in meta_refs:
        already_existing_keys.append(meta_ref.key)
        meta_ref.update({"value": metadata[meta_ref.key]})

    new_keys = set(all_keys) - set(already_existing_keys)
    for key in new_keys:
        meta_ref = models.InstanceSystemMetadata()
        meta_ref.update({"key": key, "value": metadata[key],
                         "instance_uuid": instance_uuid})
        context.session.add(meta_ref)

    return metadata


####################


@pick_context_manager_writer
def agent_build_create(context, values):
    agent_build_ref = models.AgentBuild()
    agent_build_ref.update(values)
    try:
        agent_build_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.AgentBuildExists(hypervisor=values['hypervisor'],
                        os=values['os'], architecture=values['architecture'])
    return agent_build_ref


@pick_context_manager_reader
def agent_build_get_by_triple(context, hypervisor, os, architecture):
    return model_query(context, models.AgentBuild, read_deleted="no").\
                   filter_by(hypervisor=hypervisor).\
                   filter_by(os=os).\
                   filter_by(architecture=architecture).\
                   first()


@pick_context_manager_reader
def agent_build_get_all(context, hypervisor=None):
    if hypervisor:
        return model_query(context, models.AgentBuild, read_deleted="no").\
                   filter_by(hypervisor=hypervisor).\
                   all()
    else:
        return model_query(context, models.AgentBuild, read_deleted="no").\
                   all()


@pick_context_manager_writer
def agent_build_destroy(context, agent_build_id):
    rows_affected = model_query(context, models.AgentBuild).filter_by(
                                        id=agent_build_id).soft_delete()
    if rows_affected == 0:
        raise exception.AgentBuildNotFound(id=agent_build_id)


@pick_context_manager_writer
def agent_build_update(context, agent_build_id, values):
    rows_affected = model_query(context, models.AgentBuild).\
                   filter_by(id=agent_build_id).\
                   update(values)
    if rows_affected == 0:
        raise exception.AgentBuildNotFound(id=agent_build_id)


####################

@require_context
@pick_context_manager_reader_allow_async
def bw_usage_get(context, uuid, start_period, mac):
    values = {'start_period': start_period}
    values = convert_objects_related_datetimes(values, 'start_period')
    return model_query(context, models.BandwidthUsage, read_deleted="yes").\
                           filter_by(start_period=values['start_period']).\
                           filter_by(uuid=uuid).\
                           filter_by(mac=mac).\
                           first()


@require_context
@pick_context_manager_reader_allow_async
def bw_usage_get_by_uuids(context, uuids, start_period):
    values = {'start_period': start_period}
    values = convert_objects_related_datetimes(values, 'start_period')
    return (
        model_query(context, models.BandwidthUsage, read_deleted="yes").
        filter(models.BandwidthUsage.uuid.in_(uuids)).
        filter_by(start_period=values['start_period']).
        all()
    )


@require_context
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out,
                    last_ctr_in, last_ctr_out, last_refreshed=None):

    if last_refreshed is None:
        last_refreshed = timeutils.utcnow()

    # NOTE(comstud): More often than not, we'll be updating records vs
    # creating records.  Optimize accordingly, trying to update existing
    # records.  Fall back to creation when no rows are updated.
    ts_values = {'last_refreshed': last_refreshed,
                 'start_period': start_period}
    ts_keys = ('start_period', 'last_refreshed')
    ts_values = convert_objects_related_datetimes(ts_values, *ts_keys)
    values = {'last_refreshed': ts_values['last_refreshed'],
              'last_ctr_in': last_ctr_in,
              'last_ctr_out': last_ctr_out,
              'bw_in': bw_in,
              'bw_out': bw_out}
    # NOTE(pkholkin): order_by() is needed here to ensure that the
    # same record is updated every time. It can be removed after adding
    # unique constraint to this model.
    bw_usage = model_query(context, models.BandwidthUsage,
            read_deleted='yes').\
                    filter_by(start_period=ts_values['start_period']).\
                    filter_by(uuid=uuid).\
                    filter_by(mac=mac).\
                    order_by(asc(models.BandwidthUsage.id)).first()

    if bw_usage:
        bw_usage.update(values)
        return bw_usage

    bwusage = models.BandwidthUsage()
    bwusage.start_period = ts_values['start_period']
    bwusage.uuid = uuid
    bwusage.mac = mac
    bwusage.last_refreshed = ts_values['last_refreshed']
    bwusage.bw_in = bw_in
    bwusage.bw_out = bw_out
    bwusage.last_ctr_in = last_ctr_in
    bwusage.last_ctr_out = last_ctr_out
    bwusage.save(context.session)

    return bwusage


####################


@require_context
@pick_context_manager_reader
def vol_get_usage_by_time(context, begin):
    """Return volumes usage that have been updated after a specified time."""
    return model_query(context, models.VolumeUsage, read_deleted="yes").\
                   filter(or_(models.VolumeUsage.tot_last_refreshed == null(),
                              models.VolumeUsage.tot_last_refreshed > begin,
                              models.VolumeUsage.curr_last_refreshed == null(),
                              models.VolumeUsage.curr_last_refreshed > begin,
                              )).all()


@require_context
@pick_context_manager_writer
def vol_usage_update(context, id, rd_req, rd_bytes, wr_req, wr_bytes,
                     instance_id, project_id, user_id, availability_zone,
                     update_totals=False):

    refreshed = timeutils.utcnow()

    values = {}
    # NOTE(dricco): We will be mostly updating current usage records vs
    # updating total or creating records. Optimize accordingly.
    if not update_totals:
        values = {'curr_last_refreshed': refreshed,
                  'curr_reads': rd_req,
                  'curr_read_bytes': rd_bytes,
                  'curr_writes': wr_req,
                  'curr_write_bytes': wr_bytes,
                  'instance_uuid': instance_id,
                  'project_id': project_id,
                  'user_id': user_id,
                  'availability_zone': availability_zone}
    else:
        values = {'tot_last_refreshed': refreshed,
                  'tot_reads': models.VolumeUsage.tot_reads + rd_req,
                  'tot_read_bytes': models.VolumeUsage.tot_read_bytes +
                                    rd_bytes,
                  'tot_writes': models.VolumeUsage.tot_writes + wr_req,
                  'tot_write_bytes': models.VolumeUsage.tot_write_bytes +
                                     wr_bytes,
                  'curr_reads': 0,
                  'curr_read_bytes': 0,
                  'curr_writes': 0,
                  'curr_write_bytes': 0,
                  'instance_uuid': instance_id,
                  'project_id': project_id,
                  'user_id': user_id,
                  'availability_zone': availability_zone}

    current_usage = model_query(context, models.VolumeUsage,
                        read_deleted="yes").\
                        filter_by(volume_id=id).\
                        first()
    if current_usage:
        if (rd_req < current_usage['curr_reads'] or
            rd_bytes < current_usage['curr_read_bytes'] or
            wr_req < current_usage['curr_writes'] or
                wr_bytes < current_usage['curr_write_bytes']):
            LOG.info("Volume(%s) has lower stats then what is in "
                     "the database. Instance must have been rebooted "
                     "or crashed. Updating totals.", id)
            if not update_totals:
                values['tot_reads'] = (models.VolumeUsage.tot_reads +
                                       current_usage['curr_reads'])
                values['tot_read_bytes'] = (
                    models.VolumeUsage.tot_read_bytes +
                    current_usage['curr_read_bytes'])
                values['tot_writes'] = (models.VolumeUsage.tot_writes +
                                        current_usage['curr_writes'])
                values['tot_write_bytes'] = (
                    models.VolumeUsage.tot_write_bytes +
                    current_usage['curr_write_bytes'])
            else:
                values['tot_reads'] = (models.VolumeUsage.tot_reads +
                                       current_usage['curr_reads'] +
                                       rd_req)
                values['tot_read_bytes'] = (
                    models.VolumeUsage.tot_read_bytes +
                    current_usage['curr_read_bytes'] + rd_bytes)
                values['tot_writes'] = (models.VolumeUsage.tot_writes +
                                        current_usage['curr_writes'] +
                                        wr_req)
                values['tot_write_bytes'] = (
                    models.VolumeUsage.tot_write_bytes +
                    current_usage['curr_write_bytes'] + wr_bytes)

        current_usage.update(values)
        current_usage.save(context.session)
        context.session.refresh(current_usage)
        return current_usage

    vol_usage = models.VolumeUsage()
    vol_usage.volume_id = id
    vol_usage.instance_uuid = instance_id
    vol_usage.project_id = project_id
    vol_usage.user_id = user_id
    vol_usage.availability_zone = availability_zone

    if not update_totals:
        vol_usage.curr_last_refreshed = refreshed
        vol_usage.curr_reads = rd_req
        vol_usage.curr_read_bytes = rd_bytes
        vol_usage.curr_writes = wr_req
        vol_usage.curr_write_bytes = wr_bytes
    else:
        vol_usage.tot_last_refreshed = refreshed
        vol_usage.tot_reads = rd_req
        vol_usage.tot_read_bytes = rd_bytes
        vol_usage.tot_writes = wr_req
        vol_usage.tot_write_bytes = wr_bytes

    vol_usage.save(context.session)

    return vol_usage


####################


@pick_context_manager_reader
def s3_image_get(context, image_id):
    """Find local s3 image represented by the provided id."""
    result = model_query(context, models.S3Image, read_deleted="yes").\
                 filter_by(id=image_id).\
                 first()

    if not result:
        raise exception.ImageNotFound(image_id=image_id)

    return result


@pick_context_manager_reader
def s3_image_get_by_uuid(context, image_uuid):
    """Find local s3 image represented by the provided uuid."""
    result = model_query(context, models.S3Image, read_deleted="yes").\
                 filter_by(uuid=image_uuid).\
                 first()

    if not result:
        raise exception.ImageNotFound(image_id=image_uuid)

    return result


@pick_context_manager_writer
def s3_image_create(context, image_uuid):
    """Create local s3 image represented by provided uuid."""
    try:
        s3_image_ref = models.S3Image()
        s3_image_ref.update({'uuid': image_uuid})
        s3_image_ref.save(context.session)
    except Exception as e:
        raise db_exc.DBError(e)

    return s3_image_ref


####################


def _aggregate_get_query(context, model_class, id_field=None, id=None,
                         read_deleted=None):
    columns_to_join = {models.Aggregate: ['_hosts', '_metadata']}

    query = model_query(context, model_class, read_deleted=read_deleted)

    for c in columns_to_join.get(model_class, []):
        query = query.options(joinedload(c))

    if id and id_field:
        query = query.filter(id_field == id)

    return query


@pick_context_manager_writer
def aggregate_create(context, values, metadata=None):
    query = _aggregate_get_query(context,
                                 models.Aggregate,
                                 models.Aggregate.name,
                                 values['name'],
                                 read_deleted='no')
    aggregate = query.first()
    if not aggregate:
        aggregate = models.Aggregate()
        aggregate.update(values)
        aggregate.save(context.session)
        # We don't want these to be lazy loaded later.  We know there is
        # nothing here since we just created this aggregate.
        aggregate._hosts = []
        aggregate._metadata = []
    else:
        raise exception.AggregateNameExists(aggregate_name=values['name'])
    if metadata:
        aggregate_metadata_add(context, aggregate.id, metadata)
        # NOTE(pkholkin): '_metadata' attribute was updated during
        # 'aggregate_metadata_add' method, so it should be expired and
        # read from db
        context.session.expire(aggregate, ['_metadata'])
        aggregate._metadata

    return aggregate


@pick_context_manager_reader
def aggregate_get(context, aggregate_id):
    query = _aggregate_get_query(context,
                                 models.Aggregate,
                                 models.Aggregate.id,
                                 aggregate_id)
    aggregate = query.first()

    if not aggregate:
        raise exception.AggregateNotFound(aggregate_id=aggregate_id)

    return aggregate


@pick_context_manager_reader
def aggregate_get_by_uuid(context, uuid):
    query = _aggregate_get_query(context,
                                 models.Aggregate,
                                 models.Aggregate.uuid,
                                 uuid)
    aggregate = query.first()

    if not aggregate:
        raise exception.AggregateNotFound(aggregate_id=uuid)

    return aggregate


@pick_context_manager_reader
def aggregate_get_by_host(context, host, key=None):
    """Return rows that match host (mandatory) and metadata key (optional).

    :param host matches host, and is required.
    :param key Matches metadata key, if not None.
    """
    query = model_query(context, models.Aggregate)
    query = query.options(joinedload('_hosts'))
    query = query.options(joinedload('_metadata'))
    query = query.join('_hosts')
    query = query.filter(models.AggregateHost.host == host)

    if key:
        query = query.join("_metadata").filter(
            models.AggregateMetadata.key == key)
    return query.all()


@pick_context_manager_reader
def aggregate_metadata_get_by_host(context, host, key=None):
    query = model_query(context, models.Aggregate)
    query = query.join("_hosts")
    query = query.join("_metadata")
    query = query.filter(models.AggregateHost.host == host)
    query = query.options(contains_eager("_metadata"))

    if key:
        query = query.filter(models.AggregateMetadata.key == key)
    rows = query.all()

    metadata = collections.defaultdict(set)
    for agg in rows:
        for kv in agg._metadata:
            metadata[kv['key']].add(kv['value'])
    return dict(metadata)


@pick_context_manager_reader
def aggregate_get_by_metadata_key(context, key):
    """Return rows that match metadata key.

    :param key Matches metadata key.
    """
    query = model_query(context, models.Aggregate)
    query = query.join("_metadata")
    query = query.filter(models.AggregateMetadata.key == key)
    query = query.options(contains_eager("_metadata"))
    query = query.options(joinedload("_hosts"))
    return query.all()


@pick_context_manager_writer
def aggregate_update(context, aggregate_id, values):
    if "name" in values:
        aggregate_by_name = (_aggregate_get_query(context,
                                                  models.Aggregate,
                                                  models.Aggregate.name,
                                                  values['name'],
                                                  read_deleted='no').first())
        if aggregate_by_name and aggregate_by_name.id != aggregate_id:
            # there is another aggregate with the new name
            raise exception.AggregateNameExists(aggregate_name=values['name'])

    aggregate = (_aggregate_get_query(context,
                                     models.Aggregate,
                                     models.Aggregate.id,
                                     aggregate_id).first())

    set_delete = True
    if aggregate:
        if "availability_zone" in values:
            az = values.pop('availability_zone')
            if 'metadata' not in values:
                values['metadata'] = {'availability_zone': az}
                set_delete = False
            else:
                values['metadata']['availability_zone'] = az
        metadata = values.get('metadata')
        if metadata is not None:
            aggregate_metadata_add(context,
                                   aggregate_id,
                                   values.pop('metadata'),
                                   set_delete=set_delete)

        aggregate.update(values)
        aggregate.save(context.session)
        return aggregate_get(context, aggregate.id)
    else:
        raise exception.AggregateNotFound(aggregate_id=aggregate_id)


@pick_context_manager_writer
def aggregate_delete(context, aggregate_id):
    count = _aggregate_get_query(context,
                                 models.Aggregate,
                                 models.Aggregate.id,
                                 aggregate_id).\
                soft_delete()
    if count == 0:
        raise exception.AggregateNotFound(aggregate_id=aggregate_id)

    # Delete Metadata
    model_query(context, models.AggregateMetadata).\
                filter_by(aggregate_id=aggregate_id).\
                soft_delete()


@pick_context_manager_reader
def aggregate_get_all(context):
    return _aggregate_get_query(context, models.Aggregate).all()


def _aggregate_metadata_get_query(context, aggregate_id, read_deleted="yes"):
    return model_query(context,
                       models.AggregateMetadata,
                       read_deleted=read_deleted).\
                filter_by(aggregate_id=aggregate_id)


@require_aggregate_exists
@pick_context_manager_reader
def aggregate_metadata_get(context, aggregate_id):
    rows = model_query(context,
                       models.AggregateMetadata).\
                       filter_by(aggregate_id=aggregate_id).all()

    return {r['key']: r['value'] for r in rows}


@require_aggregate_exists
@pick_context_manager_writer
def aggregate_metadata_delete(context, aggregate_id, key):
    count = _aggregate_get_query(context,
                                 models.AggregateMetadata,
                                 models.AggregateMetadata.aggregate_id,
                                 aggregate_id).\
                                 filter_by(key=key).\
                                 soft_delete()
    if count == 0:
        raise exception.AggregateMetadataNotFound(aggregate_id=aggregate_id,
                                                  metadata_key=key)


@require_aggregate_exists
@pick_context_manager_writer
def aggregate_metadata_add(context, aggregate_id, metadata, set_delete=False,
                           max_retries=10):
    all_keys = metadata.keys()
    for attempt in range(max_retries):
        try:
            query = _aggregate_metadata_get_query(context, aggregate_id,
                                                  read_deleted='no')
            if set_delete:
                query.filter(~models.AggregateMetadata.key.in_(all_keys)).\
                    soft_delete(synchronize_session=False)

            already_existing_keys = set()
            if all_keys:
                query = query.filter(
                    models.AggregateMetadata.key.in_(all_keys))
                for meta_ref in query.all():
                    key = meta_ref.key
                    meta_ref.update({"value": metadata[key]})
                    already_existing_keys.add(key)

            new_entries = []
            for key, value in metadata.items():
                if key in already_existing_keys:
                    continue
                new_entries.append({"key": key,
                                    "value": value,
                                    "aggregate_id": aggregate_id})
            if new_entries:
                context.session.execute(
                    models.AggregateMetadata.__table__.insert(),
                    new_entries)

            return metadata
        except db_exc.DBDuplicateEntry:
            # a concurrent transaction has been committed,
            # try again unless this was the last attempt
            with excutils.save_and_reraise_exception() as ctxt:
                if attempt < max_retries - 1:
                    ctxt.reraise = False
                else:
                    LOG.warning("Add metadata failed for aggregate %(id)s "
                                "after %(retries)s retries",
                                {"id": aggregate_id, "retries": max_retries})


@require_aggregate_exists
@pick_context_manager_reader
def aggregate_host_get_all(context, aggregate_id):
    rows = model_query(context,
                       models.AggregateHost).\
                       filter_by(aggregate_id=aggregate_id).all()

    return [r.host for r in rows]


@require_aggregate_exists
@pick_context_manager_writer
def aggregate_host_delete(context, aggregate_id, host):
    count = _aggregate_get_query(context,
                                 models.AggregateHost,
                                 models.AggregateHost.aggregate_id,
                                 aggregate_id).\
            filter_by(host=host).\
            soft_delete()
    if count == 0:
        raise exception.AggregateHostNotFound(aggregate_id=aggregate_id,
                                              host=host)


@require_aggregate_exists
@pick_context_manager_writer
def aggregate_host_add(context, aggregate_id, host):
    host_ref = models.AggregateHost()
    host_ref.update({"host": host, "aggregate_id": aggregate_id})
    try:
        host_ref.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.AggregateHostExists(host=host,
                                            aggregate_id=aggregate_id)
    return host_ref


################


@pick_context_manager_writer
def instance_fault_create(context, values):
    """Create a new InstanceFault."""
    fault_ref = models.InstanceFault()
    fault_ref.update(values)
    fault_ref.save(context.session)
    return dict(fault_ref)


@pick_context_manager_reader
def instance_fault_get_by_instance_uuids(context, instance_uuids,
                                         latest=False):
    """Get all instance faults for the provided instance_uuids.

    :param instance_uuids: List of UUIDs of instances to grab faults for
    :param latest: Optional boolean indicating we should only return the latest
                   fault for the instance
    """
    if not instance_uuids:
        return {}

    faults_tbl = models.InstanceFault.__table__
    # NOTE(rpodolyaka): filtering by instance_uuids is performed in both
    # code branches below for the sake of a better query plan. On change,
    # make sure to update the other one as well.
    query = model_query(context, models.InstanceFault,
                        [faults_tbl],
                        read_deleted='no')

    if latest:
        # NOTE(jaypipes): We join instance_faults to a derived table of the
        # latest faults per instance UUID. The SQL produced below looks like
        # this:
        #
        #  SELECT instance_faults.*
        #  FROM instance_faults
        #  JOIN (
        #    SELECT instance_uuid, MAX(id) AS max_id
        #    FROM instance_faults
        #    WHERE instance_uuid IN ( ... )
        #    AND deleted = 0
        #    GROUP BY instance_uuid
        #  ) AS latest_faults
        #    ON instance_faults.id = latest_faults.max_id;
        latest_faults = model_query(
            context, models.InstanceFault,
            [faults_tbl.c.instance_uuid,
             sql.func.max(faults_tbl.c.id).label('max_id')],
            read_deleted='no'
        ).filter(
            faults_tbl.c.instance_uuid.in_(instance_uuids)
        ).group_by(
            faults_tbl.c.instance_uuid
        ).subquery(name="latest_faults")

        query = query.join(latest_faults,
                           faults_tbl.c.id == latest_faults.c.max_id)
    else:
        query = query.filter(models.InstanceFault.instance_uuid.in_(
                                        instance_uuids)).order_by(desc("id"))

    output = {}
    for instance_uuid in instance_uuids:
        output[instance_uuid] = []

    for row in query:
        output[row.instance_uuid].append(row._asdict())

    return output


##################


@pick_context_manager_writer
def action_start(context, values):
    convert_objects_related_datetimes(values, 'start_time', 'updated_at')
    action_ref = models.InstanceAction()
    action_ref.update(values)
    action_ref.save(context.session)
    return action_ref


@pick_context_manager_writer
def action_finish(context, values):
    convert_objects_related_datetimes(values, 'start_time', 'finish_time',
                                      'updated_at')
    query = model_query(context, models.InstanceAction).\
                        filter_by(instance_uuid=values['instance_uuid']).\
                        filter_by(request_id=values['request_id'])
    if query.update(values) != 1:
        raise exception.InstanceActionNotFound(
                                    request_id=values['request_id'],
                                    instance_uuid=values['instance_uuid'])
    return query.one()


@pick_context_manager_reader
def actions_get(context, instance_uuid, limit=None, marker=None,
                filters=None):
    """Get all instance actions for the provided uuid and filters."""
    if limit == 0:
        return []

    sort_keys = ['created_at', 'id']
    sort_dirs = ['desc', 'desc']

    query_prefix = model_query(context, models.InstanceAction).\
        filter_by(instance_uuid=instance_uuid)
    if filters and 'changes-since' in filters:
        changes_since = timeutils.normalize_time(filters['changes-since'])
        query_prefix = query_prefix. \
            filter(models.InstanceAction.updated_at >= changes_since)

    if marker is not None:
        marker = action_get_by_request_id(context, instance_uuid, marker)
        if not marker:
            raise exception.MarkerNotFound(marker=marker)
    actions = sqlalchemyutils.paginate_query(query_prefix,
                                             models.InstanceAction, limit,
                                             sort_keys, marker=marker,
                                             sort_dirs=sort_dirs).all()
    return actions


@pick_context_manager_reader
def action_get_by_request_id(context, instance_uuid, request_id):
    """Get the action by request_id and given instance."""
    action = _action_get_by_request_id(context, instance_uuid, request_id)
    return action


def _action_get_by_request_id(context, instance_uuid, request_id):
    result = model_query(context, models.InstanceAction).\
                         filter_by(instance_uuid=instance_uuid).\
                         filter_by(request_id=request_id).\
                         order_by(desc("created_at"), desc("id")).\
                         first()
    return result


def _action_get_last_created_by_instance_uuid(context, instance_uuid):
    result = (model_query(context, models.InstanceAction).
                     filter_by(instance_uuid=instance_uuid).
                     order_by(desc("created_at"), desc("id")).
                     first())
    return result


@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def action_event_start(context, values):
    """Start an event on an instance action."""
    convert_objects_related_datetimes(values, 'start_time')
    action = _action_get_by_request_id(context, values['instance_uuid'],
                                       values['request_id'])
    # When nova-compute restarts, the context is generated again in
    # init_host workflow, the request_id was different with the request_id
    # recorded in InstanceAction, so we can't get the original record
    # according to request_id. Try to get the last created action so that
    # init_instance can continue to finish the recovery action, like:
    # powering_off, unpausing, and so on.
    update_action = True
    if not action and not context.project_id:
        action = _action_get_last_created_by_instance_uuid(
            context, values['instance_uuid'])
        # If we couldn't find an action by the request_id, we don't want to
        # update this action since it likely represents an inactive action.
        update_action = False

    if not action:
        raise exception.InstanceActionNotFound(
                                    request_id=values['request_id'],
                                    instance_uuid=values['instance_uuid'])

    values['action_id'] = action['id']

    event_ref = models.InstanceActionEvent()
    event_ref.update(values)
    context.session.add(event_ref)

    # Update action updated_at.
    if update_action:
        action.update({'updated_at': values['start_time']})
        action.save(context.session)

    return event_ref


# NOTE: We need the retry_on_deadlock decorator for cases like resize where
# a lot of events are happening at once between multiple hosts trying to
# update the same action record in a small time window.
@oslo_db_api.wrap_db_retry(max_retries=5, retry_on_deadlock=True)
@pick_context_manager_writer
def action_event_finish(context, values):
    """Finish an event on an instance action."""
    convert_objects_related_datetimes(values, 'start_time', 'finish_time')
    action = _action_get_by_request_id(context, values['instance_uuid'],
                                       values['request_id'])
    # When nova-compute restarts, the context is generated again in
    # init_host workflow, the request_id was different with the request_id
    # recorded in InstanceAction, so we can't get the original record
    # according to request_id. Try to get the last created action so that
    # init_instance can continue to finish the recovery action, like:
    # powering_off, unpausing, and so on.
    update_action = True
    if not action and not context.project_id:
        action = _action_get_last_created_by_instance_uuid(
            context, values['instance_uuid'])
        # If we couldn't find an action by the request_id, we don't want to
        # update this action since it likely represents an inactive action.
        update_action = False

    if not action:
        raise exception.InstanceActionNotFound(
                                    request_id=values['request_id'],
                                    instance_uuid=values['instance_uuid'])

    event_ref = model_query(context, models.InstanceActionEvent).\
                            filter_by(action_id=action['id']).\
                            filter_by(event=values['event']).\
                            first()

    if not event_ref:
        raise exception.InstanceActionEventNotFound(action_id=action['id'],
                                                    event=values['event'])
    event_ref.update(values)

    if values['result'].lower() == 'error':
        action.update({'message': 'Error'})

    # Update action updated_at.
    if update_action:
        action.update({'updated_at': values['finish_time']})
        action.save(context.session)

    return event_ref


@pick_context_manager_reader
def action_events_get(context, action_id):
    events = model_query(context, models.InstanceActionEvent).\
                         filter_by(action_id=action_id).\
                         order_by(desc("created_at"), desc("id")).\
                         all()

    return events


@pick_context_manager_reader
def action_event_get_by_id(context, action_id, event_id):
    event = model_query(context, models.InstanceActionEvent).\
                        filter_by(action_id=action_id).\
                        filter_by(id=event_id).\
                        first()

    return event


##################


@require_context
@pick_context_manager_writer
def ec2_instance_create(context, instance_uuid, id=None):
    """Create ec2 compatible instance by provided uuid."""
    ec2_instance_ref = models.InstanceIdMapping()
    ec2_instance_ref.update({'uuid': instance_uuid})
    if id is not None:
        ec2_instance_ref.update({'id': id})

    ec2_instance_ref.save(context.session)

    return ec2_instance_ref


@require_context
@pick_context_manager_reader
def ec2_instance_get_by_uuid(context, instance_uuid):
    result = _ec2_instance_get_query(context).\
                    filter_by(uuid=instance_uuid).\
                    first()

    if not result:
        raise exception.InstanceNotFound(instance_id=instance_uuid)

    return result


@require_context
@pick_context_manager_reader
def ec2_instance_get_by_id(context, instance_id):
    result = _ec2_instance_get_query(context).\
                    filter_by(id=instance_id).\
                    first()

    if not result:
        raise exception.InstanceNotFound(instance_id=instance_id)

    return result


@require_context
@pick_context_manager_reader
def get_instance_uuid_by_ec2_id(context, ec2_id):
    result = ec2_instance_get_by_id(context, ec2_id)
    return result['uuid']


def _ec2_instance_get_query(context):
    return model_query(context, models.InstanceIdMapping, read_deleted='yes')


##################


def _task_log_get_query(context, task_name, period_beginning,
                        period_ending, host=None, state=None):
    values = {'period_beginning': period_beginning,
              'period_ending': period_ending}
    values = convert_objects_related_datetimes(values, *values.keys())

    query = model_query(context, models.TaskLog).\
                     filter_by(task_name=task_name).\
                     filter_by(period_beginning=values['period_beginning']).\
                     filter_by(period_ending=values['period_ending'])
    if host is not None:
        query = query.filter_by(host=host)
    if state is not None:
        query = query.filter_by(state=state)
    return query


@pick_context_manager_reader
def task_log_get(context, task_name, period_beginning, period_ending, host,
                 state=None):
    return _task_log_get_query(context, task_name, period_beginning,
                               period_ending, host, state).first()


@pick_context_manager_reader
def task_log_get_all(context, task_name, period_beginning, period_ending,
                     host=None, state=None):
    return _task_log_get_query(context, task_name, period_beginning,
                               period_ending, host, state).all()


@pick_context_manager_writer
def task_log_begin_task(context, task_name, period_beginning, period_ending,
                        host, task_items=None, message=None):
    values = {'period_beginning': period_beginning,
              'period_ending': period_ending}
    values = convert_objects_related_datetimes(values, *values.keys())

    task = models.TaskLog()
    task.task_name = task_name
    task.period_beginning = values['period_beginning']
    task.period_ending = values['period_ending']
    task.host = host
    task.state = "RUNNING"
    if message:
        task.message = message
    if task_items:
        task.task_items = task_items
    try:
        task.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.TaskAlreadyRunning(task_name=task_name, host=host)


@pick_context_manager_writer
def task_log_end_task(context, task_name, period_beginning, period_ending,
                      host, errors, message=None):
    values = dict(state="DONE", errors=errors)
    if message:
        values["message"] = message

    rows = _task_log_get_query(context, task_name, period_beginning,
                               period_ending, host).update(values)
    if rows == 0:
        # It's not running!
        raise exception.TaskNotRunning(task_name=task_name, host=host)


##################


def _archive_if_instance_deleted(table, shadow_table, instances, conn,
                                 max_rows):
    """Look for records that pertain to deleted instances, but may not be
    deleted themselves. This catches cases where we delete an instance,
    but leave some residue because of a failure in a cleanup path or
    similar.

    Logic is: if I have a column called instance_uuid, and that instance
    is deleted, then I can be deleted.
    """
    query_insert = shadow_table.insert(inline=True).\
        from_select(
            [c.name for c in table.c],
            sql.select(
                [table],
                and_(instances.c.deleted != instances.c.deleted.default.arg,
                     instances.c.uuid == table.c.instance_uuid)).
            order_by(table.c.id).limit(max_rows))

    query_delete = sql.select(
        [table.c.id],
        and_(instances.c.deleted != instances.c.deleted.default.arg,
             instances.c.uuid == table.c.instance_uuid)).\
        order_by(table.c.id).limit(max_rows)
    delete_statement = DeleteFromSelect(table, query_delete,
                                        table.c.id)

    try:
        with conn.begin():
            conn.execute(query_insert)
            result_delete = conn.execute(delete_statement)
            return result_delete.rowcount
    except db_exc.DBReferenceError as ex:
        LOG.warning('Failed to archive %(table)s: %(error)s',
                    {'table': table.name,
                     'error': six.text_type(ex)})
        return 0


def _archive_deleted_rows_for_table(tablename, max_rows):
    """Move up to max_rows rows from one tables to the corresponding
    shadow table.

    :returns: number of rows archived
    """
    engine = get_engine()
    conn = engine.connect()
    metadata = MetaData()
    metadata.bind = engine
    # NOTE(tdurakov): table metadata should be received
    # from models, not db tables. Default value specified by SoftDeleteMixin
    # is known only by models, not DB layer.
    # IMPORTANT: please do not change source of metadata information for table.
    table = models.BASE.metadata.tables[tablename]

    shadow_tablename = _SHADOW_TABLE_PREFIX + tablename
    rows_archived = 0
    deleted_instance_uuids = []
    try:
        shadow_table = Table(shadow_tablename, metadata, autoload=True)
    except NoSuchTableError:
        # No corresponding shadow table; skip it.
        return rows_archived, deleted_instance_uuids

    if tablename == "dns_domains":
        # We have one table (dns_domains) where the key is called
        # "domain" rather than "id"
        column = table.c.domain
    else:
        column = table.c.id
    # NOTE(guochbo): Use DeleteFromSelect to avoid
    # database's limit of maximum parameter in one SQL statement.
    deleted_column = table.c.deleted
    columns = [c.name for c in table.c]

    # NOTE(clecomte): Tables instance_actions and instances_actions_events
    # have to be manage differently so we soft-delete them here to let
    # the archive work the same for all tables
    # NOTE(takashin): The record in table migrations should be
    # soft deleted when the instance is deleted.
    # This is just for upgrading.
    if tablename in ("instance_actions", "migrations"):
        instances = models.BASE.metadata.tables["instances"]
        deleted_instances = sql.select([instances.c.uuid]).\
            where(instances.c.deleted != instances.c.deleted.default.arg)
        update_statement = table.update().values(deleted=table.c.id).\
            where(table.c.instance_uuid.in_(deleted_instances))

        conn.execute(update_statement)

    elif tablename == "instance_actions_events":
        # NOTE(clecomte): we have to grab all the relation from
        # instances because instance_actions_events rely on
        # action_id and not uuid
        instances = models.BASE.metadata.tables["instances"]
        instance_actions = models.BASE.metadata.tables["instance_actions"]
        deleted_instances = sql.select([instances.c.uuid]).\
            where(instances.c.deleted != instances.c.deleted.default.arg)
        deleted_actions = sql.select([instance_actions.c.id]).\
            where(instance_actions.c.instance_uuid.in_(deleted_instances))

        update_statement = table.update().values(deleted=table.c.id).\
            where(table.c.action_id.in_(deleted_actions))

        conn.execute(update_statement)

    select = sql.select([column],
                        deleted_column != deleted_column.default.arg).\
                        order_by(column).limit(max_rows)
    rows = conn.execute(select).fetchall()
    records = [r[0] for r in rows]

    if records:
        insert = shadow_table.insert(inline=True).\
                from_select(columns, sql.select([table], column.in_(records)))
        delete = table.delete().where(column.in_(records))
        # NOTE(tssurya): In order to facilitate the deletion of records from
        # instance_mappings and request_specs tables in the nova_api DB, the
        # rows of deleted instances from the instances table are stored prior
        # to their deletion. Basically the uuids of the archived instances
        # are queried and returned.
        if tablename == "instances":
            query_select = sql.select([table.c.uuid], table.c.id.in_(records))
            rows = conn.execute(query_select).fetchall()
            deleted_instance_uuids = [r[0] for r in rows]

        try:
            # Group the insert and delete in a transaction.
            with conn.begin():
                conn.execute(insert)
                result_delete = conn.execute(delete)
            rows_archived = result_delete.rowcount
        except db_exc.DBReferenceError as ex:
            # A foreign key constraint keeps us from deleting some of
            # these rows until we clean up a dependent table.  Just
            # skip this table for now; we'll come back to it later.
            LOG.warning("IntegrityError detected when archiving table "
                        "%(tablename)s: %(error)s",
                        {'tablename': tablename, 'error': six.text_type(ex)})

    if ((max_rows is None or rows_archived < max_rows)
            and 'instance_uuid' in columns):
        instances = models.BASE.metadata.tables['instances']
        limit = max_rows - rows_archived if max_rows is not None else None
        extra = _archive_if_instance_deleted(table, shadow_table, instances,
                                             conn, limit)
        rows_archived += extra

    return rows_archived, deleted_instance_uuids


def archive_deleted_rows(max_rows=None):
    """Move up to max_rows rows from production tables to the corresponding
    shadow tables.

    :returns: dict that maps table name to number of rows archived from that
              table, for example:

    ::

        {
            'instances': 5,
            'block_device_mapping': 5,
            'pci_devices': 2,
        }

    """
    table_to_rows_archived = {}
    deleted_instance_uuids = []
    total_rows_archived = 0
    meta = MetaData(get_engine(use_slave=True))
    meta.reflect()
    # Reverse sort the tables so we get the leaf nodes first for processing.
    for table in reversed(meta.sorted_tables):
        tablename = table.name
        rows_archived = 0
        # skip the special sqlalchemy-migrate migrate_version table and any
        # shadow tables
        if (tablename == 'migrate_version' or
                tablename.startswith(_SHADOW_TABLE_PREFIX)):
            continue
        rows_archived,\
        deleted_instance_uuid = _archive_deleted_rows_for_table(
                tablename, max_rows=max_rows - total_rows_archived)
        total_rows_archived += rows_archived
        if tablename == 'instances':
            deleted_instance_uuids = deleted_instance_uuid
        # Only report results for tables that had updates.
        if rows_archived:
            table_to_rows_archived[tablename] = rows_archived
        if total_rows_archived >= max_rows:
            break
    return table_to_rows_archived, deleted_instance_uuids


@pick_context_manager_writer
def service_uuids_online_data_migration(context, max_count):
    from nova.objects import service

    count_all = 0
    count_hit = 0

    db_services = model_query(context, models.Service).filter_by(
        uuid=None).limit(max_count)
    for db_service in db_services:
        count_all += 1
        service_obj = service.Service._from_db_object(
            context, service.Service(), db_service)
        if 'uuid' in service_obj:
            count_hit += 1
    return count_all, count_hit


####################


def _instance_group_get_query(context, model_class, id_field=None, id=None,
                              read_deleted=None):
    columns_to_join = {models.InstanceGroup: ['_policies', '_members']}
    query = model_query(context, model_class, read_deleted=read_deleted,
                        project_only=True)
    for c in columns_to_join.get(model_class, []):
        query = query.options(joinedload(c))

    if id and id_field:
        query = query.filter(id_field == id)

    return query


@pick_context_manager_writer
def instance_group_create(context, values, policies=None, members=None):
    """Create a new group."""
    uuid = values.get('uuid', None)
    if uuid is None:
        uuid = uuidutils.generate_uuid()
        values['uuid'] = uuid

    try:
        group = models.InstanceGroup()
        group.update(values)
        group.save(context.session)
    except db_exc.DBDuplicateEntry:
        raise exception.InstanceGroupIdExists(group_uuid=uuid)

    # We don't want '_policies' and '_members' attributes to be lazy loaded
    # later. We know there is nothing here since we just created this
    # instance group.
    if policies:
        _instance_group_policies_add(context, group.id, policies)
    else:
        group._policies = []
    if members:
        _instance_group_members_add(context, group.id, members)
    else:
        group._members = []

    return instance_group_get(context, uuid)


@pick_context_manager_reader
def instance_group_get(context, group_uuid):
    """Get a specific group by uuid."""
    group = _instance_group_get_query(context,
                                      models.InstanceGroup,
                                      models.InstanceGroup.uuid,
                                      group_uuid).\
                            first()
    if not group:
        raise exception.InstanceGroupNotFound(group_uuid=group_uuid)
    return group


@pick_context_manager_reader
def instance_group_get_by_instance(context, instance_uuid):
    group_member = model_query(context, models.InstanceGroupMember).\
                               filter_by(instance_id=instance_uuid).\
                               first()
    if not group_member:
        raise exception.InstanceGroupNotFound(group_uuid='')
    group = _instance_group_get_query(context, models.InstanceGroup,
                                      models.InstanceGroup.id,
                                      group_member.group_id).first()
    if not group:
        raise exception.InstanceGroupNotFound(
                group_uuid=group_member.group_id)
    return group


@pick_context_manager_writer
def instance_group_update(context, group_uuid, values):
    """Update the attributes of a group.

    If values contains a metadata key, it updates the aggregate metadata
    too. Similarly for the policies and members.
    """
    group = model_query(context, models.InstanceGroup).\
            filter_by(uuid=group_uuid).\
            first()
    if not group:
        raise exception.InstanceGroupNotFound(group_uuid=group_uuid)

    policies = values.get('policies')
    if policies is not None:
        _instance_group_policies_add(context,
                                     group.id,
                                     values.pop('policies'),
                                     set_delete=True)
    members = values.get('members')
    if members is not None:
        _instance_group_members_add(context,
                                    group.id,
                                    values.pop('members'),
                                    set_delete=True)

    group.update(values)

    if policies:
        values['policies'] = policies
    if members:
        values['members'] = members


@pick_context_manager_writer
def instance_group_delete(context, group_uuid):
    """Delete a group."""
    group_id = _instance_group_id(context, group_uuid)

    count = _instance_group_get_query(context,
                                      models.InstanceGroup,
                                      models.InstanceGroup.uuid,
                                      group_uuid).soft_delete()
    if count == 0:
        raise exception.InstanceGroupNotFound(group_uuid=group_uuid)

    # Delete policies, metadata and members
    instance_models = [models.InstanceGroupPolicy,
                       models.InstanceGroupMember]
    for model in instance_models:
        model_query(context, model).filter_by(group_id=group_id).soft_delete()


@pick_context_manager_reader
def instance_group_get_all(context):
    """Get all groups."""
    return _instance_group_get_query(context, models.InstanceGroup).all()


@pick_context_manager_reader
def instance_group_get_all_by_project_id(context, project_id):
    """Get all groups."""
    return _instance_group_get_query(context, models.InstanceGroup).\
                            filter_by(project_id=project_id).\
                            all()


def _instance_group_count_by_project_and_user(context, project_id, user_id):
    return model_query(context, models.InstanceGroup, read_deleted="no").\
                   filter_by(project_id=project_id).\
                   filter_by(user_id=user_id).\
                   count()


def _instance_group_model_get_query(context, model_class, group_id,
                                    read_deleted='no'):
    return model_query(context,
                       model_class,
                       read_deleted=read_deleted).\
                filter_by(group_id=group_id)


def _instance_group_id(context, group_uuid):
    """Returns the group database ID for the group UUID."""

    result = model_query(context,
                         models.InstanceGroup,
                         (models.InstanceGroup.id,)).\
                filter_by(uuid=group_uuid).\
                first()
    if not result:
        raise exception.InstanceGroupNotFound(group_uuid=group_uuid)
    return result.id


def _instance_group_members_add(context, id, members, set_delete=False):
    all_members = set(members)
    query = _instance_group_model_get_query(context,
                                            models.InstanceGroupMember, id)
    if set_delete:
        query.filter(~models.InstanceGroupMember.instance_id.in_(
                     all_members)).\
              soft_delete(synchronize_session=False)

    query = query.filter(
            models.InstanceGroupMember.instance_id.in_(all_members))
    already_existing = set()
    for member_ref in query.all():
        already_existing.add(member_ref.instance_id)

    for instance_id in members:
        if instance_id in already_existing:
            continue
        member_ref = models.InstanceGroupMember()
        member_ref.update({'instance_id': instance_id,
                           'group_id': id})
        context.session.add(member_ref)

    return members


@pick_context_manager_writer
def instance_group_members_add(context, group_uuid, members,
                               set_delete=False):
    id = _instance_group_id(context, group_uuid)
    return _instance_group_members_add(context, id, members,
                                       set_delete=set_delete)


@pick_context_manager_writer
def instance_group_member_delete(context, group_uuid, instance_id):
    id = _instance_group_id(context, group_uuid)
    count = _instance_group_model_get_query(context,
                                            models.InstanceGroupMember,
                                            id).\
                            filter_by(instance_id=instance_id).\
                            soft_delete()
    if count == 0:
        raise exception.InstanceGroupMemberNotFound(group_uuid=group_uuid,
                                                    instance_id=instance_id)


@pick_context_manager_reader
def instance_group_members_get(context, group_uuid):
    id = _instance_group_id(context, group_uuid)
    instances = model_query(context,
                            models.InstanceGroupMember,
                            (models.InstanceGroupMember.instance_id,)).\
                    filter_by(group_id=id).all()
    return [instance[0] for instance in instances]


def _instance_group_policies_add(context, id, policies, set_delete=False):
    allpols = set(policies)
    query = _instance_group_model_get_query(context,
                                            models.InstanceGroupPolicy, id)
    if set_delete:
        query.filter(~models.InstanceGroupPolicy.policy.in_(allpols)).\
            soft_delete(synchronize_session=False)

    query = query.filter(models.InstanceGroupPolicy.policy.in_(allpols))
    already_existing = set()
    for policy_ref in query.all():
        already_existing.add(policy_ref.policy)

    for policy in policies:
        if policy in already_existing:
            continue
        policy_ref = models.InstanceGroupPolicy()
        policy_ref.update({'policy': policy,
                           'group_id': id})
        context.session.add(policy_ref)

    return policies


####################


@pick_context_manager_reader
def pci_device_get_by_addr(context, node_id, dev_addr):
    pci_dev_ref = model_query(context, models.PciDevice).\
                        filter_by(compute_node_id=node_id).\
                        filter_by(address=dev_addr).\
                        first()
    if not pci_dev_ref:
        raise exception.PciDeviceNotFound(node_id=node_id, address=dev_addr)
    return pci_dev_ref


@pick_context_manager_reader
def pci_device_get_by_id(context, id):
    pci_dev_ref = model_query(context, models.PciDevice).\
                        filter_by(id=id).\
                        first()
    if not pci_dev_ref:
        raise exception.PciDeviceNotFoundById(id=id)
    return pci_dev_ref


@pick_context_manager_reader
def pci_device_get_all_by_node(context, node_id):
    return model_query(context, models.PciDevice).\
                       filter_by(compute_node_id=node_id).\
                       all()


@pick_context_manager_reader
def pci_device_get_all_by_parent_addr(context, node_id, parent_addr):
    return model_query(context, models.PciDevice).\
                       filter_by(compute_node_id=node_id).\
                       filter_by(parent_addr=parent_addr).\
                       all()


@require_context
@pick_context_manager_reader
def pci_device_get_all_by_instance_uuid(context, instance_uuid):
    return model_query(context, models.PciDevice).\
                       filter_by(status='allocated').\
                       filter_by(instance_uuid=instance_uuid).\
                       all()


@pick_context_manager_reader
def _instance_pcidevs_get_multi(context, instance_uuids):
    if not instance_uuids:
        return []
    return model_query(context, models.PciDevice).\
        filter_by(status='allocated').\
        filter(models.PciDevice.instance_uuid.in_(instance_uuids))


@pick_context_manager_writer
def pci_device_destroy(context, node_id, address):
    result = model_query(context, models.PciDevice).\
                         filter_by(compute_node_id=node_id).\
                         filter_by(address=address).\
                         soft_delete()
    if not result:
        raise exception.PciDeviceNotFound(node_id=node_id, address=address)


@pick_context_manager_writer
def pci_device_update(context, node_id, address, values):
    query = model_query(context, models.PciDevice, read_deleted="no").\
                    filter_by(compute_node_id=node_id).\
                    filter_by(address=address)
    if query.update(values) == 0:
        device = models.PciDevice()
        device.update(values)
        context.session.add(device)
    return query.one()


####################


@pick_context_manager_writer
def instance_tag_add(context, instance_uuid, tag):
    tag_ref = models.Tag()
    tag_ref.resource_id = instance_uuid
    tag_ref.tag = tag

    try:
        _check_instance_exists_in_project(context, instance_uuid)
        with get_context_manager(context).writer.savepoint.using(context):
            context.session.add(tag_ref)
    except db_exc.DBDuplicateEntry:
        # NOTE(snikitin): We should ignore tags duplicates
        pass

    return tag_ref


@pick_context_manager_writer
def instance_tag_set(context, instance_uuid, tags):
    _check_instance_exists_in_project(context, instance_uuid)

    existing = context.session.query(models.Tag.tag).filter_by(
        resource_id=instance_uuid).all()

    existing = set(row.tag for row in existing)
    tags = set(tags)
    to_delete = existing - tags
    to_add = tags - existing

    if to_delete:
        context.session.query(models.Tag).filter_by(
            resource_id=instance_uuid).filter(
            models.Tag.tag.in_(to_delete)).delete(
            synchronize_session=False)

    if to_add:
        data = [
            {'resource_id': instance_uuid, 'tag': tag} for tag in to_add]
        context.session.execute(models.Tag.__table__.insert(), data)

    return context.session.query(models.Tag).filter_by(
        resource_id=instance_uuid).all()


@pick_context_manager_reader
def instance_tag_get_by_instance_uuid(context, instance_uuid):
    _check_instance_exists_in_project(context, instance_uuid)
    return context.session.query(models.Tag).filter_by(
        resource_id=instance_uuid).all()


@pick_context_manager_writer
def instance_tag_delete(context, instance_uuid, tag):
    _check_instance_exists_in_project(context, instance_uuid)
    result = context.session.query(models.Tag).filter_by(
        resource_id=instance_uuid, tag=tag).delete()

    if not result:
        raise exception.InstanceTagNotFound(instance_id=instance_uuid,
                                            tag=tag)


@pick_context_manager_writer
def instance_tag_delete_all(context, instance_uuid):
    _check_instance_exists_in_project(context, instance_uuid)
    context.session.query(models.Tag).filter_by(
        resource_id=instance_uuid).delete()


@pick_context_manager_reader
def instance_tag_exists(context, instance_uuid, tag):
    _check_instance_exists_in_project(context, instance_uuid)
    q = context.session.query(models.Tag).filter_by(
        resource_id=instance_uuid, tag=tag)
    return context.session.query(q.exists()).scalar()


####################


@pick_context_manager_writer
def console_auth_token_create(context, values):
    instance_uuid = values.get('instance_uuid')
    _check_instance_exists_in_project(context, instance_uuid)
    token_ref = models.ConsoleAuthToken()
    token_ref.update(values)
    context.session.add(token_ref)
    return token_ref


@pick_context_manager_reader
def console_auth_token_get_valid(context, token_hash, instance_uuid=None):
    if instance_uuid is not None:
        _check_instance_exists_in_project(context, instance_uuid)
    query = context.session.query(models.ConsoleAuthToken).\
        filter_by(token_hash=token_hash)
    if instance_uuid is not None:
        query = query.filter_by(instance_uuid=instance_uuid)
    return query.filter(
        models.ConsoleAuthToken.expires > timeutils.utcnow_ts()).first()


@pick_context_manager_writer
def console_auth_token_destroy_all_by_instance(context, instance_uuid):
    context.session.query(models.ConsoleAuthToken).\
        filter_by(instance_uuid=instance_uuid).delete()


@pick_context_manager_writer
def console_auth_token_destroy_expired_by_host(context, host):
    context.session.query(models.ConsoleAuthToken).\
        filter_by(host=host).\
        filter(models.ConsoleAuthToken.expires <= timeutils.utcnow_ts()).\
        delete()