Source

baseten / Sources / BXDatabaseContext.m

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
//
// BXDatabaseContext.m
// BaseTen
//
// Copyright (C) 2006-2009 Marko Karppinen & Co. LLC.
//
// Before using this software, please review the available licensing options
// by visiting http://basetenframework.org/licensing/ or by contacting
// us at sales@karppinen.fi. Without an additional license, this software
// may be distributed only in compliance with the GNU General Public License.
//
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 2.0,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
// $Id$
//

#import <AppKit/AppKit.h>
#import <stdlib.h>
#import <string.h>
#import <pthread.h>

#import "BXSetFunctions.h"
#import "BXDictionaryFunctions.h"
#import "BXHOM.h"
#import "BXDatabaseContext.h"
#import "BXDatabaseContextPrivate.h"
#import "BXConstants.h"
#import "BXInterface.h"
#import "BXPGInterface.h"
#import "BXDatabaseObject.h"
#import "BXDatabaseObjectPrivate.h"
#import "BXEntityDescription.h"
#import "BXEntityDescriptionPrivate.h"
#import "BXDatabaseObjectID.h"
#import "BXDatabaseObjectIDPrivate.h"
#import "BXConstants.h"
#import "BXException.h"
#import "BXContainerProxy.h"
#import "BXArrayProxy.h"
#import "BXDatabaseContextAdditions.h"
#import "BXConnectionSetupManagerProtocol.h"
#import "BXConstantsPrivate.h"
#import "BXInvocationRecorder.h"
#import "BXLogger.h"
#import "BXProbes.h"
#import "BXDelegateProxy.h"
#import "BXDatabaseContextDelegateDefaultImplementation.h"
#import "BXRelationshipDescriptionPrivate.h"
#import "BXEnumerate.h"
#import "BXLocalizedString.h"
#import "BXDatabaseObjectModel.h"
#import "BXDatabaseObjectModelPrivate.h"
#import "BXDatabaseObjectModelStorage.h"
#import "BXAttributeDescriptionPrivate.h"
#import "BXError.h"
#import "BXForeignKey.h"
#import "BXArraySize.h"

#import "NSURL+BaseTenAdditions.h"


__strong static NSMutableDictionary* gInterfaceClassSchemes = nil;
static BOOL gHaveAppKitFramework = NO;


#define BXHandleError( ERROR, LOCAL_ERROR ) BXHandleError2( self, mDelegateProxy, ERROR, LOCAL_ERROR )

void
BXHandleError2 (BXDatabaseContext *ctx, id <BXDatabaseContextDelegate> delegateProxy, NSError **error, NSError *localError)
{
    if (nil != localError)
    {
        BOOL haveError = (NULL != error);
        [delegateProxy databaseContext: ctx hadError: localError willBePassedOn: haveError];
        if (haveError)
            *error = localError;
    }
}

static NSMutableDictionary*
ObjectsByEntity (NSArray *objects)
{
    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    BXEnumerate (currentObject, e, [objects objectEnumerator])
    {
        id entity = [currentObject entity];
        NSMutableArray* array = [dict objectForKey: entity];
        if (nil == array)
        {
            array = [NSMutableArray array];
            [dict setObject: array forKey: entity];
        }
        [array addObject: currentObject];
    }
    return dict;
}

static void
AddObjectIDsForInheritance2 (NSMutableDictionary *idsByEntity, BXEntityDescription* entity)
{
    id superEntities = [entity inheritedEntities];
    BXEnumerate (currentEntity, e, [superEntities objectEnumerator])
    {
        NSMutableArray* superIds = [idsByEntity objectForKey: currentEntity];
        if (nil == superIds)
        {
            superIds = [NSMutableArray array];
            [idsByEntity setObject: superIds forKey: currentEntity];
        }
        
        //Create the corresponding ids.
        BXEnumerate (objectID, e, [[idsByEntity objectForKey: entity] objectEnumerator])
        {
			NSDictionary* pkeyFields = nil;
			BOOL parsed = [BXDatabaseObjectID parseURI: [objectID URIRepresentation]
												entity: NULL
												schema: NULL
									  primaryKeyFields: &pkeyFields];
			BXAssertVoidReturn (parsed, @"Expected object URI to be parseable.");
			if (! parsed) break;
			
            BXDatabaseObjectID* newID = [BXDatabaseObjectID IDWithEntity: currentEntity primaryKeyFields: pkeyFields];
            [superIds addObject: newID];
        }
        AddObjectIDsForInheritance2 (idsByEntity, currentEntity);
    }    
}

static void
AddObjectIDsForInheritance (NSMutableDictionary *idsByEntity)
{
    BXEnumerate (entity, e, [[idsByEntity allKeys] objectEnumerator])
        AddObjectIDsForInheritance2 (idsByEntity, entity);
}

static void
bx_query_during_reconnect ()
{
	BXLogError (@"Tried to send a query during reconnection attempt.");
	BXLogInfo (@"Break on bx_query_during_reconnect to inspect.");
}


static enum BXModificationType
ObjectToModType (NSValue* value)
{
    enum BXModificationType retval = kBXNoModification;
    [value getValue: &retval];
    return retval;
}


static NSValue*
ModTypeToObject (enum BXModificationType value)
{
    return [NSValue valueWithBytes: &value objCType: @encode (enum BXModificationType)];
}


/** 
 * \brief The database context. 
 *
 * A database context connects to a given database, sends queries and commands to it and
 * creates objects from rows in its tables. In order to function properly, it needs an URI formatted 
 * like pgsql://username:password\@hostname/database_name/.
 *
 * Various methods of this class take an NSError parameter. If the parameter isn't set, the context
 * will handle errors by throwing a BXException named \em kBXFailedToExecuteQueryException. 
 * See BXDatabaseContextDelegate::databaseContext:hadError:willBePassedOn:.
 *
 * \note This class is not thread-safe, i.e. 
 *		 if methods of a BXDatabaseContext instance will be called from 
 *		 different threads the result is undefined and deadlocks are possible.
 * \ingroup baseten
 */
@implementation BXDatabaseContext

+ (void) initialize
{
    static BOOL tooLate = NO;
    if (NO == tooLate)
    {
        tooLate = YES;
        gInterfaceClassSchemes = [[NSMutableDictionary alloc] init];

        //If this class were in a separate framework, this method should be called from the
        //framework initializer function
        [BXPGInterface initialize];
    }
}

+ (BOOL) accessInstanceVariablesDirectly
{
    return NO;
}

+ (BOOL) isSchemeSupported: (NSString *) scheme
{
    return (nil != [gInterfaceClassSchemes valueForKey: scheme]);
}

+ (BOOL) setInterfaceClass: (Class) aClass forScheme: (NSString *) scheme
{
    BOOL retval = NO;
    if ([aClass conformsToProtocol: @protocol (BXInterface)])
    {
        retval = YES;
        [gInterfaceClassSchemes setValue: aClass forKey: scheme];
    }
    return retval;
}

+ (Class) interfaceClassForScheme: (NSString *) scheme
{
    return [gInterfaceClassSchemes valueForKey: scheme];
}

/** \name Creating a database context */
//@{
/**
 * \brief A convenience method.
 * \param   uri     URI of the target database
 * \return          The database context
 * \throw   NSException named \em kBXUnsupportedDatabaseException in case the given URI cannot be handled.
 */
+ (id) contextWithDatabaseURI: (NSURL *) uri
{
    return [[[self alloc] initWithDatabaseURI: uri] autorelease];
}

/**
 * \brief An initializer.
 *
 * The database URI has to be set afterwards.
 * \return          The database context
 */
- (id) init
{
    return [self initWithDatabaseURI: nil];
}

/**
 * \brief The designated initializer.
 * \param   uri     URI of the target database
 * \return          The database context
 * \throw           NSException named \em kBXUnsupportedDatabaseException in case the given URI cannot be handled.
 */
- (id) initWithDatabaseURI: (NSURL *) uri
{
    if ((self = [super init]))
    {
        [self setDatabaseURI: uri];
        
        mDeallocating = NO;
        mRetainRegisteredObjects = NO;
		mCanConnect = YES;
		mConnectsOnAwake = NO;
		mSendsLockQueries = YES;
		mUsesKeychain = YES;
		
		mDelegateProxy = [[BXDelegateProxy alloc] initWithDelegateDefaultImplementation:
						  [[[BXDatabaseContextDelegateDefaultImplementation alloc] init] autorelease]];
    }
    return self;
}
//@}


- (void) dealloc
{
    mDeallocating = YES;
    //[self rollback]; //FIXME: I don't think this is really needed.
    if (mRetainRegisteredObjects)
        [mObjects makeObjectsPerformSelector:@selector (release) withObject:nil];
    [mObjects makeObjectsPerformSelector: @selector (BXDatabaseContextWillDealloc) withObject: nil];
    
	[mObjectModel release];
	[mObjectModelStorage release];
	
	[mDatabaseInterface disconnect];
    [mDatabaseInterface release];
	
    [mDatabaseURI release];
    [mObjects release];
    [mModifiedObjectIDs release];
    [mUndoManager release];
	[mUndoGroupingLevels release];
	[mConnectionSetupManager release];
    [mNotificationCenter release];
	[mDelegateProxy release];
	[mLastConnectionError release];
    
    if (NULL != mKeychainPasswordItem)
        CFRelease (mKeychainPasswordItem);
    
    BXLogDebug (@"Deallocating BXDatabaseContext");
    [super dealloc];
}

/** \name Handling registered objects */
//@{
/**
 * Whether the receiver retains registered objects.
 */
- (BOOL) retainsRegisteredObjects
{
    return mRetainRegisteredObjects;
}

/**
 * \brief Set whether the receiver should retain all registered objects.
 */
- (void) setRetainsRegisteredObjects: (BOOL) flag
{
    if (mRetainRegisteredObjects != flag) {
        mRetainRegisteredObjects = flag;
        
        if (mRetainRegisteredObjects)
            [mObjects makeObjectsPerformSelector:@selector (retain) withObject:nil];
        else
            [mObjects makeObjectsPerformSelector:@selector (release) withObject:nil];
    }
}
//@}

- (BOOL) connectIfNeeded: (NSError **) error
{
	return [self connectSync: error];
}

/** \name Connecting and disconnecting */
//@{
/**
 * \brief Set the database URI.
 *
 * Also clears the context's strong references to entity descriptions received from it.
 * \param   uri     The database URI
 * \throw   NSException named \em kBXUnsupportedDatabaseException in case the given URI cannot be handled.
 */
- (void) setDatabaseURI: (NSURL *) URI
{
	if (mDatabaseURI != URI)
	{
		[self setKeychainPasswordItem: NULL];
		if (! [[URI scheme] isEqual: [mDatabaseURI scheme]])
		{
			[self setDatabaseInterface: nil];
			[self databaseInterface];
		}

		if (mDatabaseURI && 0 < [[mDatabaseURI host] length])
			[self setDatabaseObjectModel: nil];
	
		[self setDatabaseURIInternal: URI];

		if (0 < [[mDatabaseURI host] length])
		{
			[self databaseObjectModel];

			[mDelegateProxy databaseContextGotDatabaseURI: self];
			NSNotificationCenter* nc = [self notificationCenter];
			[nc postNotificationName: kBXGotDatabaseURINotification object: self];	
		}
	}
}

/**
 * \brief The database URI.
 */
- (NSURL *) databaseURI
{
    return mDatabaseURI;
}

/**
 * \brief Whether connection is attempted on -awakeFromNib.
 */
- (BOOL) connectsOnAwake
{
	return mConnectsOnAwake;
}

/**
 * \brief Set whether connection should be attempted on -awakeFromNib.
 */
- (void) setConnectsOnAwake: (BOOL) aBool
{
	mConnectsOnAwake = aBool;
}

/**
 * \brief Establishing a connection.
 *
 * Returns a boolean indicating whether connecting can be attempted using -connect:.
 * Presently this method returns YES when connection attempt hasn't already been started and after
 * the attempt has failed.
 */
- (BOOL) canConnect
{
	return mCanConnect;
}

/**
 * \brief Connection status.
 */
- (BOOL) isConnected
{
	return [[self databaseInterface] connected];
}

/**
 * \brief Connect to the database.
 *
 * This method returns after the connection has been made.
 */
- (BOOL) connectSync: (NSError **) error
{
	BOOL retval = NO;
    NSError* localError = nil;
	mDidDisconnect = NO;
	if ([self isConnected])
		retval = YES;
	else if ([self checkDatabaseURI: &localError])
	{
		[self setCanConnect: NO];
		[self lazyInit];
		retval = [[self databaseInterface] connectSync: &localError];
		retval = [self connectedToDatabase: retval async: NO error: &localError];
		
		if (! retval)
		{
			[mDatabaseInterface release];
			mDatabaseInterface = nil;
		}
	}
    BXHandleError (error, localError);
	return retval;
}

