summaryrefslogtreecommitdiff
path: root/sc/source/core/data/dptablecache.cxx
blob: bc97696cff2b1480745037bb374f548a160ca2bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * 
 * Copyright IBM Corporation 2009.
 * Copyright 2009 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dptablecache.cxx,v $
 * $Revision: 1.0 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
 // MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include "dptablecache.hxx"
#include "document.hxx"
#include "cell.hxx"
#include "globstr.hrc"

#include <rtl/math.hxx>
#include "queryparam.hxx"
#include "dpglobal.hxx"

#include "docoptio.hxx" //for ValidQuery
#include <unotools/textsearch.hxx> //for ValidQuery

#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/XRowSet.hpp>
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
const double D_TIMEFACTOR = 86400.0;

using namespace ::com::sun::star;

using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
// -----------------------------------------------------------------------
namespace 
{
    BOOL lcl_isDate( ULONG nNumType )
    {
        return ( (nNumType & NUMBERFORMAT_DATE) != 0 )? 1:0 ;
    }

    BOOL lcl_Search( const std::vector<ScDPItemData*>& list, const ::std::vector<SCROW>& rOrder, const ScDPItemData& item, SCROW& rIndex)
    {
        rIndex = list.size();
        BOOL bFound = FALSE;
        SCROW nLo = 0;
        SCROW nHi = list.size() - 1;
        SCROW nIndex;
        long nCompare;
        while (nLo <= nHi)
        {
            nIndex = (nLo + nHi) / 2;
            nCompare = ScDPItemData::Compare( *list[rOrder[nIndex]], item );
            if (nCompare < 0)
                nLo = nIndex + 1;
            else
            {
                nHi = nIndex - 1;
                if (nCompare == 0)
                {
                    bFound = TRUE;
                    nLo = nIndex;
                }
            }
        }
        rIndex = nLo;
        return bFound;
    }
    
    ScDPItemData*  lcl_GetItemValue(const Reference<sdbc::XRow>& xRow, sal_Int32 nType, long nCol,
                  const Date& rNullDate )
    {
        short nNumType = NUMBERFORMAT_NUMBER;
        try
        {
            String rStr = xRow->getString(nCol);
            double fValue = 0.0;
            switch (nType)
            {
            case sdbc::DataType::BIT:
            case sdbc::DataType::BOOLEAN:
                {
                    nNumType = NUMBERFORMAT_LOGICAL;
                    fValue  = xRow->getBoolean(nCol) ? 1 : 0;    
                    return new ScDPItemData( rStr, fValue,TRUE,nNumType);
                }
                //break;

            case sdbc::DataType::TINYINT:
            case sdbc::DataType::SMALLINT:
            case sdbc::DataType::INTEGER:
            case sdbc::DataType::BIGINT:
            case sdbc::DataType::FLOAT:
            case sdbc::DataType::REAL:
            case sdbc::DataType::DOUBLE:
            case sdbc::DataType::NUMERIC:
            case sdbc::DataType::DECIMAL:
                {
                    //! do the conversion here?
                    fValue = xRow->getDouble(nCol);
                    return new ScDPItemData( rStr, fValue,TRUE);
                }
                //break;

            case sdbc::DataType::DATE:
                {
                    nNumType = NUMBERFORMAT_DATE;

                    util::Date aDate = xRow->getDate(nCol);
                    fValue = Date(aDate.Day, aDate.Month, aDate.Year) - rNullDate;
                    return new ScDPItemData( rStr, fValue, TRUE, nNumType );
                }
                //break;

            case sdbc::DataType::TIME:
                {
                    nNumType = NUMBERFORMAT_TIME;

                    util::Time aTime = xRow->getTime(nCol);
                    fValue = ( aTime.Hours * 3600 + aTime.Minutes * 60 +
                        aTime.Seconds + aTime.HundredthSeconds / 100.0 ) / D_TIMEFACTOR;
                    return new ScDPItemData( rStr,fValue, TRUE, nNumType );
                }
                //break;

            case sdbc::DataType::TIMESTAMP:
                {
                    nNumType = NUMBERFORMAT_DATETIME;

                    util::DateTime aStamp = xRow->getTimestamp(nCol);
                    fValue = ( Date( aStamp.Day, aStamp.Month, aStamp.Year ) - rNullDate ) +
                        ( aStamp.Hours * 3600 + aStamp.Minutes * 60 +
                        aStamp.Seconds + aStamp.HundredthSeconds / 100.0 ) / D_TIMEFACTOR;
                    return new ScDPItemData( rStr,fValue, TRUE, nNumType );
                }
                //break;
            case sdbc::DataType::CHAR:
            case sdbc::DataType::VARCHAR:
            case sdbc::DataType::LONGVARCHAR:
            case sdbc::DataType::SQLNULL:
            case sdbc::DataType::BINARY:
            case sdbc::DataType::VARBINARY:
            case sdbc::DataType::LONGVARBINARY:
            default:
                return new ScDPItemData ( rStr );
                //break;
            }
        }
        catch (uno::Exception&)
        {
        }
        catch ( ... )
        {

        }
      return NULL;
    }
}
// Wang Xu Ming -- 12/23/2008
//Refactor cache data
ScDPItemData::ScDPItemData( const String& rS, double fV/* = 0.0*/, BOOL bHV/* = FALSE*/, const ULONG nNumFormatP /*= 0*/ , BOOL bData/* = TRUE*/) :
nNumFormat( nNumFormatP ), aString(rS), fValue(fV),
mbFlag( (MK_VAL*!!bHV) | (MK_DATA*!!bData) | (MK_ERR*!!FALSE) | (MK_DATE*!!lcl_isDate( nNumFormat ) ) )
{ 
}

