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
/* -*- 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 <osl/diagnose.h>
#include <odbc/OStatement.hxx>
#include <odbc/OConnection.hxx>
#include <odbc/OResultSet.hxx>
#include <comphelper/property.hxx>
#include <odbc/OTools.hxx>
#include <com/sun/star/sdbc/ResultSetConcurrency.hpp>
#include <com/sun/star/sdbc/ResultSetType.hpp>
#include <com/sun/star/sdbc/FetchDirection.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <comphelper/sequence.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <comphelper/types.hxx>
#include <rtl/strbuf.hxx>
#include <algorithm>
#include <strings.hrc>
#include <connectivity/dbexception.hxx>

using namespace ::comphelper;

#define THROW_SQL(x) \
    OTools::ThrowException(m_pConnection.get(),x,m_aStatementHandle,SQL_HANDLE_STMT,*this)


using namespace connectivity::odbc;

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
using namespace com::sun::star::container;
using namespace com::sun::star::io;
using namespace com::sun::star::util;

OStatement_Base::OStatement_Base(OConnection* _pConnection )
    :OStatement_BASE(m_aMutex)
    ,OPropertySetHelper(OStatement_BASE::rBHelper)
    ,m_pConnection(_pConnection)
    ,m_aStatementHandle(SQL_NULL_HANDLE)
    ,m_pRowStatusArray(nullptr)
{
    osl_atomic_increment( &m_refCount );
    m_aStatementHandle = m_pConnection->createStatementHandle();

    //setMaxFieldSize(0);
    // Don't do this. By ODBC spec, "0" is the default for the SQL_ATTR_MAX_LENGTH attribute. We once introduced
    // this line since a PostgreSQL ODBC driver had a default other than 0. However, current drivers (at least 8.3
    // and later) have a proper default of 0, so there should be no need anymore.
    // On the other hand, the NotesSQL driver (IBM's ODBC driver for the Lotus Notes series) wrongly interprets
    // "0" as "0", whereas the ODBC spec says it should in fact mean "unlimited".
    // So, removing this line seems to be the best option for now.
    // If we ever again encounter an ODBC driver which needs this option, then we should introduce a data source
    // setting for it, instead of unconditionally doing it.

    osl_atomic_decrement( &m_refCount );
}

OStatement_Base::~OStatement_Base()
{
    OSL_ENSURE(!m_aStatementHandle,"Sohould ne null here!");
}

void OStatement_Base::disposeResultSet()
{
    // free the cursor if alive
    Reference< XComponent > xComp(m_xResultSet.get(), UNO_QUERY);
    if (xComp.is())
        xComp->dispose();
    m_xResultSet.clear();
}

void SAL_CALL OStatement_Base::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    disposeResultSet();
    ::comphelper::disposeComponent(m_xGeneratedStatement);

    OSL_ENSURE(m_aStatementHandle,"OStatement_BASE2::disposing: StatementHandle is null!");
    if (m_pConnection.is())
    {
        m_pConnection->freeStatementHandle(m_aStatementHandle);
        m_pConnection.clear();
    }
    OSL_ENSURE(!m_aStatementHandle,"Sohould ne null here!");

    OStatement_BASE::disposing();
}

void OStatement_BASE2::disposing()
{
    ::osl::MutexGuard aGuard1(m_aMutex);
    OStatement_Base::disposing();
}

Any SAL_CALL OStatement_Base::queryInterface( const Type & rType )
{
    if ( m_pConnection.is() && !m_pConnection->isAutoRetrievingEnabled() && rType == cppu::UnoType<XGeneratedResultSet>::get())
        return Any();
    Any aRet = OStatement_BASE::queryInterface(rType);
    return aRet.hasValue() ? aRet : OPropertySetHelper::queryInterface(rType);
}

Sequence< Type > SAL_CALL OStatement_Base::getTypes(  )
{
    ::cppu::OTypeCollection aTypes( cppu::UnoType<XMultiPropertySet>::get(),
                                    cppu::UnoType<XFastPropertySet>::get(),
                                    cppu::UnoType<XPropertySet>::get());
    Sequence< Type > aOldTypes = OStatement_BASE::getTypes();
    if ( m_pConnection.is() && !m_pConnection->isAutoRetrievingEnabled() )
    {
        auto newEnd = std::remove(aOldTypes.begin(), aOldTypes.end(),
                                  cppu::UnoType<XGeneratedResultSet>::get());
        aOldTypes.realloc(std::distance(aOldTypes.begin(), newEnd));
    }

    return ::comphelper::concatSequences(aTypes.getTypes(),aOldTypes);
}

Reference< XResultSet > SAL_CALL OStatement_Base::getGeneratedValues(  )
{
    OSL_ENSURE( m_pConnection.is() && m_pConnection->isAutoRetrievingEnabled(),"Illegal call here. isAutoRetrievingEnabled is false!");
    Reference< XResultSet > xRes;
    if ( m_pConnection.is() )
    {
        OUString sStmt = m_pConnection->getTransformedGeneratedStatement(m_sSqlStatement);
        if ( !sStmt.isEmpty() )
        {
            ::comphelper::disposeComponent(m_xGeneratedStatement);
            m_xGeneratedStatement = m_pConnection->createStatement();
            xRes = m_xGeneratedStatement->executeQuery(sStmt);
        }
    }
    return xRes;
}

void SAL_CALL OStatement_Base::cancel(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);

    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    N3SQLCancel(m_aStatementHandle);
}


void SAL_CALL OStatement_Base::close(  )
{
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OStatement_BASE::rBHelper.bDisposed);

    }
    dispose();
}


void SAL_CALL OStatement::clearBatch(  )
{

}

void OStatement_Base::reset()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    clearWarnings ();

    if (m_xResultSet.get().is())
    {
        clearMyResultSet();
    }
    if(m_aStatementHandle)
    {
        THROW_SQL(N3SQLFreeStmt(m_aStatementHandle, SQL_CLOSE));
    }
}

// clearMyResultSet
// If a ResultSet was created for this Statement, close it
void OStatement_Base::clearMyResultSet()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);

    try
    {
        Reference<XCloseable> xCloseable(
            m_xResultSet.get(), css::uno::UNO_QUERY);
        if ( xCloseable.is() )
            xCloseable->close();
    }
    catch( const DisposedException& ) { }

    m_xResultSet.clear();
}

SQLLEN OStatement_Base::getRowCount()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    SQLLEN numRows = 0;

    try {
        THROW_SQL(N3SQLRowCount(m_aStatementHandle,&numRows));
    }
    catch (const SQLException&)
    {
    }
    return numRows;
}

// lockIfNecessary
// If the given SQL statement contains a 'FOR UPDATE' clause, change
// the concurrency to lock so that the row can then be updated.  Returns
// true if the concurrency has been changed
bool OStatement_Base::lockIfNecessary (const OUString& sql)
{
    bool rc = false;

    // First, convert the statement to upper case

    OUString sqlStatement = sql.toAsciiUpperCase ();

    // Now, look for the FOR UPDATE keywords.  If there is any extra white
    // space between the FOR and UPDATE, this will fail.

    sal_Int32 index = sqlStatement.indexOf(" FOR UPDATE");

    // We found it.  Change our concurrency level to ensure that the
    // row can be updated.

    if (index > 0)
    {
        OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
        try
        {
            THROW_SQL((setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY, SQL_CONCUR_LOCK)));
        }
        catch (const SQLWarning& warn)
        {
            // Catch any warnings and place on the warning stack
            setWarning (warn);
        }
        rc = true;
    }

    return rc;
}

// setWarning
// Sets the warning


void OStatement_Base::setWarning (const SQLWarning &ex)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    m_aLastWarning = ex;
}


// getColumnCount
// Return the number of columns in the ResultSet
sal_Int32 OStatement_Base::getColumnCount()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    sal_Int16   numCols = 0;
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");

    try {
        THROW_SQL(N3SQLNumResultCols(m_aStatementHandle,&numCols));
    }
    catch (const SQLException&)
    {
    }
    return numCols;
}


sal_Bool SAL_CALL OStatement_Base::execute( const OUString& sql )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);
    m_sSqlStatement = sql;


    OString aSql(OUStringToOString(sql,getOwnConnection()->getTextEncoding()));

    bool hasResultSet = false;
    SQLWarning aWarning;

    // Reset the statement handle and warning

    reset();

    // Check for a 'FOR UPDATE' statement.  If present, change
    // the concurrency to lock

    lockIfNecessary (sql);

    // Call SQLExecDirect
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");

    try {
        THROW_SQL(N3SQLExecDirect(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(aSql.getStr())), aSql.getLength()));
    }
    catch (const SQLWarning& ex) {

        // Save pointer to warning and save with ResultSet
        // object once it is created.

        aWarning = ex;<--- Variable 'aWarning' is assigned a value that is never used.
    }

    // Now determine if there is a result set associated with
    // the SQL statement that was executed.  Get the column
    // count, and if it is not zero, there is a result set.

    if (getColumnCount () > 0)
    {
        hasResultSet = true;
    }

    return hasResultSet;
}

// getResultSet
// getResultSet returns the current result as a ResultSet.  It
// returns NULL if the current result is not a ResultSet.

Reference< XResultSet > OStatement_Base::getResultSet(bool checkCount)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    if (m_xResultSet.get().is())  // if resultset already retrieved,
    {
        // throw exception to avoid sequence error
        ::dbtools::throwFunctionSequenceException(*this);
    }

    OResultSet* pRs = nullptr;
    sal_Int32 numCols = 1;

    // If we already know we have result columns, checkCount
    // is false.  This is an optimization to prevent unneeded
    // calls to getColumnCount

    if (checkCount)
        numCols = getColumnCount ();

    // Only return a result set if there are result columns

    if (numCols > 0)
    {
        OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
        pRs = createResulSet();
        pRs->construct();

        // Save a copy of our last result set
        // Changed to save copy at getResultSet.
        //m_xResultSet = rs;
    }
    else
        clearMyResultSet ();

    return pRs;
}

// getStmtOption
// Invoke SQLGetStmtOption with the given option.


template < typename T, SQLINTEGER BufferLength > T OStatement_Base::getStmtOption (SQLINTEGER fOption) const
{
    T result (0);
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    N3SQLGetStmtAttr(m_aStatementHandle, fOption, &result, BufferLength, nullptr);
    return result;
}
template < typename T, SQLINTEGER BufferLength > SQLRETURN OStatement_Base::setStmtOption (SQLINTEGER fOption, T value) const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLPOINTER sv = reinterpret_cast<SQLPOINTER>(value);
    return N3SQLSetStmtAttr(m_aStatementHandle, fOption, sv, BufferLength);
}


Reference< XResultSet > SAL_CALL OStatement_Base::executeQuery( const OUString& sql )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    Reference< XResultSet > xRS;

    // Execute the statement.  If execute returns true, a result
    // set exists.

    if (execute (sql))
    {
        xRS = getResultSet (false);
        m_xResultSet = xRS;
    }
    else
    {
        // No ResultSet was produced.  Raise an exception
        m_pConnection->throwGenericSQLException(STR_NO_RESULTSET,*this);
    }
    return xRS;
}


Reference< XConnection > SAL_CALL OStatement_Base::getConnection(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);

    return Reference< XConnection >(m_pConnection.get());
}


Any SAL_CALL OStatement::queryInterface( const Type & rType )
{
    Any aRet = ::cppu::queryInterface(rType,static_cast< XBatchExecution*> (this));
    return aRet.hasValue() ? aRet : OStatement_Base::queryInterface(rType);
}


void SAL_CALL OStatement::addBatch( const OUString& sql )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    m_aBatchVector.push_back(sql);
}

Sequence< sal_Int32 > SAL_CALL OStatement::executeBatch(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);

    OStringBuffer aBatchSql;
    sal_Int32 nLen = m_aBatchVector.size();

    for (auto const& elem : m_aBatchVector)
    {
        aBatchSql.append(OUStringToOString(elem,getOwnConnection()->getTextEncoding()));
        aBatchSql.append(";");
    }

    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    auto s = aBatchSql.makeStringAndClear();
    THROW_SQL(N3SQLExecDirect(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(s.getStr())), s.getLength()));

    Sequence< sal_Int32 > aRet(nLen);
    sal_Int32* pArray = aRet.getArray();
    for(sal_Int32 j=0;j<nLen;++j)
    {
        SQLRETURN nError = N3SQLMoreResults(m_aStatementHandle);
        if(nError == SQL_SUCCESS)
        {
            SQLLEN nRowCount=0;
            N3SQLRowCount(m_aStatementHandle,&nRowCount);
            pArray[j] = nRowCount;
        }
    }
    return aRet;
}


sal_Int32 SAL_CALL OStatement_Base::executeUpdate( const OUString& sql )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    sal_Int32 numRows = -1;

    // Execute the statement.  If execute returns false, a
    // row count exists.

    if (!execute (sql)) {
        numRows = getUpdateCount();
    }
    else {

        // No update count was produced (a ResultSet was).  Raise
        // an exception

        ::connectivity::SharedResources aResources;
        const OUString sError( aResources.getResourceString(STR_NO_ROWCOUNT));
        throw SQLException (sError, *this,OUString(),0,Any());
    }
    return numRows;

}


Reference< XResultSet > SAL_CALL OStatement_Base::getResultSet(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    m_xResultSet = getResultSet(true);
    return m_xResultSet;
}


sal_Int32 SAL_CALL OStatement_Base::getUpdateCount(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    sal_Int32 rowCount = -1;

    // Only return a row count for SQL statements that did not
    // return a result set.

    if (getColumnCount () == 0)
        rowCount = getRowCount ();

    return rowCount;
}


sal_Bool SAL_CALL OStatement_Base::getMoreResults(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    SQLWarning  warning;
    bool hasResultSet = false;

    // clear previous warnings

    clearWarnings ();

    // Call SQLMoreResults
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");

    try {
        hasResultSet = N3SQLMoreResults(m_aStatementHandle) == SQL_SUCCESS;
    }
    catch (const SQLWarning &ex) {

        // Save pointer to warning and save with ResultSet
        // object once it is created.

        warning = ex;
    }

    // There are more results (it may not be a result set, though)

    if (hasResultSet)
    {

        // Now determine if there is a result set associated
        // with the SQL statement that was executed.  Get the
        // column count, and if it is zero, there is not a
        // result set.

        if (getColumnCount () == 0)
            hasResultSet = false;
    }

    // Set the warning for the statement, if one was generated

    setWarning (warning);

    // Return the result set indicator

    return hasResultSet;
}


Any SAL_CALL OStatement_Base::getWarnings(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    return makeAny(m_aLastWarning);
}


void SAL_CALL OStatement_Base::clearWarnings(  )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OStatement_BASE::rBHelper.bDisposed);


    m_aLastWarning = SQLWarning();
}


sal_Int64 OStatement_Base::getQueryTimeOut() const
{
    return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_QUERY_TIMEOUT);
}

sal_Int64 OStatement_Base::getMaxRows() const
{
    return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_ROWS);
}

sal_Int32 OStatement_Base::getResultSetConcurrency() const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLULEN nValue (getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY));
    if(nValue == SQL_CONCUR_READ_ONLY)
        nValue = ResultSetConcurrency::READ_ONLY;
    else
        nValue = ResultSetConcurrency::UPDATABLE;
    return nValue;
}

sal_Int32 OStatement_Base::getResultSetType() const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLULEN nValue (getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE));
    switch(nValue)
    {
        case SQL_CURSOR_FORWARD_ONLY:
            nValue = ResultSetType::FORWARD_ONLY;
            break;
        case SQL_CURSOR_KEYSET_DRIVEN:
        case SQL_CURSOR_STATIC:
            nValue = ResultSetType::SCROLL_INSENSITIVE;
            break;
        case SQL_CURSOR_DYNAMIC:
            nValue = ResultSetType::SCROLL_SENSITIVE;
            break;
        default:
            OSL_FAIL("Unknown ODBC Cursor Type");
    }

    return nValue;
}

sal_Int32 OStatement_Base::getFetchDirection() const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLULEN nValue (getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SCROLLABLE));
    switch(nValue)
    {
        case SQL_SCROLLABLE:
            nValue = FetchDirection::REVERSE;
            break;
        default:
            nValue = FetchDirection::FORWARD;
            break;
    }

    return nValue;
}

sal_Int32 OStatement_Base::getFetchSize() const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_ARRAY_SIZE);
}

sal_Int64 OStatement_Base::getMaxFieldSize() const
{
    return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_LENGTH);
}

OUString OStatement_Base::getCursorName() const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLCHAR pName[258];
    SQLSMALLINT nRealLen = 0;
    N3SQLGetCursorName(m_aStatementHandle,pName,256,&nRealLen);
    return OUString::createFromAscii(reinterpret_cast<char*>(pName));
}

void OStatement_Base::setQueryTimeOut(sal_Int64 seconds)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_QUERY_TIMEOUT,seconds);
}

void OStatement_Base::setMaxRows(sal_Int64 _par0)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_ROWS, _par0);
}

void OStatement_Base::setResultSetConcurrency(sal_Int32 _par0)
{
    SQLULEN nSet;
    if(_par0 == ResultSetConcurrency::READ_ONLY)
        nSet = SQL_CONCUR_READ_ONLY;
    else
        nSet = SQL_CONCUR_VALUES;

    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY, nSet);
}

void OStatement_Base::setResultSetType(sal_Int32 _par0)
{

    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_BIND_TYPE, SQL_BIND_BY_COLUMN);

    bool bUseBookmark = isUsingBookmarks();
    SQLULEN nSet( SQL_UNSPECIFIED );
    switch(_par0)
    {
        case ResultSetType::FORWARD_ONLY:
            nSet =  SQL_UNSPECIFIED;
            break;
        case ResultSetType::SCROLL_INSENSITIVE:
            nSet =  SQL_INSENSITIVE;
            setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_KEYSET_DRIVEN);
            break;
        case ResultSetType::SCROLL_SENSITIVE:
            if(bUseBookmark)
            {
                SQLUINTEGER nCurProp = getCursorProperties(SQL_CURSOR_DYNAMIC,true);
                if((nCurProp & SQL_CA1_BOOKMARK) != SQL_CA1_BOOKMARK) // check if bookmark for this type isn't supported
                { // we have to test the next one
                    nCurProp = getCursorProperties(SQL_CURSOR_KEYSET_DRIVEN,true);
                    bool bNotBookmarks = ((nCurProp & SQL_CA1_BOOKMARK) != SQL_CA1_BOOKMARK);
                    nCurProp = getCursorProperties(SQL_CURSOR_KEYSET_DRIVEN,false);
                    nSet = SQL_CURSOR_KEYSET_DRIVEN;
                    if( bNotBookmarks ||
                        ((nCurProp & SQL_CA2_SENSITIVITY_DELETIONS) != SQL_CA2_SENSITIVITY_DELETIONS) ||
                        ((nCurProp & SQL_CA2_SENSITIVITY_ADDITIONS) != SQL_CA2_SENSITIVITY_ADDITIONS))
                    {
                        // bookmarks for keyset isn't supported so reset bookmark setting
                        setUsingBookmarks(false);
                        nSet = SQL_CURSOR_DYNAMIC;
                    }
                }
                else
                    nSet = SQL_CURSOR_DYNAMIC;
            }
            else
                nSet = SQL_CURSOR_DYNAMIC;
            if( setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, nSet) != SQL_SUCCESS )
            {
                setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_KEYSET_DRIVEN);
            }
            nSet =  SQL_SENSITIVE;
            break;
        default:
            OSL_FAIL( "OStatement_Base::setResultSetType: invalid result set type!" );
            break;
    }


    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SENSITIVITY, nSet);
}

void OStatement_Base::setEscapeProcessing( const bool _bEscapeProc )
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLULEN nEscapeProc( _bEscapeProc ? SQL_NOSCAN_OFF : SQL_NOSCAN_ON );
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_NOSCAN, nEscapeProc);
}


void OStatement_Base::setFetchDirection(sal_Int32 _par0)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    if(_par0 == FetchDirection::FORWARD)
    {
        setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SCROLLABLE, SQL_NONSCROLLABLE);
    }
    else if(_par0 == FetchDirection::REVERSE)
    {
        setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SCROLLABLE, SQL_SCROLLABLE);
    }
}

void OStatement_Base::setFetchSize(sal_Int32 _par0)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    OSL_ENSURE(_par0>0,"Illegal fetch size!");
    if ( _par0 > 0 )
    {
        setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_ARRAY_SIZE, _par0);

        delete[] m_pRowStatusArray;
        m_pRowStatusArray = new SQLUSMALLINT[_par0];
        setStmtOption<SQLUSMALLINT*, SQL_IS_POINTER>(SQL_ATTR_ROW_STATUS_PTR, m_pRowStatusArray);
    }
}

void OStatement_Base::setMaxFieldSize(sal_Int64 _par0)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_LENGTH, _par0);
}

void OStatement_Base::setCursorName(const OUString &_par0)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    OString aName(OUStringToOString(_par0,getOwnConnection()->getTextEncoding()));
    N3SQLSetCursorName(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(aName.getStr())), static_cast<SQLSMALLINT>(aName.getLength()));
}

bool OStatement_Base::isUsingBookmarks() const
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    return SQL_UB_OFF != getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS);
}

bool OStatement_Base::getEscapeProcessing() const
{
    OSL_ENSURE( m_aStatementHandle, "StatementHandle is null!" );
    return SQL_NOSCAN_OFF == getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS);
}

void OStatement_Base::setUsingBookmarks(bool _bUseBookmark)
{
    OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!");
    SQLULEN nValue = _bUseBookmark ? SQL_UB_VARIABLE : SQL_UB_OFF;
    setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS, nValue);
}

::cppu::IPropertyArrayHelper* OStatement_Base::createArrayHelper( ) const
{
    Sequence< Property > aProps(10);
    Property* pProperties = aProps.getArray();
    sal_Int32 nPos = 0;
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME),
        PROPERTY_ID_CURSORNAME, cppu::UnoType<OUString>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ESCAPEPROCESSING),
        PROPERTY_ID_ESCAPEPROCESSING, cppu::UnoType<bool>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION),
        PROPERTY_ID_FETCHDIRECTION, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE),
        PROPERTY_ID_FETCHSIZE, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_MAXFIELDSIZE),
        PROPERTY_ID_MAXFIELDSIZE, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_MAXROWS),
        PROPERTY_ID_MAXROWS, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_QUERYTIMEOUT),
        PROPERTY_ID_QUERYTIMEOUT, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY),
        PROPERTY_ID_RESULTSETCONCURRENCY, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE),
        PROPERTY_ID_RESULTSETTYPE, cppu::UnoType<sal_Int32>::get(), 0);
    pProperties[nPos++] = css::beans::Property(::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_USEBOOKMARKS),
        PROPERTY_ID_USEBOOKMARKS, cppu::UnoType<bool>::get(), 0);

    return new ::cppu::OPropertyArrayHelper(aProps);
}


::cppu::IPropertyArrayHelper & OStatement_Base::getInfoHelper()
{
    return *getArrayHelper();
}

sal_Bool OStatement_Base::convertFastPropertyValue(
                            Any & rConvertedValue,
                            Any & rOldValue,
                            sal_Int32 nHandle,
                            const Any& rValue )
{
    bool bConverted = false;
    try
    {
        switch(nHandle)
        {
            case PROPERTY_ID_QUERYTIMEOUT:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getQueryTimeOut());
                break;

            case PROPERTY_ID_MAXFIELDSIZE:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getMaxFieldSize());
                break;

            case PROPERTY_ID_MAXROWS:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getMaxRows());
                break;

            case PROPERTY_ID_CURSORNAME:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getCursorName());
                break;

            case PROPERTY_ID_RESULTSETCONCURRENCY:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getResultSetConcurrency());
                break;

            case PROPERTY_ID_RESULTSETTYPE:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getResultSetType());
                break;

            case PROPERTY_ID_FETCHDIRECTION:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchDirection());
                break;

            case PROPERTY_ID_FETCHSIZE:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchSize());
                break;

            case PROPERTY_ID_USEBOOKMARKS:
                bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, isUsingBookmarks());
                break;

            case PROPERTY_ID_ESCAPEPROCESSING:
                bConverted = ::comphelper::tryPropertyValue( rConvertedValue, rOldValue, rValue, getEscapeProcessing() );
                break;

        }
    }
    catch(const SQLException&)
    {
        //  throw Exception(e.Message,*this);
    }
    return bConverted;
}

void OStatement_Base::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)
{
    try
    {
        switch(nHandle)
        {
            case PROPERTY_ID_QUERYTIMEOUT:
                setQueryTimeOut(comphelper::getINT64(rValue));
                break;
            case PROPERTY_ID_MAXFIELDSIZE:
                setMaxFieldSize(comphelper::getINT64(rValue));
                break;
            case PROPERTY_ID_MAXROWS:
                setMaxRows(comphelper::getINT64(rValue));
                break;
            case PROPERTY_ID_CURSORNAME:
                setCursorName(comphelper::getString(rValue));
                break;
            case PROPERTY_ID_RESULTSETCONCURRENCY:
                setResultSetConcurrency(comphelper::getINT32(rValue));
                break;
            case PROPERTY_ID_RESULTSETTYPE:
                setResultSetType(comphelper::getINT32(rValue));
                break;
            case PROPERTY_ID_FETCHDIRECTION:
                setFetchDirection(comphelper::getINT32(rValue));
                break;
            case PROPERTY_ID_FETCHSIZE:
                setFetchSize(comphelper::getINT32(rValue));
                break;
            case PROPERTY_ID_USEBOOKMARKS:
                setUsingBookmarks(comphelper::getBOOL(rValue));
                break;
            case PROPERTY_ID_ESCAPEPROCESSING:
                setEscapeProcessing( ::comphelper::getBOOL( rValue ) );
                break;
            default:
                OSL_FAIL( "OStatement_Base::setFastPropertyValue_NoBroadcast: what property?" );
                break;
        }
    }
    catch(const SQLException& )
    {
        //  throw Exception(e.Message,*this);
    }
}

void OStatement_Base::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const
{
    switch(nHandle)
    {
        case PROPERTY_ID_QUERYTIMEOUT:
            rValue <<= getQueryTimeOut();
            break;
        case PROPERTY_ID_MAXFIELDSIZE:
            rValue <<= getMaxFieldSize();
            break;
        case PROPERTY_ID_MAXROWS:
            rValue <<= getMaxRows();
            break;
        case PROPERTY_ID_CURSORNAME:
            rValue <<= getCursorName();
            break;
        case PROPERTY_ID_RESULTSETCONCURRENCY:
            rValue <<= getResultSetConcurrency();
            break;
        case PROPERTY_ID_RESULTSETTYPE:
            rValue <<= getResultSetType();
            break;
        case PROPERTY_ID_FETCHDIRECTION:
            rValue <<= getFetchDirection();
            break;
        case PROPERTY_ID_FETCHSIZE:
            rValue <<= getFetchSize();
            break;
        case PROPERTY_ID_USEBOOKMARKS:
            rValue <<= isUsingBookmarks();
            break;
        case PROPERTY_ID_ESCAPEPROCESSING:
            rValue <<= getEscapeProcessing();
            break;
        default:
            OSL_FAIL( "OStatement_Base::getFastPropertyValue: what property?" );
            break;
    }
}

IMPLEMENT_SERVICE_INFO(OStatement,"com.sun.star.sdbcx.OStatement","com.sun.star.sdbc.Statement");

void SAL_CALL OStatement_Base::acquire() throw()
{
    OStatement_BASE::acquire();
}

void SAL_CALL OStatement_Base::release() throw()
{
    OStatement_BASE::release();
}

void SAL_CALL OStatement::acquire() throw()
{
    OStatement_BASE2::acquire();
}

void SAL_CALL OStatement::release() throw()
{
    OStatement_BASE2::release();
}

OResultSet* OStatement_Base::createResulSet()
{
    return new OResultSet(m_aStatementHandle,this);
}

Reference< css::beans::XPropertySetInfo > SAL_CALL OStatement_Base::getPropertySetInfo(  )
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}

SQLUINTEGER OStatement_Base::getCursorProperties(SQLINTEGER _nCursorType, bool bFirst)
{
    SQLUINTEGER nValueLen = 0;
    try
    {
        SQLUSMALLINT nAskFor = SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2;
        if(SQL_CURSOR_KEYSET_DRIVEN == _nCursorType)
            nAskFor = bFirst ? SQL_KEYSET_CURSOR_ATTRIBUTES1 : SQL_KEYSET_CURSOR_ATTRIBUTES2;
        else if(SQL_CURSOR_STATIC  == _nCursorType)
            nAskFor = bFirst ? SQL_STATIC_CURSOR_ATTRIBUTES1 : SQL_STATIC_CURSOR_ATTRIBUTES2;
        else if(SQL_CURSOR_FORWARD_ONLY == _nCursorType)
            nAskFor = bFirst ? SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 : SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2;
        else if(SQL_CURSOR_DYNAMIC == _nCursorType)
            nAskFor = bFirst ? SQL_DYNAMIC_CURSOR_ATTRIBUTES1 : SQL_DYNAMIC_CURSOR_ATTRIBUTES2;


        OTools::GetInfo(getOwnConnection(),getConnectionHandle(),nAskFor,nValueLen,nullptr);
    }
    catch(const Exception&)
    { // we don't want our result destroy here
        nValueLen = 0;
    }
    return nValueLen;
}


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