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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>
#include <sal/log.hxx>

#include <map>
#include <utility>

#include "RowSet.hxx"
#include <stringconstants.hxx>
#include <sdbcoretools.hxx>
#include <SingleSelectQueryComposer.hxx>
#include "CRowSetColumn.hxx"
#include "CRowSetDataColumn.hxx"
#include "RowSetCache.hxx"
#include <strings.hrc>
#include <core_resource.hxx>
#include <tablecontainer.hxx>

#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/sdb/CommandType.hpp>
#include <com/sun/star/sdb/DatabaseContext.hpp>
#include <com/sun/star/sdb/ErrorCondition.hpp>
#include <com/sun/star/sdb/RowChangeAction.hpp>
#include <com/sun/star/sdb/RowSetVetoException.hpp>
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#include <com/sun/star/sdb/XParametersSupplier.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/sdbc/FetchDirection.hpp>
#include <com/sun/star/sdbc/ResultSetConcurrency.hpp>
#include <com/sun/star/sdbc/ResultSetType.hpp>
#include <com/sun/star/sdbc/XDataSource.hpp>
#include <com/sun/star/sdbcx/Privilege.hpp>
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>

#include <comphelper/extract.hxx>
#include <comphelper/seqstream.hxx>
#include <comphelper/sequence.hxx>
#include <comphelper/servicehelper.hxx>
#include <comphelper/types.hxx>
#include <comphelper/uno3.hxx>
#include <connectivity/BlobHelper.hxx>
#include <connectivity/dbconversion.hxx>
#include <connectivity/dbexception.hxx>
#include <connectivity/dbtools.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <o3tl/safeint.hxx>
#include <unotools/syslocale.hxx>
#include <tools/diagnose_ex.h>

using namespace utl;
using namespace dbaccess;
using namespace connectivity;
using namespace comphelper;
using namespace dbtools;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::util;
using namespace ::cppu;
using namespace ::osl;

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
com_sun_star_comp_dba_ORowSet_get_implementation(css::uno::XComponentContext* context,<--- The function 'com_sun_star_comp_dba_ORowSet_get_implementation' is never used.
                                                 css::uno::Sequence<css::uno::Any> const &)
{
    return cppu::acquire(new ORowSet(context));
}

#define NOTIFY_LISTENERS_CHECK(_rListeners,T,method)                             \
    std::vector< Reference< XInterface > > aListenerSeq = _rListeners.getElements(); \
                                                                                  \
    _rGuard.clear();                                                              \
    bool bCheck = std::all_of(aListenerSeq.rbegin(), aListenerSeq.rend(),         \
        [&aEvt](Reference<XInterface>& rxItem) {                                  \
            try                                                                   \
            {                                                                     \
                return static_cast<bool>(static_cast<T*>(rxItem.get())->method(aEvt)); \
            }                                                                     \
            catch( RuntimeException& )                                            \
            {                                                                     \
                return true;                                                      \
            }                                                                     \
        });                                                                       \
    _rGuard.reset();


namespace dbaccess
{
ORowSet::ORowSet( const Reference< css::uno::XComponentContext >& _rxContext )
    :ORowSet_BASE1(m_aMutex)
    ,ORowSetBase( _rxContext, ORowSet_BASE1::rBHelper, &m_aMutex )
    ,m_aPrematureParamValues(new ORowSetValueVector)
    ,m_aParameterValueForCache(new ORowSetValueVector)
    ,m_aRowsetListeners(*m_pMutex)
    ,m_aApproveListeners(*m_pMutex)
    ,m_aRowsChangeListener(*m_pMutex)
    ,m_nFetchDirection(FetchDirection::FORWARD)
    ,m_nFetchSize(50)
    ,m_nMaxFieldSize(0)
    ,m_nMaxRows(0)
    ,m_nQueryTimeOut(0)
    ,m_nCommandType(CommandType::COMMAND)
    ,m_nTransactionIsolation(0)
    ,m_nPrivileges(0)
    ,m_nLastKnownRowCount(0)
    ,m_nInAppend(0)
    ,m_bInsertingRow(false)
    ,m_bLastKnownRowCountFinal(false)
    ,m_bUseEscapeProcessing(true)
    ,m_bApplyFilter(false)
    ,m_bCommandFacetsDirty( true )
    ,m_bParametersDirty( true )
    ,m_bModified(false)
    ,m_bRebuildConnOnExecute(false)
    ,m_bIsBookmarkable(true)
    ,m_bNew(false)
    ,m_bCanUpdateInsertedRows(true)
    ,m_bOwnConnection(false)
    ,m_bPropChangeNotifyEnabled(true)
{
    m_nResultSetType = ResultSetType::SCROLL_SENSITIVE;
    m_nResultSetConcurrency = ResultSetConcurrency::UPDATABLE;
    m_pMySelf = this;
    m_aActiveConnection <<= m_xActiveConnection;

    sal_Int32 const nRBT = PropertyAttribute::READONLY   | PropertyAttribute::BOUND      | PropertyAttribute::TRANSIENT;
    sal_Int32 const nRT  = PropertyAttribute::READONLY   | PropertyAttribute::TRANSIENT;
    sal_Int32 const nBT  = PropertyAttribute::BOUND      | PropertyAttribute::TRANSIENT;

    m_aPrematureParamValues->resize( 0 );

    // sdb.RowSet Properties
    registerMayBeVoidProperty(PROPERTY_ACTIVE_CONNECTION,PROPERTY_ID_ACTIVE_CONNECTION, PropertyAttribute::MAYBEVOID|PropertyAttribute::TRANSIENT|PropertyAttribute::BOUND, &m_aActiveConnection,   cppu::UnoType<XConnection>::get());
    registerProperty(PROPERTY_DATASOURCENAME,       PROPERTY_ID_DATASOURCENAME,         PropertyAttribute::BOUND,       &m_aDataSourceName,     ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_COMMAND,              PROPERTY_ID_COMMAND,                PropertyAttribute::BOUND,       &m_aCommand,            ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_COMMAND_TYPE,         PROPERTY_ID_COMMAND_TYPE,           PropertyAttribute::BOUND,       &m_nCommandType,        ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_ACTIVECOMMAND,        PROPERTY_ID_ACTIVECOMMAND,          nRBT,                           &m_aActiveCommand,      ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_IGNORERESULT,         PROPERTY_ID_IGNORERESULT,           PropertyAttribute::BOUND,       &m_bIgnoreResult,       cppu::UnoType<bool>::get());
    registerProperty(PROPERTY_FILTER,               PROPERTY_ID_FILTER,                 PropertyAttribute::BOUND,       &m_aFilter,             ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_HAVING_CLAUSE,        PROPERTY_ID_HAVING_CLAUSE,          PropertyAttribute::BOUND,       &m_aHavingClause,       ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_GROUP_BY,             PROPERTY_ID_GROUP_BY,               PropertyAttribute::BOUND,       &m_aGroupBy,            ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_APPLYFILTER,          PROPERTY_ID_APPLYFILTER,            PropertyAttribute::BOUND,       &m_bApplyFilter,        cppu::UnoType<bool>::get());
    registerProperty(PROPERTY_ORDER,                PROPERTY_ID_ORDER,                  PropertyAttribute::BOUND,       &m_aOrder,              ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_PRIVILEGES,           PROPERTY_ID_PRIVILEGES,             nRT,                            &m_nPrivileges,         ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_ISMODIFIED,           PROPERTY_ID_ISMODIFIED,             nBT,                            &m_bModified,           cppu::UnoType<bool>::get());
    registerProperty(PROPERTY_ISNEW,                PROPERTY_ID_ISNEW,                  nRBT,                           &m_bNew,                cppu::UnoType<bool>::get());
    registerProperty(PROPERTY_SINGLESELECTQUERYCOMPOSER,PROPERTY_ID_SINGLESELECTQUERYCOMPOSER,  nRT,                    &m_xComposer,   cppu::UnoType<XSingleSelectQueryComposer>::get());

    // sdbcx.ResultSet Properties
    registerProperty(PROPERTY_ISBOOKMARKABLE,       PROPERTY_ID_ISBOOKMARKABLE,         nRT,                            &m_bIsBookmarkable,      cppu::UnoType<bool>::get());
    registerProperty(PROPERTY_CANUPDATEINSERTEDROWS,PROPERTY_ID_CANUPDATEINSERTEDROWS,  nRT,                            &m_bCanUpdateInsertedRows,      cppu::UnoType<bool>::get());
    // sdbc.ResultSet Properties
    registerProperty(PROPERTY_RESULTSETCONCURRENCY, PROPERTY_ID_RESULTSETCONCURRENCY,   PropertyAttribute::TRANSIENT,   &m_nResultSetConcurrency,::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_RESULTSETTYPE,        PROPERTY_ID_RESULTSETTYPE,          PropertyAttribute::TRANSIENT,   &m_nResultSetType,      ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_FETCHDIRECTION,       PROPERTY_ID_FETCHDIRECTION,         PropertyAttribute::TRANSIENT,   &m_nFetchDirection,     ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_FETCHSIZE,            PROPERTY_ID_FETCHSIZE,              PropertyAttribute::TRANSIENT,   &m_nFetchSize,          ::cppu::UnoType<sal_Int32>::get());

    // sdbc.RowSet Properties
    registerProperty(PROPERTY_URL,                  PROPERTY_ID_URL,                    0,                              &m_aURL,                ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_TRANSACTIONISOLATION, PROPERTY_ID_TRANSACTIONISOLATION,   PropertyAttribute::TRANSIENT,   &m_nTransactionIsolation,::cppu::UnoType<sal_Int32>::get());
    registerMayBeVoidProperty(PROPERTY_TYPEMAP,     PROPERTY_ID_TYPEMAP,                PropertyAttribute::MAYBEVOID|PropertyAttribute::TRANSIENT,  &m_aTypeMap,            cppu::UnoType<XNameAccess>::get());
    registerProperty(PROPERTY_ESCAPE_PROCESSING,PROPERTY_ID_ESCAPE_PROCESSING,  PropertyAttribute::BOUND,       &m_bUseEscapeProcessing,cppu::UnoType<bool>::get()  );
    registerProperty(PROPERTY_QUERYTIMEOUT,         PROPERTY_ID_QUERYTIMEOUT,           PropertyAttribute::TRANSIENT,   &m_nQueryTimeOut,       ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_MAXFIELDSIZE,         PROPERTY_ID_MAXFIELDSIZE,           PropertyAttribute::TRANSIENT,   &m_nMaxFieldSize,       ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_MAXROWS,              PROPERTY_ID_MAXROWS,                0,                              &m_nMaxRows,            ::cppu::UnoType<sal_Int32>::get() );
    registerProperty(PROPERTY_USER,                 PROPERTY_ID_USER,                   PropertyAttribute::TRANSIENT,   &m_aUser,               ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_PASSWORD,             PROPERTY_ID_PASSWORD,               PropertyAttribute::TRANSIENT,   &m_aPassword,           ::cppu::UnoType<OUString>::get());

    registerProperty(PROPERTY_UPDATE_CATALOGNAME,   PROPERTY_ID_UPDATE_CATALOGNAME,     PropertyAttribute::BOUND,       &m_aUpdateCatalogName,  ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_UPDATE_SCHEMANAME,    PROPERTY_ID_UPDATE_SCHEMANAME,      PropertyAttribute::BOUND,       &m_aUpdateSchemaName,   ::cppu::UnoType<OUString>::get());
    registerProperty(PROPERTY_UPDATE_TABLENAME,     PROPERTY_ID_UPDATE_TABLENAME,       PropertyAttribute::BOUND,       &m_aUpdateTableName,    ::cppu::UnoType<OUString>::get());

    // ???
    registerProperty(PROPERTY_CHANGE_NOTIFICATION_ENABLED, PROPERTY_ID_PROPCHANGE_NOTIFY, PropertyAttribute::BOUND,     &m_bPropChangeNotifyEnabled, cppu::UnoType<bool>::get());
}

ORowSet::~ORowSet()
{
    if ( !m_rBHelper.bDisposed && !m_rBHelper.bInDispose )
    {
        SAL_WARN("dbaccess", "Please check who doesn't dispose this component!");
        osl_atomic_increment( &m_refCount );
        dispose();
    }
}

void ORowSet::getPropertyDefaultByHandle( sal_Int32 _nHandle, Any& _rDefault ) const
{
    switch( _nHandle )
    {
        case PROPERTY_ID_COMMAND_TYPE:
            _rDefault <<= CommandType::COMMAND;
            break;
        case PROPERTY_ID_IGNORERESULT:
            _rDefault <<= false;
            break;
        case PROPERTY_ID_APPLYFILTER:
            _rDefault <<= false;
            break;
        case PROPERTY_ID_ISMODIFIED:
            _rDefault <<= false;
            break;
        case PROPERTY_ID_ISBOOKMARKABLE:
            _rDefault <<= true;
            break;
        case PROPERTY_ID_CANUPDATEINSERTEDROWS:
            _rDefault <<= true;
            break;
        case PROPERTY_ID_RESULTSETTYPE:
            _rDefault <<= ResultSetType::SCROLL_INSENSITIVE;
            break;
        case PROPERTY_ID_RESULTSETCONCURRENCY:
            _rDefault <<= ResultSetConcurrency::UPDATABLE;
            break;
        case PROPERTY_ID_FETCHDIRECTION:
            _rDefault <<= FetchDirection::FORWARD;
            break;
        case PROPERTY_ID_FETCHSIZE:
            _rDefault <<= static_cast<sal_Int32>(1);
            break;
        case PROPERTY_ID_ESCAPE_PROCESSING:
            _rDefault <<= true;
            break;
        case PROPERTY_ID_MAXROWS:
            _rDefault <<= sal_Int32( 0 );
            break;
        case PROPERTY_ID_FILTER:
        case PROPERTY_ID_HAVING_CLAUSE:
        case PROPERTY_ID_GROUP_BY:
        case PROPERTY_ID_ORDER:
        case PROPERTY_ID_UPDATE_CATALOGNAME:
        case PROPERTY_ID_UPDATE_SCHEMANAME:
        case PROPERTY_ID_UPDATE_TABLENAME:
            _rDefault <<= OUString();
            break;
    }
}

void SAL_CALL ORowSet::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)
{
    switch(nHandle)
    {
        case PROPERTY_ID_ISMODIFIED:
            m_bModified = cppu::any2bool(rValue);
            break;
        case PROPERTY_ID_FETCHDIRECTION:
            if( m_nResultSetType == ResultSetType::FORWARD_ONLY)
                throw Exception("resultsettype is FORWARD_ONLY", nullptr);
            [[fallthrough]];
        default:
            OPropertyStateContainer::setFastPropertyValue_NoBroadcast(nHandle,rValue);
    }

    if  (   ( nHandle == PROPERTY_ID_ACTIVE_CONNECTION )
        ||  ( nHandle == PROPERTY_ID_DATASOURCENAME )
        ||  ( nHandle == PROPERTY_ID_COMMAND )
        ||  ( nHandle == PROPERTY_ID_COMMAND_TYPE )
        ||  ( nHandle == PROPERTY_ID_IGNORERESULT )
        ||  ( nHandle == PROPERTY_ID_FILTER )
        ||  ( nHandle == PROPERTY_ID_HAVING_CLAUSE )
        ||  ( nHandle == PROPERTY_ID_GROUP_BY )
        ||  ( nHandle == PROPERTY_ID_APPLYFILTER )
        ||  ( nHandle == PROPERTY_ID_ORDER )
        ||  ( nHandle == PROPERTY_ID_URL )
        ||  ( nHandle == PROPERTY_ID_USER )
        )
    {
        m_bCommandFacetsDirty = true;
    }


    switch(nHandle)
    {
        case PROPERTY_ID_ACTIVE_CONNECTION:
            // the new connection
            {
                assert(m_aActiveConnection == rValue);
                Reference< XConnection > xNewConnection(m_aActiveConnection,UNO_QUERY);
                setActiveConnection(xNewConnection, false);
            }

            m_bOwnConnection        = false;
            m_bRebuildConnOnExecute = false;
            break;

        case PROPERTY_ID_DATASOURCENAME:
            if(!m_xStatement.is())
            {
                Reference< XConnection >  xNewConn;
                Any aNewConn;
                aNewConn <<= xNewConn;
                setFastPropertyValue(PROPERTY_ID_ACTIVE_CONNECTION, aNewConn);
            }
            else
                m_bRebuildConnOnExecute = true;
            break;
        case PROPERTY_ID_FETCHSIZE:
            if(m_pCache)
            {
                m_pCache->setFetchSize(m_nFetchSize);
                fireRowcount();
            }
            break;
        case PROPERTY_ID_URL:
            // is the connection-to-be-built determined by the url (which is the case if m_aDataSourceName is empty) ?
            if (m_aDataSourceName.isEmpty())
            {
                // are we active at the moment ?
                if (m_xStatement.is())
                    // yes -> the next execute needs to rebuild our connection because of this new property
                    m_bRebuildConnOnExecute = true;
                else
                {   // no -> drop our active connection (if we have one) as it doesn't correspond to this new property value anymore
                    Reference< XConnection >  xNewConn;
                    Any aNewConn;
                    aNewConn <<= xNewConn;
                    setFastPropertyValue(PROPERTY_ID_ACTIVE_CONNECTION, aNewConn);
                }
            }
            m_bOwnConnection = true;
            break;
        case PROPERTY_ID_TYPEMAP:
            m_xTypeMap.set(m_aTypeMap, css::uno::UNO_QUERY);
            break;
        case PROPERTY_ID_PROPCHANGE_NOTIFY:
            m_bPropChangeNotifyEnabled = ::cppu::any2bool(rValue);
            break;
        default:
            break;
    }
}