ScDPItemData::ScDPItemData( ScDocument* pDoc, SCROW nRow, USHORT nCol, USHORT nDocTab  ):
        nNumFormat( 0 ), fValue(0.0), mbFlag( 0 )
{
    String aDocStr;
    pDoc->GetString( nCol, nRow, nDocTab, aDocStr );
        
    SvNumberFormatter* pFormatter = pDoc->GetFormatTable();
        
    ScAddress aPos( nCol, nRow, nDocTab );
    ScBaseCell* pCell = pDoc->GetCell( aPos );

    if ( pCell && pCell->GetCellType() == CELLTYPE_FORMULA && ((ScFormulaCell*)pCell)->GetErrCode() )
    {
        SetString ( aDocStr );      //[SODC_19347] add liyi
        //bErr = TRUE;              //[SODC_19347] del liyi
        mbFlag |= MK_ERR;
    }
    else if ( pDoc->HasValueData( nCol, nRow, nDocTab ) )
    {
        double fVal = pDoc->GetValue(ScAddress(nCol, nRow, nDocTab));
        ULONG nFormat = NUMBERFORMAT_NUMBER;
        if ( pFormatter )
            nFormat = pFormatter->GetType( pDoc->GetNumberFormat( ScAddress( nCol, nRow, nDocTab ) ) );
        aString = aDocStr;
        fValue = fVal;
        mbFlag |= MK_VAL|MK_DATA;
        nNumFormat = pDoc->GetNumberFormat( ScAddress( nCol, nRow, nDocTab ) );
        lcl_isDate( nFormat ) ? ( mbFlag |= MK_DATE ) : (mbFlag &= ~MK_DATE);
    }
    else if ( pDoc->HasData( nCol,nRow, nDocTab ) )
        SetString ( aDocStr );
}
// End Comments

BOOL ScDPItemData::IsCaseInsEqual( const ScDPItemData& r ) const
{ //TODO: indified Date?
    //! pass Transliteration?
    //!	inline?
    return IsValue() ? ( r.IsValue() && rtl::math::approxEqual( fValue, r.fValue ) ) :
                       ( !r.IsValue() &&
                        ScGlobal::GetpTransliteration()->isEqual( aString, r.aString ) );
}

size_t ScDPItemData::Hash() const
{
    if ( IsValue() )
        return (size_t) rtl::math::approxFloor( fValue );
    else
        // If we do unicode safe case insensitive hash we can drop
        // ScDPItemData::operator== and use ::IsCasInsEqual
        return rtl_ustr_hashCode_WithLength( aString.GetBuffer(), aString.Len() );
}

BOOL ScDPItemData::operator==( const ScDPItemData& r ) const
{
    if ( IsValue() )
    {
        if( (HasDatePart() != r.HasDatePart())  || (HasDatePart() && mnDatePart != r.mnDatePart) )
            return FALSE;

// Wang Xu Ming -- 1/9/2009
// Add Data Cache Support.
// Identify date
        if ( IsDate() != r.IsDate() )
            return FALSE;
      else 
        if ( r.IsValue() )
            return rtl::math::approxEqual( fValue, r.fValue );
        else
            return FALSE;
// End Comments
    }
    else if ( r.IsValue() )
        return FALSE;
    else
        // need exact equality until we have a safe case insensitive string hash
        return aString == r.aString;
}

sal_Int32 ScDPItemData::Compare( const ScDPItemData& rA,
                                 const ScDPItemData& rB )
{
    if ( rA.IsValue() )
    {
        if ( rB.IsValue() )
        {
            if ( rtl::math::approxEqual( rA.fValue, rB.fValue ) )
            {
// Wang Xu Ming -- 1/9/2009
// Add Data Cache Support.
// Date > number
                if ( rA.IsDate() == rB.IsDate() )
                    return 0;
                else
                    return rA.IsDate() ? 1: -1;
// End Comments
            }
            else if ( rA.fValue < rB.fValue )
                return -1;
            else
                return 1;
        }
        else
            return -1;           // values first
    }
    else if ( rB.IsValue() )
        return 1;                // values first
    else
        return ScGlobal::GetCollator()->compareString( rA.aString, rB.aString );
}
//
//Wang Xu Ming SODC_17561
#ifdef DEBUG
void	ScDPItemData::dump() const
{
    DBG_TRACE1( "Numberformat= %o",  nNumFormat );
    DBG_TRACESTR(aString );
    DBG_TRACE1( "fValue= %f", fValue );
    DBG_TRACE1( "mbFlag= %d", mbFlag);
}
#endif
//End