/**
 * \brief Connect to the database.
 *
 * Hand over the connection setup to \em mConnectionSetupManager. In BaseTenAppKit 
 * applications, a BXNetServiceConnector will be created automatically if 
 * one doesn't exist.
 *
 * \image html connect.png "Message sequence when using -connect:"
 * \image latex connect.eps "Message sequence when using -connect:" width=\textwidth
 */
- (IBAction) connect: (id) sender
{
	if (NO == [[self databaseInterface] connected])
	{
		if (nil == mConnectionSetupManager && 0 != pthread_main_np () &&
            [self respondsToSelector: @selector (copyDefaultConnectionSetupManager)])
		{
			mConnectionSetupManager = [self copyDefaultConnectionSetupManager];
			[mConnectionSetupManager setDatabaseContext: self];
			[mConnectionSetupManager setModalWindow: modalWindow];
		}
		if (nil != mConnectionSetupManager)
		{
			[mConnectionSetupManager connect: sender];
			[self setCanConnect: NO];
		}
	}
}

/**
 * \brief Connect to the database.
 *
 * This method returns immediately.
 * After the attempt, either a \em kBXConnectionSuccessfulNotification or a 
 * \em kBXConnectionFailedNotification will be posted to the context's
 * notification center.
 */
- (void) connectAsync
{
	NSError* localError = nil;
	mDidDisconnect = NO;
	if ([self checkDatabaseURI: &localError])
	{
		BXLogDebug (@"Checking whether to connect.");
		if (NO == [self isConnected])
		{
			BXLogDebug (@"Making database interface connect.");
			[self lazyInit];
			[mDatabaseInterface connectAsync];
		}
	}
	
	if (nil == localError)
		[self setCanConnect: NO];
	else
	{
		[mDatabaseInterface release];
		mDatabaseInterface = nil;
		
		NSDictionary* userInfo = [NSDictionary dictionaryWithObject: localError forKey: kBXErrorKey];
        NSNotification* notification = [NSNotification notificationWithName: kBXConnectionFailedNotification object: self userInfo: userInfo];
		[mDelegateProxy databaseContext: self failedToConnect: localError];
        [[self notificationCenter] postNotification: notification];
	}	
}

/**
 * \brief Disconnect from the database.
 */
- (void) disconnect
{
	mDidDisconnect = YES;
	[mDatabaseInterface disconnect];
	[mDatabaseInterface release];
	mDatabaseInterface = nil;
}
//@}

/** \name Transactions and undo */
//@{
/**
 * \brief Set the query execution method.
 *
 * In manual commit mode, savepoints are inserted after each query
 * Changes don't get propagated immediately to other clients.
 * Instead, other users get information about locked rows.
 * If the context gets deallocated during a transaction, a ROLLBACK
 * is sent to the database.
 * \note If autocommit is enabled, sending lock queries will be turned off. It may be re-enabled afterwards, though.
 * \param   aBool   Whether or not to use autocommit.
 */
- (void) setAutocommits: (BOOL) aBool
{
	if ([mDatabaseInterface connected])
		[NSException raise: NSInvalidArgumentException format: @"Commit mode cannot be set after connecting."];
    mAutocommits = aBool;
	if (mAutocommits)
		[self setSendsLockQueries: NO];
}

/**
 * \brief Query execution method
 * \return          A BOOL indicating whether or not autocommit is in use.
 */
- (BOOL) autocommits
{
    return mAutocommits;
}

/**
 * \brief Set whether the context should mark rows locked after editing.
 *
 * Makes the receiver send notifications to other BaseTen clients
 * about updated or deleted rows being locked when the receiver
 * has an ongoing transaction. This causes some additional queries to
 * be sent. The context may still receive lock notifications from other 
 * contexts.
 * \see BXDatabaseObject::isLockedForKey:
 * \see BXSynchronizedArrayController::setLocksRowsOnBeginEditing:
 */
- (void) setSendsLockQueries: (BOOL) aBool
{
	if ([mDatabaseInterface connected])
		[NSException raise: NSInvalidArgumentException format: @"Lock mode cannot be set after connecting."];
	mSendsLockQueries = aBool;
}

/**
 * \brief Whether the context tries to lock rows after editing.
 */
- (BOOL) sendsLockQueries
{
	return mSendsLockQueries;
}

/**
 * \brief The undo manager used by this context.
 */
- (NSUndoManager *) undoManager
{
    return mUndoManager;
}

/**
 * \brief Set the undo manager used by the context.
 *
 * Instead of creating an undo manager owned by the context, the undo invocations 
 * can be sent to a window's undo manager, for example. The change is done only if there isn't an
 * open undo group in the current undo manager.
 * \param       aManager    The supplied undo manager
 * \return                  Whether or not changing the undo manager was successful.
 */
- (BOOL) setUndoManager: (NSUndoManager *) aManager
{
    BOOL rval = NO;
    if (aManager == mUndoManager)
        rval = YES;
    else if (0 == [mUndoManager groupingLevel])
    {
        rval = YES;
		NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
		
		[nc removeObserver: self name: NSUndoManagerWillCloseUndoGroupNotification object: mUndoManager];
        [mUndoManager release];
        mUndoManager = [aManager retain];
		[mUndoGroupingLevels removeAllIndexes];
		[nc addObserver: self selector: @selector (undoGroupWillClose:)
				   name: NSUndoManagerWillCloseUndoGroupNotification object: mUndoManager];
    }
    return rval;
}

/**
 * \brief Rollback the transaction ina manual commit mode.
 *
 * Guaranteed to succeed.
 */
- (void) rollback
{
    if (NO == [mDatabaseInterface autocommits] && [mDatabaseInterface connected])
    {
        //First rollback, then fault and notify the listeners about modifications
        [mDatabaseInterface rollback];
		
        //FIXME: order by entity either here or in addedObjects and deletedObjects methods
        NSMutableArray* added = [NSMutableArray array];
        NSMutableArray* deleted = [NSMutableArray array];
        BXEnumerate (currentID, e, [(id) mModifiedObjectIDs keyEnumerator])
        {
			BXDatabaseObject* registeredObject = [self registeredObjectWithID: currentID];
            switch (ObjectToModType ([mModifiedObjectIDs objectForKey: currentID]))
            {
                case kBXUpdateModification:
                    [registeredObject removeFromCache: nil postingKVONotifications: YES];
                    break;
                case kBXInsertModification:
                    [added addObject: currentID];
                    break;
                case kBXDeleteModification:
                    [deleted addObject: currentID];
                    break;
                default:
                    break;
            }
			
			if (kBXObjectDeletePending == [registeredObject deletionStatus])
			{
				if (![registeredObject isInserted])
					[registeredObject setDeleted: kBXObjectExists];
				else
				{
					[registeredObject setDeleted: kBXObjectDeleted];
					[registeredObject setCreatedInCurrentTransaction: NO];
				}
			}
			
			[registeredObject clearStatus];
			[registeredObject setDeleted: kBXObjectExists];
        }
        [(id) mModifiedObjectIDs removeAllObjects];
        //In case of rollback, the objects deleted during the last transaction 
        //appear as inserted and vice-versa
        //If we are deallocating, don't bother to send the notification.
        if (NO == mDeallocating)
        {
            [self addedObjectsToDatabase: deleted];
            [self deletedObjectsFromDatabase: added];
        }
		
        [mUndoManager removeAllActions];
    }    
}

/**
 * \brief Commit the current transaction in manual commit mode.
 *
 * Undo will be disabled after this.
 * \return      A boolean indicating whether the commit was successful or not.
 */
- (BOOL) save: (NSError **) error
{
    BOOL retval = YES;
    if ([self checkErrorHandling] && NO == [mDatabaseInterface autocommits])
    {
        NSError* localError = nil;
        BXEnumerate (currentID, e, [(id) mModifiedObjectIDs keyEnumerator])
		{
			BXDatabaseObject* currentObject = [self registeredObjectWithID: currentID];
			[currentObject setCreatedInCurrentTransaction: NO];
			if ([currentObject isDeleted])
				[currentObject setDeleted: kBXObjectDeleted];
		}
        [(id) mModifiedObjectIDs removeAllObjects];
		
        [mUndoManager removeAllActions];
        retval = [mDatabaseInterface save: &localError];
        BXHandleError (error, localError);
    }
    return retval;
}

/** 
 * \brief Commit the changes.
 * \param sender Ignored.
 * \throw BXException named \em kBXFailedToExecuteQueryException if commit fails.
 */
- (IBAction) saveDocument: (id) sender
{
    NSError* error = nil;
    [self save: &error];
    if (nil != error)
    {
        [[error BXExceptionWithName: kBXFailedToExecuteQueryException] raise];
    }
}

/**
 * \brief Rollback the changes.
 * \param sender Ignored.
 */
- (IBAction) revertDocumentToSaved: (id) sender
{
    [self rollback];
}
//@}

/** 
 * \name Getting database objects without performing a fetch 
 */
//@{
/**
 * \brief Objects with given IDs.
 *
 * If the objects do not exist yet, they get created.
 * The database is not queried in any case. It is the user's responsibility to
 * provide this method with valid IDs.
 */
- (NSArray *) faultsWithIDs: (NSArray *) anArray
{
    NSMutableArray* rval = nil;
    NSUInteger count = [anArray count];
    if (0 < count)
    {
        rval = [NSMutableArray arrayWithCapacity: count];
        BXEnumerate (currentID, e, [anArray objectEnumerator])
        {
            BXDatabaseObject* object = [self registeredObjectWithID: currentID];
            if (nil == object)
            {
                BXEntityDescription* entity = [(BXDatabaseObjectID *) currentID entity];
                object = [[[[entity databaseObjectClass] alloc] init] autorelease];
                [object registerWithContext: self objectID: currentID];
            }
            [rval addObject: object];
        }
    }
    return rval;
}

/**
 * \brief Retrieve a registered database object.
 *
 * Looks up an object from the cache. The database is not queried in any case.
 * \return The cached object or nil.
 */
- (BXDatabaseObject *) registeredObjectWithID: (BXDatabaseObjectID *) objectID
{
    return [mObjects objectForKey: objectID];
}

/**
 * \brief Retrieve registered database objects.
 *
 * Looks up objects from the cache. The database is not queried in any case.
 * \param objectIDs         The object IDs to look for.
 * \return An NSArray of cached objects and NSNulls.
 */
- (NSArray *) registeredObjectsWithIDs: (NSArray *) objectIDs
{
    return [self registeredObjectsWithIDs: objectIDs nullObjects: YES];
}

/**
 * \brief Retrieve registered database objects.
 *
 * Looks up objects from the cache. The database is not queried in any case.
 * \param objectIDs         The object IDs to look for.
 * \param returnNullObjects Whether the returned array should be filled with NSNulls
 *                          if corresponding objects were not found.
 * \return An NSArray of cached objects and possibly NSNulls.
 */
- (NSArray *) registeredObjectsWithIDs: (NSArray *) objectIDs nullObjects: (BOOL) returnNullObjects
{
    NSArray* rval = [mObjects objectsForKeys: objectIDs notFoundMarker: [NSNull null]];
    if (NO == returnNullObjects)
    {
        NSNull* nullObject = [NSNull null];
        NSMutableArray* objects = [NSMutableArray arrayWithCapacity: [objectIDs count]];
        BXEnumerate (currentObject, e, [rval objectEnumerator])
        {
            if (nullObject != currentObject)
                [objects addObject: currentObject];
        }
        rval = objects;
    }
    return rval;
}
//@}


/** 
 * \brief The delegate. 
 */
- (id <BXDatabaseContextDelegate>) delegate
{
	return delegate;
}

/**
 * \brief Set the delegate.
 *
 * The delegate object will not be retained.
 */
- (void) setDelegate: (id <BXDatabaseContextDelegate>) anObject;
{
	delegate = anObject;
	[(BXDelegateProxy *) mDelegateProxy setDelegateForBXDelegateProxy: delegate];
}

/** \name Using the Keychain */
//@{
/**
 * \brief Whether the default keychain is searched for database passwords.
 */
- (BOOL) usesKeychain
{
    return mUsesKeychain;
}

/**
 * \brief Set whether the default keychain should be searched for database passwords.
 */
- (void) setUsesKeychain: (BOOL) usesKeychain
{
	mUsesKeychain = usesKeychain;
}

/** \brief Whether a known-to-work password will be stored into the default keychain. */
- (BOOL) storesURICredentials
{
	return mShouldStoreURICredentials;
}

/** \brief Set whether a known-to-work password should be stored into the default keychain. */
- (void) setStoresURICredentials: (BOOL) shouldStore
{
	mShouldStoreURICredentials = shouldStore;
}
//@}

/**
 * \internal
 * \brief Store login credentials from the database URI to the default keychain.
 */