void SAL_CALL ORowSet::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const
{
    if(m_pCache)
    {
        switch(nHandle)
        {
        case PROPERTY_ID_ISMODIFIED:
            rValue <<= m_bModified;
            break;
        case PROPERTY_ID_ISNEW:
            rValue <<= m_bNew;
            break;
        case PROPERTY_ID_PRIVILEGES:
            rValue <<= m_pCache->m_nPrivileges;
            break;
        case PROPERTY_ID_ACTIVE_CONNECTION:
            rValue <<= m_xActiveConnection;
            break;
        case PROPERTY_ID_TYPEMAP:
            rValue <<= m_xTypeMap;
            break;
        default:
            ORowSetBase::getFastPropertyValue(rValue,nHandle);
        }
    }
    else
    {
        switch(nHandle)
        {
            case PROPERTY_ID_ACTIVE_CONNECTION:
                rValue <<= m_xActiveConnection;
                break;
            case PROPERTY_ID_TYPEMAP:
                rValue <<= m_xTypeMap;
                break;
            case PROPERTY_ID_PROPCHANGE_NOTIFY:
                rValue <<= m_bPropChangeNotifyEnabled;
                break;
            default:
                ORowSetBase::getFastPropertyValue(rValue,nHandle);
        }
    }
}

// css::XTypeProvider
Sequence< Type > SAL_CALL ORowSet::getTypes()
{
    OTypeCollection aTypes(cppu::UnoType<XPropertySet>::get(),
                            cppu::UnoType<XFastPropertySet>::get(),
                            cppu::UnoType<XMultiPropertySet>::get(),
                           ::comphelper::concatSequences(ORowSet_BASE1::getTypes(),ORowSetBase::getTypes()));
    return aTypes.getTypes();
}

Sequence< sal_Int8 > SAL_CALL ORowSet::getImplementationId()
{
    return css::uno::Sequence<sal_Int8>();
}

// css::XInterface
Any SAL_CALL ORowSet::queryInterface( const Type & rType )
{
    return ORowSet_BASE1::queryInterface( rType);
}

void SAL_CALL ORowSet::acquire() throw()
{
    ORowSet_BASE1::acquire();
}

void SAL_CALL ORowSet::release() throw()
{
    ORowSet_BASE1::release();
}

// css::XUnoTunnel
sal_Int64 SAL_CALL ORowSet::getSomething( const Sequence< sal_Int8 >& rId )
{
    if (isUnoTunnelId<ORowSet>(rId))
        return reinterpret_cast<sal_Int64>(this);

    return 0;
}

Sequence< sal_Int8 > ORowSet::getUnoTunnelId()
{
    static ::cppu::OImplementationId s_Id;

    return s_Id.getImplementationId();
}

// css::XAggregation
Any SAL_CALL ORowSet::queryAggregation( const Type& rType )
{
    Any aRet(ORowSetBase::queryInterface(rType));
    if (!aRet.hasValue())
        aRet = ORowSet_BASE1::queryAggregation(rType);
    return aRet;
}

// css::XServiceInfo
OUString SAL_CALL ORowSet::getImplementationName()
{
    return "com.sun.star.comp.dba.ORowSet";
}

sal_Bool SAL_CALL ORowSet::supportsService( const OUString& _rServiceName )
{
    return cppu::supportsService(this, _rServiceName);
}

Sequence< OUString > SAL_CALL ORowSet::getSupportedServiceNames()
{
    return { SERVICE_SDBC_RESULTSET, SERVICE_SDBC_ROWSET, SERVICE_SDBCX_RESULTSET,
             SERVICE_SDB_RESULTSET, SERVICE_SDB_ROWSET };
}

// OComponentHelper
void SAL_CALL ORowSet::disposing()
{
    OPropertyStateContainer::disposing();

    MutexGuard aGuard(m_aMutex);
    EventObject aDisposeEvent;
    aDisposeEvent.Source = static_cast< XComponent* >(this);
    m_aRowsetListeners.disposeAndClear( aDisposeEvent );
    m_aApproveListeners.disposeAndClear( aDisposeEvent );
    m_aRowsChangeListener.disposeAndClear( aDisposeEvent );

    freeResources( true );

    // remove myself as dispose listener
    Reference< XComponent >  xComponent(m_xActiveConnection, UNO_QUERY);
    if (xComponent.is())
    {
        Reference<XEventListener> xEvt;
        query_aggregation(this,xEvt);
        xComponent->removeEventListener(xEvt);
    }

    m_aActiveConnection = Any(); // the any contains a reference too
    if(m_bOwnConnection)
        ::comphelper::disposeComponent(m_xActiveConnection);
    m_xActiveConnection = nullptr;


    ORowSetBase::disposing();
}

void ORowSet::freeResources( bool _bComplete )
{
    MutexGuard aGuard(m_aMutex);

    // free all clones
    for (auto const& clone : m_aClones)
    {
        Reference< XComponent > xComp(clone.get(), UNO_QUERY);
        if (xComp.is())
            xComp->dispose();
    }
    m_aClones.clear();

    doCancelModification();

    m_aBookmark     = Any();
    m_bBeforeFirst  = true;
    m_bAfterLast    = false;
    m_bNew          = false;
    m_bModified     = false;
    m_bIsInsertRow  = false;
    m_bLastKnownRowCountFinal = false;
    m_nLastKnownRowCount      = 0;

    if ( !_bComplete )
        return;

    // the columns must be disposed before the querycomposer is disposed because
    // their owner can be the composer
    TDataColumns().swap(m_aDataColumns);// clear and resize capacity
    std::vector<bool>().swap(m_aReadOnlyDataColumns);

    m_xColumns      = nullptr;
    if ( m_pColumns )
        m_pColumns->disposing();
    // dispose the composer to avoid that everybody knows that the querycomposer is eol
    try { ::comphelper::disposeComponent( m_xComposer ); }
    catch(Exception&)
    {
        DBG_UNHANDLED_EXCEPTION("dbaccess");
        m_xComposer = nullptr;
    }

    // let our warnings container forget the reference to the (possibly disposed) old result set
    m_aWarnings.setExternalWarnings( nullptr );

    m_pCache.reset();

    impl_resetTables_nothrow();

    m_xStatement    = nullptr;
    m_xTypeMap      = nullptr;

    if ( m_aOldRow.is() )
        m_aOldRow->clearRow();

    impl_disposeParametersContainer_nothrow();

    m_bCommandFacetsDirty = true;
}

void ORowSet::setActiveConnection( Reference< XConnection > const & _rxNewConn, bool _bFireEvent )
{
    if (_rxNewConn.get() == m_xActiveConnection.get())
        // nothing to do
        return;

    // remove the event listener for the old connection
    Reference< XComponent >  xComponent(m_xActiveConnection, UNO_QUERY);
    if (xComponent.is())
    {
        Reference<XEventListener> xListener;
        query_aggregation(this, xListener);
        xComponent->removeEventListener(xListener);
    }

    // if we owned the connection, remember it for later disposing
    if(m_bOwnConnection)
        m_xOldConnection = m_xActiveConnection;

    // for firing the PropertyChangeEvent
    sal_Int32 nHandle = PROPERTY_ID_ACTIVE_CONNECTION;
    Any aOldConnection; aOldConnection <<= m_xActiveConnection;
    Any aNewConnection; aNewConnection <<= _rxNewConn;

    // set the new connection
    m_xActiveConnection = _rxNewConn;
    if (m_xActiveConnection.is())
        m_aActiveConnection <<= m_xActiveConnection;
    else
        m_aActiveConnection.clear();

    // fire the event
    if (_bFireEvent)
        fire(&nHandle, &aNewConnection, &aOldConnection, 1, false);

    // register as event listener for the new connection
    xComponent.set(m_xActiveConnection,UNO_QUERY);
    if (xComponent.is())
    {
        Reference<XEventListener> xListener;
        query_aggregation(this, xListener);
        xComponent->addEventListener(xListener);
    }
}

// css::XEventListener
void SAL_CALL ORowSet::disposing( const css::lang::EventObject& Source )
{
    // close rowset because the connection is going to be deleted (someone told me :-)
    Reference<XConnection> xCon(Source.Source,UNO_QUERY);
    if(m_xActiveConnection == xCon)
    {
        close();
        {
            MutexGuard aGuard( m_aMutex );
            Reference< XConnection > xXConnection;
            setActiveConnection( xXConnection );
        }
    }
}

// XCloseable
void SAL_CALL ORowSet::close(  )
{
    {
        MutexGuard aGuard( m_aMutex );
        ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    }
    // additionals things to set
    freeResources( true );
}

// comphelper::OPropertyArrayUsageHelper
::cppu::IPropertyArrayHelper* ORowSet::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}

// cppu::OPropertySetHelper
::cppu::IPropertyArrayHelper& SAL_CALL ORowSet::getInfoHelper()
{
    return *::comphelper::OPropertyArrayUsageHelper<ORowSet>::getArrayHelper();
}

void ORowSet::updateValue(sal_Int32 columnIndex,const ORowSetValue& x)
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( *m_pMutex );
    checkUpdateConditions(columnIndex);
    checkUpdateIterator();

    ORowSetValueVector::Vector& rRow = **m_aCurrentRow;
    ORowSetNotifier aNotify(this,rRow);
    m_pCache->updateValue(columnIndex,x,rRow,aNotify.getChangedColumns());
    m_bModified = m_bModified || !aNotify.getChangedColumns().empty();
    aNotify.firePropertyChange();
}