TypedStrData*  ScDPItemData::CreateTypeString( )
{
    if ( IsValue() )
        return new TypedStrData( aString, fValue, SC_STRTYPE_VALUE );
    else
        return new TypedStrData( aString );
}

sal_uInt8 ScDPItemData::GetType() const
{
    
    if ( IsHasErr() )
        return SC_VALTYPE_ERROR;
    else if ( !IsHasData() )
        return SC_VALTYPE_EMPTY;
    else if ( IsValue())
        return SC_VALTYPE_VALUE;
    else 
        return SC_VALTYPE_STRING;

}

BOOL ScDPItemData::IsHasData() const 
{
    return !!(mbFlag&MK_DATA);
}

BOOL ScDPItemData::IsHasErr() const 
{ 
    return !!(mbFlag&MK_ERR); 
}

BOOL ScDPItemData::IsValue() const 
{ 
    return !!(mbFlag&MK_VAL);
}

String ScDPItemData::GetString() const 
{ 

    return aString;
}

double ScDPItemData::GetValue() const 
{ 
    return fValue;
}
ULONG  ScDPItemData::GetNumFormat() const 
{ 
    return nNumFormat;
}

BOOL ScDPItemData::HasStringData() const 

{ 
    return IsHasData()&&!IsHasErr()&&!IsValue();
}
BOOL ScDPItemData::IsDate() const
{ 
    return !!(mbFlag&MK_DATE); 
}
BOOL ScDPItemData::HasDatePart() const
{
    return !!(mbFlag&MK_DATEPART); 
}
void ScDPItemData::SetDate( BOOL b ) 
{
    b ? ( mbFlag |= MK_DATE ) : ( mbFlag &= ~MK_DATE ); 
}

// -----------------------------------------------------------------------
//class ScDPTableDataCache
//To cache the pivot table data source

BOOL ScDPTableDataCache::operator== ( const ScDPTableDataCache& r ) const
{
    if ( GetColumnCount() == r.GetColumnCount() )
    {
        for ( SCCOL i = 0 ; i < GetColumnCount(); i++ )
        {	//check dim names
            if ( GetDimensionName( i ) != r.GetDimensionName( i ) )
                return FALSE;
            //check rows count
            if ( GetRowCount() != r.GetRowCount() )
                return FALSE;
            //check dim member values
            size_t nMembersCount = GetDimMemberValues( i ).size();
            if ( GetDimMemberValues( i ).size() == r. GetDimMemberValues( i ).size() )
            {
                for ( size_t j = 0; j < nMembersCount; j++ )
                {
                    if ( *( GetDimMemberValues( i )[j] ) == *( r.GetDimMemberValues( i )[j] ) )
                        continue;
                    else 
                        return FALSE;
                }
            }
            else 
                return FALSE;		
            //check source table index
            for ( SCROW k=0 ; k < GetRowCount(); k ++ )
            {
                if ( GetItemDataId( i, k, FALSE ) == r.GetItemDataId( i,k,FALSE) )
                    continue;
                else
                    return FALSE;
            }				
        }
    }
    return TRUE;
}

ScDPTableDataCache::ScDPTableDataCache(  ScDocument* pDoc  ) :
mpDoc( pDoc ),
mnColumnCount ( 0 ),
mpTableDataValues ( NULL ),
mpSourceData ( NULL ),
mpGlobalOrder( NULL ),
mpIndexOrder( NULL)
{
    mnID = -1;
}

ScDPTableDataCache::~ScDPTableDataCache()
{
    if ( IsValid() )
    {
// Wang Xu Ming -- 2/17/2009
// Performance issue
        USHORT nCol;
        for (  nCol=0; nCol < GetColumnCount() ; nCol++ )
        {
            for ( ULONG row = 0 ;  row < mpTableDataValues[nCol].size(); row++ )
                delete mpTableDataValues[nCol][row];
        }
        for ( nCol =0; nCol < mrLabelNames.size(); nCol++ )		
                delete mrLabelNames[nCol];
// End Comments

        mnColumnCount = 0;
        delete [] mpTableDataValues;
        mpTableDataValues = NULL;
        delete [] mpSourceData;
        mpSourceData = NULL;
        delete [] mpGlobalOrder;
        mpGlobalOrder = NULL;
        delete [] mpIndexOrder;
        mpIndexOrder = NULL;
    }
}

// -----------------------------------------------------------------------
void ScDPTableDataCache::AddRow( ScDPItemData* pRow, USHORT nCount )
{ 
    DBG_ASSERT( pRow , " empty pointer" );
    if ( !mrLabelNames.size() )
    {
        mnColumnCount= nCount;
        mpTableDataValues = new std::vector<ScDPItemData*>[ mnColumnCount ];
        mpSourceData	  = new std::vector<SCROW>[ mnColumnCount ];
        mpGlobalOrder	  = new	std::vector<SCROW>[ mnColumnCount ];
        mpIndexOrder	  = new std::vector<SCROW>[ mnColumnCount ];

        for ( USHORT i = 0; i < nCount ; i ++ )
            AddLabel( new ScDPItemData( pRow[i] ) );
    }
    else
    {
        for ( USHORT i = 0; i < nCount && i < mnColumnCount; i ++ )
            AddData( i, new ScDPItemData( pRow[i] ) );
    }
}