- (void) storeURICredentials
{
    OSStatus status = noErr;
    const char* serverName = [[mDatabaseURI host] UTF8String];
    const char* username = [[mDatabaseURI user] UTF8String];
    const char* path = [[mDatabaseURI path] UTF8String];    
    NSNumber* portObject = [mDatabaseURI port];
    UInt16 port = (portObject ? [portObject unsignedShortValue] : 5432U);
    
    const char* password = [[mDatabaseURI password] UTF8String];
	if (! (password && [mDatabaseInterface usedPassword]))
    	password = "";
    
	if (mKeychainPasswordItem)
		status = SecKeychainItemModifyAttributesAndData (mKeychainPasswordItem, NULL, strlen (password), password);
	else
	{
		SecKeychainItemRef item = NULL;
		status = SecKeychainAddInternetPassword (NULL, //Default keychain
												 strlen (serverName), serverName,
												 0, NULL,
												 strlen (username), username,
												 strlen (path), path,
												 port,
												 0, kSecAuthenticationTypeDefault,
												 strlen (password), password, 
												 &item);
		
		if (noErr == status)
			[self setKeychainPasswordItem: item];
		else if (errSecDuplicateItem == status)
		{
			status = SecKeychainFindInternetPassword (NULL, 
													  strlen (serverName), serverName, 
													  0, NULL, 
													  strlen (username), username, 
													  strlen (path), path, 
													  port, 
													  0, kSecAuthenticationTypeDefault, 
													  0, NULL,
													  &item);
			if (noErr == status)
				status = SecKeychainItemModifyAttributesAndData (item, NULL, strlen (password), password);
		}
	}
	
	[self setKeychainPasswordItem: NULL];
}

/** \name Faulting database objects */
//@{
/**
 * \brief Refresh or fault an object.
 *
 * This method is provided for Core Data compatibility.
 * \param flag   If NO, all the object's cached values including related objects will be released.
 *               A new fetch won't be performed until any of the object's values is requested.
 *               If YES, this is a no-op.
 * \param object The object to fault.
 * \note         Since changes always get sent to the database immediately, this method's behaviour
 *		         is a bit different than in Core Data. When firing a fault, the database
 *               gets queried in any case.
 * \see          BXDatabaseObject::faultKey:
 */
- (void) refreshObject: (BXDatabaseObject *) object mergeChanges: (BOOL) flag
{
    if (NO == flag)
        [object faultKey: nil];
}
//@}

/** \name Receiving notifications */
//@{
/**
 * \brief The notification center for this context.
 *
 * Context-related notifications, such as connection notifications,
 * are posted to this notification center instead of the default center.
 */
- (NSNotificationCenter *) notificationCenter
{
    if (nil == mNotificationCenter)
        mNotificationCenter = [[NSNotificationCenter alloc] init];
    
    return mNotificationCenter;
}
//@}

/** \name Error handling */
//@{
/** \brief The NSWindow used with various sheets. */
- (NSWindow *) modalWindow
{
	return modalWindow;
}

/**
 * \brief Set the NSWindow used with various sheets.
 *
 * If set to nil, application modal alerts will be used.
 */
- (void) setModalWindow: (NSWindow *) aWindow
{
	if (aWindow != modalWindow)
	{
		[modalWindow release];
		modalWindow = [aWindow retain];
	}
}
//@}

- (void) setAllowReconnecting: (BOOL) shouldAllow
{
	mConnectionErrorHandlingState = (shouldAllow ? kBXConnectionErrorNone : kBXConnectionErrorNoReconnect);
}

/** \brief Whether SSL is currently in use. */
- (BOOL) isSSLInUse
{
	return [mDatabaseInterface isSSLInUse];
}

/** \brief Whether queries are logged to stdout. */
- (BOOL) logsQueries
{
	return [mDatabaseInterface logsQueries];
}

/** \brief Set whether queries are logged to stdout. */
- (void) setLogsQueries: (BOOL) shouldLog
{
	[mDatabaseInterface setLogsQueries: shouldLog];
}


/** \brief The database objectModel for the current database URI. */
- (BXDatabaseObjectModel *) databaseObjectModel
{
	if (! mObjectModel && mDatabaseURI)
	{
		NSNumber* port = [mDatabaseURI port];
		if (! port)
			port = [mDatabaseInterface defaultPort];
		
		NSURL* key = [mDatabaseURI BXURIForHost: nil port: port database: nil username: @"" password: @""];
		BXDatabaseObjectModelStorage *storage = mObjectModelStorage;
		if (! storage)
			storage = [BXDatabaseObjectModelStorage defaultStorage];
		[self setDatabaseObjectModel: [storage objectModelForURI: key]];
	}
	return mObjectModel;
}


- (BXDatabaseObjectModelStorage *) databaseObjectModelStorage
{
	return mObjectModelStorage;
}


- (void) setDatabaseObjectModelStorage: (BXDatabaseObjectModelStorage *) storage
{
	if (! ([[mDatabaseURI host] length]))
	{
		if (storage != mObjectModelStorage)
		{
			[mObjectModelStorage release];
			mObjectModelStorage = [storage retain];
		}
	}
}
@end


#pragma mark UnnamedCategoryEnd


@implementation BXDatabaseContext (Undoing)
- (void) undoGroupWillClose: (NSNotification *) notification
{
	NSUInteger groupingLevel = [mUndoManager groupingLevel];
	NSUInteger currentLevel = NSNotFound;
	BOOL shouldEstablishSavepoint = NO;
	if (mUndoGroupingLevels)
	{
		while (NSNotFound != (currentLevel = [mUndoGroupingLevels lastIndex]))
		{
			if (currentLevel < groupingLevel)
				break;
			
			shouldEstablishSavepoint = YES;
			[mUndoGroupingLevels removeIndex: currentLevel];
		}
	}
	
	if (shouldEstablishSavepoint)
	{
		NSError* localError = nil;
		[mDatabaseInterface establishSavepoint: &localError];
		if (nil != localError)
			[mDelegateProxy databaseContext: self hadError: localError willBePassedOn: NO];
		[[mUndoManager prepareWithInvocationTarget: self] rollbackToLastSavepoint];
	}
}

/**
 * \internal
 * When modifications are made, the respective undo grouping levels get stored in a stack,
 * mUndoGroupingLevels. When an undo group closes, a savepoint gets created for the group.
 * If there is no active undo group, establish the savepoint immediately.
 */
- (BOOL) prepareSavepointIfNeeded: (NSError **) error
{
	BOOL rval = NO;
	NSError* localError = nil;
	int groupingLevel = [mUndoManager groupingLevel];

	BXAssertLog (NULL != error, @"Expected error to be set.");

	if ([mUndoManager isRedoing])
		--groupingLevel;
	
	if (0 == groupingLevel)
	{
		[mDatabaseInterface establishSavepoint: &localError];
		if (nil == localError)
			rval = YES;
	}
	else
	{
		NSUInteger lastLevel = [mUndoGroupingLevels lastIndex];
		if (lastLevel != groupingLevel)
		{
			BXAssertValueReturn (NSNotFound == lastLevel || lastLevel < groupingLevel, NO, 
								   @"Undo group level stack is corrupt.");
			[mUndoGroupingLevels addIndex: groupingLevel];
		}
	}
	
	if (NULL != error)
		*error = localError;
	
	return rval;
}

- (void) undoWithRedoInvocations: (NSArray *) invocations
{
    [[mUndoManager prepareWithInvocationTarget: self] redoInvocations: invocations];
}

- (void) redoInvocations: (NSArray *) invocations
{
    [invocations makeObjectsPerformSelector: @selector (invoke)];
}

- (void) rollbackToLastSavepoint
{
	NSError* error = nil;
    [mDatabaseInterface rollbackToLastSavepoint: &error];
	//FIXME: in which case does the query fail? Should we be prepared for that?
	if (nil != error)
		[mDelegateProxy databaseContext: self hadError: error willBePassedOn: NO];
}

#if 0
- (void) reregisterObjects: (NSArray *) objectIDs values: (NSDictionary *) pkeyValues
{
	BXEnumerate (currentID, e, [objectIDs objectEnumerator])
	{
		BXDatabaseObject* currentObject = [self registeredObjectWithID: currentID];
		if (nil != currentObject)
		{
			[currentObject setCachedValuesForKeysWithDictionary: pkeyValues];
			[self unregisterObject: currentObject];
			[currentObject registerWithContext: self entity: nil];
		}
	}
}
#endif

- (void) undoUpdateObjects: (NSArray *) objectIDs 
					oldIDs: (NSArray *) oldIDs 
				attributes: (NSArray *) updatedAttributes
		  createdSavepoint: (BOOL) createdSavepoint 
			   updatedPkey: (BOOL) updatedPkey 
				   oldPkey: (NSDictionary *) oldPkey
		   redoInvocations: (NSArray *) redoInvocations
{
	[[mUndoManager prepareWithInvocationTarget: self] redoInvocations: redoInvocations];
	
	if (createdSavepoint)
		[self rollbackToLastSavepoint];
	
	if (updatedPkey)
	{
		BXEnumerate (currentID, e, [objectIDs objectEnumerator])
		{
			BXDatabaseObject* currentObject = [self registeredObjectWithID: currentID];
			if (nil != currentObject)
			{
				[currentObject setCachedValuesForKeysWithDictionary: oldPkey];
				[self unregisterObject: currentObject];
				[currentObject registerWithContext: self entity: nil];
			}
		}
	}
	[self updatedObjectsInDatabase: oldIDs attributes: updatedAttributes faultObjects: YES];
}
@end


@implementation BXDatabaseContext (Queries)

/** 
 * \name Retrieving objects from the database
 * \brief These methods block until the result has been retrieved.
 */
//@{
/**
 * \brief Fetch an object with a given ID.
 *
 * The database is queried only if the object isn't in cache.
 */
- (id) objectWithID: (BXDatabaseObjectID *) anID error: (NSError **) error
{
    id retval = [self registeredObjectWithID: anID];
    if (nil == retval && [self checkErrorHandling])
    {
        NSError* localError = nil;
		if (! [self connectSync: &localError])
			goto error;
		
		NSArray* objects = [self executeFetchForEntity: (BXEntityDescription *) [anID entity] 
										 withPredicate: [anID predicate] returningFaults: NO error: &localError];
		if (localError) goto error;
		
		if (0 < [objects count])
			retval = [objects objectAtIndex: 0];
		else
		{
			//FIXME: some human-readable error?
			localError = [BXError errorWithDomain: kBXErrorDomain code: kBXErrorObjectNotFound userInfo: nil];
		}
		
	error:
        BXHandleError (error, localError);
    }
    return retval;
}

/**
 * \brief Fetch objects with given IDs.
 *
 * The database is queried only if the object aren't in cache.
 */
- (NSSet *) objectsWithIDs: (NSArray *) anArray error: (NSError **) error
{
    NSMutableSet* rval = nil;
    if (0 < [anArray count])
    {
        rval = [NSMutableSet setWithCapacity: [anArray count]];
        NSMutableDictionary* entities = [NSMutableDictionary dictionary];
        BXEnumerate (currentID, e, [anArray objectEnumerator])
        {
            id currentObject = [self registeredObjectWithID: currentID];
            if (nil == currentObject)
			{
				BXEntityDescription* entity = [(BXDatabaseObjectID *) currentID entity];
				NSMutableArray* predicates = [entities objectForKey: entity];
				if (nil == predicates)
				{
					predicates = [NSMutableArray array];
					[entities setObject: predicates forKey: entity];
				}
                [predicates addObject: [currentID predicate]];
			}
            else
			{
                [rval addObject: currentObject];
			}
        }
        
        if (0 < [entities count])
        {
            NSError* localError = nil;
			BXEnumerate (currentEntity, e, [entities keyEnumerator])
			{
				NSPredicate* predicate = [NSCompoundPredicate orPredicateWithSubpredicates: [entities objectForKey: currentEntity]];
				NSArray* fetched = [self executeFetchForEntity: currentEntity withPredicate: predicate error: &localError];
				if (nil != localError)
					break;
				[rval addObjectsFromArray: fetched];
			}
            BXHandleError (error, localError);
        }
    }
    return rval;
}

/**
 * \brief Fetch objects from the database.
 *
 * Essentially calls #executeFetchForEntity:withPredicate:returningFaults:error: with \em returningFaults set to NO.
 *  
 * \param       entity          The entity from which rows are fetched.
 * \param       predicate       A WHERE clause is constructed using this predicate. May be nil.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return                      An NSArray that reflects the state of the database at query 
 *                              execution time.
 */
- (NSArray *) executeFetchForEntity: (BXEntityDescription *) entity withPredicate: (NSPredicate *) predicate error: (NSError **) error
{
    return [self executeFetchForEntity: entity withPredicate: predicate returningFaults: NO error: error];
}

/**
 * \brief Fetch objects from the database.
 *
 * Instead of fetching the field values, the context can retrieve objects that
 * contain only the object ID. The other values get fetched on-demand.\n
 * Essentially calls #executeFetchForEntity:withPredicate:returningFaults:updateAutomatically:error: with \em updateAutomatically set to NO.
 *
 * \param       entity          The entity from which rows are fetched.
 * \param       predicate       A WHERE clause is constructed using this predicate. May be nil.
 * \param       returnFaults    A boolean indicating whether faults should
 *                              be returned or not.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return                      An NSArray that reflects the state of the database at query 
 *                              execution time.
 */