// XRowUpdate
void SAL_CALL ORowSet::updateNull( sal_Int32 columnIndex )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( *m_pMutex );
    checkUpdateConditions(columnIndex);
    checkUpdateIterator();

    ORowSetValueVector::Vector& rRow = **m_aCurrentRow;
    ORowSetNotifier aNotify(this,rRow);
    m_pCache->updateNull(columnIndex,rRow,aNotify.getChangedColumns());
    m_bModified = m_bModified || !aNotify.getChangedColumns().empty();
    aNotify.firePropertyChange();
}

void SAL_CALL ORowSet::updateBoolean( sal_Int32 columnIndex, sal_Bool x )
{
    updateValue(columnIndex, static_cast<bool>(x));
}

void SAL_CALL ORowSet::updateByte( sal_Int32 columnIndex, sal_Int8 x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateShort( sal_Int32 columnIndex, sal_Int16 x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateInt( sal_Int32 columnIndex, sal_Int32 x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateLong( sal_Int32 columnIndex, sal_Int64 x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateFloat( sal_Int32 columnIndex, float x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateDouble( sal_Int32 columnIndex, double x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateString( sal_Int32 columnIndex, const OUString& x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateBytes( sal_Int32 columnIndex, const Sequence< sal_Int8 >& x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateDate( sal_Int32 columnIndex, const css::util::Date& x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateTime( sal_Int32 columnIndex, const css::util::Time& x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateTimestamp( sal_Int32 columnIndex, const css::util::DateTime& x )
{
    updateValue(columnIndex,x);
}

void SAL_CALL ORowSet::updateBinaryStream( sal_Int32 columnIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( *m_pMutex );
    checkUpdateConditions(columnIndex);
    checkUpdateIterator();

    {
        Sequence<sal_Int8> aSeq;
        if(x.is())
            x->readBytes(aSeq,length);
        updateValue(columnIndex,aSeq);
    }
}

void SAL_CALL ORowSet::updateCharacterStream( sal_Int32 columnIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( *m_pMutex );
    checkUpdateConditions(columnIndex);
    checkUpdateIterator();
    ORowSetValueVector::Vector& rRow = **m_aCurrentRow;
    ORowSetNotifier aNotify(this,rRow);
    m_pCache->updateCharacterStream(columnIndex,x,length,rRow,aNotify.getChangedColumns());
    m_bModified = m_bModified || !aNotify.getChangedColumns().empty();
    aNotify.firePropertyChange();
}

void SAL_CALL ORowSet::updateObject( sal_Int32 columnIndex, const Any& x )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( *m_pMutex );
    checkUpdateConditions(columnIndex);
    checkUpdateIterator();

    Any aNewValue = x;

    if ( m_pColumns )
    {
        Reference<XPropertySet> xColumn(m_pColumns->getByIndex(columnIndex-1),UNO_QUERY);
        sal_Int32 nColType = 0;
        xColumn->getPropertyValue(PROPERTY_TYPE) >>= nColType;
        switch( nColType )
        {
            case DataType::DATE:
            case DataType::TIME:
            case DataType::TIMESTAMP:
            {
                double nValue = 0;
                if ( x >>= nValue )
                {
                    if ( DataType::TIMESTAMP == nColType )
                        aNewValue <<= dbtools::DBTypeConversion::toDateTime( nValue );
                    else if ( DataType::DATE == nColType )
                        aNewValue <<= dbtools::DBTypeConversion::toDate( nValue );
                    else
                        aNewValue <<= dbtools::DBTypeConversion::toTime( nValue );
                }
                break;
            }
        }
    }

    if (!::dbtools::implUpdateObject(this, columnIndex, aNewValue))
    {   // there is no other updateXXX call which can handle the value in x
        ORowSetValueVector::Vector& rRow = **m_aCurrentRow;
        ORowSetNotifier aNotify(this,rRow);
        m_pCache->updateObject(columnIndex,aNewValue,rRow,aNotify.getChangedColumns());
        m_bModified = m_bModified || !aNotify.getChangedColumns().empty();
        aNotify.firePropertyChange();
    }
}

void SAL_CALL ORowSet::updateNumericObject( sal_Int32 columnIndex, const Any& x, sal_Int32 /*scale*/ )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    ::osl::MutexGuard aGuard( *m_pMutex );
    checkUpdateConditions(columnIndex);
    checkUpdateIterator();
    ORowSetValueVector::Vector& rRow = **m_aCurrentRow;
    ORowSetNotifier aNotify(this,rRow);
    m_pCache->updateNumericObject(columnIndex,x,rRow,aNotify.getChangedColumns());
    m_bModified = m_bModified || !aNotify.getChangedColumns().empty();
    aNotify.firePropertyChange();
}

namespace
{
    class ProtectFlag
    {
        bool& m_rInsertingRow;
    public:
        explicit ProtectFlag(bool& rInsertingRow)
            : m_rInsertingRow(rInsertingRow)
        {
            if (m_rInsertingRow)
            {
                throw std::runtime_error("recursion in insertRow");
            }
            m_rInsertingRow = true;
        }
        ~ProtectFlag()
        {
            m_rInsertingRow = false;
        }
    };
}

// XResultSetUpdate
void SAL_CALL ORowSet::insertRow()
{
    ProtectFlag aFlagControl(m_bInsertingRow);

    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    // insertRow is not allowed when
    // standing not on the insert row nor
    // when the row isn't modified
    // or the concurrency is read only
    ::osl::ResettableMutexGuard aGuard( *m_pMutex );

    if(!m_pCache || !m_bNew || !m_bModified || m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY)
        throwFunctionSequenceException(*this);

    // remember old value for fire
    bool bOld = m_bNew;

    ORowSetRow aOldValues;
    if ( !m_aCurrentRow.isNull() )
        aOldValues = new ORowSetValueVector( *(*m_aCurrentRow));
    Sequence<Any> aChangedBookmarks;
    RowsChangeEvent aEvt(*this,RowChangeAction::INSERT,1,aChangedBookmarks);
    notifyAllListenersRowBeforeChange(aGuard,aEvt);

    std::vector< Any > aBookmarks;
    bool bInserted = m_pCache->insertRow(aBookmarks);

    // make sure that our row is set to the new inserted row before clearing the insert flags in the cache
    m_pCache->resetInsertRow(bInserted);

    // notification order
    // - column values
    setCurrentRow( false, true, aOldValues, aGuard ); // we don't move here

    // read-only flag restored
    impl_restoreDataColumnsWriteable_throw();

    // - rowChanged
    notifyAllListenersRowChanged(aGuard,aEvt);

    if ( !aBookmarks.empty() )
    {
        RowsChangeEvent aUpEvt(*this,RowChangeAction::UPDATE,aBookmarks.size(),comphelper::containerToSequence(aBookmarks));
        notifyAllListenersRowChanged(aGuard,aUpEvt);
    }

    // - IsModified
    if(!m_bModified)
        fireProperty(PROPERTY_ID_ISMODIFIED,false,true);
    OSL_ENSURE( !m_bModified, "ORowSet::insertRow: just updated, but _still_ modified?" );

    // - IsNew
    if(m_bNew != bOld)
        fireProperty(PROPERTY_ID_ISNEW,m_bNew,bOld);

    // - RowCount/IsRowCountFinal
    fireRowcount();
}

void SAL_CALL ORowSet::updateRow(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
    // not allowed when standing on insert row
    ::osl::ResettableMutexGuard aGuard( *m_pMutex );
    if ( !m_pCache || m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY || m_bNew || ((m_pCache->m_nPrivileges & Privilege::UPDATE ) != Privilege::UPDATE) )
        throwFunctionSequenceException(*this);


    if(!m_bModified)
        return;

    ORowSetRow aOldValues;
    if ( !m_aCurrentRow.isNull() )
        aOldValues = new ORowSetValueVector( *(*m_aCurrentRow) );

    Sequence<Any> aChangedBookmarks;
    RowsChangeEvent aEvt(*this,RowChangeAction::UPDATE,1,aChangedBookmarks);
    notifyAllListenersRowBeforeChange(aGuard,aEvt);

    std::vector< Any > aBookmarks;
    m_pCache->updateRow(m_aCurrentRow.operator ->(),aBookmarks);
    if ( !aBookmarks.empty() )
        aEvt.Bookmarks = comphelper::containerToSequence(aBookmarks);
    aEvt.Rows += aBookmarks.size();
    m_aBookmark     = m_pCache->getBookmark();
    m_aCurrentRow   = m_pCache->m_aMatrixIter;
    m_bIsInsertRow  = false;
    if ( m_pCache->m_aMatrixIter != m_pCache->getEnd() && (*m_pCache->m_aMatrixIter).is() )
    {
        if ( m_pCache->isResultSetChanged() )
        {
            impl_rebuild_throw(aGuard);
        }
        else
        {
            m_aOldRow->setRow(new ORowSetValueVector(*(*m_aCurrentRow)));

            // notification order
            // - column values
            ORowSetBase::firePropertyChange(aOldValues);
        }
        // - rowChanged
        notifyAllListenersRowChanged(aGuard,aEvt);

        // - IsModified
        if(!m_bModified)
            fireProperty(PROPERTY_ID_ISMODIFIED,false,true);
        OSL_ENSURE( !m_bModified, "ORowSet::updateRow: just updated, but _still_ modified?" );

        // - RowCount/IsRowCountFinal
        fireRowcount();
    }
    else if ( !m_bAfterLast ) // the update went wrong
    {
        ::dbtools::throwSQLException( DBA_RES( RID_STR_UPDATE_FAILED ), StandardSQLState::INVALID_CURSOR_POSITION, *this );
    }
}

void SAL_CALL ORowSet::deleteRow(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::ResettableMutexGuard aGuard( *m_pMutex );
    checkCache();

    if ( m_bBeforeFirst || m_bAfterLast )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_NO_DELETE_BEFORE_AFTER ), StandardSQLState::INVALID_CURSOR_POSITION, *this );
    if ( m_bNew )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_NO_DELETE_INSERT_ROW ), StandardSQLState::INVALID_CURSOR_POSITION, *this );
    if  ( m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_RESULT_IS_READONLY ), StandardSQLState::FUNCTION_SEQUENCE_ERROR, *this );
    if ( ( m_pCache->m_nPrivileges & Privilege::DELETE ) != Privilege::DELETE )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_NO_DELETE_PRIVILEGE ), StandardSQLState::FUNCTION_SEQUENCE_ERROR, *this );
    if ( rowDeleted() )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_ROW_ALREADY_DELETED ), StandardSQLState::FUNCTION_SEQUENCE_ERROR, *this );

    // this call position the cache indirect
    Any aBookmarkToDelete( m_aBookmark );
    positionCache( MOVE_NONE );
    sal_Int32 nDeletePosition = m_pCache->getRow();

    notifyRowSetAndClonesRowDelete( aBookmarkToDelete );

    ORowSetRow aOldValues;
    if ( m_pCache->m_aMatrixIter != m_pCache->getEnd() && m_pCache->m_aMatrixIter->is() )
        aOldValues = new ORowSetValueVector( *(*(m_pCache->m_aMatrixIter)) );<--- Variable 'aOldValues' is assigned a value that is never used.

    Sequence<Any> aChangedBookmarks;
    RowsChangeEvent aEvt(*this,RowChangeAction::DELETE,1,aChangedBookmarks);
    notifyAllListenersRowBeforeChange(aGuard,aEvt);

    m_pCache->deleteRow();
    notifyRowSetAndClonesRowDeleted( aBookmarkToDelete, nDeletePosition );

    ORowSetNotifier aNotifier( this );
        // this will call cancelRowModification on the cache if necessary

    // notification order
    // - rowChanged
    notifyAllListenersRowChanged(aGuard,aEvt);

    // - IsModified
    // - IsNew
    aNotifier.fire( );

    // - RowCount/IsRowCountFinal
    fireRowcount();
}

void ORowSet::implCancelRowUpdates( bool _bNotifyModified )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( *m_pMutex );
    if ( m_bBeforeFirst || m_bAfterLast || rowDeleted() )
        return; // nothing to do so return

    checkCache();
    // cancelRowUpdates is not allowed when:
    // - standing on the insert row
    // - the concurrency is read only
    // - the current row is deleted
    if ( m_bNew || m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY )
        throwFunctionSequenceException(*this);

    positionCache( MOVE_NONE );

    ORowSetRow aOldValues;
    if ( !m_bModified && _bNotifyModified && !m_aCurrentRow.isNull() )
        aOldValues = new ORowSetValueVector( *(*m_aCurrentRow) );

    m_pCache->cancelRowUpdates();

    m_aBookmark     = m_pCache->getBookmark();
    m_aCurrentRow   = m_pCache->m_aMatrixIter;
    m_bIsInsertRow  = false;

    // notification order
    // IsModified
    if( !m_bModified && _bNotifyModified )
    {
        // - column values
        ORowSetBase::firePropertyChange(aOldValues);
        fireProperty(PROPERTY_ID_ISMODIFIED,false,true);
    }
}

void SAL_CALL ORowSet::cancelRowUpdates(  )
{
    implCancelRowUpdates( true );
}

void SAL_CALL ORowSet::addRowSetListener( const Reference< XRowSetListener >& listener )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );
    if(listener.is())
        m_aRowsetListeners.addInterface(listener);
}