// -----------------------------------------------------------------------
bool  ScDPTableDataCache::IsValid() const
{ //TODO: continue check valid
    return mpTableDataValues!=NULL && mpSourceData!= NULL && mnColumnCount>0;
}

// -----------------------------------------------------------------------

namespace {

/** 
 * While the macro interpret level is incremented, the formula cells are 
 * (semi-)guaranteed to be interpreted. 
 */ 
class MacroInterpretIncrementer
{
public:
    MacroInterpretIncrementer(ScDocument* pDoc) :
        mpDoc(pDoc)
    {
        mpDoc->IncMacroInterpretLevel();
    }
    ~MacroInterpretIncrementer()
    {
        mpDoc->DecMacroInterpretLevel();
    }
private:
    ScDocument* mpDoc;
};

}

// -----------------------------------------------------------------------
bool ScDPTableDataCache::InitFromDoc(  ScDocument* pDoc, const ScRange& rRange )
{
    // Make sure the formula cells within the data range are interpreted 
    // during this call, for this method may be called from the interpretation
    // of GETPIVOTDATA, which disables nested formula interpretation without
    // increasing the macro level.
    MacroInterpretIncrementer aMacroInc(pDoc);

    //
    SCROW nStartRow = rRange.aStart.Row();	// start of data
    SCROW nEndRow = rRange.aEnd.Row();
    USHORT nStartCol = rRange.aStart.Col();
    USHORT nEndCol = rRange.aEnd.Col();
    USHORT nDocTab = rRange.aStart.Tab();
        
    //init 
     long nOldColumCount = mnColumnCount;
    mnColumnCount = nEndCol - nStartCol + 1;
    if ( IsValid() )
    {
        for ( USHORT nCol=0; nCol < nOldColumCount ; nCol++ )
        {
            for ( ULONG row = 0 ;  row < mpTableDataValues[nCol].size(); row++ )
                delete mpTableDataValues[nCol][row];
            delete mrLabelNames[nCol];
        }
        delete [] mpTableDataValues;
        delete [] mpSourceData;
        delete [] mpGlobalOrder;
        delete [] mpIndexOrder;
        mrLabelNames.clear();
    }
        
    mpTableDataValues = new std::vector<ScDPItemData*>[ mnColumnCount ];
    mpSourceData	  = new std::vector<SCROW>[ mnColumnCount ];
    mpGlobalOrder	  = new	std::vector<SCROW>[ mnColumnCount ];
    mpIndexOrder	  = new std::vector<SCROW>[ mnColumnCount ];
    //check valid
    for ( SCROW nRow = nStartRow; nRow <= nEndRow; nRow ++ )
    {
        for ( USHORT nCol = nStartCol; nCol <= nEndCol; nCol++ )
        {
            if ( nRow == nStartRow )
                AddLabel( new ScDPItemData( pDoc, nRow, nCol, nDocTab  ) );
            else
                AddData( nCol - nStartCol, new ScDPItemData( pDoc, nRow, nCol, nDocTab  ) );
        }
    }
    return TRUE;
}

// -----------------------------------------------------------------------
bool ScDPTableDataCache::InitFromDataBase (const Reference<sdbc::XRowSet>& xRowSet, const Date& rNullDate)
{
  if (!xRowSet.is())
        // Dont' even waste time to go any further.
        return false;
    try
    {
        Reference<sdbc::XResultSetMetaDataSupplier> xMetaSupp(xRowSet, UNO_QUERY_THROW);
        Reference<sdbc::XResultSetMetaData> xMeta = xMetaSupp->getMetaData();
        if (!xMeta.is())
            return false;

       long nOldColumCount = mnColumnCount;
    mnColumnCount = xMeta->getColumnCount();
    if ( IsValid() )
    {
        for ( USHORT nCol=0; nCol < nOldColumCount ; nCol++ )
        {
            for ( ULONG row = 0 ;  row < mpTableDataValues[nCol].size(); row++ )
                delete mpTableDataValues[nCol][row];
            delete mrLabelNames[nCol];
        }
        delete [] mpTableDataValues;
        delete [] mpSourceData;
        delete [] mpGlobalOrder;
        delete [] mpIndexOrder;
        mrLabelNames.clear();
    }
        // Get column titles and types.
    mrLabelNames.reserve(mnColumnCount);
    mpTableDataValues = new std::vector<ScDPItemData*>[ mnColumnCount ];
    mpSourceData	  = new std::vector<SCROW>[ mnColumnCount ];
    mpGlobalOrder	  = new	std::vector<SCROW>[ mnColumnCount ];
    mpIndexOrder	  = new std::vector<SCROW>[ mnColumnCount ];

    std::vector<sal_Int32> aColTypes(mnColumnCount);

        for (sal_Int32 nCol = 0; nCol < mnColumnCount; ++nCol)
        {
            String aColTitle = xMeta->getColumnLabel(nCol+1);
            aColTypes[nCol]  = xMeta->getColumnType(nCol+1);
           AddLabel( new ScDPItemData( aColTitle) );
        }

        // Now get the data rows.
        Reference<sdbc::XRow> xRow(xRowSet, UNO_QUERY_THROW);
        xRowSet->first();
        do
        {      
            for (sal_Int32 nCol = 0; nCol < mnColumnCount; ++nCol)
            {
               ScDPItemData * pNew =  lcl_GetItemValue( xRow, aColTypes[nCol], nCol+1, rNullDate );
                if ( pNew )
                    AddData(  nCol , pNew );
            }
        }
        while (xRowSet->next());

    xRowSet->beforeFirst();

    return true;
    }
    catch (const Exception&)
    {
        return false;
    }
}
// -----------------------------------------------------------------------
ULONG ScDPTableDataCache::GetDimNumType( SCCOL nDim) const
{
    DBG_ASSERT( IsValid(), "  IsValid() == false " );
    DBG_ASSERT( nDim < mnColumnCount && nDim >=0, " dimention out of bound " );
    if ( mpTableDataValues[nDim].size()==0 )
        return NUMBERFORMAT_UNDEFINED;
    else
        return GetNumType(mpTableDataValues[nDim][0]->nNumFormat);
}