- (NSArray *) executeFetchForEntity: (BXEntityDescription *) entity 
                      withPredicate: (NSPredicate *) predicate 
                    returningFaults: (BOOL) returnFaults 
                              error: (NSError **) error
{
    return [self executeFetchForEntity: entity withPredicate: predicate 
                       returningFaults: returnFaults updateAutomatically: NO error: error];
}

/**
 * \brief Fetch objects from the database.
 *
 * Instead of fetching all the columns, the user may supply a list of fields
 * that are excluded from the query results. The returned objects are 
 * faults. Values for the non-excluded fields are cached, though.\n
 * Essentially calls #executeFetchForEntity:withPredicate:excludingFields:updateAutomatically:error:
 * with \em updateAutomatically set to NO.
 *
 * \param       entity          The entity from which rows are fetched.
 * \param       predicate       A WHERE clause is constructed using this predicate. May be nil.
 * \param       excludedFields  An NSArray containing the BXPropertyDescriptors for the columns
 *                              that should be excluded. May be nil.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return                      An NSArray that reflects the state of the database at query 
 *                              execution time.
 */
- (NSArray *) executeFetchForEntity: (BXEntityDescription *) entity 
                      withPredicate: (NSPredicate *) predicate 
                    excludingFields: (NSArray *) excludedFields 
                              error: (NSError **) error
{
    return [self executeFetchForEntity: entity withPredicate: predicate 
                       excludingFields: excludedFields
				   updateAutomatically: NO error: error];
}

/** 
 * \brief Fetch objects from the database.
 *
 * The result array can be set to be updated automatically. 
 * \param       entity          The entity from which rows are fetched.
 * \param       predicate       A WHERE clause is constructed using this predicate. May be nil.
 * \param       returnFaults    A boolean indicating whether faults should be returned or not.
 * \param       shouldUpdate    A boolean indicating whether the results 
 *                              should be updated by the context or not.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return                      An NSArray that reflects the state of the database at query 
 *                              execution time, or a BXArrayProxy.
 */
- (NSArray *) executeFetchForEntity: (BXEntityDescription *) entity withPredicate: (NSPredicate *) predicate 
                    returningFaults: (BOOL) returnFaults updateAutomatically: (BOOL) shouldUpdate error: (NSError **) error
{
    return [self executeFetchForEntity: entity withPredicate: predicate
                       returningFaults: returnFaults excludingFields: nil
                         returnedClass: (shouldUpdate ? [BXArrayProxy class] : Nil) 
                                 error: error];
}

/**
 * \brief Fetch objects from the database.
 *
 * The result array can be set to be updated automatically.
 * \param       entity          The entity from which rows are fetched.
 * \param       predicate       A WHERE clause is constructed using this predicate. May be nil.
 * \param       excludedFields  An NSArray containing the BXPropertyDescriptors for the columns
 *                              that should be excluded. May be nil.
 * \param       shouldUpdate    A boolean indicating whether the results 
 *                              should be updated by the context or not.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return                      An NSArray that reflects the state of the database at query 
 *                              execution time, or a BXArrayProxy.
 */
- (NSArray *) executeFetchForEntity: (BXEntityDescription *) entity withPredicate: (NSPredicate *) predicate 
                    excludingFields: (NSArray *) excludedFields updateAutomatically: (BOOL) shouldUpdate error: (NSError **) error
{
	[entity resetAttributeExclusion];
    return [self executeFetchForEntity: entity withPredicate: predicate
                       returningFaults: NO excludingFields: excludedFields
                         returnedClass: (shouldUpdate ? [BXArrayProxy class] : Nil) 
                                 error: error];
}
//@}


/** \name Creating new database objects */
//@{
/**
 * \brief Create a new database object.
 *
 * Essentially inserts a new row into the database and retrieves it.
 * \param       entity           The target entity.
 * \param       givenFieldValues Initial values for fields. May be nil or left empty if
 *                               values for the primary key can be determined by the database.
 * \param       error            If an error occurs, this pointer is set to an NSError instance.
 *                               May be NULL.
 * \return                       A subclass of BXDatabaseObject or nil, if an error has occured.
 */
- (id) createObjectForEntity: (BXEntityDescription *) entity 
             withFieldValues: (NSDictionary *) givenFieldValues 
                       error: (NSError **) error
{
    NSError* localError = nil;
    BXDatabaseObject* retval = nil;
	if ([self checkErrorHandling] && [self checkDatabaseURI: &localError])
	{
		if ([self connectSync: &localError])
		{
			//The interface wants only attribute descriptions as keys
			NSDictionary* properties = [entity propertiesByName];
			NSMutableDictionary* changedObjectsByRelationship = [NSMutableDictionary dictionaryWithCapacity: [givenFieldValues count]];
			NSMutableDictionary* fieldValues = [NSMutableDictionary dictionaryWithCapacity: [givenFieldValues count]];
			BXEnumerate (currentKey, e, [givenFieldValues keyEnumerator])
			{
				id value = [givenFieldValues objectForKey: currentKey];
				if ([currentKey isKindOfClass: [NSString class]])
				{
					NSString* oldValue = currentKey;
					currentKey = [properties objectForKey: currentKey];
					BXAssertValueReturn (currentKey, nil, @"Key %@ wasn't known.", oldValue);
				}
				else
				{
					BXAssertValueReturn ([currentKey isKindOfClass: [BXPropertyDescription class]], nil,
										 @"Expected %@ to be either a string or a property description.", currentKey);
				}
				
				switch ([currentKey propertyKind])
				{
					case kBXPropertyKindAttribute:
						[fieldValues setObject: value forKey: currentKey];
						break;
						
					case kBXPropertyKindRelationship:
					{
						BXAssertValueReturn (![currentKey isToMany], nil, 
											 @"%@ was specified in value dictionary, but only to-one relationships are allowed.",
											 [currentKey name]);
						BXAssertValueReturn ([currentKey isInverse], nil,
											 @"%@ was specified in value dictionary, but its foreign key columns don't exist in %@.",
											 [currentKey name], entity);
						
						if ([value isKindOfClass: [BXDatabaseObjectID class]])
						{
							value = [[self faultsWithIDs: [NSArray arrayWithObject: value]] lastObject];
							BXAssertValueReturn (value, nil, @"Couldn't get object for object id %@.",
												 [givenFieldValues objectForKey: currentKey]);
						}
						
						NSDictionary* values = BXFkeySrcDictionary ([currentKey foreignKey], entity, value);
						[fieldValues addEntriesFromDictionary: values];
						
						[value willChangeValueForKey: [currentKey name]];
						[changedObjectsByRelationship setObject: value forKey: currentKey];
						break;
					}
						
					default:
						BXLogWarning (@"Got a strange key in values dictionary: %@", currentKey);
						break;
				}				
			}
			
			//First make the object
			retval = [mDatabaseInterface createObjectForEntity: entity withFieldValues: fieldValues
													   class: [entity databaseObjectClass]
													   error: &localError];
			
			//Then use the values received from the database with the redo invocation
			if (nil != retval && nil == localError)
			{
				//FIXME: when refactoring different commit modes out of BXDatabaseContext, rethink handling of creating and deleting objects within transactions.
                //If registration fails, there should be a suitable object in memory.
				//In that case, we'll probably want to empty the value cache.
				if (NO == [retval registerWithContext: self entity: entity])
				{
					retval = [self registeredObjectWithID: [retval objectID]];
					[retval setCachedValuesForKeysWithDictionary: nil];
				}
				BXDatabaseObjectID* objectID = [retval objectID];
				Expect (objectID);
				
				//Cache some of the values we got earlier.
				{
					NSMutableDictionary* valuesByName = [NSMutableDictionary dictionaryWithCapacity: [fieldValues count]];
					BXEnumerate (currentKey, e, [fieldValues keyEnumerator])
					{
						id value = [fieldValues objectForKey: currentKey];
						NSString* name = [currentKey name];
						
						//NSStrings get special treatment.
						if ([value isKindOfClass: [NSString class]])
							value = [value decomposedStringWithCanonicalMapping];
						
						[valuesByName setObject: value forKey: name];
					}
					[valuesByName addEntriesFromDictionary: [retval cachedValues]];
					[retval setCachedValuesForKeysWithDictionary: valuesByName];
				}
				
				if (YES == [mDatabaseInterface autocommits])
				{
					[retval awakeFromInsertIfNeeded];
					if (! [entity getsChangedByTriggers])
						[self addedObjectsToDatabase: [NSArray arrayWithObject: objectID]];
				}
				else
				{
					[retval setCreatedInCurrentTransaction: YES];
					BOOL createdSavepoint = [self prepareSavepointIfNeeded: &localError];
					if (nil == localError)
					{
						[retval awakeFromInsertIfNeeded];

						//This is needed for self-updating collections. See the deletion method.
						[self addedObjectsToDatabase: [NSArray arrayWithObject: objectID]];
						
						//For redo
						BXInvocationRecorder* recorder = [BXInvocationRecorder recorder];
						NSMutableDictionary* values = [NSMutableDictionary dictionary];
						[values addEntriesFromDictionary: [retval cachedObjects]];
						[[recorder recordWithPersistentTarget: self] createObjectForEntity: entity 
																		   withFieldValues: values
																					 error: NULL];
						
						//Undo manager does things in reverse order
						NSArray* invocations = [recorder recordedInvocations];
						if (![mUndoManager groupsByEvent])
    						[mUndoManager beginUndoGrouping];
						[[mUndoManager prepareWithInvocationTarget: self] deletedObjectsFromDatabase: [NSArray arrayWithObject: objectID]];
						if (createdSavepoint)
							[[mUndoManager prepareWithInvocationTarget: self] rollbackToLastSavepoint];
						[[mUndoManager prepareWithInvocationTarget: self] undoWithRedoInvocations: invocations];
						[[mUndoManager prepareWithInvocationTarget: mModifiedObjectIDs] setObject: [mModifiedObjectIDs objectForKey: objectID] 
                                                                                           forKey: objectID];
						if (![mUndoManager groupsByEvent])
    						[mUndoManager endUndoGrouping];        
						
						//Remember the modification type for ROLLBACK
                        [mModifiedObjectIDs setObject: ModTypeToObject (kBXInsertModification) forKey: objectID];
					}
				}
				
				//Call -didChangeValueForKey: for related objects that got a new target.
				BXEnumerate (currentKey, e, [changedObjectsByRelationship keyEnumerator])
				{
					BXDatabaseObject* object = [changedObjectsByRelationship objectForKey: currentKey];
					[object didChangeValueForKey: [[currentKey inverseRelationship] name]];
				}
			}
		}		
	}
	BXHandleError (error, localError);
	return retval;
}
//@}

- (BOOL) fireFault: (BXDatabaseObject *) anObject key: (id) aKey error: (NSError **) error
{
    NSError* localError = nil;
	BOOL retval = NO;
	if ([self checkErrorHandling])
	{
	    //Always fetch all keys when firing a fault
		NSArray* keys = [anObject keysIncludedInQuery: aKey];
		
		if (BASETEN_BEGIN_FETCH_ENABLED ())
			BASETEN_BEGIN_FETCH ();
		
	    retval = [mDatabaseInterface fireFault: anObject keys: keys error: &localError];
		
		if (BASETEN_END_FETCH_ENABLED ())
		{
			BXEntityDescription* entity = [anObject entity];
			char* schema_s = strdup ([[entity schemaName] UTF8String]);
			char* table_s = strdup ([[entity name] UTF8String]);
			BASETEN_END_FETCH (self, schema_s, table_s, 1);
			free (schema_s);
			free (table_s);
		}
		
		if (YES == retval)
			[anObject awakeFromFetchIfNeeded];
	    BXHandleError (error, localError);
	}
	else
	{
		retval = YES;
	}
    return retval;
}


- (BOOL) observeEntity: (BXEntityDescription *) entity options: (enum BXObservingOption) options error: (NSError **) error
{
	NSError *localError = nil;
	BOOL retval = NO;
	if ([self checkErrorHandling])
	{
		if ([entity hasCapability: kBXEntityCapabilityAutomaticUpdate])
			retval = [mDatabaseInterface observeEntity: entity options: options error: &localError];
		else
		{
			// FIXME: set an error if no observing capability.
		}
		
		BXHandleError (error, localError);
	}
	else
	{
		retval = YES;
	}
	return retval;
}


/** \name Deleting database objects */
//@{
/**
 * \brief Delete a database object.
 *
 * Essentially this method deletes a single row from the database.
 * \param       anObject        The object to be deleted.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return                      A boolean indicating whether the deletion was successful or not.
 */
- (BOOL) executeDeleteObject: (BXDatabaseObject *) anObject error: (NSError **) error
{
    return (nil != [self executeDeleteObject: anObject entity: nil predicate: nil error: error]);
}
//@}

/** \name Executing arbitrary queries */
//@{
/**
 * \brief Execute a query directly.
 *
 * This method should only be used when fetching objects and modifying 
 * them is cumbersome or doesn't accomplish the task altogether.
 * \return An NSArray of NSDictionaries that correspond to each row.
 */