void SAL_CALL ORowSet::removeRowSetListener( const Reference< XRowSetListener >& listener )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );
    if(listener.is())
        m_aRowsetListeners.removeInterface(listener);
}

void ORowSet::notifyAllListeners(::osl::ResettableMutexGuard& _rGuard)
{
    EventObject aEvt(*m_pMySelf);
    _rGuard.clear();
    m_aRowsetListeners.notifyEach( &XRowSetListener::rowSetChanged, aEvt );
    _rGuard.reset();
}

void ORowSet::notifyAllListenersCursorMoved(::osl::ResettableMutexGuard& _rGuard)
{
    EventObject aEvt(*m_pMySelf);
    _rGuard.clear();
    m_aRowsetListeners.notifyEach( &XRowSetListener::cursorMoved, aEvt );
    _rGuard.reset();
}

void ORowSet::notifyAllListenersRowChanged(::osl::ResettableMutexGuard& _rGuard, const RowsChangeEvent& aEvt)
{
    _rGuard.clear();
    m_aRowsetListeners.notifyEach( &XRowSetListener::rowChanged, static_cast<EventObject>(aEvt) );
    m_aRowsChangeListener.notifyEach( &XRowsChangeListener::rowsChanged, aEvt );
    _rGuard.reset();
}

bool ORowSet::notifyAllListenersCursorBeforeMove(::osl::ResettableMutexGuard& _rGuard)
{
    EventObject aEvt(*m_pMySelf);
    NOTIFY_LISTENERS_CHECK(m_aApproveListeners,XRowSetApproveListener,approveCursorMove);
    return bCheck;
}

void ORowSet::notifyAllListenersRowBeforeChange(::osl::ResettableMutexGuard& _rGuard,const RowChangeEvent &aEvt)
{
    NOTIFY_LISTENERS_CHECK(m_aApproveListeners,XRowSetApproveListener,approveRowChange);
    if ( !bCheck )
        m_aErrors.raiseTypedException( sdb::ErrorCondition::ROW_SET_OPERATION_VETOED, *this, ::cppu::UnoType< RowSetVetoException >::get() );
}

void ORowSet::fireRowcount()
{
    sal_Int32 nCurrentRowCount( impl_getRowCount() );
    bool bCurrentRowCountFinal( m_pCache->m_bRowCountFinal );

    if ( m_nLastKnownRowCount != nCurrentRowCount )
    {
        sal_Int32 nHandle = PROPERTY_ID_ROWCOUNT;
        Any aNew,aOld;
        aNew <<= nCurrentRowCount; aOld <<= m_nLastKnownRowCount;
        fire(&nHandle,&aNew,&aOld,1,false);
        m_nLastKnownRowCount = nCurrentRowCount;
    }
    if ( !m_bLastKnownRowCountFinal && ( m_bLastKnownRowCountFinal != bCurrentRowCountFinal ) )
    {
        sal_Int32 nHandle = PROPERTY_ID_ISROWCOUNTFINAL;
        Any aNew,aOld;
        aNew <<= bCurrentRowCountFinal;
        aOld <<= m_bLastKnownRowCountFinal;
        fire(&nHandle,&aNew,&aOld,1,false);
        m_bLastKnownRowCountFinal = bCurrentRowCountFinal;
    }
}

void SAL_CALL ORowSet::moveToInsertRow(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::ResettableMutexGuard aGuard( *m_pMutex );
    checkPositioningAllowed();
    if ( ( m_pCache->m_nPrivileges & Privilege::INSERT ) != Privilege::INSERT )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_NO_INSERT_PRIVILEGE ), StandardSQLState::GENERAL_ERROR, *this );

    if ( !notifyAllListenersCursorBeforeMove( aGuard ) )
        return;

    // remember old value for fire
    ORowSetRow aOldValues;
    if ( rowDeleted() )
    {
        positionCache( MOVE_FORWARD );
        m_pCache->next();
        setCurrentRow( true, false, aOldValues, aGuard);
    }
    else
        positionCache( MOVE_NONE );

    // check before because the resultset could be empty
    if  (   !m_bBeforeFirst
        &&  !m_bAfterLast
        &&  m_pCache->m_aMatrixIter != m_pCache->getEnd()
        &&  m_pCache->m_aMatrixIter->is()
        )
        aOldValues = new ORowSetValueVector( *(*(m_pCache->m_aMatrixIter)) );

    const bool bNewState = m_bNew;
    const bool bModState = m_bModified;

    m_pCache->moveToInsertRow();
    m_aCurrentRow = m_pCache->m_aInsertRow;
    m_bIsInsertRow  = true;

    // set read-only flag to false
    impl_setDataColumnsWriteable_throw();

    // notification order
    // - column values
    ORowSetBase::firePropertyChange(aOldValues);

    // - cursorMoved
    notifyAllListenersCursorMoved(aGuard);

    // - IsModified
    if ( bModState != m_bModified )
        fireProperty( PROPERTY_ID_ISMODIFIED, m_bModified, bModState );

    // - IsNew
    if ( bNewState != m_bNew )
        fireProperty( PROPERTY_ID_ISNEW, m_bNew, bNewState );

    // - RowCount/IsRowCountFinal
    fireRowcount();
}

void ORowSet::impl_setDataColumnsWriteable_throw()
{
    impl_restoreDataColumnsWriteable_throw();
    m_aReadOnlyDataColumns.resize(m_aDataColumns.size(),false);
    std::vector<bool, std::allocator<bool> >::iterator aReadIter = m_aReadOnlyDataColumns.begin();
    for (auto const& dataColumn : m_aDataColumns)
    {
        bool bReadOnly = false;
        dataColumn->getPropertyValue(PROPERTY_ISREADONLY) >>= bReadOnly;
        *aReadIter = bReadOnly;

        dataColumn->setPropertyValue(PROPERTY_ISREADONLY,makeAny(false));
        ++aReadIter;
    }
}

void ORowSet::impl_restoreDataColumnsWriteable_throw()
{
    assert(m_aDataColumns.size() == m_aReadOnlyDataColumns.size() || m_aReadOnlyDataColumns.size() == 0 );
    TDataColumns::const_iterator aIter = m_aDataColumns.begin();
    for (bool readOnlyDataColumn : m_aReadOnlyDataColumns)
    {
        (*aIter)->setPropertyValue(PROPERTY_ISREADONLY, makeAny(readOnlyDataColumn) );
        ++aIter;
    }
    m_aReadOnlyDataColumns.clear();
}

void SAL_CALL ORowSet::moveToCurrentRow(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::ResettableMutexGuard aGuard( *m_pMutex );
    checkPositioningAllowed();

    if ( !m_pCache->m_bNew && !m_bModified )
        // nothing to do if we're not on the insertion row, and not modified otherwise
        return;

    if ( rowDeleted() )
        // this would perhaps even justify a RuntimeException...
        // if the current row is deleted, then no write access to this row should be possible. So,
        // m_bModified should be true. Also, as soon as somebody calls moveToInsertRow,
        // our current row should not be deleted anymore. So, we should not have survived the above
        // check "if ( !m_pCache->m_bNew && !m_bModified )"
        ::dbtools::throwSQLException( DBA_RES( RID_STR_ROW_ALREADY_DELETED ), StandardSQLState::FUNCTION_SEQUENCE_ERROR, *this );

    if ( !notifyAllListenersCursorBeforeMove( aGuard ) )
        return;

    positionCache( MOVE_NONE_REFRESH );

    ORowSetNotifier aNotifier( this );

    // notification order
    // - cursorMoved
    notifyAllListenersCursorMoved(aGuard);

    // - IsModified
    // - IsNew
    aNotifier.fire();
}

// XRow
sal_Bool SAL_CALL ORowSet::wasNull(  )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    checkCache();

    return ( m_pCache && isInsertRow() ) ? (**m_pCache->m_aInsertRow)[m_nLastColumnIndex].isNull() : ORowSetBase::wasNull();
}

const ORowSetValue& ORowSet::getInsertValue(sal_Int32 columnIndex)
{
    checkCache();

    if ( m_pCache && isInsertRow() )
    {
        m_nLastColumnIndex = columnIndex;
        return  (**m_pCache->m_aInsertRow)[m_nLastColumnIndex];
    }
    return getValue(columnIndex);
}