// -----------------------------------------------------------------------
bool ScDPTableDataCache::ValidQuery( SCROW nRow, const ScQueryParam &rParam, BOOL *pSpecial) 
{ //Copied and modified from ScTable::ValidQuery
        if (!rParam.GetEntry(0).bDoQuery)
            return TRUE;
        BOOL	bMatchWholeCell = mpDoc->GetDocOptions().IsMatchWholeCell();
    
        //---------------------------------------------------------------

        const SCSIZE nFixedBools = 32;
        BOOL aBool[nFixedBools];
        BOOL aTest[nFixedBools];
        SCSIZE nEntryCount = rParam.GetEntryCount();
        BOOL* pPasst = ( nEntryCount <= nFixedBools ? &aBool[0] : new BOOL[nEntryCount] );
        BOOL* pTest = ( nEntryCount <= nFixedBools ? &aTest[0] : new BOOL[nEntryCount] );

        long	nPos = -1;
        SCSIZE	i	 = 0;
        CollatorWrapper* pCollator = (rParam.bCaseSens ? ScGlobal::GetCaseCollator() :
            ScGlobal::GetCollator() );
        ::utl::TransliterationWrapper* pTransliteration = (rParam.bCaseSens ?
            ScGlobal::GetCaseTransliteration() : ScGlobal::GetpTransliteration());

        while ( (i < nEntryCount) && rParam.GetEntry(i).bDoQuery )
        {
            ScQueryEntry& rEntry = rParam.GetEntry(i);
            // we can only handle one single direct query
            // #i115431# nField in QueryParam is the sheet column, not the field within the source range
            SCCOL nQueryCol = (SCCOL)rEntry.nField;
            if ( nQueryCol < rParam.nCol1 )
                nQueryCol = rParam.nCol1;
            if ( nQueryCol > rParam.nCol2 )
                nQueryCol = rParam.nCol2;
            SCCOL nSourceField = nQueryCol - rParam.nCol1;
            SCROW nId = GetItemDataId( nSourceField, nRow, FALSE ); 
            const ScDPItemData* pCellData = GetItemDataById( nSourceField, nId ); 

            BOOL bOk = FALSE;
            BOOL bTestEqual = FALSE;

            if ( pSpecial && pSpecial[i] )
            {
                if (rEntry.nVal == SC_EMPTYFIELDS)
                    bOk = ! pCellData->IsHasData();
                else // if (rEntry.nVal == SC_NONEMPTYFIELDS)
                    bOk =  pCellData->IsHasData();
            }
            else if ( !rEntry.bQueryByString && pCellData->IsValue() )
            {	// by Value
                double nCellVal = pCellData->GetValue();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                switch (rEntry.eOp)
                {
                    case SC_EQUAL :
                        bOk = ::rtl::math::approxEqual( nCellVal, rEntry.nVal );
                        break;
                    case SC_LESS :
                        bOk = (nCellVal < rEntry.nVal) && !::rtl::math::approxEqual( nCellVal, rEntry.nVal );
                        break;
                    case SC_GREATER :
                        bOk = (nCellVal > rEntry.nVal) && !::rtl::math::approxEqual( nCellVal, rEntry.nVal );
                        break;
                    case SC_LESS_EQUAL :
                        bOk = (nCellVal < rEntry.nVal) || ::rtl::math::approxEqual( nCellVal, rEntry.nVal );
                        break;
                    case SC_GREATER_EQUAL :
                        bOk = (nCellVal > rEntry.nVal) || ::rtl::math::approxEqual( nCellVal, rEntry.nVal );
                        break;
                    case SC_NOT_EQUAL :
                        bOk = !::rtl::math::approxEqual( nCellVal, rEntry.nVal );
                        break;
                                 default:
                                    bOk= FALSE;
                                    break;
                }
            }
            else if ( (rEntry.eOp == SC_EQUAL || rEntry.eOp == SC_NOT_EQUAL)
                    || (rEntry.bQueryByString
                        && pCellData->HasStringData() )
                )
            {	// by String
                String	aCellStr = pCellData->GetString();

                BOOL bRealRegExp = (rParam.bRegExp && ((rEntry.eOp == SC_EQUAL)
                    || (rEntry.eOp == SC_NOT_EQUAL)));
                BOOL bTestRegExp = FALSE;
                if ( bRealRegExp || bTestRegExp )
                {
                    xub_StrLen nStart = 0;
                    xub_StrLen nEnd   = aCellStr.Len();
                    BOOL bMatch = (BOOL) rEntry.GetSearchTextPtr( rParam.bCaseSens )
                        ->SearchFrwrd( aCellStr, &nStart, &nEnd );
                    // from 614 on, nEnd is behind the found text
                    if ( bMatch && bMatchWholeCell
                            && (nStart != 0 || nEnd != aCellStr.Len()) )
                        bMatch = FALSE;    // RegExp must match entire cell string
                    if ( bRealRegExp )
                        bOk = ((rEntry.eOp == SC_NOT_EQUAL) ? !bMatch : bMatch);
                    else
                        bTestEqual = bMatch;
                }
                if ( !bRealRegExp )
                {
                    if ( rEntry.eOp == SC_EQUAL || rEntry.eOp == SC_NOT_EQUAL )
                    {
                        if ( bMatchWholeCell )
                        {
                                        bOk = pTransliteration->isEqual( aCellStr, *rEntry.pStr );
                            //Added by zhaosz,for sodc_2702,20060808
                            String aStr = *rEntry.pStr;//"f*"
                            //modified by weihuaw,for SODC_16698
                            //use another way to find "*" in aStr
                            sal_Bool bHasStar = sal_False;
                            xub_StrLen nIndex;
                            if( ( nIndex = aStr.Search('*') ) != STRING_NOTFOUND )
                                bHasStar = sal_True;
                            if(bHasStar && (nIndex>0))
                            {
                                for(i=0;(i<nIndex) && (i< aCellStr.Len()) ; i++)
                                {
                                    if(aCellStr.GetChar( (USHORT)i ) == aStr.GetChar((USHORT) i ))
                                    {
                                        bOk=1;
                                    }
                                    else
                                    {
                                        bOk=0;
                                        break;
                                    }
                                }
                            }
                            //end modified
                            //Added end,20060808
                        }
                        else
                        {
                            ::com::sun::star::uno::Sequence< sal_Int32 > xOff;
                            String aCell( pTransliteration->transliterate(
                                aCellStr, ScGlobal::eLnge, 0, aCellStr.Len(),
                                &xOff ) );
                            String aQuer( pTransliteration->transliterate(
                                *rEntry.pStr, ScGlobal::eLnge, 0, rEntry.pStr->Len(),
                                &xOff ) );
                            bOk = (aCell.Search( aQuer ) != STRING_NOTFOUND);
                        }
                        if ( rEntry.eOp == SC_NOT_EQUAL )
                            bOk = !bOk;
                    }
                    else
                    {   // use collator here because data was probably sorted
                        sal_Int32 nCompare = pCollator->compareString(
                            aCellStr, *rEntry.pStr );
                        switch (rEntry.eOp)
                        {
                            case SC_LESS :
                                bOk = (nCompare < 0);
                                break;
                            case SC_GREATER :
                                bOk = (nCompare > 0);
                                break;
                            case SC_LESS_EQUAL :
                                bOk = (nCompare <= 0);
                                break;
                            case SC_GREATER_EQUAL :
                                bOk = (nCompare >= 0);
                                break;
                            case SC_NOT_EQUAL:
                                DBG_ASSERT( false , "SC_NOT_EQUAL");
                                break;
                            case SC_TOPVAL:
                            case SC_BOTVAL:
                            case SC_TOPPERC:
                            case SC_BOTPERC:
                            default:
                                break;
                        }
                    }
                }
            }

            if (nPos == -1)
            {
                nPos++;
                pPasst[nPos] = bOk;
                pTest[nPos] = bTestEqual;
            }
            else
            {
                if (rEntry.eConnect == SC_AND)
                {
                    pPasst[nPos] = pPasst[nPos] && bOk;
                    pTest[nPos] = pTest[nPos] && bTestEqual;
                }
                else
                {
                    nPos++;
                    pPasst[nPos] = bOk;
                    pTest[nPos] = bTestEqual;
                }
            }
            i++;
        }

        for ( long j=1; j <= nPos; j++ )
        {
            pPasst[0] = pPasst[0] || pPasst[j];
            pTest[0] = pTest[0] || pTest[j];
        }

        BOOL bRet = pPasst[0];
        if ( pPasst != &aBool[0] )
            delete [] pPasst;
        if ( pTest != &aTest[0] )
            delete [] pTest;

        return bRet;
}