- (NSArray *) executeQuery: (NSString *) queryString error: (NSError **) error
{
	return [self executeQuery: queryString parameters: nil error: error];
}

/**
 * \brief Execute a query directly.
 *
 * This method should only be used when fetching objects and modifying 
 * them is cumbersome or doesn't accomplish the task altogether.
 * \param queryString The SQL query.
 * \param parameters An NSArray of objects that are passed as replacements for $1, $2 etc. in the query.
 * \param       error           If an error occurs, this pointer is set to an NSError instance.
 *                              May be NULL.
 * \return An NSArray of NSDictionaries that correspond to each row.
 */
- (NSArray *) executeQuery: (NSString *) queryString parameters: (NSArray *) parameters error: (NSError **) error
{
	NSError* localError = nil;
	id retval = nil;
	if ([self checkErrorHandling])
	{
		if ([self connectSync: &localError])
			retval = [mDatabaseInterface executeQuery: queryString parameters: parameters error: &localError];
		BXHandleError (error, localError);
	}
	return retval;
}

/**
 * \brief Execute a command directly.
 *
 * This method should only be used when fetching objects and modifying 
 * them is cumbersome or doesn't accomplish the task altogether.
 * \return The number of rows affected by the command.
 */
- (unsigned long long) executeCommand: (NSString *) commandString error: (NSError **) error
{
	NSError* localError = nil;
	unsigned long long retval = 0;
	if ([self checkErrorHandling])
	{
		if ([self connectSync: &localError])
			retval = [mDatabaseInterface executeCommand: commandString error: &localError];
		BXHandleError (error, localError);
	}
	return retval;
}
//@}
@end


@implementation BXDatabaseContext (DBInterfaces)

- (NSError *) packQueryError: (NSError *) error
{
	NSString* title = BXLocalizedString (@"databaseError", @"Database Error", @"Title for a sheet");
	NSMutableDictionary* userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
									 title, NSLocalizedDescriptionKey,
									 self, kBXDatabaseContextKey,
									 nil];
	if (error) 
	{
		[userInfo setObject: error forKey: NSUnderlyingErrorKey];
		if ([error localizedFailureReason])
			[userInfo setObject: [error localizedFailureReason] forKey: NSLocalizedFailureReasonErrorKey];
		if ([error localizedRecoverySuggestion])
			[userInfo setObject: [error localizedRecoverySuggestion] forKey: NSLocalizedRecoverySuggestionErrorKey];
	}
	return [BXError errorWithDomain: kBXErrorDomain code: kBXErrorUnsuccessfulQuery userInfo: userInfo];	
}


- (void) connectionLost: (NSError *) error
{
	[mDelegateProxy databaseContext: self lostConnection: error];
}


//FIXME: We do too many things in this method. It should be refactored.
- (BOOL) connectedToDatabase: (BOOL) connected async: (BOOL) async error: (NSError **) error;
{
	BXAssertLog (NULL != error || (YES == async && YES == connected), @"Expected error to be set.");
	BOOL retval = connected;
	
	if (NO == connected)
	{
		ExpectR (error, NO);
		[self setLastConnectionError: *error];
		if (NO == mDisplayingSheet)
		{
			//If the certificate wasn't verified, our delegate will handle the situation.
			//On any other SSL error retry the connection.
			BOOL authenticationFailed = NO;
			BOOL sslFailed = NO;
			if ([[mLastConnectionError domain] isEqualToString: kBXErrorDomain])
			{
				NSInteger code = [mLastConnectionError code];
				switch (code)
				{
					case kBXErrorAuthenticationFailed:
						authenticationFailed = YES;
						break;
						
					case kBXErrorSSLError:
					case kBXErrorSSLUnavailable:
						sslFailed = YES;
						break;
						
					case kBXErrorSSLCertificateVerificationFailed:
					default:
						break;
				}
			}
			
			if (sslFailed)
			{
				[mDatabaseInterface disconnect];
				if (async)
					[self connectAsync];
				else if ([self connectSync: error])
				{
					retval = YES;
					if (error)
						*error = nil;
				}
			}
			else
			{
                //If we have a keychain item, mark it invalid.
                if (NULL != mKeychainPasswordItem && authenticationFailed)
                {
                    //FIXME: enable this after debugging
#if 0
                    OSStatus status = noErr;
                    Boolean value = TRUE;
                    SecKeychainAttribute attribute = {.tag = kSecNegativeItemAttr, .length = sizeof (Boolean), .data = &value};
                    SecKeychainAttributeList attributeList = {.count = 1, .attr = &attribute};
                    status = SecKeychainItemModifyAttributesAndData (mKeychainPasswordItem, &attributeList, 0, NULL);
#endif
                }
                
				//If we have a connection setup manager, it will call a method when it's finished.
				if (nil == mConnectionSetupManager)
					[self setCanConnect: YES];
				
				//Don't set the error if we were supposed to disconnect.
				NSDictionary* userInfo = nil;
				if (! mDidDisconnect && mLastConnectionError)
					userInfo = [NSDictionary dictionaryWithObject: mLastConnectionError forKey: kBXErrorKey];
				NSNotification* notification = [NSNotification notificationWithName: kBXConnectionFailedNotification object: self userInfo: userInfo];
				[mDelegateProxy databaseContext: self failedToConnect: mLastConnectionError];
				[[self notificationCenter] postNotification: notification];
				
				//Strip password from the URI
                //FIXME: should we remove the username as well?
				NSURL* newURI = [mDatabaseURI BXURIForHost: nil database: nil username: nil password: @""];
				[self setDatabaseURIInternal: newURI];
			}
		}
	}
	else //YES == connected
	{
		NSError* localError = nil;
		
		if (mShouldStoreURICredentials)
			[self storeURICredentials];

		//Strip password from the URI
		NSURL* newURI = [mDatabaseURI BXURIForHost: nil database: nil username: nil password: @""];
		[self setDatabaseURIInternal: newURI];
				
		NSNotification* notification = nil;
		if ([[self databaseObjectModel] contextConnectedUsingDatabaseInterface: mDatabaseInterface error: &localError])
		{
			notification = [NSNotification notificationWithName: kBXConnectionSuccessfulNotification object: self userInfo: nil];
			if (async)
				[mDelegateProxy databaseContextConnectionSucceeded: self];
		}
		else
		{
			retval = NO;
			NSDictionary* userInfo = nil;
			[mDatabaseInterface disconnect];

			if (localError)
			{
				userInfo = [NSDictionary dictionaryWithObject: localError forKey: kBXErrorKey];
				if (NULL != error)
					*error = localError;
			}
			notification = [NSNotification notificationWithName: kBXConnectionFailedNotification object: self userInfo: userInfo];
			[mDelegateProxy databaseContext: self failedToConnect: localError];
		}
		[[self notificationCenter] postNotification: notification];
		[self setConnectionSetupManager: nil];
	}
	[self setLastConnectionError: nil];
	[self setKeychainPasswordItem: NULL];
	return retval;
}

- (NSDictionary *) targetsByObject: (NSArray *) objects forRelationships: (id) rels fireFaults: (BOOL) shouldFire
{
	NSMutableDictionary* targetsByObject = [NSMutableDictionary dictionaryWithCapacity: [objects count]];
	BXEnumerate (currentObject, e, [objects objectEnumerator])
	{
		if ([NSNull null] != currentObject)
		{
			id targets = [[rels BX_CollectDK] registeredTargetFor: currentObject fireFault: shouldFire]; 
			if (targets)
				[targetsByObject setObject: targets forKey: currentObject];
		}
	}
	return targetsByObject;
}