OUString SAL_CALL ORowSet::getString( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

sal_Bool SAL_CALL ORowSet::getBoolean( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    // the extra cast is to recognise the "true" or "false" strings
    return static_cast<bool>(getInsertValue(columnIndex));
}

sal_Int8 SAL_CALL ORowSet::getByte( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

sal_Int16 SAL_CALL ORowSet::getShort( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

sal_Int32 SAL_CALL ORowSet::getInt( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

sal_Int64 SAL_CALL ORowSet::getLong( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

float SAL_CALL ORowSet::getFloat( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

double SAL_CALL ORowSet::getDouble( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

Sequence< sal_Int8 > SAL_CALL ORowSet::getBytes( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

css::util::Date SAL_CALL ORowSet::getDate( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

css::util::Time SAL_CALL ORowSet::getTime( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

css::util::DateTime SAL_CALL ORowSet::getTimestamp( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex);
}

Reference< css::io::XInputStream > SAL_CALL ORowSet::getBinaryStream( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    if ( m_pCache && isInsertRow() )
    {
        checkCache();
        m_nLastColumnIndex = columnIndex;
        return new ::comphelper::SequenceInputStream((**m_pCache->m_aInsertRow)[m_nLastColumnIndex].getSequence());
    }

    return ORowSetBase::getBinaryStream(columnIndex);
}

Reference< css::io::XInputStream > SAL_CALL ORowSet::getCharacterStream( sal_Int32 columnIndex )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    if(m_pCache && isInsertRow() )
    {
        checkCache();
        m_nLastColumnIndex = columnIndex;
        return new ::comphelper::SequenceInputStream((**m_pCache->m_aInsertRow)[m_nLastColumnIndex].getSequence());
    }

    return ORowSetBase::getCharacterStream(columnIndex);
}

Any SAL_CALL ORowSet::getObject( sal_Int32 columnIndex, const Reference< XNameAccess >& /*typeMap*/ )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    return getInsertValue(columnIndex).makeAny();
}

Reference< XRef > SAL_CALL ORowSet::getRef( sal_Int32 /*columnIndex*/ )
{
    return Reference< XRef >();
}

Reference< XBlob > SAL_CALL ORowSet::getBlob( sal_Int32 columnIndex )
{
    if ( m_pCache && isInsertRow() )
    {
        checkCache();
        m_nLastColumnIndex = columnIndex;
        return new ::connectivity::BlobHelper((**m_pCache->m_aInsertRow)[m_nLastColumnIndex].getSequence());
    }
    return ORowSetBase::getBlob(columnIndex);
}

Reference< XClob > SAL_CALL ORowSet::getClob( sal_Int32 columnIndex )
{
    return Reference< XClob >(getInsertValue(columnIndex).makeAny(),UNO_QUERY);
}

Reference< XArray > SAL_CALL ORowSet::getArray( sal_Int32 /*columnIndex*/ )
{
    return Reference< XArray >();
}

void SAL_CALL ORowSet::executeWithCompletion( const Reference< XInteractionHandler >& _rxHandler )
{
    if (!_rxHandler.is())
        execute();

    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    // tell everybody that we will change the result set
    approveExecution();

    ResettableMutexGuard aGuard( m_aMutex );

    try
    {
        freeResources( m_bCommandFacetsDirty );

        // calc the connection to be used
        if (m_xActiveConnection.is() && m_bRebuildConnOnExecute)
        {
            // there was a setProperty(ActiveConnection), but a setProperty(DataSource) _after_ that, too
            Reference< XConnection > xXConnection;
            setActiveConnection( xXConnection );
        }
        calcConnection( _rxHandler );
        m_bRebuildConnOnExecute = false;

        Reference< XSingleSelectQueryComposer > xComposer = getCurrentSettingsComposer( this, m_aContext, nullptr );
        Reference<XParametersSupplier>  xParameters(xComposer, UNO_QUERY);

        Reference<XIndexAccess>  xParamsAsIndicies = xParameters.is() ? xParameters->getParameters() : Reference<XIndexAccess>();
        const sal_Int32 nParamCount = xParamsAsIndicies.is() ? xParamsAsIndicies->getCount() : 0;
        if ( m_aParametersSet.size() < o3tl::make_unsigned(nParamCount) )
            m_aParametersSet.resize( nParamCount ,false);

        ::dbtools::askForParameters( xComposer, this, m_xActiveConnection, _rxHandler,m_aParametersSet );
    }
    // ensure that only the allowed exceptions leave this block
    catch(SQLException&)
    {
        throw;
    }
    catch(RuntimeException&)
    {
        throw;
    }
    catch(Exception const &)
    {
        TOOLS_WARN_EXCEPTION("dbaccess", "ORowSet::executeWithCompletion: caught an unexpected exception type while filling in the parameters");
    }

    // we're done with the parameters, now for the real execution

    //  do the real execute
    execute_NoApprove_NoNewConn(aGuard);
}

Reference< XIndexAccess > SAL_CALL ORowSet::getParameters(  )
{
    ::osl::MutexGuard aGuard( *m_pMutex );
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    if ( m_bCommandFacetsDirty )
        // need to rebuild the parameters, since some property which contributes to the
        // complete command, and thus the parameters, changed
        impl_disposeParametersContainer_nothrow();

    if ( !m_pParameters && !m_aCommand.isEmpty() )
    {
        try
        {
            OUString sNotInterestedIn;
            impl_initComposer_throw( sNotInterestedIn );
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("dbaccess");
        }
    }

    // our caller could change our parameters at any time
    m_bParametersDirty = true;

    return m_pParameters.get();
}

void ORowSet::approveExecution()
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );
    EventObject aEvt(*this);

    OInterfaceIteratorHelper2 aApproveIter( m_aApproveListeners );
    while ( aApproveIter.hasMoreElements() )
    {
        Reference< XRowSetApproveListener > xListener( static_cast< XRowSetApproveListener* >( aApproveIter.next() ) );
        try
        {
            if ( xListener.is() && !xListener->approveRowSetChange( aEvt ) )
                throw RowSetVetoException();
        }
        catch ( const DisposedException& e )
        {
            if ( e.Context == xListener )
                aApproveIter.remove();
        }
        catch ( const RuntimeException& ) { throw; }
        catch ( const RowSetVetoException& ) { throw; }
        catch ( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("dbaccess");
        }
    }
}

// XRowSet
void SAL_CALL ORowSet::execute(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    // tell everybody that we will change the result set
    approveExecution();

    ResettableMutexGuard aGuard( m_aMutex );
    freeResources( m_bCommandFacetsDirty );

    // calc the connection to be used
    if (m_xActiveConnection.is() && m_bRebuildConnOnExecute) {
        // there was a setProperty(ActiveConnection), but a setProperty(DataSource) _after_ that, too
        Reference< XConnection> xXConnection;
        setActiveConnection( xXConnection );
    }

    calcConnection(nullptr);
    m_bRebuildConnOnExecute = false;

    // do the real execute
    execute_NoApprove_NoNewConn(aGuard);
}

void ORowSet::setStatementResultSetType( const Reference< XPropertySet >& _rxStatement, sal_Int32 _nDesiredResultSetType, sal_Int32 _nDesiredResultSetConcurrency )
{
    OSL_ENSURE( _rxStatement.is(), "ORowSet::setStatementResultSetType: invalid statement - this will crash!" );

    sal_Int32 nResultSetType( _nDesiredResultSetType );
    sal_Int32 nResultSetConcurrency( _nDesiredResultSetConcurrency );

    // there *might* be a data source setting which tells use to be more defensive with those settings
    // #i15113#
    bool bRespectDriverRST = false;<--- Assignment 'bRespectDriverRST=false', assigned value is 0
    Any aSetting;
    if ( getDataSourceSetting( ::dbaccess::getDataSource( m_xActiveConnection ), "RespectDriverResultSetType", aSetting ) )<--- Assuming condition is false
    {
        OSL_VERIFY( aSetting >>= bRespectDriverRST );
    }

    if ( bRespectDriverRST )<--- Condition 'bRespectDriverRST' is always false
    {
        // try type/concurrency settings with decreasing usefulness, and rely on what the connection claims
        // to support
        Reference< XDatabaseMetaData > xMeta( m_xActiveConnection->getMetaData() );

        sal_Int32 nCharacteristics[5][2] =
        {   { ResultSetType::SCROLL_SENSITIVE, ResultSetConcurrency::UPDATABLE },
            { ResultSetType::SCROLL_INSENSITIVE, ResultSetConcurrency::UPDATABLE },
            { ResultSetType::SCROLL_SENSITIVE, ResultSetConcurrency::READ_ONLY },
            { ResultSetType::SCROLL_INSENSITIVE, ResultSetConcurrency::READ_ONLY },
            { ResultSetType::FORWARD_ONLY, ResultSetConcurrency::READ_ONLY }
        };
        sal_Int32 i=0;
        if ( m_xActiveConnection->getMetaData()->isReadOnly() )
            i = 2; // if the database is read-only we only should use read-only concurrency

        for ( ; i<5; ++i )
        {
            nResultSetType = nCharacteristics[i][0];
            nResultSetConcurrency = nCharacteristics[i][1];

            // don't try type/concurrency pairs which are more featured than what our caller requested
            if ( nResultSetType > _nDesiredResultSetType )
                continue;
            if ( nResultSetConcurrency > _nDesiredResultSetConcurrency )
                continue;

            if ( xMeta.is() && xMeta->supportsResultSetConcurrency( nResultSetType, nResultSetConcurrency ) )
                break;
        }
    }

    _rxStatement->setPropertyValue( PROPERTY_RESULTSETTYPE, makeAny( nResultSetType ) );
    _rxStatement->setPropertyValue( PROPERTY_RESULTSETCONCURRENCY, makeAny( nResultSetConcurrency ) );
}

void ORowSet::impl_ensureStatement_throw()
{
    OUString sCommandToExecute;
    if(m_bCommandFacetsDirty)
    {
        impl_initComposer_throw( sCommandToExecute );
    }
    else
    {
        sCommandToExecute = m_bUseEscapeProcessing ? m_xComposer->getQueryWithSubstitution() : m_aActiveCommand;
    }

    try
    {
        m_xStatement = m_xActiveConnection->prepareStatement( sCommandToExecute );
        if ( !m_xStatement.is() )
        {
            ::dbtools::throwSQLException( DBA_RES( RID_STR_INTERNAL_ERROR ), StandardSQLState::GENERAL_ERROR, *this );
        }

        Reference< XPropertySet > xStatementProps( m_xStatement, UNO_QUERY_THROW );
        // set the result set type and concurrency
        try
        {
            xStatementProps->setPropertyValue( PROPERTY_USEBOOKMARKS, makeAny( true ) );
            xStatementProps->setPropertyValue( PROPERTY_MAXROWS, makeAny( m_nMaxRows ) );

            setStatementResultSetType( xStatementProps, m_nResultSetType, m_nResultSetConcurrency );
        }
        catch ( const Exception& )
        {
            // this exception doesn't matter here because when we catch an exception
            // then the driver doesn't support this feature
        }
    }
    catch( const SQLException& )
    {
        SQLExceptionInfo aError( ::cppu::getCaughtException() );
        OSL_ENSURE( aError.isValid(), "ORowSet::impl_makeNewStatement_throw: caught an SQLException which we cannot analyze!" );

        // append information about what we were actually going to execute
        try
        {
            OUString sInfo(DBA_RES_PARAM( RID_STR_COMMAND_LEADING_TO_ERROR, "$command$", sCommandToExecute )  );
            aError.append( SQLExceptionInfo::TYPE::SQLContext, sInfo );
        }
        catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION("dbaccess"); }

        // propagate
        aError.doThrow();
    }
}

Reference< XResultSet > ORowSet::impl_prepareAndExecute_throw()
{
    impl_ensureStatement_throw();

    m_aParameterValueForCache->resize(1);
    Reference< XParameters > xParam( m_xStatement, UNO_QUERY_THROW );
    size_t nParamCount( m_pParameters.is() ? m_pParameters->size() : m_aPrematureParamValues->size() );
    for ( size_t i=1; i<=nParamCount; ++i )
    {
        ORowSetValue& rParamValue( getParameterStorage( static_cast<sal_Int32>(i) ) );
        ::dbtools::setObjectWithInfo( xParam, i, rParamValue.makeAny(), rParamValue.getTypeKind() );
        m_aParameterValueForCache->push_back(rParamValue);
    }
    m_bParametersDirty = false;

    Reference< XResultSet > xResultSet(m_xStatement->executeQuery());

    OUString aComposedUpdateTableName;
    if ( !m_aUpdateTableName.isEmpty() )
        aComposedUpdateTableName = composeTableName( m_xActiveConnection->getMetaData(), m_aUpdateCatalogName, m_aUpdateSchemaName, m_aUpdateTableName, false, ::dbtools::EComposeRule::InDataManipulation );

    SAL_INFO("dbaccess", "ORowSet::impl_prepareAndExecute_throw: creating cache" );
    m_pCache =
        std::make_shared<ORowSetCache>(xResultSet, m_xComposer.get(), m_aContext, aComposedUpdateTableName,
               m_bModified, m_bNew, *m_aParameterValueForCache, m_aFilter, m_nMaxRows);
    if ( m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY )
    {
        m_nPrivileges = Privilege::SELECT;
        m_pCache->m_nPrivileges = Privilege::SELECT;
    }
    m_pCache->setFetchSize(m_nFetchSize);
    m_aCurrentRow   = m_pCache->createIterator(this);
    m_bIsInsertRow  = false;
    m_aOldRow       = m_pCache->registerOldRow();

    return xResultSet;
}

void ORowSet::impl_initializeColumnSettings_nothrow( const Reference< XPropertySet >& _rxTemplateColumn, const Reference< XPropertySet >& _rxRowSetColumn )
{
    OSL_ENSURE( _rxTemplateColumn.is() && _rxRowSetColumn.is(),
        "ORowSet::impl_initializeColumnSettings_nothrow: this will crash!" );

    bool bHaveAnyColumnSetting = false;
    try
    {
        Reference< XPropertySetInfo > xInfo( _rxTemplateColumn->getPropertySetInfo(), UNO_SET_THROW );

        // a number of properties is plain copied
        const OUString aPropertyNames[] = {
            OUString(PROPERTY_ALIGN), OUString(PROPERTY_RELATIVEPOSITION), OUString(PROPERTY_WIDTH), OUString(PROPERTY_HIDDEN), OUString(PROPERTY_CONTROLMODEL),
            OUString(PROPERTY_HELPTEXT), OUString(PROPERTY_CONTROLDEFAULT)
        };
        for (const auto & aPropertyName : aPropertyNames)
        {
            if ( xInfo->hasPropertyByName( aPropertyName ) )
            {
                _rxRowSetColumn->setPropertyValue( aPropertyName, _rxTemplateColumn->getPropertyValue( aPropertyName ) );
                bHaveAnyColumnSetting = true;
            }
        }

        // the format key is slightly more complex
        sal_Int32 nFormatKey = 0;<--- Assignment 'nFormatKey=0', assigned value is 0
        if( xInfo->hasPropertyByName( PROPERTY_NUMBERFORMAT ) )
        {
            _rxTemplateColumn->getPropertyValue( PROPERTY_NUMBERFORMAT ) >>= nFormatKey;
            bHaveAnyColumnSetting = true;
        }
        if ( !nFormatKey && m_xNumberFormatTypes.is() )<--- Condition '!nFormatKey' is always true
            nFormatKey = ::dbtools::getDefaultNumberFormat( _rxTemplateColumn, m_xNumberFormatTypes, SvtSysLocale().GetLanguageTag().getLocale() );
        _rxRowSetColumn->setPropertyValue( PROPERTY_NUMBERFORMAT, makeAny( nFormatKey ) );
    }
    catch(Exception&)
    {
        DBG_UNHANDLED_EXCEPTION("dbaccess");
        return;
    }

    if ( bHaveAnyColumnSetting )
        return;

    // the template column could not provide *any* setting. Okay, probably it's a parser column, which
    // does not offer those. However, perhaps the template column refers to a table column, which we
    // can use as new template column
    try
    {
        Reference< XPropertySetInfo > xInfo( _rxTemplateColumn->getPropertySetInfo(), UNO_SET_THROW );
        if ( !xInfo->hasPropertyByName( PROPERTY_TABLENAME ) )
            // no chance
            return;

        OUString sTableName;
        OSL_VERIFY( _rxTemplateColumn->getPropertyValue( PROPERTY_TABLENAME ) >>= sTableName );

        Reference< XNameAccess > xTables( impl_getTables_throw(), UNO_SET_THROW );
        if ( !xTables->hasByName( sTableName ) )
            // no chance
            return;

        Reference< XColumnsSupplier > xTableColSup( xTables->getByName( sTableName ), UNO_QUERY_THROW );
        Reference< XNameAccess > xTableCols( xTableColSup->getColumns(), UNO_SET_THROW );

        OUString sTableColumnName;

        // get the "Name" or (preferred) "RealName" property of the column
        OUString sNamePropertyName( PROPERTY_NAME );
        if ( xInfo->hasPropertyByName( PROPERTY_REALNAME ) )
            sNamePropertyName = PROPERTY_REALNAME;
        OSL_VERIFY( _rxTemplateColumn->getPropertyValue( sNamePropertyName ) >>= sTableColumnName );

        if ( !xTableCols->hasByName( sTableColumnName ) )
            return;

        Reference< XPropertySet > xTableColumn( xTableCols->getByName( sTableColumnName ), UNO_QUERY_THROW );
        impl_initializeColumnSettings_nothrow( xTableColumn, _rxRowSetColumn );
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("dbaccess");
    }
}

void ORowSet::execute_NoApprove_NoNewConn(ResettableMutexGuard& _rClearForNotification)
{
    // now we can dispose our old connection
    ::comphelper::disposeComponent(m_xOldConnection);
    m_xOldConnection = nullptr;

    // do we need a new statement
    if ( m_bCommandFacetsDirty )
    {
        m_xStatement    = nullptr;
        m_xComposer     = nullptr;

        Reference< XResultSet > xResultSet( impl_prepareAndExecute_throw() );

        // let our warnings container forget the reference to the (possibly disposed) old result set
        m_aWarnings.setExternalWarnings( nullptr );
        // clear all current warnings
        m_aWarnings.clearWarnings();
        // let the warnings container know about the new "external warnings"
        m_aWarnings.setExternalWarnings( Reference< XWarningsSupplier >( xResultSet, UNO_QUERY ) );

        // get the locale
        Locale aLocale = SvtSysLocale().GetLanguageTag().getLocale();

        // get the numberformatTypes
        OSL_ENSURE(m_xActiveConnection.is(),"No ActiveConnection");
        Reference< XNumberFormatsSupplier> xNumberFormat = ::dbtools::getNumberFormats(m_xActiveConnection);
        if ( xNumberFormat.is() )
            m_xNumberFormatTypes.set(xNumberFormat->getNumberFormats(),UNO_QUERY);

        ::rtl::Reference< ::connectivity::OSQLColumns> aColumns = new ::connectivity::OSQLColumns();
        std::vector< OUString> aNames;
        OUString aDescription;

        const std::map<sal_Int32,sal_Int32>& rKeyColumns = m_pCache->getKeyColumns();
        if(!m_xColumns.is())
        {
            SAL_INFO("dbaccess", "ORowSet::execute_NoApprove_NoNewConn::creating columns" );
            // use the meta data
            Reference<XResultSetMetaDataSupplier> xMetaSup(m_xStatement,UNO_QUERY);
            try
            {
                Reference<XResultSetMetaData> xMetaData = xMetaSup->getMetaData();
                if ( xMetaData.is() )
                {
                    sal_Int32 nCount = xMetaData->getColumnCount();
                    m_aDataColumns.reserve(nCount+1);
                    aColumns->reserve(nCount+1);
                    std::map< OUString, int > aColumnMap;
                    for (sal_Int32 i = 0 ; i < nCount; ++i)
                    {
                        // retrieve the name of the column
                        OUString sName = xMetaData->getColumnName(i + 1);
                        // check for duplicate entries
                        if(aColumnMap.find(sName) != aColumnMap.end())
                        {
                            OUString sAlias(sName);
                            sal_Int32 searchIndex=1;
                            while(aColumnMap.find(sAlias) != aColumnMap.end())
                            {
                                sAlias = sName + OUString::number(searchIndex++);
                            }
                            sName = sAlias;
                        }
                        ORowSetDataColumn* pColumn = new ORowSetDataColumn( getMetaData(),
                                                                            this,
                                                                            this,
                                                                            i+1,
                                                                            m_xActiveConnection->getMetaData(),
                                                                            aDescription,
                                                                            OUString(),
                            [this] (sal_Int32 const column) -> ORowSetValue const& {
                                return this->getInsertValue(column);
                            });
                        aColumnMap.insert(std::make_pair(sName,0));
                        aColumns->emplace_back(pColumn);
                        pColumn->setName(sName);
                        aNames.push_back(sName);
                        m_aDataColumns.push_back(pColumn);

                        pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_ISREADONLY,makeAny(rKeyColumns.find(i+1) != rKeyColumns.end()));

                        try
                        {
                            sal_Int32 nFormatKey = 0;
                            if(m_xNumberFormatTypes.is())
                                nFormatKey = ::dbtools::getDefaultNumberFormat(pColumn,m_xNumberFormatTypes,aLocale);


                            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_NUMBERFORMAT,makeAny(nFormatKey));
                            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_RELATIVEPOSITION,makeAny(sal_Int32(i+1)));
                            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_WIDTH,makeAny(sal_Int32(227)));
                            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_ALIGN,makeAny(sal_Int32(0)));
                            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_HIDDEN, css::uno::Any(false));
                        }
                        catch(Exception&)
                        {
                        }
                    }
                }
            }
            catch (SQLException&)
            {
            }
        }
        else
        {
            // create the rowset columns
            Reference< XResultSetMetaData > xMeta( getMetaData(), UNO_SET_THROW );
            sal_Int32 nCount = xMeta->getColumnCount();
            m_aDataColumns.reserve(nCount+1);
            aColumns->reserve(nCount+1);
            std::set< Reference< XPropertySet > > aAllColumns;

            for(sal_Int32 i=1; i <= nCount ;++i)
            {
                OUString sName = xMeta->getColumnName(i);
                OUString sColumnLabel = xMeta->getColumnLabel(i);

                // retrieve the column number |i|
                Reference<XPropertySet> xColumn;
                {
                    bool bReFetchName = false;
                    if (m_xColumns->hasByName(sColumnLabel))
                        m_xColumns->getByName(sColumnLabel) >>= xColumn;
                    if (!xColumn.is() && m_xColumns->hasByName(sName))
                        m_xColumns->getByName(sName) >>= xColumn;

                    // check if column already in the list we need another
                    if ( aAllColumns.find( xColumn ) != aAllColumns.end() )
                    {
                        xColumn = nullptr;
                        bReFetchName = true;
                        sColumnLabel.clear();
                    }
                    if(!xColumn.is())
                    {
                        // no column found so we could look at the position i
                        Reference<XIndexAccess> xIndexAccess(m_xColumns,UNO_QUERY);
                        if(xIndexAccess.is() && i <= xIndexAccess->getCount())
                        {
                            xIndexAccess->getByIndex(i-1) >>= xColumn;
                        }
                        else
                        {
                            Sequence< OUString> aSeq = m_xColumns->getElementNames();
                            if( i <= aSeq.getLength())
                            {
                                m_xColumns->getByName(aSeq.getConstArray()[i-1]) >>= xColumn;
                            }
                        }
                    }
                    if(bReFetchName && xColumn.is())
                        xColumn->getPropertyValue(PROPERTY_NAME) >>= sName;
                    aAllColumns.insert( xColumn );
                }

                // create a RowSetDataColumn
                {
                    Reference<XPropertySetInfo> xInfo = xColumn.is() ? xColumn->getPropertySetInfo() : Reference<XPropertySetInfo>();
                    if(xInfo.is() && xInfo->hasPropertyByName(PROPERTY_DESCRIPTION))
                        aDescription = comphelper::getString(xColumn->getPropertyValue(PROPERTY_DESCRIPTION));

                    OUString sParseLabel;
                    if ( xColumn.is() )
                    {
                        xColumn->getPropertyValue(PROPERTY_LABEL) >>= sParseLabel;
                    }
                    ORowSetDataColumn* pColumn = new ORowSetDataColumn( getMetaData(),
                                                                        this,
                                                                        this,
                                                                        i,
                                                                        m_xActiveConnection->getMetaData(),
                                                                        aDescription,
                                                                        sParseLabel,
                        [this] (sal_Int32 const column) -> ORowSetValue const& {
                            return this->getInsertValue(column);
                        });
                    aColumns->emplace_back(pColumn);

                    pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_ISREADONLY,makeAny(rKeyColumns.find(i) != rKeyColumns.end()));

                    if(sColumnLabel.isEmpty())
                    {
                        if(xColumn.is())
                            xColumn->getPropertyValue(PROPERTY_NAME) >>= sColumnLabel;
                        else
                            sColumnLabel = DBA_RES( RID_STR_EXPRESSION1 );
                    }
                    pColumn->setName(sColumnLabel);
                    aNames.push_back(sColumnLabel);
                    m_aDataColumns.push_back(pColumn);

                    if ( xColumn.is() )
                        impl_initializeColumnSettings_nothrow( xColumn, pColumn );
                }
            }
        }
        // now create the columns we need
        if(m_pColumns)
            m_pColumns->assign(aColumns,aNames);
        else
        {
            Reference<XDatabaseMetaData> xMeta = m_xActiveConnection->getMetaData();
            m_pColumns.reset( new ORowSetDataColumns(xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers(),
                                                aColumns,*this,m_aColumnsMutex,aNames) );
        }
    }
    else // !m_bCommandFacetsDirty
    {
        Reference< XResultSet > xResultSet;
        if(m_bParametersDirty)
        {
            xResultSet = impl_prepareAndExecute_throw();
        }
        else
        {
            xResultSet = m_xStatement->executeQuery();
            m_pCache->reset(xResultSet);
        }
        // let our warnings container forget the reference to the (possibly disposed) old result set
        m_aWarnings.setExternalWarnings( nullptr );
        // clear all current warnings
        m_aWarnings.clearWarnings();
        // let the warnings container know about the new "external warnings"
        m_aWarnings.setExternalWarnings( Reference< XWarningsSupplier >( xResultSet, UNO_QUERY ) );
    }
    checkCache();
    // notify the rowset listeners
    notifyAllListeners(_rClearForNotification);
}