// -----------------------------------------------------------------------
bool ScDPTableDataCache::IsRowEmpty( SCROW nRow ) const
{
    return 	mbEmptyRow[ nRow ];

}

// -----------------------------------------------------------------------
bool ScDPTableDataCache::IsEmptyMember( SCROW nRow, USHORT nColumn ) const
{
    return !GetItemDataById( nColumn, GetItemDataId( nColumn, nRow, FALSE ) )->IsHasData();
}

BOOL ScDPTableDataCache::AddData(long nDim, ScDPItemData* pitemData)
{
    DBG_ASSERT( IsValid(), "  IsValid() == false " );
    DBG_ASSERT( nDim < mnColumnCount && nDim >=0 , "dimension out of bound" );
    SCROW nIndex = 0; 

    BOOL	bInserted = FALSE;
    
    pitemData->SetDate( lcl_isDate( GetNumType( pitemData->nNumFormat ) ) );

    if ( !lcl_Search( mpTableDataValues[nDim], mpGlobalOrder[nDim], *pitemData, nIndex ) )
    {
        mpTableDataValues[nDim].push_back( pitemData );
        mpGlobalOrder[nDim].insert( mpGlobalOrder[nDim].begin()+nIndex, mpTableDataValues[nDim].size()-1  );
        DBG_ASSERT( (size_t) mpGlobalOrder[nDim][nIndex] == mpTableDataValues[nDim].size()-1 ,"ScDPTableDataCache::AddData ");
        mpSourceData[nDim].push_back( mpTableDataValues[nDim].size()-1 );
        bInserted = TRUE;
    }
    else
        mpSourceData[nDim].push_back( mpGlobalOrder[nDim][nIndex] );
//init empty row tag
    size_t  nCurRow = mpSourceData[nDim].size() -1 ;

    while ( mbEmptyRow.size() <= nCurRow )
        mbEmptyRow.push_back( TRUE );

    if ( pitemData->IsHasData() )
        mbEmptyRow[ nCurRow ] = FALSE;

    if ( !bInserted ) 
        delete pitemData;

    return TRUE;
}