//FIXME: clean me up.
- (void) updatedObjectsInDatabase: (NSArray *) givenObjectIDs attributes: (NSArray *) attrs faultObjects: (BOOL) shouldFault
{
    if (0 < [givenObjectIDs count])
    {
		NSMutableDictionary* idsByEntity = ObjectsByEntity (givenObjectIDs);
		AddObjectIDsForInheritance (idsByEntity);
		NSNotificationCenter* nc = [self notificationCenter];

		BXEnumerate (entity, e, [idsByEntity keyEnumerator])
		{
			NSArray* objectIDs = [idsByEntity objectForKey: entity];
			NSArray* objects = [self registeredObjectsWithIDs: objectIDs nullObjects: YES];
			
			id rels = [entity inverseToOneRelationships];
			NSDictionary* oldTargets = nil;
			NSDictionary* newTargets = nil;
			
			if (0 < [rels count])
			{
				oldTargets = [self targetsByObject: objects forRelationships: rels fireFaults: NO];
				newTargets = [self targetsByObject: objects forRelationships: rels fireFaults: YES];
				
				BXEnumerate (currentObject, e, [objects objectEnumerator])
				{
					if ([NSNull null] != currentObject)
						[currentObject willChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
				}
			}
			
			//Fault the objects and send the notifications
			if (shouldFault)
			{
				BXEnumerate (currentObject, e, [objects objectEnumerator])
				{
					if ([NSNull null] != currentObject)
						[currentObject removeFromCache: nil postingKVONotifications: YES];
				}
			}
			
			NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
									  objectIDs, kBXObjectIDsKey,
									  objects, kBXObjectsKey,
									  self, kBXDatabaseContextKey,
									  nil];
			
			[nc postNotificationName: kBXUpdateEarlyNotification object: entity userInfo: userInfo];
			if (0 < [rels count])
			{
				BXEnumerate (currentObject, e, [objects objectEnumerator])
				{
					if ([NSNull null] != currentObject)
						[currentObject didChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
				}
			}
			
			[nc postNotificationName: kBXUpdateNotification object: entity userInfo: userInfo];
		}
    }
}

- (void) addedObjectsToDatabase: (NSArray *) objectIDs
{
    if (0 < [objectIDs count])
    {
        NSMutableDictionary* idsByEntity = ObjectsByEntity (objectIDs);
        AddObjectIDsForInheritance (idsByEntity);
        NSNotificationCenter* nc = [self notificationCenter];
        		
        //Post the notifications
        BXEnumerate (entity, e, [idsByEntity keyEnumerator])
        {
            NSArray* objectIDs = [idsByEntity objectForKey: entity];
			NSArray* objects = [self faultsWithIDs: objectIDs];
			
			id rels = [entity inverseToOneRelationships];
			NSDictionary* oldTargets = nil;
			NSDictionary* newTargets = nil;
			if (0 < [rels count])
			{
				oldTargets = [self targetsByObject: objects forRelationships: rels fireFaults: NO];
				newTargets= [self targetsByObject: objects forRelationships: rels fireFaults: YES];
				BXEnumerate (currentObject, e, [objects objectEnumerator])
					[currentObject willChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
			}

            //Send the notifications
            NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                objectIDs, kBXObjectIDsKey,
                self, kBXDatabaseContextKey,
                nil];
			
			[nc postNotificationName: kBXInsertEarlyNotification object: entity userInfo: userInfo];
			if (0 < [rels count])
			{
				BXEnumerate (currentObject, e, [objects objectEnumerator])
					[currentObject didChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
			}

			[nc postNotificationName: kBXInsertNotification object: entity userInfo: userInfo];
        }
    }
}

- (void) deletedObjectsFromDatabase: (NSArray *) objectIDs
{
	if (0 < [objectIDs count])
    {
        NSMutableDictionary* idsByEntity = ObjectsByEntity (objectIDs);
        AddObjectIDsForInheritance (idsByEntity);
        NSNotificationCenter* nc = [self notificationCenter];
		
        //Post the notifications
        BXEnumerate (entity, e, [idsByEntity keyEnumerator])
        {
			NSArray* objectIDs = [idsByEntity objectForKey: entity];
			id objects = [mObjects objectsForKeys: objectIDs notFoundMarker: [NSNull null]];

			BXEnumerate (currentID, e, [objectIDs objectEnumerator])
				[[self registeredObjectWithID: currentID] setDeleted: kBXObjectDeleted];
        
			id rels = [entity inverseToOneRelationships];
			NSDictionary* oldTargets = nil;
			NSDictionary* newTargets = nil;
			if (0 < [rels count])
			{
				oldTargets= [self targetsByObject: objects forRelationships: rels fireFaults: NO];
				newTargets = [self targetsByObject: objects forRelationships: rels fireFaults: YES];
				BXEnumerate (currentObject, e, [objects objectEnumerator])
				{
					if ([NSNull null] != currentObject)
						[currentObject willChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
				}
			}
        
			//Send the notifications
			NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
									  objectIDs, kBXObjectIDsKey,
									  objects, kBXObjectsKey,
									  self, kBXDatabaseContextKey,
									  nil];
			
			[nc postNotificationName: kBXDeleteEarlyNotification object: entity userInfo: userInfo];
			
			if (0 < [rels count])
			{
				BXEnumerate (currentObject, e, [objects objectEnumerator])
				{
					if ([NSNull null] != currentObject)
						[currentObject didChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
				}
			}
			
			[nc postNotificationName: kBXDeleteNotification object: entity userInfo: userInfo];
		}
	}
}
		
- (void) lockedObjectsInDatabase: (NSArray *) objectIDs status: (enum BXObjectLockStatus) status
{
    NSUInteger count = [objectIDs count];
    if (0 < count)
    {
        NSMutableArray* foundObjects = [NSMutableArray arrayWithCapacity: count];
        BXEnumerate (currentID, e, [objectIDs objectEnumerator])
        {
            BXDatabaseObject* object = [self registeredObjectWithID: currentID];
            if (nil != object)
			{
				switch (status)
				{
					case kBXObjectDeletedStatus:
						[object lockForDelete];
						break;
					case kBXObjectLockedStatus:
						[object setLockedForKey: nil]; //TODO: set the key accordingly
						break;
					default:
						break;
				}
				[foundObjects addObject: object];
			}
		}
        NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
            objectIDs, kBXObjectIDsKey,
            self, kBXDatabaseContextKey,
            foundObjects, kBXObjectsKey,
            [NSValue valueWithBytes: &status objCType: @encode (enum BXObjectLockStatus)], kBXObjectLockStatusKey,
            nil];
        [[self notificationCenter] postNotificationName: kBXLockNotification
                                                 object: [[objectIDs objectAtIndex: 0] entity]
                                               userInfo: userInfo];
    }
}

- (void) unlockedObjectsInDatabase: (NSArray *) objectIDs
{
    NSUInteger count = [objectIDs count];
    if (0 < count)
    {
        NSArray* foundObjects = [self registeredObjectsWithIDs: objectIDs];
        NSMutableArray* iteratedObjects = [NSMutableArray arrayWithCapacity: [foundObjects count]];
        BXEnumerate (currentObject, e, [foundObjects objectEnumerator])
        {
            if ([NSNull null] != currentObject)
            {
                [currentObject clearStatus];
                [iteratedObjects addObject: currentObject];
            }
        }
        NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
            objectIDs, kBXObjectIDsKey,
            self, kBXDatabaseContextKey, 
            iteratedObjects, kBXObjectsKey,
            nil];
        [[self notificationCenter] postNotificationName: kBXUnlockNotification
                                                 object: [[objectIDs objectAtIndex: 0] entity]
                                               userInfo: userInfo];
    }
}


- (void) changedEntity: (BXEntityDescription *) entity
{
	NSNotificationCenter *nc = [self notificationCenter];
	NSDictionary *userInfo = [NSDictionary dictionaryWithObject: self forKey: kBXDatabaseContextKey];
	[nc postNotificationName: kBXEntityChangeNotification object: entity userInfo: userInfo];
}


- (BOOL) handleInvalidTrust: (SecTrustRef) trust result: (SecTrustResultType) result
{
	BOOL retval = NO;
	enum BXCertificatePolicy policy = [mDelegateProxy databaseContext: self handleInvalidTrust: trust result: result];
	switch (policy)
	{			
		case kBXCertificatePolicyAllow:
		case kBXCertificatePolicyUndefined:
			retval = YES;
			break;
			
		case kBXCertificatePolicyDeny:
		default:
			break;
	}
	return retval;
}

- (void) handleInvalidCopiedTrustAsync: (NSValue *) value
{
	struct BXTrustResult trustResult = {};
	[value getValue: &trustResult];
	SecTrustRef trust = trustResult.trust;
	SecTrustResultType result = trustResult.result;
	
	enum BXCertificatePolicy policy = [mDelegateProxy databaseContext: self handleInvalidTrust: trust result: result];	
	switch (policy)
	{			
		case kBXCertificatePolicyAllow:
			[self connectAsync];
			break;
			
		case kBXCertificatePolicyDisplayTrustPanel:
			//These are in BaseTenAppKit framework.
			if (! mConnectionSetupManager)
				[self displayPanelForTrust: trust];
			else
				[mConnectionSetupManager databaseContext: self displayPanelForTrust: trust];
			
			break;
			
		case kBXCertificatePolicyDeny:
		case kBXCertificatePolicyUndefined:
		default:
			break;
	}
	
	CFRelease (trust);
}

- (enum BXSSLMode) sslMode
{
	enum BXSSLMode mode = [mDelegateProxy SSLModeForDatabaseContext: self];
	if ([kBXErrorDomain isEqualToString: [mLastConnectionError domain]])
	{
		if (kBXSSLModePrefer == mode)
		{
			switch ([mLastConnectionError code])
			{
				case kBXErrorSSLError:
				case kBXErrorSSLUnavailable:
				case kBXErrorSSLCertificateVerificationFailed:
					mode = kBXSSLModeDisable;
					break;
					
				default:
					break;
			}
		}
	}
	return mode;
}

- (void) networkStatusChanged: (SCNetworkConnectionFlags) newFlags
{
	[mDelegateProxy databaseContext: self networkStatusChanged: newFlags];
}
@end


@implementation BXDatabaseContext (HelperMethods)
- (NSArray *) objectIDsForEntity: (BXEntityDescription *) anEntity error: (NSError **) error
{
    return [self objectIDsForEntity: anEntity predicate: nil error: error];
}

- (NSArray *) objectIDsForEntity: (BXEntityDescription *) anEntity predicate: (NSPredicate *) predicate error: (NSError **) error
{
    return [[self executeFetchForEntity: anEntity withPredicate: predicate returningFaults: YES error: error] valueForKey: @"objectID"];
}

/** 
 * \brief Entity for a table in the given schema.
 * \note Unlike PostgreSQL, leaving \em schemaName unspecified does not cause the search path to be used but 
 *       instead will search the \em public schema.
 * \note Entities are associated with a database URI. Thus the database context needs an URI containing a host and 
 *       the database name before entities may be received.
 * \deprecated This method has been deprecated in BaseTen 1.8. BXDatabaseObjectModel should be used instead.
 */
- (BXEntityDescription *) entityForTable: (NSString *) name inSchema: (NSString *) schemaName error: (NSError **) outError
{
	BXDeprecationLog ();
	if (! schemaName) schemaName = @"public";
	id retval = [mObjectModel entityForTable: name inSchema: schemaName];
	if (! retval)
		BXHandleError (outError, [BXDatabaseObjectModel errorForMissingEntity: name inSchema: schemaName]);
	return retval;
}

/** 
 * \brief Entity for a table in the schema \em public
 * \note Entities are associated with a database URI. Thus the database context needs an URI containing a host and 
 *       the database name before entities may be received.
 * \deprecated This method has been deprecated in BaseTen 1.8. BXDatabaseObjectModel should be used instead.
 */
- (BXEntityDescription *) entityForTable: (NSString *) name error: (NSError **) outError
{
	BXDeprecationLog ();
	return [mObjectModel entityForTable: name inSchema: @"public"];
}

/**
 * \brief All entities found in the database.
 *
 * Entities in private and metadata schemata won't be included.
 * \param reload Whether the entity list should be reloaded.
 * \param outError If an error occurs, this pointer is set to an NSError instance. May be NULL.
 * \return An NSDicionary with NSStrings corresponding to schema names as keys and NSDictionarys as objects. 
 *         Each of them will have NSStrings corresponding to relation names as keys and BXEntityDescriptions
 *         as objects.
 * \deprecated This method has been deprecated in BaseTen 1.8. BXDatabaseObjectModel should be used instead.
 */
- (NSDictionary *) entitiesBySchemaAndName: (BOOL) reload error: (NSError **) outError
{
	BXDeprecationLog ();
	NSError* localError = nil;
	NSDictionary* retval = [mObjectModel entitiesBySchemaAndName: mDatabaseInterface reload: reload error: &localError];
	BXHandleError (outError, localError);
	return retval;
}


- (BOOL) entity: (NSEntityDescription *) entity existsInSchema: (NSString *) schemaName error: (NSError **) error
{
	BXDeprecationLog ();
	return [mObjectModel entity: entity existsInSchema: schemaName];
}


- (BXEntityDescription *) matchingEntity: (NSEntityDescription *) entity inSchema: (NSString *) schemaName error: (NSError **) error
{
	BXDeprecationLog ();
	return [mObjectModel entityForTable: [entity name] inSchema: schemaName];
}


- (BOOL) canGiveEntities
{
	BXDeprecationLog ();
	NSError* localError = nil;
	return ([self checkDatabaseURI: &localError] && [mDatabaseURI host] && [mDatabaseURI path]);
}
@end


@implementation BXDatabaseContext (NSCoding)
- (void) encodeWithCoder: (NSCoder *) encoder
{
    [encoder encodeObject: mDatabaseURI forKey: @"databaseURI"];
    [encoder encodeBool: mAutocommits forKey: @"autocommits"];
	[encoder encodeBool: mConnectsOnAwake forKey: @"connectsOnAwake"];
}

- (id) initWithCoder: (NSCoder *) decoder
{
	if (([self init]))
    {
        [self setDatabaseURI: [decoder decodeObjectForKey: @"databaseURI"]];
        [self setAutocommits: [decoder decodeBoolForKey: @"autocommits"]];
		[self setConnectsOnAwake: [decoder decodeBoolForKey: @"connectsOnAwake"]];
    }
    return self;
}
@end


@implementation BXDatabaseContext (PrivateMethods)
- (id <BXDatabaseContextDelegate>) internalDelegate
{
	return mDelegateProxy;
}

/** 
 * \internal
 * \brief Delete multiple objects at the same time. 
 * \note Redoing this re-executes the query with the given predicate and thus
 *       might cause other objects to be deleted than those which were in the original invocation.
 */
- (BOOL) executeDeleteFromEntity: (BXEntityDescription *) anEntity withPredicate: (NSPredicate *) predicate 
                           error: (NSError **) error
{
    return (nil != [self executeDeleteObject: nil entity: anEntity predicate: predicate error: error]);
}

/**
 * \internal
 * \param aKey Currently ignored, since PostgreSQL only supports row-level locks.
 */
- (void) lockObject: (BXDatabaseObject *) object key: (id) key status: (enum BXObjectLockStatus) status
             sender: (id <BXObjectAsynchronousLocking>) sender
{
	if (mSendsLockQueries && [self checkErrorHandling]) [mDatabaseInterface lockObject: object key: key lockType: status sender: sender];    
}

/**
 * \internal
 * \param aKey Currently ignored, since PostgreSQL only supports row-level locks.
 */
- (void) unlockObject: (BXDatabaseObject *) anObject key: (id) aKey
{
    if (mSendsLockQueries && [self checkErrorHandling]) [mDatabaseInterface unlockObject: anObject key: aKey];
}

/**
 * \internal
 * \brief Fetch objects from the database.
 * \param       returnedClass   The class an instance of which gets returned. The class should be a
 *                              subclass of BXContainerProxy.
 */
- (id) executeFetchForEntity: (BXEntityDescription *) entity 
               withPredicate: (NSPredicate *) predicate 
             returningFaults: (BOOL) returnFaults 
             excludingFields: (NSArray *) excludedFields 
               returnedClass: (Class) returnedClass 
                       error: (NSError **) error
{
    NSError* localError = nil;
    id retval = nil;
	if ([self checkErrorHandling])
	{
		if ([self connectSync: &localError])
		{
			if (nil != excludedFields)
			{
				excludedFields = [entity attributes: excludedFields];
				[[excludedFields BX_Do] setExcluded: YES];
			}
			
			if (BASETEN_BEGIN_FETCH_ENABLED ())
				BASETEN_BEGIN_FETCH ();
							
			Class databaseObjectClass = [entity databaseObjectClass];
			retval = [mDatabaseInterface executeFetchForEntity: entity 
												 withPredicate: predicate 
											   returningFaults: returnFaults 
														 class: databaseObjectClass
														 error: &localError];
			
			if (BASETEN_END_FETCH_ENABLED ())
			{
				char* schema_s = strdup ([[entity schemaName] UTF8String]);
				char* table_s = strdup ([[entity name] UTF8String]);
				BASETEN_END_FETCH (self, schema_s, table_s, [retval count]);
				free (schema_s);
				free (table_s);
			}
			
			if (nil == localError)
			{
				[retval makeObjectsPerformSelector: @selector (awakeFromFetchIfNeeded)];
				
				if (Nil != returnedClass)
				{
					retval = [[[returnedClass alloc] BXInitWithArray: retval] autorelease];
					[retval setDatabaseContext: self];
					[(BXContainerProxy *) retval fetchedForEntity: entity predicate: predicate];
				}
				else if (0 == [retval count])
				{
					//If an automatically updating container wasn't requested, we might as well return nil.
					retval = nil;
				}
			}
		}
		BXHandleError (error, localError);
	}
	return retval;    
}

//FIXME: do the following methods set modification types correctly in undo & redo, or do they get set in callbacks?
/** 
 * \internal
 * \brief Update multiple objects at the same time. 
 * \note Redoing this re-executes the query with the given predicate and thus
 *       might cause modifications in other objects than in the original invocation.
 */
- (NSArray *) executeUpdateObject: (BXDatabaseObject *) anObject
                           entity: (BXEntityDescription *) anEntity 
                        predicate: (NSPredicate *) predicate 
                   withDictionary: (NSDictionary *) aDict 
                            error: (NSError **) error
{
	BXAssertValueReturn ((anObject || anEntity) && aDict, nil, @"Expected to be called with parameters.");
    NSError* localError = nil;
	NSArray* objectIDs = nil;
	if ([self checkErrorHandling] && [self checkDatabaseURI: &localError])
	{
        NSArray* primaryKeyFields = [[[anObject objectID] entity] primaryKeyFields];
        if (nil == primaryKeyFields)
            primaryKeyFields = [anEntity primaryKeyFields];
        BOOL updatedPkey = (nil != [primaryKeyFields firstObjectCommonWithArray: [aDict allKeys]]);
        BXAssertValueReturn (!updatedPkey || anObject, nil, 
                               @"Expected anObject to be known in case its pkey should be modified.");

		NSDictionary* oldPkey = nil;
		if (updatedPkey)
			oldPkey = [anObject primaryKeyFieldObjects];

		//Handle KVO.
		NSArray* updatedObjects = nil;
		{
			if (anObject)
				updatedObjects = [NSArray arrayWithObject: anObject];
			else
			{
				updatedObjects = [self executeFetchForEntity: anEntity withPredicate: predicate returningFaults: YES error: &localError];
				if (localError)
					goto bail;
			}
		}
		struct update_kvo_ctx updateCtx = [self handleWillChangeForUpdate: updatedObjects newValues: aDict];
		
		objectIDs = [mDatabaseInterface executeUpdateWithDictionary: aDict objectID: [anObject objectID]
															 entity: anEntity predicate: predicate error: &localError];
		
		[self handleDidChangeForUpdate: &updateCtx newValues: aDict 
					 sendNotifications: !localError && [mDatabaseInterface autocommits]
						  targetEntity: anEntity];
		
		if (nil == localError)
        {
            NSArray* oldIDs = objectIDs;
            if (updatedPkey)
                oldIDs = [NSArray arrayWithObject: [anObject objectID]];
            
            //If autocommit is on, the update notification will be received immediately.
            //It won't be handled, though, since it originates from the same connection.
            //Therefore, we need to notify about the change.
            if (YES == [mDatabaseInterface autocommits])
			{
#if 0
				if (! [anEntity getsChangedByTriggers])
					[self updatedObjectsInDatabase: oldIDs faultObjects: NO];
#endif			
				
				//FIXME: move this to the if block where oldIDs are set.
				if (updatedPkey)
				{
					[self unregisterObject: anObject];
					[anObject registerWithContext: self entity: nil];
				}						
			}
            else
            {
                BOOL createdSavepoint = [self prepareSavepointIfNeeded: &localError];
                if (nil == localError)
                {
                    //This is needed for self-updating collections. See the deletion method.
					[self updatedObjectsInDatabase: oldIDs attributes: [aDict allKeys] faultObjects: NO];
                    
                    //For redo
                    BXInvocationRecorder* recorder = [BXInvocationRecorder recorder];
                    [[recorder recordWithPersistentTarget: self] executeUpdateObject: anObject entity: anEntity 
                                                                           predicate: predicate withDictionary: aDict error: NULL];
#if 0
                    //Finally fault the object.
                    //FIXME: do we need this?
                    [[recorder recordWithPersistentTarget: self] faultKeys: [aDict allKeys] inObjectsWithIDs: objectIDs];
#endif
                    
					//For undo
                    //Undo manager does things in reverse order.
					[[mUndoManager prepareWithInvocationTarget: self] undoUpdateObjects: objectIDs
																				 oldIDs: oldIDs
																			 attributes: [aDict allKeys]
																	   createdSavepoint: createdSavepoint
																			updatedPkey: updatedPkey
																				oldPkey: oldPkey
																		redoInvocations: [recorder recordedInvocations]];                    

                    //Set the modification type. No need for undo since insert and delete override this anyway.
                    BXEnumerate (currentID, e, [objectIDs objectEnumerator])
                    {
                        enum BXModificationType modificationType = ObjectToModType ([mModifiedObjectIDs objectForKey: currentID]);
                        if (! (kBXDeleteModification == modificationType || kBXInsertModification == modificationType))
                            [mModifiedObjectIDs setObject: ModTypeToObject (kBXUpdateModification) forKey: currentID];
                    }
                    
					//FIXME: move this to the if block where oldIDs are set.
					if (updatedPkey)
					{
						[self unregisterObject: anObject];
						[anObject registerWithContext: self entity: nil];
					}											
                }
            }
        }
    }
	
bail:
    BXHandleError (error, localError);
    return objectIDs;
}

/**
 * \internal
 */
- (NSArray *) executeDeleteObject: (BXDatabaseObject *) anObject 
                           entity: (BXEntityDescription *) entity
                        predicate: (NSPredicate *) predicate
                            error: (NSError **) error
{
    NSError* localError = nil;
	NSArray* objectIDs = nil;
	if ([self checkErrorHandling] && [self checkDatabaseURI: &localError])
	{
		objectIDs = [mDatabaseInterface executeDeleteObjectWithID: [anObject objectID] entity: entity 
														predicate: predicate error: &localError];
        
		if (nil == localError)
		{
			//See the private updating method
			
			if (YES == [mDatabaseInterface autocommits])
			{
				if (! [entity getsChangedByTriggers])
					[self deletedObjectsFromDatabase: objectIDs];
			}
			else
			{
				BOOL createdSavepoint = [self prepareSavepointIfNeeded: &localError];
				if (nil == localError)
				{
					BXEnumerate (currentID, e, [objectIDs objectEnumerator])
                        [[self registeredObjectWithID: currentID] setDeleted: kBXObjectDeletePending];
					
					//The change notice will only be delivered at commit time, but there could be e.g. two
					//BXSetHelperTableRelationProxies for one relationship, and objects get deleted from one of them.
					[self deletedObjectsFromDatabase: objectIDs];

					//For redo
					BXInvocationRecorder* recorder = [BXInvocationRecorder recorder];
					[[recorder recordWithPersistentTarget: self] executeDeleteObject: anObject entity: entity 
																		   predicate: predicate error: NULL];
					
					//Undo manager does things in reverse order.
					if (![mUndoManager groupsByEvent])
    					[mUndoManager beginUndoGrouping];

					[[mUndoManager prepareWithInvocationTarget: self] addedObjectsToDatabase: objectIDs];
                    //Object status.
                    BXEnumerate (currentID, e, [objectIDs objectEnumerator])
					{
						enum BXObjectDeletionStatus status = [[self registeredObjectWithID: currentID] deletionStatus];
						[[mUndoManager prepareWithInvocationTarget: currentID] setStatus: status forObjectRegisteredInContext: self];
					}
                    //Do the actual rollback.
					if (createdSavepoint)
						[[mUndoManager prepareWithInvocationTarget: self] rollbackToLastSavepoint];
					[[mUndoManager prepareWithInvocationTarget: self] undoWithRedoInvocations: [recorder recordedInvocations]];
                    //Remember the modification type for ROLLBACK.
					BXEnumerate (currentID, e, [objectIDs objectEnumerator])
					{
                        [[mUndoManager prepareWithInvocationTarget: mModifiedObjectIDs] setObject: [mModifiedObjectIDs objectForKey: currentID] 
                                                                                           forKey: currentID];                        
                        [mModifiedObjectIDs setObject: ModTypeToObject (kBXDeleteModification) forKey: currentID];
					}
					if (![mUndoManager groupsByEvent])
    					[mUndoManager endUndoGrouping];
				}
			}
		}
    }
    BXHandleError (error, localError);
    return objectIDs;
}

- (BOOL) checkDatabaseURI: (NSError **) error
{
	BOOL rval = YES;
	BXAssertLog (NULL != error, @"Expected error not to be null.");
	if (nil == mDatabaseURI)
	{
		rval = NO;
		NSString* reason = BXLocalizedString (@"noConnectionURI", @"No connection URI given.", @"Error description");
		NSString* title = BXLocalizedString (@"databaseError", @"Database error", @"Title for a sheet");
		NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
			title, NSLocalizedDescriptionKey,
			title, NSLocalizedFailureReasonErrorKey, 
			reason, NSLocalizedRecoverySuggestionErrorKey, 
			self, kBXDatabaseContextKey,
			nil];
		
		if (NULL != error)
			*error = [BXError errorWithDomain: kBXErrorDomain code: kBXErrorNoDatabaseURI userInfo: userInfo];
	}
	return rval;
}