// XRowSetApproveBroadcaster
void SAL_CALL ORowSet::addRowSetApproveListener( const Reference< XRowSetApproveListener >& listener )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    m_aApproveListeners.addInterface(listener);
}

void SAL_CALL ORowSet::removeRowSetApproveListener( const Reference< XRowSetApproveListener >& listener )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    m_aApproveListeners.removeInterface(listener);
}

// XRowsChangeBroadcaster
void SAL_CALL ORowSet::addRowsChangeListener( const Reference< XRowsChangeListener >& listener )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    m_aRowsChangeListener.addInterface(listener);
}

void SAL_CALL ORowSet::removeRowsChangeListener( const Reference< XRowsChangeListener >& listener )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    m_aRowsChangeListener.removeInterface(listener);
}

// XResultSetAccess
Reference< XResultSet > SAL_CALL ORowSet::createResultSet(  )
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    if(m_xStatement.is())
    {
        ORowSetClone* pClone = new ORowSetClone( m_aContext, *this, m_pMutex );
        Reference< XResultSet > xRet(pClone);
        m_aClones.emplace_back(xRet);
        return xRet;
    }
    return Reference< XResultSet >();
}

// css::util::XCancellable
void SAL_CALL ORowSet::cancel(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);
}

// css::sdbcx::XDeleteRows
Sequence< sal_Int32 > SAL_CALL ORowSet::deleteRows( const Sequence< Any >& rows )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    if(!m_pCache || m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY)
        throwFunctionSequenceException(*this);

    ::osl::ResettableMutexGuard aGuard( *m_pMutex );

    Sequence<Any> aChangedBookmarks;
    RowsChangeEvent aEvt(*this,RowChangeAction::DELETE,rows.getLength(),aChangedBookmarks);
    // notify the rowset listeners
    notifyAllListenersRowBeforeChange(aGuard,aEvt);

    Sequence< sal_Int32 > aResults( rows.getLength() );
    const Any* row = rows.getConstArray();
    const Any* rowEnd = rows.getConstArray() + rows.getLength();
    sal_Int32* result = aResults.getArray();
    for ( ; row != rowEnd; ++row, ++result )
    {
        *result = 0;
        if ( !m_pCache->moveToBookmark( *row ) )
            continue;
        sal_Int32 nDeletePosition = m_pCache->getRow();

        // first notify the clones so that they can save their position
        notifyRowSetAndClonesRowDelete( *row );

        // now delete the row
        if ( !m_pCache->deleteRow() )
            continue;
        *result = 1;
        // now notify that we have deleted
        notifyRowSetAndClonesRowDeleted( *row, nDeletePosition );
    }
    aEvt.Rows = aResults.getLength();

    // we have to check if we stand on the insert row and if so we have to reset it
    ORowSetNotifier aNotifier( this );
        // this will call cancelRowModification on the cache if necessary
    // notification order
    // - rowChanged
    notifyAllListenersRowChanged(aGuard,aEvt);

    // - IsModified
    // - IsNew
    aNotifier.fire();

    // - RowCount/IsRowCountFinal
    fireRowcount();

    return aResults;
}

void ORowSet::notifyRowSetAndClonesRowDelete( const Any& _rBookmark )
{
    // notify ourself
    onDeleteRow( _rBookmark );
    // notify the clones
    for (auto const& elem : m_aClones)
    {
        auto pClone = comphelper::getUnoTunnelImplementation<ORowSetClone>(elem.get());
        if(pClone)
            pClone->onDeleteRow( _rBookmark );
    }
}

void ORowSet::notifyRowSetAndClonesRowDeleted( const Any& _rBookmark, sal_Int32 _nPos )
{
    // notify ourself
    onDeletedRow( _rBookmark, _nPos );
    // notify the clones
    for (auto const& clone : m_aClones)
    {
        auto pClone = comphelper::getUnoTunnelImplementation<ORowSetClone>(clone.get());
        if(pClone)
            pClone->onDeletedRow( _rBookmark, _nPos );
    }
}

Reference< XConnection >  ORowSet::calcConnection(const Reference< XInteractionHandler >& _rxHandler)
{
    MutexGuard aGuard(m_aMutex);
    if (!m_xActiveConnection.is())
    {
        Reference< XConnection > xNewConn;
        if ( !m_aDataSourceName.isEmpty() )
        {
            Reference< XDatabaseContext > xDatabaseContext( DatabaseContext::create(m_aContext) );
            try
            {
                Reference< XDataSource > xDataSource( xDatabaseContext->getByName( m_aDataSourceName ), UNO_QUERY_THROW );

                // try connecting with the interaction handler
                Reference< XCompletedConnection > xComplConn( xDataSource, UNO_QUERY );
                if ( _rxHandler.is() && xComplConn.is() )
                {
                    xNewConn = xComplConn->connectWithCompletion( _rxHandler );
                }
                else
                {
                    xNewConn = xDataSource->getConnection( m_aUser, m_aPassword );
                }
            }
            catch ( const SQLException& )
            {
                throw;
            }
            catch ( const Exception& )
            {
                Any aError = ::cppu::getCaughtException();
                OUString sMessage = ResourceManager::loadString( RID_NO_SUCH_DATA_SOURCE,
                    "$name$", m_aDataSourceName, "$error$", extractExceptionMessage( m_aContext, aError ) );
                ::dbtools::throwGenericSQLException( sMessage, *this, aError );
            }
        }
        setActiveConnection(xNewConn);
        m_bOwnConnection = true;
    }
    return m_xActiveConnection;
}