String ScDPTableDataCache::GetDimensionName( USHORT nColumn ) const
{
    DBG_ASSERT( /* nColumn>=0 && */ nColumn < mrLabelNames.size()-1 , "ScDPTableDataCache::GetDimensionName");
    DBG_ASSERT( mrLabelNames.size() == static_cast <USHORT> (mnColumnCount+1), "ScDPTableDataCache::GetDimensionName");
    if ( static_cast<size_t>(nColumn+1) < mrLabelNames.size() )
    { 
        return mrLabelNames[nColumn+1]->aString;
    }
    else
        return String();
}

void ScDPTableDataCache::AddLabel(ScDPItemData *pData)
{  
    DBG_ASSERT( IsValid(), "  IsValid() == false " );

    if ( mrLabelNames.size() == 0 )
        mrLabelNames.push_back( new ScDPItemData(  ScGlobal::GetRscString(STR_PIVOT_DATA) ) ); 


    //reset name if needed
    String strNewName = pData->aString;
    BOOL bFound = FALSE;
    long nIndex = 1;
    do
    {
        for ( long i= mrLabelNames.size()-1; i>=0; i-- )
        {
            if( mrLabelNames[i]->aString == strNewName )
            {
                strNewName  =  pData->aString;
                strNewName += String::CreateFromInt32( nIndex );
                nIndex ++ ;
                bFound = TRUE;
            }
        }
        bFound = !bFound;
    }
    while ( !bFound );

    pData->aString = strNewName;
    mrLabelNames.push_back( pData );  
}

SCROW ScDPTableDataCache::GetItemDataId(USHORT nDim, SCROW nRow, BOOL bRepeatIfEmpty) const
{ //
    DBG_ASSERT( IsValid(), "  IsValid() == false " );
    DBG_ASSERT( /* nDim >= 0 && */ nDim < mnColumnCount, "ScDPTableDataCache::GetItemDataId " );

    if ( bRepeatIfEmpty )
    { 
        while ( nRow >0 && !mpTableDataValues[nDim][ mpSourceData[nDim][nRow] ]->IsHasData() )
        --nRow;
    }

    return mpSourceData[nDim][nRow];
}

const ScDPItemData* ScDPTableDataCache::GetItemDataById(long nDim, SCROW nId) const
{
    if ( nId >= GetRowCount()  )
        return maAdditionalDatas.getData( nId - GetRowCount() );

    if (  (size_t)nId >= mpTableDataValues[nDim].size() || nDim >= mnColumnCount  || nId < 0  )
        return NULL;
    else
        return mpTableDataValues[nDim][nId];
}

SCROW ScDPTableDataCache::GetRowCount() const
{
    if ( IsValid() )
        return mpSourceData[0].size();
    else
        return 0;
}

const std::vector<ScDPItemData*>& ScDPTableDataCache::GetDimMemberValues(SCCOL nDim) const
{
    DBG_ASSERT( nDim>=0 && nDim < mnColumnCount ," nDim < mnColumnCount ");
    return mpTableDataValues[nDim];
}