- (void) setDatabaseInterface: (id <BXInterface>) interface
{
	if (interface != mDatabaseInterface)
	{
		[mDatabaseInterface release];
		mDatabaseInterface  = [interface retain];
	}
}

- (id <BXInterface>) databaseInterface
{
	if (nil == mDatabaseInterface && mDatabaseURI)
	{
		mDatabaseInterface = [[[[self class] interfaceClassForScheme: 
            [mDatabaseURI scheme]] alloc] initWithContext: self];
		[mDatabaseInterface setAutocommits: mAutocommits];
	}
	return mDatabaseInterface;
}

- (void) lazyInit
{
	if (nil == mUndoManager)
		mUndoManager = [[NSUndoManager alloc] init];
		
	if (nil == mObjects)
	{
		mObjects = BXDictionaryCreateMutableWeakNonretainedObjects ();
	}
	
	if (nil == mModifiedObjectIDs)
        mModifiedObjectIDs = [[NSMutableDictionary alloc] init];
	
	if (nil == mUndoGroupingLevels)
		mUndoGroupingLevels = [[NSMutableIndexSet alloc] init];
	
	if (mUsesKeychain && ![[mDatabaseURI password] length])
        [self fetchPasswordFromKeychain];	    
}

+ (void) loadedAppKitFramework
{
	gHaveAppKitFramework = YES;
}

- (void) setDatabaseURIInternal: (NSURL *) uri
{
	if (uri != mDatabaseURI)
    {
        if (nil != uri && [self checkURIScheme: uri error: NULL])
		{
			[mDatabaseURI release];
			mDatabaseURI = [uri retain];
		}
    }	
}

- (void) faultKeys: (NSArray *) keys inObjectsWithIDs: (NSArray *) ids
{
    BXEnumerate (currentObject, e, [[self registeredObjectsWithIDs: ids] objectEnumerator])
    {
        if ([NSNull null] != currentObject)
        {
            if (nil == keys)
                [currentObject faultKey: nil];
            else
            {
                BXEnumerate (currentKey, e, [keys objectEnumerator])
                    [currentObject faultKey: currentKey];
            }
        }
    }
}

- (void) setConnectionSetupManager: (id <BXConnector>) anObject
{
	if (mConnectionSetupManager != anObject)
	{
		[mConnectionSetupManager release];
		mConnectionSetupManager = [anObject retain];
	}
}

- (void) BXDatabaseObjectWillDealloc: (BXDatabaseObject *) anObject
{
    [mObjects removeObjectForKey: [anObject objectID]];
}

/**
 * \internal
 * \brief Register an object to the context.
 *
 * After fetching objects from the database, a database interface should register them with a context.
 * This enables updating the database as well as automatic synchronization, if this has been implemented
 * in the database interface class.
 * \return A boolean. NO indicates that an object was already registered.
 */
- (BOOL) registerObject: (BXDatabaseObject *) anObject
{
    BOOL retval = NO;
    BXDatabaseObjectID* objectID = [anObject objectID];
    if (nil == [mObjects objectForKey: objectID])
    {
        retval = YES;
        [mObjects setObject: anObject forKey: objectID];
        if (mRetainRegisteredObjects)
            [anObject retain];
    }
    return retval;
}

- (void) unregisterObject: (BXDatabaseObject *) anObject
{
    if (mRetainRegisteredObjects) {
        [[mObjects objectForKey: [anObject objectID]] autorelease];
    }
    [mObjects removeObjectForKey: [anObject objectID]];
}

- (void) setCanConnect: (BOOL) aBool
{
	if (aBool != mCanConnect)
	{
		[self willChangeValueForKey: @"canConnect"];
		mCanConnect = aBool;
		[self didChangeValueForKey: @"canConnect"];
	}
}

- (BOOL) checkURIScheme: (NSURL *) url error: (NSError **) error
{
	//FIXME: set error instead of raising an exception.
	BOOL retval = YES;
    if (Nil == [[self class] interfaceClassForScheme: [url scheme]])
    {
		retval = NO;
        NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
								  self,   kBXDatabaseContextKey,
								  url,    kBXURIKey,
								  nil];
        @throw [NSException exceptionWithName: kBXUnsupportedDatabaseException 
                                       reason: nil
                                     userInfo: userInfo];
    }
	return retval;
}

- (BOOL) checkErrorHandling
{
	BOOL retval = YES;
	switch (mConnectionErrorHandlingState) 
	{
		case kBXConnectionErrorResolving:
			bx_query_during_reconnect ();
			//Fall through.
			
		case kBXConnectionErrorNoReconnect:
			retval = NO;
			break;
			
		case kBXConnectionErrorNone:
		default:
			break;
	}
	return retval;
}