Reference< XNameAccess > ORowSet::impl_getTables_throw()
{
    Reference< XNameAccess > xTables;

    Reference< XTablesSupplier >  xTablesAccess( m_xActiveConnection, UNO_QUERY );
    if ( xTablesAccess.is() )
    {
        xTables.set( xTablesAccess->getTables(), UNO_SET_THROW );
    }
    else if ( m_xTables )
    {
        xTables = m_xTables.get();
    }
    else
    {
        if ( !m_xActiveConnection.is() )
            throw SQLException(DBA_RES(RID_STR_CONNECTION_INVALID),*this,SQLSTATE_GENERAL,1000,Any() );

        bool bCase = true;
        try
        {
            Reference<XDatabaseMetaData> xMeta = m_xActiveConnection->getMetaData();
            bCase = xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers();
        }
        catch(SQLException&)
        {
            DBG_UNHANDLED_EXCEPTION("dbaccess");
        }

        m_xTables = new OTableContainer(*this,m_aMutex,m_xActiveConnection,bCase,nullptr,nullptr,m_nInAppend);
        xTables = m_xTables.get();
        Sequence<OUString> aTableFilter { "%" };
        m_xTables->construct(aTableFilter,Sequence< OUString>());
    }

    return xTables;
}

void ORowSet::impl_resetTables_nothrow()
{
    if ( !m_xTables )
        return;

    try
    {
        m_xTables->dispose();
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("dbaccess");
    }

    m_xTables.clear();
}

void ORowSet::impl_initComposer_throw( OUString& _out_rCommandToExecute )
{
    bool bUseEscapeProcessing = impl_buildActiveCommand_throw( );
    _out_rCommandToExecute = m_aActiveCommand;
    if ( !bUseEscapeProcessing )
        return;

    if (m_bCommandFacetsDirty)
        m_xComposer = nullptr;

    Reference< XMultiServiceFactory > xFactory( m_xActiveConnection, UNO_QUERY );
    if ( !m_xComposer.is() && xFactory.is() )
    {
        try
        {
            m_xComposer.set( xFactory->createInstance( SERVICE_NAME_SINGLESELECTQUERYCOMPOSER ), UNO_QUERY_THROW );
        }
        catch (const Exception& ) { m_xComposer = nullptr; }
    }
    if ( !m_xComposer.is() )
        m_xComposer = new OSingleSelectQueryComposer( impl_getTables_throw(), m_xActiveConnection, m_aContext );

    m_xComposer->setCommand( m_aCommand,m_nCommandType );
    m_aActiveCommand = m_xComposer->getQuery();

    m_xComposer->setFilter( m_bApplyFilter ? m_aFilter : OUString() );
    m_xComposer->setHavingClause( m_bApplyFilter ? m_aHavingClause : OUString() );

    if ( m_bIgnoreResult )
    {   // append a "0=1" filter
        // don't simply overwrite an existent filter, this would lead to problems if this existent
        // filter contains parameters (since a keyset may add parameters itself)
        m_xComposer->setElementaryQuery( m_xComposer->getQuery( ) );
        m_xComposer->setFilter( "0 = 1" );
    }

    m_xComposer->setOrder( m_aOrder );
    m_xComposer->setGroup( m_aGroupBy );

    if ( !m_xColumns.is() )
    {
        Reference< XColumnsSupplier > xCols( m_xComposer, UNO_QUERY_THROW );
        m_xColumns = xCols->getColumns();
    }

    impl_initParametersContainer_nothrow();

    _out_rCommandToExecute = m_xComposer->getQueryWithSubstitution();

    m_bCommandFacetsDirty = false;
}

bool ORowSet::impl_buildActiveCommand_throw()
{
    // create the sql command
    // from a table name or get the command out of a query (not a view)
    // the last use the command as it is
    bool bDoEscapeProcessing = m_bUseEscapeProcessing;

    m_aActiveCommand.clear();
    OUString sCommand;

    if ( m_aCommand.isEmpty() )
        return bDoEscapeProcessing;

    switch (m_nCommandType)
    {
        case CommandType::TABLE:
        {
            impl_resetTables_nothrow();
            if ( bDoEscapeProcessing )
            {
                Reference< XNameAccess > xTables( impl_getTables_throw() );
                if ( xTables->hasByName(m_aCommand) )
                {
                }
                else
                {
                    OUString sMessage( DBA_RES( RID_STR_TABLE_DOES_NOT_EXIST ) );
                    throwGenericSQLException(sMessage.replaceAll( "$table$", m_aCommand ),*this);
                }
            }
            else
            {
                sCommand = "SELECT * FROM ";
                OUString sCatalog, sSchema, sTable;
                ::dbtools::qualifiedNameComponents( m_xActiveConnection->getMetaData(), m_aCommand, sCatalog, sSchema, sTable, ::dbtools::EComposeRule::InDataManipulation );
                sCommand += ::dbtools::composeTableNameForSelect( m_xActiveConnection, sCatalog, sSchema, sTable );
            }
        }
        break;

        case CommandType::QUERY:
        {
            Reference< XQueriesSupplier >  xQueriesAccess(m_xActiveConnection, UNO_QUERY);
            if (!xQueriesAccess.is())
                throw SQLException(DBA_RES(RID_STR_NO_XQUERIESSUPPLIER),*this,OUString(),0,Any());
            Reference< css::container::XNameAccess >  xQueries(xQueriesAccess->getQueries());
            if (xQueries->hasByName(m_aCommand))
            {
                Reference< XPropertySet > xQuery(xQueries->getByName(m_aCommand),UNO_QUERY);
                OSL_ENSURE(xQuery.is(),"ORowSet::impl_buildActiveCommand_throw: Query is NULL!");
                if ( xQuery.is() )
                {
                    xQuery->getPropertyValue(PROPERTY_COMMAND) >>= sCommand;
                    xQuery->getPropertyValue(PROPERTY_ESCAPE_PROCESSING) >>= bDoEscapeProcessing;
                    if ( bDoEscapeProcessing != m_bUseEscapeProcessing )
                    {
                        bool bOldValue = m_bUseEscapeProcessing;
                        m_bUseEscapeProcessing = bDoEscapeProcessing;
                        fireProperty(PROPERTY_ID_ESCAPE_PROCESSING,bOldValue,bDoEscapeProcessing);
                    }

                    OUString aCatalog,aSchema,aTable;
                    xQuery->getPropertyValue(PROPERTY_UPDATE_CATALOGNAME)   >>= aCatalog;
                    xQuery->getPropertyValue(PROPERTY_UPDATE_SCHEMANAME)    >>= aSchema;
                    xQuery->getPropertyValue(PROPERTY_UPDATE_TABLENAME)     >>= aTable;
                    if(!aTable.isEmpty())
                        m_aUpdateTableName = composeTableName( m_xActiveConnection->getMetaData(), aCatalog, aSchema, aTable, false, ::dbtools::EComposeRule::InDataManipulation );
                }
            }
            else
            {
                OUString sMessage( DBA_RES( RID_STR_QUERY_DOES_NOT_EXIST ) );
                throwGenericSQLException(sMessage.replaceAll( "$table$", m_aCommand ),*this);
            }
        }
        break;

        default:
            sCommand = m_aCommand;
            break;
    }

    m_aActiveCommand = sCommand;

    if ( m_aActiveCommand.isEmpty() && !bDoEscapeProcessing )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_NO_SQL_COMMAND ), StandardSQLState::FUNCTION_SEQUENCE_ERROR, *this );

    return bDoEscapeProcessing;
}

void ORowSet::impl_initParametersContainer_nothrow()
{
    OSL_PRECOND( !m_pParameters.is(), "ORowSet::impl_initParametersContainer_nothrow: already initialized the parameters!" );

    m_pParameters = new param::ParameterWrapperContainer( m_xComposer.get() );
    // copy the premature parameters into the final ones
    size_t nParamCount( std::min( m_pParameters->size(), m_aPrematureParamValues->size() ) );
    for ( size_t i=0; i<nParamCount; ++i )
    {
        (*m_pParameters)[i] = (*m_aPrematureParamValues)[i];
    }
}

void ORowSet::impl_disposeParametersContainer_nothrow()
{
    if ( !m_pParameters.is() )
        return;

    // copy the actual values to our "premature" ones, to preserve them for later use
    size_t nParamCount( m_pParameters->size() );
    m_aPrematureParamValues->resize( nParamCount );
    for ( size_t i=0; i<nParamCount; ++i )
    {
        (*m_aPrematureParamValues)[i] = (*m_pParameters)[i];
    }

    m_pParameters->dispose();
    m_pParameters = nullptr;
}

ORowSetValue& ORowSet::getParameterStorage(sal_Int32 parameterIndex)
{
    ::connectivity::checkDisposed( ORowSet_BASE1::rBHelper.bDisposed );
    if ( parameterIndex < 1 )
        throwInvalidIndexException( *this );

    if ( m_aParametersSet.size() < o3tl::make_unsigned(parameterIndex) )
        m_aParametersSet.resize( parameterIndex ,false);
    m_aParametersSet[parameterIndex - 1] = true;

    if ( m_pParameters.is() )
    {
        if ( m_bCommandFacetsDirty )
        // need to rebuild the parameters, since some property which contributes to the
        // complete command, and thus the parameters, changed
            impl_disposeParametersContainer_nothrow();
        if ( m_pParameters.is() )
        {
            if ( o3tl::make_unsigned(parameterIndex) > m_pParameters->size() )
                throwInvalidIndexException( *this );
            return (*m_pParameters)[ parameterIndex - 1 ];
        }
    }

    if ( m_aPrematureParamValues->size() < o3tl::make_unsigned(parameterIndex) )
        m_aPrematureParamValues->resize( parameterIndex );
    return (*m_aPrematureParamValues)[ parameterIndex - 1 ];
}

// XParameters
void SAL_CALL ORowSet::setNull( sal_Int32 parameterIndex, sal_Int32 /*sqlType*/ )
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    getParameterStorage( parameterIndex ).setNull();
    m_bParametersDirty = true;
}

void SAL_CALL ORowSet::setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const OUString& /*typeName*/ )
{
    setNull( parameterIndex, sqlType );
}

void ORowSet::setParameter(sal_Int32 parameterIndex, const ORowSetValue& x)
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    getParameterStorage( parameterIndex ) = x;
    m_bParametersDirty = true;
}

void SAL_CALL ORowSet::setBoolean( sal_Int32 parameterIndex, sal_Bool x )
{
    setParameter(parameterIndex, static_cast<bool>(x));
}

void SAL_CALL ORowSet::setByte( sal_Int32 parameterIndex, sal_Int8 x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setShort( sal_Int32 parameterIndex, sal_Int16 x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setInt( sal_Int32 parameterIndex, sal_Int32 x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setLong( sal_Int32 parameterIndex, sal_Int64 x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setFloat( sal_Int32 parameterIndex, float x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setDouble( sal_Int32 parameterIndex, double x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setString( sal_Int32 parameterIndex, const OUString& x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setBytes( sal_Int32 parameterIndex, const Sequence< sal_Int8 >& x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setDate( sal_Int32 parameterIndex, const css::util::Date& x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setTime( sal_Int32 parameterIndex, const css::util::Time& x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setTimestamp( sal_Int32 parameterIndex, const css::util::DateTime& x )
{
    setParameter(parameterIndex,x);
}

void SAL_CALL ORowSet::setBinaryStream( sal_Int32 parameterIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length )
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );
    ORowSetValue& rParamValue( getParameterStorage( parameterIndex ) );

    try
    {
        Sequence <sal_Int8> aData;
        x->readBytes(aData, length);
        rParamValue = aData;
        m_bParametersDirty = true;
        x->closeInput();
    }
    catch( Exception const & )
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw SQLException("ORowSet::setBinaryStream", *this, "S1000", 0,anyEx);
    }
}

void SAL_CALL ORowSet::setCharacterStream( sal_Int32 parameterIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length )
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );
    ORowSetValue& rParamValue( getParameterStorage( parameterIndex ) );
    try
    {
        Sequence <sal_Int8> aData;
        OUString aDataStr;
        // the data is given as character data and the length defines the character length
        sal_Int32 nSize = x->readBytes(aData, length * sizeof(sal_Unicode));
        if (nSize / sizeof(sal_Unicode))
            aDataStr = OUString(reinterpret_cast<sal_Unicode const *>(aData.getConstArray()), nSize / sizeof(sal_Unicode));
        m_bParametersDirty = true;
        rParamValue = aDataStr;
        rParamValue.setTypeKind( DataType::LONGVARCHAR );
        x->closeInput();
    }
    catch( Exception const & )
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw SQLException("ORowSet::setCharacterStream", *this, "S1000", 0, anyEx);
    }
}

void SAL_CALL ORowSet::setObject( sal_Int32 parameterIndex, const Any& x )
{
    if ( !::dbtools::implSetObject( this, parameterIndex, x ) )
    {   // there is no other setXXX call which can handle the value in x
        throw SQLException();
    }
    m_bParametersDirty = true;
}

void SAL_CALL ORowSet::setObjectWithInfo( sal_Int32 parameterIndex, const Any& x, sal_Int32 targetSqlType, sal_Int32 /*scale*/ )
{
    ::osl::MutexGuard aGuard( m_aColumnsMutex );
    ORowSetValue& rParamValue( getParameterStorage( parameterIndex ) );
    setObject( parameterIndex, x );
    rParamValue.setTypeKind( targetSqlType );
}

void SAL_CALL ORowSet::setRef( sal_Int32 /*parameterIndex*/, const Reference< XRef >& /*x*/ )
{
    ::dbtools::throwFeatureNotImplementedSQLException( "XParameters::setRef", *this );
}

void SAL_CALL ORowSet::setBlob( sal_Int32 /*parameterIndex*/, const Reference< XBlob >& /*x*/ )
{
    ::dbtools::throwFeatureNotImplementedSQLException( "XParameters::setBlob", *this );
}

void SAL_CALL ORowSet::setClob( sal_Int32 /*parameterIndex*/, const Reference< XClob >& /*x*/ )
{
    ::dbtools::throwFeatureNotImplementedSQLException( "XParameters::setClob", *this );
}

void SAL_CALL ORowSet::setArray( sal_Int32 /*parameterIndex*/, const Reference< XArray >& /*x*/ )
{
    ::dbtools::throwFeatureNotImplementedSQLException( "XParameters::setArray", *this );
}

void SAL_CALL ORowSet::clearParameters(  )
{
    ::connectivity::checkDisposed(ORowSet_BASE1::rBHelper.bDisposed);

    ::osl::MutexGuard aGuard( m_aColumnsMutex );

    size_t nParamCount( m_pParameters.is() ? m_pParameters->size() : m_aPrematureParamValues->size() );
    for ( size_t i=1; i<=nParamCount; ++i )
        getParameterStorage( static_cast<sal_Int32>(i) ).setNull();
    m_aParametersSet.clear();
}

Any SAL_CALL ORowSet::getWarnings(  )
{
    return m_aWarnings.getWarnings();
}

void SAL_CALL ORowSet::clearWarnings(  )
{
    m_aWarnings.clearWarnings();
}

void ORowSet::doCancelModification( )
{
    if ( isModification() )
    {
        // read-only flag restored
        impl_restoreDataColumnsWriteable_throw();
        m_pCache->cancelRowModification();
    }
    m_bModified = false;
    m_bIsInsertRow = false;
}

bool ORowSet::isModification( )
{
    return isNew();
}

bool ORowSet::isModified( )
{
    return m_bModified;
}

bool ORowSet::isNew( )
{
    return m_bNew;
}

bool ORowSet::isPropertyChangeNotificationEnabled() const
{
    return m_bPropChangeNotifyEnabled;
}

void ORowSet::checkUpdateIterator()
{
    if(!m_bIsInsertRow)
    {
        m_pCache->setUpdateIterator(m_aCurrentRow);
        m_aCurrentRow = m_pCache->m_aInsertRow;
        m_bIsInsertRow = true;
    }
}

void ORowSet::checkUpdateConditions(sal_Int32 columnIndex)
{
    checkCache();
    if ( m_nResultSetConcurrency == ResultSetConcurrency::READ_ONLY)
        ::dbtools::throwSQLException( DBA_RES( RID_STR_RESULT_IS_READONLY ), StandardSQLState::GENERAL_ERROR, *this );

    if ( rowDeleted() )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_ROW_ALREADY_DELETED ), StandardSQLState::INVALID_CURSOR_POSITION, *this );

    if ( m_aCurrentRow.isNull() )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_INVALID_CURSOR_STATE ), StandardSQLState::INVALID_CURSOR_STATE, *this );

    if ( columnIndex <= 0 || sal_Int32((*m_aCurrentRow)->size()) <= columnIndex )
        ::dbtools::throwSQLException( DBA_RES( RID_STR_INVALID_INDEX ), StandardSQLState::INVALID_DESCRIPTOR_INDEX, *this );
}