SCROW ScDPTableDataCache::GetSortedItemDataId(SCCOL nDim, SCROW nOrder) const
{
    DBG_ASSERT ( IsValid(), "IsValid");
    DBG_ASSERT( nDim>=0 && nDim < mnColumnCount,  "nDim < mnColumnCount");
    DBG_ASSERT( nOrder >= 0 && (size_t) nOrder < mpGlobalOrder[nDim].size(), "nOrder < mpGlobalOrder[nDim].size()" );
    
    return mpGlobalOrder[nDim][nOrder];
}

ULONG ScDPTableDataCache::GetNumType(ULONG nFormat) const
{
    SvNumberFormatter* pFormatter = mpDoc->GetFormatTable();
    ULONG nType = NUMBERFORMAT_NUMBER;
    if ( pFormatter )
        nType = pFormatter->GetType( nFormat );
    return nType;
}

ULONG ScDPTableDataCache::GetNumberFormat( long nDim ) const
{
    if ( nDim >= mnColumnCount )
        return 0;
    if ( mpTableDataValues[nDim].size()==0 )
        return 0;
    else
        return mpTableDataValues[nDim][0]->nNumFormat;
}

BOOL ScDPTableDataCache::IsDateDimension( long nDim ) const 
{
    if ( nDim >= mnColumnCount )
        return false;
    else if ( mpTableDataValues[nDim].size()==0 )
        return false;
    else
        return mpTableDataValues[nDim][0]->IsDate();

}

SCROW ScDPTableDataCache::GetDimMemberCount( SCCOL nDim ) const
{
    DBG_ASSERT( nDim>=0 && nDim < mnColumnCount ," ScDPTableDataCache::GetDimMemberCount : out of bound ");
    return mpTableDataValues[nDim].size();
}

const ScDPItemData* ScDPTableDataCache::GetSortedItemData(SCCOL nDim, SCROW nOrder) const
{
    SCROW n = GetSortedItemDataId( nDim, nOrder );
    return GetItemDataById( nDim, n );
}

SCCOL ScDPTableDataCache::GetDimensionIndex(String sName) const
{
    for ( size_t n = 1; n < mrLabelNames.size(); n ++ ) //defects, label name map wrong SODC_17590, SODC_18932,SODC_18827,SODC_18960,SODC_18923
    {
        if ( mrLabelNames[n]->GetString() == sName )
            return (SCCOL)(n-1);
    }
    return -1;
}

SCROW ScDPTableDataCache::GetIdByItemData(long nDim, String sItemData ) const
{ 
    if ( nDim < mnColumnCount && nDim >=0 )
    {
        for ( size_t n = 0; n< mpTableDataValues[nDim].size(); n++ )
        {
            if ( mpTableDataValues[nDim][n]->GetString() == sItemData )
                return n;
        }
    }
    
    ScDPItemData rData ( sItemData );
    return  GetRowCount() +maAdditionalDatas.getDataId(rData);
}

SCROW ScDPTableDataCache::GetIdByItemData( long nDim, const ScDPItemData& rData  ) const
{ 
    if ( nDim < mnColumnCount && nDim >=0 )
    {
        for ( size_t n = 0; n< mpTableDataValues[nDim].size(); n++ )
        {
            if ( *mpTableDataValues[nDim][n] == rData )
                return n;
        }
    }
    return  GetRowCount() + maAdditionalDatas.getDataId(rData);
}

SCROW ScDPTableDataCache::GetAdditionalItemID ( String sItemData )
{
    ScDPItemData rData ( sItemData );
    return GetAdditionalItemID( rData );
}

SCROW ScDPTableDataCache::GetAdditionalItemID( const ScDPItemData& rData )
{
    return GetRowCount() + maAdditionalDatas.insertData( rData );
}
        

SCROW ScDPTableDataCache::GetOrder(long nDim, SCROW nIndex) const
{
    DBG_ASSERT( IsValid(), "  IsValid() == false " );
    DBG_ASSERT( nDim >=0 && nDim < mnColumnCount, "ScDPTableDataCache::GetOrder : out of bound" );

    if ( mpIndexOrder[nDim].size() !=  mpGlobalOrder[nDim].size() )
    { //not inited
        SCROW i  = 0;
        mpIndexOrder[nDim].resize(  mpGlobalOrder[nDim].size(), 0 );
        for ( size_t n = 0 ; n<  mpGlobalOrder[nDim].size(); n++ )
        {
            i =  mpGlobalOrder[nDim][n];
            mpIndexOrder[nDim][ i ] = n;
        }
    }

    DBG_ASSERT( nIndex>=0 && (size_t)nIndex < mpIndexOrder[nDim].size() , "ScDPTableDataCache::GetOrder");
    return  mpIndexOrder[nDim][nIndex];
}

ScDocument*  ScDPTableDataCache::GetDoc() const
{
    return mpDoc; 
};

long ScDPTableDataCache::GetColumnCount() const 
{
    return mnColumnCount; 
}
long	ScDPTableDataCache::GetId() const 
{
    return mnID; 
}
 

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