- (void) setLastConnectionError: (NSError *) anError
{
	if (mLastConnectionError != anError)
	{
		[mLastConnectionError release];
		mLastConnectionError = [anError retain];
	}
}


- (void) setDatabaseObjectModel: (BXDatabaseObjectModel *) model
{
	if (model != mObjectModel)
	{
		[mObjectModel release];
		mObjectModel = [model retain];
	}
}

- (struct update_kvo_ctx) handleWillChangeForUpdate: (NSArray *) givenObjects newValues: (NSDictionary *) newValues
{
	NSMutableArray* changedObjects = [NSMutableArray array];
	NSMutableDictionary* relsByEntity = [NSMutableDictionary dictionary];
	NSMutableDictionary* oldTargetsByObject = [NSMutableDictionary dictionary];
	NSMutableDictionary* newTargetsByObject = [NSMutableDictionary dictionary];
	NSArray* objectIDs = (id) [[givenObjects BX_Collect] objectID];
	NSMutableDictionary* idsByEntity = ObjectsByEntity (objectIDs);
	AddObjectIDsForInheritance (idsByEntity);
	
	BXEnumerate (entity, e, [idsByEntity keyEnumerator])
	{
		NSArray* objectIDs = [idsByEntity objectForKey: entity];
		NSArray* objects = [self registeredObjectsWithIDs: objectIDs nullObjects: NO];
		id rels = [entity inverseToOneRelationships];
		NSDictionary* oldTargets = nil;
		NSDictionary* newTargets = nil;
		
		[changedObjects addObjectsFromArray: objects];
		
		BXEnumerate (currentObject, e, [objects objectEnumerator])
		{
			BXEnumerate (currentAttr, e, [newValues keyEnumerator])
			[currentObject willChangeValueForKey: [currentAttr name]];
		}
		
		if (0 < [rels count])
		{
			[relsByEntity setObject: rels forKey: entity];
			BXEnumerate (currentObject, e, [objects objectEnumerator])
			{
				oldTargets = [[rels BX_CollectDK] registeredTargetFor: currentObject fireFault: NO] ?: [NSDictionary dictionary];
				
				//FIXME: this seems really bad.
				NSDictionary* oldValues = [[[currentObject cachedValues] copy] autorelease];
				[currentObject setCachedValuesForKeysWithDictionary: newValues];
				
				newTargets = [[rels BX_CollectDK] registeredTargetFor: currentObject fireFault: NO] ?: [NSDictionary dictionary];
				[currentObject setCachedValuesForKeysWithDictionary: oldValues];
				
				[currentObject willChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
				
				[oldTargetsByObject setObject: oldTargets forKey: currentObject];
				[newTargetsByObject setObject: newTargets forKey: currentObject];
			}
		}
	}
	
	struct update_kvo_ctx retval = {relsByEntity, changedObjects, oldTargetsByObject, newTargetsByObject};
	return retval;
}


- (void) handleDidChangeForUpdate: (struct update_kvo_ctx *) ctx newValues: (NSDictionary *) newValues sendNotifications: (BOOL) shouldSend targetEntity: (BXEntityDescription *) entity
{
	NSNotificationCenter* nc = [self notificationCenter];
	NSArray* changedObjects = ctx->ukc_objects;
	NSDictionary* relsByEntity = ctx->ukc_rels_by_entity;
	NSDictionary* oldTargetsByObject = ctx->ukc_old_targets_by_object;
	NSDictionary* newTargetsByObject = ctx->ukc_new_targets_by_object;
	
	BXEnumerate (currentObject, e, [changedObjects objectEnumerator])
	{
		[currentObject setCachedValuesForKeysWithDictionary: newValues];
	}
	
	NSDictionary* objectsByEntity = nil;
	if (shouldSend)
	{
		objectsByEntity = ObjectsByEntity (changedObjects);
		BXEnumerate (currentEntity, e, [objectsByEntity keyEnumerator])
		{
			NSArray* objects = [objectsByEntity objectForKey: currentEntity];
			NSArray* objectIDs = (id) [[objects BX_Collect] objectID];
			NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
									  objectIDs, kBXObjectIDsKey,
									  objects, kBXObjectsKey,
									  self, kBXDatabaseContextKey,
									  nil];
			[nc postNotificationName: kBXUpdateEarlyNotification object: entity userInfo: userInfo];
		}
	}
	
	BXEnumerate (currentObject, e, [changedObjects objectEnumerator])
	{
		BXEnumerate (currentAttr, e, [newValues keyEnumerator])
		[currentObject didChangeValueForKey: [currentAttr name]];
	}
	
	BXEnumerate (currentObject, e, [changedObjects objectEnumerator])
	{
		NSDictionary* oldTargets = [oldTargetsByObject objectForKey: currentObject];
		NSDictionary* newTargets = [newTargetsByObject objectForKey: currentObject];
		id rels = [relsByEntity objectForKey: [currentObject entity]];
		if (0 < [rels count])
			[currentObject didChangeInverseToOneRelationships: rels from: oldTargets to: newTargets];
	}
	
	if (shouldSend)
	{
		ExpectV (objectsByEntity);
		BXEnumerate (currentEntity, e, [objectsByEntity keyEnumerator])
		{
			NSArray* objects = [objectsByEntity objectForKey: currentEntity];
			NSArray* objectIDs = (id) [[objects BX_Collect] objectID];
			NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
									  objectIDs, kBXObjectIDsKey,
									  objects, kBXObjectsKey,
									  self, kBXDatabaseContextKey,
									  nil];
			[nc postNotificationName: kBXUpdateNotification object: entity userInfo: userInfo];
		}
	}
}


- (void) handleError: (NSError *) error outError: (NSError **) outError
{
	BXHandleError (outError, error);
}
@end


//FIXME: move these elsewhere.
@implementation BXDatabaseContext (Keychain)

static SecKeychainAttribute
KeychainAttribute (SecItemAttr tag, void* value, UInt32 length)
{
    SecKeychainAttribute attribute;
    bzero (&attribute, sizeof (SecKeychainAttribute));
    attribute.tag = tag;
    attribute.data = value;
    attribute.length = length;
    return attribute;
}

static BOOL
ConditionalKeychainAttributeFromString (SecItemAttr tag, NSString* value, SecKeychainAttribute* attribute)
{
    BOOL rval = NO;
    if (nil != value)
    {
        bzero (attribute, sizeof (SecKeychainAttribute));
        const char* utfValue = [value UTF8String];
        attribute->tag = tag;
        attribute->data = (void **) utfValue;
        attribute->length = strlen (utfValue);
        rval = YES;
    }
    return rval;
}

static void
AddKeychainAttributeString (SecItemAttr tag, NSString* value, NSMutableData* buffer)
{
    SecKeychainAttribute attribute;
    if (ConditionalKeychainAttributeFromString (tag, value, &attribute))
    {
        [buffer appendBytes: &attribute length: sizeof (SecKeychainAttribute)];
    }
}

static void
AddKeychainAttribute (SecItemAttr tag, void* value, UInt32 length, NSMutableData* buffer)
{
    SecKeychainAttribute attribute = KeychainAttribute (tag, value, length);
    [buffer appendBytes: &attribute length: sizeof (SecKeychainAttribute)];
}

- (NSArray *) keychainItems
{
    OSStatus status = noErr;
    NSMutableArray* retval = nil;
    
    NSMutableData* attributeBuffer = [NSMutableData data];
    AddKeychainAttributeString (kSecAccountItemAttr, [mDatabaseURI user], attributeBuffer);
    AddKeychainAttributeString (kSecServerItemAttr,  [mDatabaseURI host], attributeBuffer);
    AddKeychainAttributeString (kSecPathItemAttr,    [mDatabaseURI path], attributeBuffer);

    SecAuthenticationType authType = kSecAuthenticationTypeDefault;
    AddKeychainAttribute (kSecAuthenticationTypeItemAttr, &authType, 
                          sizeof (SecAuthenticationType), attributeBuffer);

    //FIXME: For some reason we can't look for only non-invalid items
#if 0
    Boolean allowNegative = false;
    AddKeychainAttribute (kSecNegativeItemAttr, &allowNegative, sizeof (Boolean), attributeBuffer);
#endif
    
    NSNumber* portObject = [mDatabaseURI port];
    UInt16 port = (portObject ? [portObject unsignedShortValue] : 5432U);
    AddKeychainAttribute (kSecPortItemAttr, &port, sizeof (UInt16), attributeBuffer);
    
    //FIXME: Do we also need the creator code? Does the current application have one?
    SecKeychainAttributeList attrList = {
        .count = ([attributeBuffer length] / sizeof (SecKeychainAttribute)), 
        .attr = (void *) [attributeBuffer bytes]
    };
    SecKeychainSearchRef search = NULL;
    status = SecKeychainSearchCreateFromAttributes (NULL, //Default keychain
                                                    kSecInternetPasswordItemClass,
                                                    &attrList,
                                                    &search);
    if (noErr == status)
    {
        retval = [NSMutableArray array];
        SecKeychainItemRef item = NULL;
        while (noErr == SecKeychainSearchCopyNext (search, &item))
            [retval addObject: (id) item];
        CFRelease (search);
    }
	
	//For GC.
	[attributeBuffer self];
	
    return retval;
}

- (SecKeychainItemRef) newestKeychainItem
{
    SecKeychainItemRef rval = NULL;
    UInt32 rvalModDate = 0;
    SecItemAttr attributes [] = {kSecModDateItemAttr, kSecNegativeItemAttr};
    SecExternalFormat formats [] = {kSecFormatUnknown, kSecFormatUnknown};
    unsigned int count = BXArraySize (attributes);
	BXAssertValueReturn (count == BXArraySize (formats), NULL,
						   @"Expected arrays to have an equal number of items.");
    SecKeychainAttributeInfo info = {count, (void *) attributes, (void *) formats};
    
    BXEnumerate (currentItem, e, [[self keychainItems] objectEnumerator])
    {
        SecKeychainItemRef item = (SecKeychainItemRef) currentItem;        
        OSStatus status = noErr;
        SecKeychainAttributeList* returnedAttributes = NULL;
        status = SecKeychainItemCopyAttributesAndData (item, &info, NULL, &returnedAttributes, NULL, NULL);
        //kSecNegativeItemAttr's data seems to be NULL at least when the attribute hasn't been set.
        if (noErr == status && NULL != returnedAttributes &&
            NULL == returnedAttributes->attr [1].data)
        {
            UInt32* datePtr = returnedAttributes->attr [0].data;
            UInt32 modDate = *datePtr;
            if (modDate > rvalModDate)
                rval = item;
            SecKeychainItemFreeAttributesAndData (returnedAttributes, NULL);
        }
    }
    return rval;
}

- (BOOL) fetchPasswordFromKeychain
{
    BOOL rval = NO;
    [self setKeychainPasswordItem: [self newestKeychainItem]];
    if (NULL != mKeychainPasswordItem)
    {
        SecItemAttr attributes [] = {kSecAccountItemAttr};
        SecExternalFormat formats [] = {kSecFormatUnknown};
        unsigned int count = BXArraySize (attributes);
        BXAssertValueReturn (count == BXArraySize (formats), NO,
							 @"Expected arrays to have an equal number of items.");
        SecKeychainAttributeInfo info = {count, (void *) attributes, (void *) formats};
        
        OSStatus status = noErr;
        SecKeychainAttributeList* returnedAttributes = NULL;
        UInt32 passwordLength = 0;        
        char* passwordData = NULL;
        status = SecKeychainItemCopyAttributesAndData (mKeychainPasswordItem, &info, NULL, &returnedAttributes, 
                                                       &passwordLength, (void **) &passwordData);
        if (noErr == status && 0 < returnedAttributes->count)
        {
            SecKeychainAttribute usernameAttribute = returnedAttributes->attr [0];
            NSString* username = [[[NSString alloc] initWithBytes: usernameAttribute.data
                                                           length: usernameAttribute.length
                                                         encoding: NSUTF8StringEncoding] autorelease];
            NSString* password = [[[NSString alloc] initWithBytes: passwordData
                                                           length: passwordLength
                                                         encoding: NSUTF8StringEncoding] autorelease];
            
            [self setDatabaseURIInternal: [mDatabaseURI BXURIForHost: nil
															database: nil 
															username: username
															password: password]];
            SecKeychainItemFreeAttributesAndData (returnedAttributes, passwordData);
            rval = YES;
        }
    }    
    return rval;
}

- (void) setKeychainPasswordItem: (SecKeychainItemRef) anItem
{
    if (anItem != mKeychainPasswordItem)
    {
        if (NULL != mKeychainPasswordItem)
            CFRelease (mKeychainPasswordItem);
        
		mKeychainPasswordItem = anItem;
		
		if (NULL != mKeychainPasswordItem)
            CFRetain (mKeychainPasswordItem);
    }
}

@end


@implementation BXDatabaseContext (Callbacks)
- (void) connectionSetupManagerFinishedAttempt
{
	if (NO == [self isConnected])
		[self setCanConnect: YES];
	[self setConnectionSetupManager: nil];
	[self setKeychainPasswordItem: NULL];
}
@end