void SAL_CALL ORowSet::refreshRow(  )
{

    ORowSetNotifier aNotifier( this );
        // this will call cancelRowModification on the cache if necessary

    // notification order:
    if ( m_bModified && m_pCache )
        implCancelRowUpdates( false ); // do _not_ notify the IsModify - will do this ourself below

    // - column values
    ORowSetBase::refreshRow();

    // - IsModified
    // - IsNew
    aNotifier.fire( );
}

void ORowSet::impl_rebuild_throw(::osl::ResettableMutexGuard& _rGuard)
{
    Reference< XResultSet > xResultSet(m_xStatement->executeQuery());
    m_pCache->reset(xResultSet);
    m_aWarnings.setExternalWarnings( Reference< XWarningsSupplier >( xResultSet, UNO_QUERY ) );
    notifyAllListeners(_rGuard);
}

// ***********************************************************
//  ORowSetClone
// ***********************************************************

ORowSetClone::ORowSetClone( const Reference<XComponentContext>& _rContext, ORowSet& rParent, ::osl::Mutex* _pMutex )
             :OSubComponent(m_aMutex, rParent)
             ,ORowSetBase( _rContext, OComponentHelper::rBHelper, _pMutex )
             ,m_pParent(&rParent)
             ,m_nFetchDirection(rParent.m_nFetchDirection)
             ,m_nFetchSize(rParent.m_nFetchSize)
             ,m_bIsBookmarkable(true)
{

    m_nResultSetType        = rParent.m_nResultSetType;
    m_nResultSetConcurrency = ResultSetConcurrency::READ_ONLY;
    m_pMySelf               = this;
    m_bClone                = true;
    m_bBeforeFirst          = rParent.m_bBeforeFirst;
    m_bAfterLast            = rParent.m_bAfterLast;
    m_pCache                = rParent.m_pCache;
    m_aBookmark             = rParent.m_aBookmark;
    m_aCurrentRow           = m_pCache->createIterator(this);
    m_xNumberFormatTypes    = rParent.m_xNumberFormatTypes;

    m_aOldRow = m_pCache->registerOldRow();

    ::rtl::Reference< ::connectivity::OSQLColumns> aColumns = new ::connectivity::OSQLColumns();
    std::vector< OUString> aNames;

    OUString aDescription;
    Locale aLocale = SvtSysLocale().GetLanguageTag().getLocale();

    if ( rParent.m_pColumns )
    {
        Sequence< OUString> aSeq = rParent.m_pColumns->getElementNames();
        const OUString* pIter    = aSeq.getConstArray();
        const OUString* pEnd     = pIter + aSeq.getLength();
        aColumns->reserve(aSeq.getLength()+1);
        for(sal_Int32 i=1;pIter != pEnd ;++pIter,++i)
        {
            Reference<XPropertySet> xColumn;
            rParent.m_pColumns->getByName(*pIter) >>= xColumn;
            if(xColumn->getPropertySetInfo()->hasPropertyByName(PROPERTY_DESCRIPTION))
                aDescription = comphelper::getString(xColumn->getPropertyValue(PROPERTY_DESCRIPTION));

            OUString sParseLabel;
            xColumn->getPropertyValue(PROPERTY_LABEL) >>= sParseLabel;
            ORowSetColumn* pColumn = new ORowSetColumn( rParent.getMetaData(),
                                                                this,
                                                                i,
                                                                rParent.m_xActiveConnection->getMetaData(),
                                                                aDescription,
                                                                sParseLabel,
                [this] (sal_Int32 const column) -> ORowSetValue const& {
                    return this->getValue(column);
                });
            aColumns->emplace_back(pColumn);
            pColumn->setName(*pIter);
            aNames.push_back(*pIter);
            m_aDataColumns.push_back(pColumn);

            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_ALIGN,xColumn->getPropertyValue(PROPERTY_ALIGN));
            sal_Int32 nFormatKey = 0;<--- Assignment 'nFormatKey=0', assigned value is 0
            xColumn->getPropertyValue(PROPERTY_NUMBERFORMAT) >>= nFormatKey;
            if(!nFormatKey && xColumn.is() && m_xNumberFormatTypes.is())<--- Condition '!nFormatKey' is always true
                nFormatKey = ::dbtools::getDefaultNumberFormat(xColumn,m_xNumberFormatTypes,aLocale);
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_NUMBERFORMAT,makeAny(nFormatKey));
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_RELATIVEPOSITION,xColumn->getPropertyValue(PROPERTY_RELATIVEPOSITION));
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_WIDTH,xColumn->getPropertyValue(PROPERTY_WIDTH));
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_HIDDEN,xColumn->getPropertyValue(PROPERTY_HIDDEN));
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_CONTROLMODEL,xColumn->getPropertyValue(PROPERTY_CONTROLMODEL));
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_HELPTEXT,xColumn->getPropertyValue(PROPERTY_HELPTEXT));
            pColumn->setFastPropertyValue_NoBroadcast(PROPERTY_ID_CONTROLDEFAULT,xColumn->getPropertyValue(PROPERTY_CONTROLDEFAULT));

        }
    }
    Reference<XDatabaseMetaData> xMeta = rParent.m_xActiveConnection->getMetaData();
    m_pColumns.reset( new ORowSetDataColumns(xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers(),
                                        aColumns,*this,m_aMutex,aNames) );

    sal_Int32 const nRT = PropertyAttribute::READONLY   | PropertyAttribute::TRANSIENT;

    // sdb.RowSet Properties
    registerMayBeVoidProperty(PROPERTY_ACTIVE_CONNECTION,PROPERTY_ID_ACTIVE_CONNECTION, PropertyAttribute::MAYBEVOID|PropertyAttribute::READONLY,   &rParent.m_aActiveConnection,   cppu::UnoType<XConnection>::get());
    registerProperty(PROPERTY_RESULTSETCONCURRENCY, PROPERTY_ID_RESULTSETCONCURRENCY,   PropertyAttribute::READONLY,    &m_nResultSetConcurrency,::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_RESULTSETTYPE,        PROPERTY_ID_RESULTSETTYPE,          PropertyAttribute::READONLY,    &m_nResultSetType,      ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_FETCHDIRECTION,       PROPERTY_ID_FETCHDIRECTION,         PropertyAttribute::TRANSIENT,   &m_nFetchDirection,     ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_FETCHSIZE,            PROPERTY_ID_FETCHSIZE,              PropertyAttribute::TRANSIENT,   &m_nFetchSize,          ::cppu::UnoType<sal_Int32>::get());
    registerProperty(PROPERTY_ISBOOKMARKABLE,       PROPERTY_ID_ISBOOKMARKABLE,         nRT,                            &m_bIsBookmarkable,      cppu::UnoType<bool>::get());
}

ORowSetClone::~ORowSetClone()
{
}

// css::XTypeProvider
Sequence< Type > ORowSetClone::getTypes()
{
    return ::comphelper::concatSequences(OSubComponent::getTypes(),ORowSetBase::getTypes());
}

// css::XInterface
Any ORowSetClone::queryInterface( const Type & rType )
{
    Any aRet = ORowSetBase::queryInterface(rType);
    if(!aRet.hasValue())
        aRet = OSubComponent::queryInterface(rType);
    return aRet;
}

void ORowSetClone::acquire() throw()
{
    OSubComponent::acquire();
}

void ORowSetClone::release() throw()
{
    OSubComponent::release();
}

// XServiceInfo
OUString ORowSetClone::getImplementationName(  )
{
    return "com.sun.star.sdb.ORowSetClone";
}

sal_Bool ORowSetClone::supportsService( const OUString& _rServiceName )
{
    return cppu::supportsService(this, _rServiceName);
}

Sequence< OUString > ORowSetClone::getSupportedServiceNames(  )
{
    return { SERVICE_SDBC_RESULTSET, SERVICE_SDB_RESULTSET };
}

// OComponentHelper
void ORowSetClone::disposing()
{
    MutexGuard aGuard( m_aMutex );
    ORowSetBase::disposing();

    m_pParent   = nullptr;
    m_pMutex    = &m_aMutex; // this must be done here because someone could hold a ref to us and try to do something
    OSubComponent::disposing();
}

// XCloseable
void ORowSetClone::close()
{
    {
        MutexGuard aGuard( m_aMutex );
        if (OComponentHelper::rBHelper.bDisposed)
            throw DisposedException();
    }
    dispose();
}

// comphelper::OPropertyArrayUsageHelper
::cppu::IPropertyArrayHelper* ORowSetClone::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}

// cppu::OPropertySetHelper
::cppu::IPropertyArrayHelper& SAL_CALL ORowSetClone::getInfoHelper()
{
    return *::comphelper::OPropertyArrayUsageHelper<ORowSetClone>::getArrayHelper();
}

Sequence< sal_Int8 > ORowSetClone::getUnoTunnelId()
{
    static ::cppu::OImplementationId implId;

    return implId.getImplementationId();
}

// css::XUnoTunnel
sal_Int64 SAL_CALL ORowSetClone::getSomething( const Sequence< sal_Int8 >& rId )
{
    if (isUnoTunnelId<ORowSetClone>(rId))
        return reinterpret_cast<sal_Int64>(this);

    return 0;
}

void SAL_CALL ORowSetClone::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)
{
    if ( nHandle == PROPERTY_ID_FETCHSIZE )
    {
        if ( m_pParent )
            m_pParent->setFastPropertyValue_NoBroadcast( nHandle, rValue );
    }

    OPropertyStateContainer::setFastPropertyValue_NoBroadcast(nHandle,rValue);
}

void ORowSetClone::doCancelModification( )
{
}

bool ORowSetClone::isModification( )
{
    return false;
}

bool ORowSetClone::isModified( )
{
    return false;
}

bool ORowSetClone::isNew( )
{
    return false;
}

void SAL_CALL ORowSetClone::execute(  )
{
    throwFunctionNotSupportedSQLException( "RowSetClone::XRowSet::execute", *this );
}

void SAL_CALL ORowSetClone::addRowSetListener( const Reference< XRowSetListener >& )
{
    throwFunctionNotSupportedRuntimeException( "RowSetClone::XRowSet", *this );
}

void SAL_CALL ORowSetClone::removeRowSetListener( const Reference< XRowSetListener >& )
{
    throwFunctionNotSupportedRuntimeException( "RowSetClone::XRowSet", *this );
}

} // dbaccess

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */