summaryrefslogtreecommitdiff
path: root/sc/source/ui/docshell/dbdocfun.cxx
blob: 8ee336edeb6f2c511b016cba9d825acb550e8aea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dbdocfun.cxx,v $
 * $Revision: 1.20.128.4 $
 *
 * 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 <sfx2/app.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/waitobj.hxx>

#include <com/sun/star/sdbc/XResultSet.hpp>

#include "dbdocfun.hxx"
#include "sc.hrc"
#include "dbcolect.hxx"
#include "undodat.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "globstr.hrc"
#include "tabvwsh.hxx"
#include "patattr.hxx"
#include "rangenam.hxx"
#include "olinetab.hxx"
#include "dpobject.hxx"
#include "dociter.hxx"		// for lcl_EmptyExcept
#include "cell.hxx"			// for lcl_EmptyExcept
#include "editable.hxx"
#include "attrib.hxx"
#include "drwlayer.hxx"
#include "dpshttab.hxx"

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

BOOL ScDBDocFunc::AddDBRange( const String& rName, const ScRange& rRange, BOOL /* bApi */ )
{

    ScDocShellModificator aModificator( rDocShell );

    ScDocument* pDoc = rDocShell.GetDocument();
    ScDBCollection* pDocColl = pDoc->GetDBCollection();
    BOOL bUndo (pDoc->IsUndoEnabled());

    ScDBCollection* pUndoColl = NULL;
    if (bUndo)
        pUndoColl = new ScDBCollection( *pDocColl );

    ScDBData* pNew = new ScDBData( rName, rRange.aStart.Tab(),
                                    rRange.aStart.Col(), rRange.aStart.Row(),
                                    rRange.aEnd.Col(), rRange.aEnd.Row() );

    // #i55926# While loading XML, formula cells only have a single string token,
    // so CompileDBFormula would never find any name (index) tokens, and would
    // unnecessarily loop through all cells.
    BOOL bCompile = !pDoc->IsImportingXML();

    if ( bCompile )
        pDoc->CompileDBFormula( TRUE );     // CreateFormulaString
    BOOL bOk = pDocColl->Insert( pNew );
    if ( bCompile )
        pDoc->CompileDBFormula( FALSE );    // CompileFormulaString

    if (!bOk)
    {
        delete pNew;
        delete pUndoColl;
        return FALSE;
    }

    if (bUndo)
    {
        ScDBCollection* pRedoColl = new ScDBCollection( *pDocColl );
        rDocShell.GetUndoManager()->AddUndoAction(
                        new ScUndoDBData( &rDocShell, pUndoColl, pRedoColl ) );
    }

    aModificator.SetDocumentModified();
    SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_DBAREAS_CHANGED ) );
    return TRUE;
}

BOOL ScDBDocFunc::DeleteDBRange( const String& rName, BOOL /* bApi */ )
{
    BOOL bDone = FALSE;
    ScDocument* pDoc = rDocShell.GetDocument();
    ScDBCollection* pDocColl = pDoc->GetDBCollection();
    BOOL bUndo (pDoc->IsUndoEnabled());

    USHORT nPos = 0;
    if (pDocColl->SearchName( rName, nPos ))
    {
        ScDocShellModificator aModificator( rDocShell );

        ScDBCollection* pUndoColl = NULL;
        if (bUndo)
            pUndoColl = new ScDBCollection( *pDocColl );

        pDoc->CompileDBFormula( TRUE );		// CreateFormulaString
        pDocColl->AtFree( nPos );
        pDoc->CompileDBFormula( FALSE );	// CompileFormulaString

        if (bUndo)
        {
            ScDBCollection* pRedoColl = new ScDBCollection( *pDocColl );
            rDocShell.GetUndoManager()->AddUndoAction(
                            new ScUndoDBData( &rDocShell, pUndoColl, pRedoColl ) );
        }

        aModificator.SetDocumentModified();
        SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_DBAREAS_CHANGED ) );
        bDone = TRUE;
    }

    return bDone;
}

BOOL ScDBDocFunc::RenameDBRange( const String& rOld, const String& rNew, BOOL /* bApi */ )
{
    BOOL bDone = FALSE;
    ScDocument* pDoc = rDocShell.GetDocument();
    ScDBCollection* pDocColl = pDoc->GetDBCollection();
    BOOL bUndo (pDoc->IsUndoEnabled());

    USHORT nPos = 0;
    USHORT nDummy = 0;
    if ( pDocColl->SearchName( rOld, nPos ) &&
         !pDocColl->SearchName( rNew, nDummy ) )
    {
        ScDocShellModificator aModificator( rDocShell );

        ScDBData* pData = (*pDocColl)[nPos];
        ScDBData* pNewData = new ScDBData(*pData);
        pNewData->SetName(rNew);

        ScDBCollection* pUndoColl = new ScDBCollection( *pDocColl );

        pDoc->CompileDBFormula( TRUE );				// CreateFormulaString
        pDocColl->AtFree( nPos );
        BOOL bInserted = pDocColl->Insert( pNewData );
        if (!bInserted)								// Fehler -> alten Zustand wiederherstellen
        {
            delete pNewData;
            pDoc->SetDBCollection( pUndoColl );		// gehoert dann dem Dokument
        }
        pDoc->CompileDBFormula( FALSE );			// CompileFormulaString

        if (bInserted)								// Einfuegen hat geklappt
        {
            if (bUndo)
            {
                ScDBCollection* pRedoColl = new ScDBCollection( *pDocColl );
                rDocShell.GetUndoManager()->AddUndoAction(
                                new ScUndoDBData( &rDocShell, pUndoColl, pRedoColl ) );
            }
            else
                delete pUndoColl;

            aModificator.SetDocumentModified();
            SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_DBAREAS_CHANGED ) );
            bDone = TRUE;
        }
    }

    return bDone;
}

BOOL ScDBDocFunc::ModifyDBData( const ScDBData& rNewData, BOOL /* bApi */ )
{
    BOOL bDone = FALSE;
    ScDocument* pDoc = rDocShell.GetDocument();
    ScDBCollection* pDocColl = pDoc->GetDBCollection();
    BOOL bUndo (pDoc->IsUndoEnabled());

    USHORT nPos = 0;
    if (pDocColl->SearchName( rNewData.GetName(), nPos ))
    {
        ScDocShellModificator aModificator( rDocShell );

        ScDBData* pData = (*pDocColl)[nPos];

        ScRange aOldRange, aNewRange;
        pData->GetArea(aOldRange);
        rNewData.GetArea(aNewRange);
        BOOL bAreaChanged = ( aOldRange != aNewRange );		// dann muss neu compiliert werden

        ScDBCollection* pUndoColl = NULL;
        if (bUndo)
            pUndoColl = new ScDBCollection( *pDocColl );

        *pData = rNewData;
        if (bAreaChanged)
            pDoc->CompileDBFormula();

        if (bUndo)
        {
            ScDBCollection* pRedoColl = new ScDBCollection( *pDocColl );
            rDocShell.GetUndoManager()->AddUndoAction(
                            new ScUndoDBData( &rDocShell, pUndoColl, pRedoColl ) );
        }

        aModificator.SetDocumentModified();
        bDone = TRUE;
    }

    return bDone;
}

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

BOOL ScDBDocFunc::RepeatDB( const String& rDBName, BOOL bRecord, BOOL bApi )
{
    //!	auch fuer ScDBFunc::RepeatDB benutzen!

    BOOL bDone = FALSE;
    ScDocument* pDoc = rDocShell.GetDocument();
    if (bRecord && !pDoc->IsUndoEnabled())
        bRecord = FALSE;
    ScDBCollection*	pColl = pDoc->GetDBCollection();
    USHORT nIndex;
    if ( pColl && pColl->SearchName( rDBName, nIndex ) )
    {
        ScDBData* pDBData = (*pColl)[nIndex];

        ScQueryParam aQueryParam;
        pDBData->GetQueryParam( aQueryParam );
        BOOL bQuery = aQueryParam.GetEntry(0).bDoQuery;

        ScSortParam aSortParam;
        pDBData->GetSortParam( aSortParam );
        BOOL bSort = aSortParam.bDoSort[0];

        ScSubTotalParam aSubTotalParam;
        pDBData->GetSubTotalParam( aSubTotalParam );
        BOOL bSubTotal = aSubTotalParam.bGroupActive[0] && !aSubTotalParam.bRemoveOnly;

        if ( bQuery || bSort || bSubTotal )
        {
            BOOL bQuerySize = FALSE;
            ScRange aOldQuery;
            ScRange aNewQuery;
            if (bQuery && !aQueryParam.bInplace)
            {
                ScDBData* pDest = pDoc->GetDBAtCursor( aQueryParam.nDestCol, aQueryParam.nDestRow,
                                                        aQueryParam.nDestTab, TRUE );
                if (pDest && pDest->IsDoSize())
                {
                    pDest->GetArea( aOldQuery );
                    bQuerySize = TRUE;
                }
            }

            SCTAB nTab;
            SCCOL nStartCol;
            SCROW nStartRow;
            SCCOL nEndCol;
            SCROW nEndRow;
            pDBData->GetArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow );

            //!		Undo nur benoetigte Daten ?

            ScDocument* pUndoDoc = NULL;
            ScOutlineTable* pUndoTab = NULL;
            ScRangeName* pUndoRange = NULL;
            ScDBCollection* pUndoDB = NULL;

            if (bRecord)
            {
                SCTAB nTabCount = pDoc->GetTableCount();
                pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
                ScOutlineTable* pTable = pDoc->GetOutlineTable( nTab );
                if (pTable)
                {
                    pUndoTab = new ScOutlineTable( *pTable );

                    // column/row state
                    SCCOLROW nOutStartCol, nOutEndCol;
                    SCCOLROW nOutStartRow, nOutEndRow;
                    pTable->GetColArray()->GetRange( nOutStartCol, nOutEndCol );
                    pTable->GetRowArray()->GetRange( nOutStartRow, nOutEndRow );

                    pUndoDoc->InitUndo( pDoc, nTab, nTab, TRUE, TRUE );
                    pDoc->CopyToDocument( static_cast<SCCOL>(nOutStartCol), 0,
                            nTab, static_cast<SCCOL>(nOutEndCol), MAXROW, nTab,
                            IDF_NONE, FALSE, pUndoDoc );
                    pDoc->CopyToDocument( 0, static_cast<SCROW>(nOutStartRow),
                            nTab, MAXCOL, static_cast<SCROW>(nOutEndRow), nTab,
                            IDF_NONE, FALSE, pUndoDoc );
                }
                else
                    pUndoDoc->InitUndo( pDoc, nTab, nTab, FALSE, TRUE );

                //	Datenbereich sichern - incl. Filter-Ergebnis
                pDoc->CopyToDocument( 0,nStartRow,nTab, MAXCOL,nEndRow,nTab, IDF_ALL, FALSE, pUndoDoc );

                //	alle Formeln wegen Referenzen
                pDoc->CopyToDocument( 0,0,0, MAXCOL,MAXROW,nTabCount-1, IDF_FORMULA, FALSE, pUndoDoc );

                //	DB- und andere Bereiche
                ScRangeName* pDocRange = pDoc->GetRangeName();
                if (pDocRange->GetCount())
                    pUndoRange = new ScRangeName( *pDocRange );
                ScDBCollection* pDocDB = pDoc->GetDBCollection();
                if (pDocDB->GetCount())
                    pUndoDB = new ScDBCollection( *pDocDB );
            }

            if (bSort && bSubTotal)
            {
                //	Sortieren ohne SubTotals

                aSubTotalParam.bRemoveOnly = TRUE;		// wird unten wieder zurueckgesetzt
                DoSubTotals( nTab, aSubTotalParam, NULL, FALSE, bApi );
            }

            if (bSort)
            {
                pDBData->GetSortParam( aSortParam );			// Bereich kann sich geaendert haben
                Sort( nTab, aSortParam, FALSE, FALSE, bApi );
            }
            if (bQuery)
            {
                pDBData->GetQueryParam( aQueryParam );			// Bereich kann sich geaendert haben
                ScRange aAdvSource;
                if (pDBData->GetAdvancedQuerySource(aAdvSource))
                    Query( nTab, aQueryParam, &aAdvSource, FALSE, bApi );
                else
                    Query( nTab, aQueryParam, NULL, FALSE, bApi );

                //	bei nicht-inplace kann die Tabelle umgestellt worden sein
//				if ( !aQueryParam.bInplace && aQueryParam.nDestTab != nTab )
//					SetTabNo( nTab );
            }
            if (bSubTotal)
            {
                pDBData->GetSubTotalParam( aSubTotalParam );	// Bereich kann sich geaendert haben
                aSubTotalParam.bRemoveOnly = FALSE;
                DoSubTotals( nTab, aSubTotalParam, NULL, FALSE, bApi );
            }

            if (bRecord)
            {
                SCTAB nDummyTab;
                SCCOL nDummyCol;
                SCROW nDummyRow;
                SCROW nNewEndRow;
                pDBData->GetArea( nDummyTab, nDummyCol,nDummyRow, nDummyCol,nNewEndRow );

                const ScRange* pOld = NULL;
                const ScRange* pNew = NULL;
                if (bQuerySize)
                {
                    ScDBData* pDest = pDoc->GetDBAtCursor( aQueryParam.nDestCol, aQueryParam.nDestRow,
                                                            aQueryParam.nDestTab, TRUE );
                    if (pDest)
                    {
                        pDest->GetArea( aNewQuery );
                        pOld = &aOldQuery;
                        pNew = &aNewQuery;
                    }
                }

                rDocShell.GetUndoManager()->AddUndoAction(
                    new ScUndoRepeatDB( &rDocShell, nTab,
                                            nStartCol, nStartRow, nEndCol, nEndRow,
                                            nNewEndRow,
                                            //nCurX, nCurY,
                                            nStartCol, nStartRow,
                                            pUndoDoc, pUndoTab,
                                            pUndoRange, pUndoDB,
                                            pOld, pNew ) );
            }

            rDocShell.PostPaint( 0,0,nTab, MAXCOL,MAXROW,nTab,
                                    PAINT_GRID | PAINT_LEFT | PAINT_TOP | PAINT_SIZE );
            bDone = TRUE;
        }
        else if (!bApi)		// "Keine Operationen auszufuehren"
            rDocShell.ErrorMessage(STR_MSSG_REPEATDB_0);
    }

    return bDone;
}

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

BOOL ScDBDocFunc::Sort( SCTAB nTab, const ScSortParam& rSortParam,
                            BOOL bRecord, BOOL bPaint, BOOL bApi )
{
    ScDocShellModificator aModificator( rDocShell );

    ScDocument* pDoc = rDocShell.GetDocument();
    if (bRecord && !pDoc->IsUndoEnabled())
        bRecord = FALSE;
    SCTAB nSrcTab = nTab;
    ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();

    ScDBData* pDBData = pDoc->GetDBAtArea( nTab, rSortParam.nCol1, rSortParam.nRow1,
                                                    rSortParam.nCol2, rSortParam.nRow2 );
    if (!pDBData)
    {
        DBG_ERROR( "Sort: keine DBData" );
        return FALSE;
    }

    ScDBData* pDestData = NULL;
    ScRange aOldDest;
    BOOL bCopy = !rSortParam.bInplace;
    if ( bCopy && rSortParam.nDestCol == rSortParam.nCol1 &&
                  rSortParam.nDestRow == rSortParam.nRow1 && rSortParam.nDestTab == nTab )
        bCopy = FALSE;
    ScSortParam aLocalParam( rSortParam );
    if ( bCopy )
    {
        aLocalParam.MoveToDest();
        if ( !ValidColRow( aLocalParam.nCol2, aLocalParam.nRow2 ) )
        {
            if (!bApi)
                rDocShell.ErrorMessage(STR_PASTE_FULL);
            return FALSE;
        }

        nTab = rSortParam.nDestTab;
        pDestData = pDoc->GetDBAtCursor( rSortParam.nDestCol, rSortParam.nDestRow,
                                            rSortParam.nDestTab, TRUE );
        if (pDestData)
            pDestData->GetArea(aOldDest);
    }

    ScEditableTester aTester( pDoc, nTab, aLocalParam.nCol1,aLocalParam.nRow1,
                                        aLocalParam.nCol2,aLocalParam.nRow2 );
    if (!aTester.IsEditable())
    {
        if (!bApi)
            rDocShell.ErrorMessage(aTester.GetMessageId());
        return FALSE;
    }

    if ( aLocalParam.bIncludePattern && pDoc->HasAttrib(
                                        aLocalParam.nCol1, aLocalParam.nRow1, nTab,
                                        aLocalParam.nCol2, aLocalParam.nRow2, nTab,
                                        HASATTR_MERGED | HASATTR_OVERLAPPED ) )
    {
        //	Merge-Attribute wuerden beim Sortieren durcheinanderkommen
        if (!bApi)
            rDocShell.ErrorMessage(STR_SORT_ERR_MERGED);
        return FALSE;
    }


    //		ausfuehren

    WaitObject aWait( rDocShell.GetActiveDialogParent() );

    BOOL bRepeatQuery = FALSE;							// bestehenden Filter wiederholen?
    ScQueryParam aQueryParam;
    pDBData->GetQueryParam( aQueryParam );
    if ( aQueryParam.GetEntry(0).bDoQuery )
        bRepeatQuery = TRUE;

    if (bRepeatQuery && bCopy)
    {
        if ( aQueryParam.bInplace ||
                aQueryParam.nDestCol != rSortParam.nDestCol ||
                aQueryParam.nDestRow != rSortParam.nDestRow ||
                aQueryParam.nDestTab != rSortParam.nDestTab )		// Query auf selben Zielbereich?
            bRepeatQuery = FALSE;
    }

    ScUndoSort* pUndoAction = 0;
    if ( bRecord )
    {
        //  Referenzen ausserhalb des Bereichs werden nicht veraendert !

        ScDocument* pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
        //  Zeilenhoehen immer (wegen automatischer Anpassung)
        //! auf ScBlockUndo umstellen
        pUndoDoc->InitUndo( pDoc, nTab, nTab, FALSE, TRUE );

        /*  #i59745# Do not copy note captions to undo document. All existing
            caption objects will be repositioned while sorting which is tracked
            in drawing undo. When undo is executed, the old positions will be
            restored, and the cells with the old notes (which still refer to the
            existing captions) will be copied back into the source document. */
        pDoc->CopyToDocument( aLocalParam.nCol1, aLocalParam.nRow1, nTab,
                                aLocalParam.nCol2, aLocalParam.nRow2, nTab,
                                IDF_ALL|IDF_NOCAPTIONS, FALSE, pUndoDoc );

        const ScRange* pR = 0;
        if (pDestData)
        {
            /*  #i59745# Do not copy note captions from destination range to
                undo document. All existing caption objects will be removed
                which is tracked in drawing undo. When undo is executed, the
                caption objects are reinserted with drawing undo, and the cells
                with the old notes (which still refer to the existing captions)
                will be copied back into the source document. */
            pDoc->CopyToDocument( aOldDest, IDF_ALL|IDF_NOCAPTIONS, FALSE, pUndoDoc );
            pR = &aOldDest;
        }

        //	Zeilenhoehen immer (wegen automatischer Anpassung)
        //!	auf ScBlockUndo umstellen
//        if (bRepeatQuery)
            pDoc->CopyToDocument( 0, aLocalParam.nRow1, nTab, MAXCOL, aLocalParam.nRow2, nTab,
                                    IDF_NONE, FALSE, pUndoDoc );

        ScDBCollection* pUndoDB = NULL;
        ScDBCollection* pDocDB = pDoc->GetDBCollection();
        if (pDocDB->GetCount())
            pUndoDB = new ScDBCollection( *pDocDB );

        pUndoAction = new ScUndoSort( &rDocShell, nTab, rSortParam, bRepeatQuery, pUndoDoc, pUndoDB, pR );
        rDocShell.GetUndoManager()->AddUndoAction( pUndoAction );

        // #i59745# collect all drawing undo actions affecting cell note captions
        if( pDrawLayer )
            pDrawLayer->BeginCalcUndo();
    }

    if ( bCopy )
    {
        if (pDestData)
            pDoc->DeleteAreaTab(aOldDest, IDF_CONTENTS);			// Zielbereich vorher loeschen

        ScRange aSource( rSortParam.nCol1,rSortParam.nRow1,nSrcTab,
                            rSortParam.nCol2,rSortParam.nRow2,nSrcTab );
        ScAddress aDest( rSortParam.nDestCol, rSortParam.nDestRow, rSortParam.nDestTab );

        rDocShell.GetDocFunc().MoveBlock( aSource, aDest, FALSE, FALSE, FALSE, TRUE );
    }

    // #105780# don't call ScDocument::Sort with an empty SortParam (may be empty here if bCopy is set)
    if ( aLocalParam.bDoSort[0] )
        pDoc->Sort( nTab, aLocalParam, bRepeatQuery );

    BOOL bSave = TRUE;
    if (bCopy)
    {
        ScSortParam aOldSortParam;
        pDBData->GetSortParam( aOldSortParam );
        if ( aOldSortParam.bDoSort[0] && aOldSortParam.bInplace )	// Inplace-Sortierung gemerkt?
        {
            bSave = FALSE;
            aOldSortParam.nDestCol = rSortParam.nDestCol;
            aOldSortParam.nDestRow = rSortParam.nDestRow;
            aOldSortParam.nDestTab = rSortParam.nDestTab;
            pDBData->SetSortParam( aOldSortParam ); 				// dann nur DestPos merken
        }
    }
    if (bSave)												// Parameter merken
    {
        pDBData->SetSortParam( rSortParam );
        pDBData->SetHeader( rSortParam.bHasHeader );		//! ???
        pDBData->SetByRow( rSortParam.bByRow );				//! ???
    }

    if (bCopy)											// neuen DB-Bereich merken
    {
        //	Tabelle umschalten von aussen (View)
        //!	SetCursor ??!?!

        ScRange aDestPos( aLocalParam.nCol1, aLocalParam.nRow1, nTab,
                            aLocalParam.nCol2, aLocalParam.nRow2, nTab );
        ScDBData* pNewData;
        if (pDestData)
            pNewData = pDestData;				// Bereich vorhanden -> anpassen
        else									// Bereich ab Cursor/Markierung wird angelegt
            pNewData = rDocShell.GetDBData(aDestPos, SC_DB_MAKE, TRUE );
        if (pNewData)
        {
            pNewData->SetArea( nTab,
                                aLocalParam.nCol1,aLocalParam.nRow1,
                                aLocalParam.nCol2,aLocalParam.nRow2 );
            pNewData->SetSortParam( aLocalParam );
            pNewData->SetHeader( aLocalParam.bHasHeader );		//! ???
            pNewData->SetByRow( aLocalParam.bByRow );
        }
        else
        {
            DBG_ERROR("Zielbereich nicht da");
        }
    }

    ScRange aDirtyRange( aLocalParam.nCol1, aLocalParam.nRow1, nTab,
        aLocalParam.nCol2, aLocalParam.nRow2, nTab );
    pDoc->SetDirty( aDirtyRange );

    if (bPaint)
    {
        USHORT nPaint = PAINT_GRID;
        SCCOL nStartX = aLocalParam.nCol1;
        SCROW nStartY = aLocalParam.nRow1;
        SCCOL nEndX = aLocalParam.nCol2;
        SCROW nEndY = aLocalParam.nRow2;
        if ( bRepeatQuery )
        {
            nPaint |= PAINT_LEFT;
            nStartX = 0;
            nEndX = MAXCOL;
        }
        if (pDestData)
        {
            if ( nEndX < aOldDest.aEnd.Col() )
                nEndX = aOldDest.aEnd.Col();
            if ( nEndY < aOldDest.aEnd.Row() )
                nEndY = aOldDest.aEnd.Row();
        }
        rDocShell.PostPaint( nStartX, nStartY, nTab, nEndX, nEndY, nTab, nPaint );
    }

    //  AdjustRowHeight( aLocalParam.nRow1, aLocalParam.nRow2, bPaint );
    rDocShell.AdjustRowHeight( aLocalParam.nRow1, aLocalParam.nRow2, nTab );

    // #i59745# set collected drawing undo actions at sorting undo action
    if( pUndoAction && pDrawLayer )
        pUndoAction->SetDrawUndoAction( pDrawLayer->GetCalcUndo() );

    aModificator.SetDocumentModified();

    return TRUE;
}

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

BOOL ScDBDocFunc::Query( SCTAB nTab, const ScQueryParam& rQueryParam,
                        const ScRange* pAdvSource, BOOL bRecord, BOOL bApi )
{
    ScDocShellModificator aModificator( rDocShell );

    ScDocument* pDoc = rDocShell.GetDocument();
    if (bRecord && !pDoc->IsUndoEnabled())
        bRecord = FALSE;
    ScDBData* pDBData = pDoc->GetDBAtArea( nTab, rQueryParam.nCol1, rQueryParam.nRow1,
                                                    rQueryParam.nCol2, rQueryParam.nRow2 );
    if (!pDBData)
    {
        DBG_ERROR( "Query: keine DBData" );
        return FALSE;
    }

    //	Wechsel von Inplace auf nicht-Inplace, dann erst Inplace aufheben:
    //	(nur, wenn im Dialog "Persistent" ausgewaehlt ist)

    if ( !rQueryParam.bInplace && pDBData->HasQueryParam() && rQueryParam.bDestPers )
    {
        ScQueryParam aOldQuery;
        pDBData->GetQueryParam(aOldQuery);
        if (aOldQuery.bInplace)
        {
            //	alte Filterung aufheben

            SCSIZE nEC = aOldQuery.GetEntryCount();
            for (SCSIZE i=0; i<nEC; i++)
                aOldQuery.GetEntry(i).bDoQuery = FALSE;
            aOldQuery.bDuplicate = TRUE;
            Query( nTab, aOldQuery, NULL, bRecord, bApi );
        }
    }

    ScQueryParam aLocalParam( rQueryParam );		// fuer Paint / Zielbereich
    BOOL bCopy = !rQueryParam.bInplace; 			// kopiert wird in Table::Query
    ScDBData* pDestData = NULL;						// Bereich, in den kopiert wird
    BOOL bDoSize = FALSE;							// Zielgroesse anpassen (einf./loeschen)
    SCCOL nFormulaCols = 0;						// nur bei bDoSize
    BOOL bKeepFmt = FALSE;
    ScRange aOldDest;
    ScRange aDestTotal;
    if ( bCopy && rQueryParam.nDestCol == rQueryParam.nCol1 &&
                  rQueryParam.nDestRow == rQueryParam.nRow1 && rQueryParam.nDestTab == nTab )
        bCopy = FALSE;
    SCTAB nDestTab = nTab;
    if ( bCopy )
    {
        aLocalParam.MoveToDest();
        nDestTab = rQueryParam.nDestTab;
        if ( !ValidColRow( aLocalParam.nCol2, aLocalParam.nRow2 ) )
        {
            if (!bApi)
                rDocShell.ErrorMessage(STR_PASTE_FULL);
            return FALSE;
        }

        ScEditableTester aTester( pDoc, nDestTab, aLocalParam.nCol1,aLocalParam.nRow1,
                                                aLocalParam.nCol2,aLocalParam.nRow2);
        if (!aTester.IsEditable())
        {
            if (!bApi)
                rDocShell.ErrorMessage(aTester.GetMessageId());
            return FALSE;
        }

        pDestData = pDoc->GetDBAtCursor( rQueryParam.nDestCol, rQueryParam.nDestRow,
                                            rQueryParam.nDestTab, TRUE );
        if (pDestData)
        {
            pDestData->GetArea( aOldDest );
            aDestTotal=ScRange( rQueryParam.nDestCol,
                                rQueryParam.nDestRow,
                                nDestTab,
                                rQueryParam.nDestCol + rQueryParam.nCol2 - rQueryParam.nCol1,
                                rQueryParam.nDestRow + rQueryParam.nRow2 - rQueryParam.nRow1,
                                nDestTab );

            bDoSize = pDestData->IsDoSize();
            //	Test, ob Formeln aufgefuellt werden muessen (nFormulaCols):
            if ( bDoSize && aOldDest.aEnd.Col() == aDestTotal.aEnd.Col() )
            {
                SCCOL nTestCol = aOldDest.aEnd.Col() + 1;		// neben dem Bereich
                SCROW nTestRow = rQueryParam.nDestRow +
                                    ( aLocalParam.bHasHeader ? 1 : 0 );
                while ( nTestCol <= MAXCOL &&
                        pDoc->GetCellType(ScAddress( nTestCol, nTestRow, nTab )) == CELLTYPE_FORMULA )
                    ++nTestCol, ++nFormulaCols;
            }

            bKeepFmt = pDestData->IsKeepFmt();
            if ( bDoSize && !pDoc->CanFitBlock( aOldDest, aDestTotal ) )
            {
                if (!bApi)
                    rDocShell.ErrorMessage(STR_MSSG_DOSUBTOTALS_2);		// kann keine Zeilen einfuegen
                return FALSE;
            }
        }
    }

    //		ausfuehren

    WaitObject aWait( rDocShell.GetActiveDialogParent() );

    BOOL bKeepSub = FALSE;							// bestehende Teilergebnisse wiederholen?
    ScSubTotalParam aSubTotalParam;
    if (rQueryParam.GetEntry(0).bDoQuery)			// nicht beim Aufheben
    {
        pDBData->GetSubTotalParam( aSubTotalParam );	// Teilergebnisse vorhanden?

        if ( aSubTotalParam.bGroupActive[0] && !aSubTotalParam.bRemoveOnly )
            bKeepSub = TRUE;
    }

    ScDocument* pUndoDoc = NULL;
    ScDBCollection* pUndoDB = NULL;
    const ScRange* pOld = NULL;

    if ( bRecord )
    {
        pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
        if (bCopy)
        {
            pUndoDoc->InitUndo( pDoc, nDestTab, nDestTab, FALSE, TRUE );
            pDoc->CopyToDocument( aLocalParam.nCol1, aLocalParam.nRow1, nDestTab,
                                    aLocalParam.nCol2, aLocalParam.nRow2, nDestTab,
                                    IDF_ALL, FALSE, pUndoDoc );
            //	Attribute sichern, falls beim Filtern mitkopiert

            if (pDestData)
            {
                pDoc->CopyToDocument( aOldDest, IDF_ALL, FALSE, pUndoDoc );
                pOld = &aOldDest;
            }
        }
        else
        {
            pUndoDoc->InitUndo( pDoc, nTab, nTab, FALSE, TRUE );
            pDoc->CopyToDocument( 0, rQueryParam.nRow1, nTab, MAXCOL, rQueryParam.nRow2, nTab,
                                        IDF_NONE, FALSE, pUndoDoc );
        }

        ScDBCollection* pDocDB = pDoc->GetDBCollection();
        if (pDocDB->GetCount())
            pUndoDB = new ScDBCollection( *pDocDB );

        pDoc->BeginDrawUndo();
    }

    ScDocument* pAttribDoc = NULL;
    ScRange aAttribRange;
    if (pDestData)										// Zielbereich loeschen
    {
        if ( bKeepFmt )
        {
            //	kleinere der End-Spalten, Header+1 Zeile
            aAttribRange = aOldDest;
            if ( aAttribRange.aEnd.Col() > aDestTotal.aEnd.Col() )
                aAttribRange.aEnd.SetCol( aDestTotal.aEnd.Col() );
            aAttribRange.aEnd.SetRow( aAttribRange.aStart.Row() +
                                        ( aLocalParam.bHasHeader ? 1 : 0 ) );

            //	auch fuer aufgefuellte Formeln
            aAttribRange.aEnd.SetCol( aAttribRange.aEnd.Col() + nFormulaCols );

            pAttribDoc = new ScDocument( SCDOCMODE_UNDO );
            pAttribDoc->InitUndo( pDoc, nDestTab, nDestTab, FALSE, TRUE );
            pDoc->CopyToDocument( aAttribRange, IDF_ATTRIB, FALSE, pAttribDoc );
        }

        if ( bDoSize )
            pDoc->FitBlock( aOldDest, aDestTotal );
        else
            pDoc->DeleteAreaTab(aOldDest, IDF_ALL);			// einfach loeschen
    }

    //	Filtern am Dokument ausfuehren
    SCSIZE nCount = pDoc->Query( nTab, rQueryParam, bKeepSub );
    if (bCopy)
    {
        aLocalParam.nRow2 = aLocalParam.nRow1 + nCount;
        if (!aLocalParam.bHasHeader && nCount > 0)
            --aLocalParam.nRow2;

        if ( bDoSize )
        {
            //	auf wirklichen Ergebnis-Bereich anpassen
            //	(das hier ist immer eine Verkleinerung)

            ScRange aNewDest( aLocalParam.nCol1, aLocalParam.nRow1, nDestTab,
                                aLocalParam.nCol2, aLocalParam.nRow2, nDestTab );
            pDoc->FitBlock( aDestTotal, aNewDest, FALSE );		// FALSE - nicht loeschen

            if ( nFormulaCols > 0 )
            {
                //	Formeln ausfuellen
                //!	Undo (Query und Repeat) !!!

                ScRange aNewForm( aLocalParam.nCol2+1, aLocalParam.nRow1, nDestTab,
                                  aLocalParam.nCol2+nFormulaCols, aLocalParam.nRow2, nDestTab );
                ScRange aOldForm = aNewForm;
                aOldForm.aEnd.SetRow( aOldDest.aEnd.Row() );
                pDoc->FitBlock( aOldForm, aNewForm, FALSE );

                ScMarkData aMark;
                aMark.SelectOneTable(nDestTab);
                SCROW nFStartY = aLocalParam.nRow1 + ( aLocalParam.bHasHeader ? 1 : 0 );
                pDoc->Fill( aLocalParam.nCol2+1, nFStartY,
                            aLocalParam.nCol2+nFormulaCols, nFStartY, aMark,
                            aLocalParam.nRow2 - nFStartY,
                            FILL_TO_BOTTOM, FILL_SIMPLE );
            }
        }

        if ( pAttribDoc )		// gemerkte Attribute zurueckkopieren
        {
            //	Header
            if (aLocalParam.bHasHeader)
            {
                ScRange aHdrRange = aAttribRange;
                aHdrRange.aEnd.SetRow( aHdrRange.aStart.Row() );
                pAttribDoc->CopyToDocument( aHdrRange, IDF_ATTRIB, FALSE, pDoc );
            }

            //	Daten
            SCCOL nAttrEndCol = aAttribRange.aEnd.Col();
            SCROW nAttrRow = aAttribRange.aStart.Row() + ( aLocalParam.bHasHeader ? 1 : 0 );
            for (SCCOL nCol = aAttribRange.aStart.Col(); nCol<=nAttrEndCol; nCol++)
            {
                const ScPatternAttr* pSrcPattern = pAttribDoc->GetPattern(
                                                    nCol, nAttrRow, nDestTab );
                DBG_ASSERT(pSrcPattern,"Pattern ist 0");
                if (pSrcPattern)
                    pDoc->ApplyPatternAreaTab( nCol, nAttrRow, nCol, aLocalParam.nRow2,
                                                    nDestTab, *pSrcPattern );
                const ScStyleSheet* pStyle = pSrcPattern->GetStyleSheet();
                if (pStyle)
                    pDoc->ApplyStyleAreaTab( nCol, nAttrRow, nCol, aLocalParam.nRow2,
                                                    nDestTab, *pStyle );
            }

            delete pAttribDoc;
        }
    }

    //	speichern: Inplace immer, sonst je nach Einstellung
    //			   alter Inplace-Filter ist ggf. schon aufgehoben

    BOOL bSave = rQueryParam.bInplace || rQueryParam.bDestPers;
    if (bSave)													// merken
    {
        pDBData->SetQueryParam( rQueryParam );
        pDBData->SetHeader( rQueryParam.bHasHeader );		//! ???
        pDBData->SetAdvancedQuerySource( pAdvSource );		// after SetQueryParam
    }

    if (bCopy)												// neuen DB-Bereich merken
    {
        //	selektieren wird hinterher von aussen (dbfunc)
        //	momentan ueber DB-Bereich an der Zielposition, darum muss dort
        //	auf jeden Fall ein Bereich angelegt werden.

        ScDBData* pNewData;
        if (pDestData)
            pNewData = pDestData;				// Bereich vorhanden -> anpassen (immer!)
        else									// Bereich anlegen
            pNewData = rDocShell.GetDBData(
                            ScRange( aLocalParam.nCol1, aLocalParam.nRow1, nDestTab,
                                     aLocalParam.nCol2, aLocalParam.nRow2, nDestTab ),
                            SC_DB_MAKE, TRUE );

        if (pNewData)
        {
            pNewData->SetArea( nDestTab, aLocalParam.nCol1, aLocalParam.nRow1,
                                            aLocalParam.nCol2, aLocalParam.nRow2 );

            //	Query-Param wird am Ziel nicht mehr eingestellt, fuehrt nur zu Verwirrung
            //	und Verwechslung mit dem Query-Param am Quellbereich (#37187#)
        }
        else
        {
            DBG_ERROR("Zielbereich nicht da");
        }
    }

    if (!bCopy)
        pDoc->UpdatePageBreaks( nTab );

    // #i23299# because of Subtotal functions, the whole rows must be set dirty
    ScRange aDirtyRange( 0 , aLocalParam.nRow1, nDestTab,
        MAXCOL, aLocalParam.nRow2, nDestTab );
    pDoc->SetDirty( aDirtyRange );

    if ( bRecord )
    {
        // create undo action after executing, because of drawing layer undo
        rDocShell.GetUndoManager()->AddUndoAction(
                    new ScUndoQuery( &rDocShell, nTab, rQueryParam, pUndoDoc, pUndoDB,
                                        pOld, bDoSize, pAdvSource ) );
    }


    if (bCopy)
    {
        SCCOL nEndX = aLocalParam.nCol2;
        SCROW nEndY = aLocalParam.nRow2;
        if (pDestData)
        {
            if ( aOldDest.aEnd.Col() > nEndX )
                nEndX = aOldDest.aEnd.Col();
            if ( aOldDest.aEnd.Row() > nEndY )
                nEndY = aOldDest.aEnd.Row();
        }
        if (bDoSize)
            nEndY = MAXROW;
        rDocShell.PostPaint( aLocalParam.nCol1, aLocalParam.nRow1, nDestTab,
                                    nEndX, nEndY, nDestTab, PAINT_GRID );
    }
    else
        rDocShell.PostPaint( 0, rQueryParam.nRow1, nTab, MAXCOL, MAXROW, nTab,
                                                PAINT_GRID | PAINT_LEFT );
    aModificator.SetDocumentModified();

    return TRUE;
}

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

BOOL ScDBDocFunc::DoSubTotals( SCTAB nTab, const ScSubTotalParam& rParam,
                                const ScSortParam* pForceNewSort, BOOL bRecord, BOOL bApi )
{
    //!	auch fuer ScDBFunc::DoSubTotals benutzen!
    //	dann bleibt aussen:
    //	- neuen Bereich (aus DBData) markieren
    //	- SelectionChanged (?)

    BOOL bDo = !rParam.bRemoveOnly;							// FALSE = nur loeschen
    BOOL bRet = FALSE;

    ScDocument* pDoc = rDocShell.GetDocument();
    if (bRecord && !pDoc->IsUndoEnabled())
        bRecord = FALSE;
    ScDBData* pDBData = pDoc->GetDBAtArea( nTab, rParam.nCol1, rParam.nRow1,
                                                rParam.nCol2, rParam.nRow2 );
    if (!pDBData)
    {
        DBG_ERROR( "SubTotals: keine DBData" );
        return FALSE;
    }

    ScEditableTester aTester( pDoc, nTab, 0,rParam.nRow1+1, MAXCOL,MAXROW );
    if (!aTester.IsEditable())
    {
        if (!bApi)
            rDocShell.ErrorMessage(aTester.GetMessageId());
        return FALSE;
    }

    if (pDoc->HasAttrib( rParam.nCol1, rParam.nRow1+1, nTab,
                         rParam.nCol2, rParam.nRow2, nTab, HASATTR_MERGED | HASATTR_OVERLAPPED ))
    {
        if (!bApi)
            rDocShell.ErrorMessage(STR_MSSG_INSERTCELLS_0);	// nicht in zusammengefasste einfuegen
        return FALSE;
    }

    BOOL bOk = TRUE;
    BOOL bDelete = FALSE;
    if (rParam.bReplace)
        if (pDoc->TestRemoveSubTotals( nTab, rParam ))
        {
            bDelete = TRUE;
            bOk = ( MessBox( rDocShell.GetActiveDialogParent(), WinBits(WB_YES_NO | WB_DEF_YES),
                // "StarCalc" "Daten loeschen?"
                ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_0 ),
                ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_1 ) ).Execute()
                == RET_YES );
        }

    if (bOk)
    {
        WaitObject aWait( rDocShell.GetActiveDialogParent() );
        ScDocShellModificator aModificator( rDocShell );

        ScSubTotalParam aNewParam( rParam );		// Bereichsende wird veraendert
        ScDocument*		pUndoDoc = NULL;
        ScOutlineTable*	pUndoTab = NULL;
        ScRangeName*	pUndoRange = NULL;
        ScDBCollection* pUndoDB = NULL;
        SCTAB 			nTabCount = 0;				// fuer Referenz-Undo

        if (bRecord)										// alte Daten sichern
        {
            BOOL bOldFilter = bDo && rParam.bDoSort;

            nTabCount = pDoc->GetTableCount();
            pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
            ScOutlineTable* pTable = pDoc->GetOutlineTable( nTab );
            if (pTable)
            {
                pUndoTab = new ScOutlineTable( *pTable );

                // column/row state
                SCCOLROW nOutStartCol, nOutEndCol;
                SCCOLROW nOutStartRow, nOutEndRow;
                pTable->GetColArray()->GetRange( nOutStartCol, nOutEndCol );
                pTable->GetRowArray()->GetRange( nOutStartRow, nOutEndRow );

                pUndoDoc->InitUndo( pDoc, nTab, nTab, TRUE, TRUE );
                pDoc->CopyToDocument( static_cast<SCCOL>(nOutStartCol), 0, nTab, static_cast<SCCOL>(nOutEndCol), MAXROW, nTab, IDF_NONE, FALSE, pUndoDoc );
                pDoc->CopyToDocument( 0, nOutStartRow, nTab, MAXCOL, nOutEndRow, nTab, IDF_NONE, FALSE, pUndoDoc );
            }
            else
                pUndoDoc->InitUndo( pDoc, nTab, nTab, FALSE, bOldFilter );

            //	Datenbereich sichern - incl. Filter-Ergebnis
            pDoc->CopyToDocument( 0,rParam.nRow1+1,nTab, MAXCOL,rParam.nRow2,nTab,
                                    IDF_ALL, FALSE, pUndoDoc );

            //	alle Formeln wegen Referenzen
            pDoc->CopyToDocument( 0,0,0, MAXCOL,MAXROW,nTabCount-1,
                                        IDF_FORMULA, FALSE, pUndoDoc );

            //	DB- und andere Bereiche
            ScRangeName* pDocRange = pDoc->GetRangeName();
            if (pDocRange->GetCount())
                pUndoRange = new ScRangeName( *pDocRange );
            ScDBCollection* pDocDB = pDoc->GetDBCollection();
            if (pDocDB->GetCount())
                pUndoDB = new ScDBCollection( *pDocDB );
        }

//		pDoc->SetOutlineTable( nTab, NULL );
        ScOutlineTable*	pOut = pDoc->GetOutlineTable( nTab );
        if (pOut)
            pOut->GetRowArray()->RemoveAll();		// nur Zeilen-Outlines loeschen

        if (rParam.bReplace)
            pDoc->RemoveSubTotals( nTab, aNewParam );
        BOOL bSuccess = TRUE;
        if (bDo)
        {
            // Sortieren
            if ( rParam.bDoSort || pForceNewSort )
            {
                pDBData->SetArea( nTab, aNewParam.nCol1,aNewParam.nRow1, aNewParam.nCol2,aNewParam.nRow2 );

                //	Teilergebnis-Felder vor die Sortierung setzen
                //	(doppelte werden weggelassen, kann darum auch wieder aufgerufen werden)

                ScSortParam aOldSort;
                pDBData->GetSortParam( aOldSort );
                ScSortParam aSortParam( aNewParam, pForceNewSort ? *pForceNewSort : aOldSort );
                Sort( nTab, aSortParam, FALSE, FALSE, bApi );
            }

            bSuccess = pDoc->DoSubTotals( nTab, aNewParam );
        }
        ScRange aDirtyRange( aNewParam.nCol1, aNewParam.nRow1, nTab,
            aNewParam.nCol2, aNewParam.nRow2, nTab );
        pDoc->SetDirty( aDirtyRange );

        if (bRecord)
        {
//			ScDBData* pUndoDBData = pDBData ? new ScDBData( *pDBData ) : NULL;
            rDocShell.GetUndoManager()->AddUndoAction(
                new ScUndoSubTotals( &rDocShell, nTab,
                                        rParam, aNewParam.nRow2,
                                        pUndoDoc, pUndoTab, // pUndoDBData,
                                        pUndoRange, pUndoDB ) );
        }

        if (!bSuccess)
        {
            // "Kann keine Zeilen einfuegen"
            if (!bApi)
                rDocShell.ErrorMessage(STR_MSSG_DOSUBTOTALS_2);
        }

                                                    // merken
        pDBData->SetSubTotalParam( aNewParam );
        pDBData->SetArea( nTab, aNewParam.nCol1,aNewParam.nRow1, aNewParam.nCol2,aNewParam.nRow2 );
        pDoc->CompileDBFormula();

        rDocShell.PostPaint( 0,0,nTab, MAXCOL,MAXROW,nTab,
                                                PAINT_GRID | PAINT_LEFT | PAINT_TOP | PAINT_SIZE );
        aModificator.SetDocumentModified();

        bRet = bSuccess;
    }
    return bRet;
}

//==================================================================

BOOL lcl_EmptyExcept( ScDocument* pDoc, const ScRange& rRange, const ScRange& rExcept )
{
    ScCellIterator aIter( pDoc, rRange );
    ScBaseCell* pCell = aIter.GetFirst();
    while (pCell)
    {
        if ( !pCell->IsBlank() )      // real content?
        {
            if ( !rExcept.In( ScAddress( aIter.GetCol(), aIter.GetRow(), aIter.GetTab() ) ) )
                return FALSE;		// cell found
        }
        pCell = aIter.GetNext();
    }

    return TRUE;		// nothing found - empty
}

BOOL ScDBDocFunc::DataPilotUpdate( ScDPObject* pOldObj, const ScDPObject* pNewObj,
                                        BOOL bRecord, BOOL bApi, BOOL bAllowMove )
{
    ScDocShellModificator aModificator( rDocShell );
    WaitObject aWait( rDocShell.GetActiveDialogParent() );

    BOOL bDone = FALSE;
    BOOL bUndoSelf = FALSE;
    USHORT nErrId = 0;

    ScDocument* pOldUndoDoc = NULL;
    ScDocument* pNewUndoDoc = NULL;
    ScDPObject* pUndoDPObj = NULL;
    if ( bRecord && pOldObj )
        pUndoDPObj = new ScDPObject( *pOldObj );	// copy old settings for undo

    ScDocument* pDoc = rDocShell.GetDocument();
    if (bRecord && !pDoc->IsUndoEnabled())
        bRecord = FALSE;
    if ( !rDocShell.IsEditable() || pDoc->GetChangeTrack() )
    {
        //	not recorded -> disallow
        //!	different error messages?

        nErrId = STR_PROTECTIONERR;
    }
    if ( pOldObj && !nErrId )
    {
        ScRange aOldOut = pOldObj->GetOutRange();
        ScEditableTester aTester( pDoc, aOldOut );
        if ( !aTester.IsEditable() )
            nErrId = aTester.GetMessageId();
    }
    if ( pNewObj && !nErrId )
    {
        //	at least one cell at the output position must be editable
        //	-> check in advance
        //	(start of output range in pNewObj is valid)

        ScRange aNewStart( pNewObj->GetOutRange().aStart );
        ScEditableTester aTester( pDoc, aNewStart );
        if ( !aTester.IsEditable() )
            nErrId = aTester.GetMessageId();
    }

    ScDPObject* pDestObj = NULL;
    if ( !nErrId )
    {
        if ( pOldObj && !pNewObj )
        {
            //	delete table

            ScRange aRange = pOldObj->GetOutRange();
            SCTAB nTab = aRange.aStart.Tab();

            if ( bRecord )
            {
                pOldUndoDoc = new ScDocument( SCDOCMODE_UNDO );
                pOldUndoDoc->InitUndo( pDoc, nTab, nTab );
                pDoc->CopyToDocument( aRange, IDF_ALL, FALSE, pOldUndoDoc );
            }

            pDoc->DeleteAreaTab( aRange.aStart.Col(), aRange.aStart.Row(),
                                 aRange.aEnd.Col(),   aRange.aEnd.Row(),
                                 nTab, IDF_ALL );
            pDoc->RemoveFlagsTab( aRange.aStart.Col(), aRange.aStart.Row(),
                                  aRange.aEnd.Col(),   aRange.aEnd.Row(),
                                  nTab, SC_MF_AUTO );

            pDoc->GetDPCollection()->FreeTable( pOldObj );  // object is deleted here

            rDocShell.PostPaintGridAll();	//! only necessary parts
            rDocShell.PostPaint( aRange.aStart.Col(), aRange.aStart.Row(), nTab,
                                 aRange.aEnd.Col(),   aRange.aEnd.Row(),   nTab,
                                 PAINT_GRID );
            bDone = TRUE;
        }
        else if ( pNewObj )
        {
            if ( pOldObj )
            {
                if ( bRecord )
                {
                    ScRange aRange = pOldObj->GetOutRange();
                    SCTAB nTab = aRange.aStart.Tab();
                    pOldUndoDoc = new ScDocument( SCDOCMODE_UNDO );
                    pOldUndoDoc->InitUndo( pDoc, nTab, nTab );
                    pDoc->CopyToDocument( aRange, IDF_ALL, FALSE, pOldUndoDoc );
                }

                if ( pNewObj == pOldObj )
                {
                    //	refresh only - no settings modified
                }
                else
                {
                    pNewObj->WriteSourceDataTo( *pOldObj );		// copy source data

                    ScDPSaveData* pData = pNewObj->GetSaveData();
                    DBG_ASSERT( pData, "no SaveData from living DPObject" );
                    if ( pData )
                        pOldObj->SetSaveData( *pData );		// copy SaveData
                }

                pDestObj = pOldObj;
                pDestObj->SetAllowMove( bAllowMove );
            }
            else
            {
                //	output range must be set at pNewObj

                pDestObj = new ScDPObject( *pNewObj );
                pDestObj->SetAlive(TRUE);
                if ( !pDoc->GetDPCollection()->InsertNewTable(pDestObj) )
                {
                    DBG_ERROR("cannot insert DPObject");
                    DELETEZ( pDestObj );
                }
            }
            if ( pDestObj )
            {
                // #78541# create new database connection for "refresh"
                // (and re-read column entry collections)
                // so all changes take effect
                if ( pNewObj == pOldObj && pDestObj->IsImportData() )
                    pDestObj->InvalidateSource();

                pDestObj->InvalidateData();				// before getting the new output area

                //	make sure the table has a name (not set by dialog)
                if ( !pDestObj->GetName().Len() )
                    pDestObj->SetName( pDoc->GetDPCollection()->CreateNewName() );

                BOOL bOverflow = FALSE;
                ScRange aNewOut = pDestObj->GetNewOutputRange( bOverflow );

                //!	test for overlap with other data pilot tables
                if( pOldObj )
                {   
                    const ScSheetSourceDesc* pSheetDesc = pOldObj->GetSheetDesc();
                    if( pSheetDesc && pSheetDesc->aSourceRange.Intersects( aNewOut ) )
                    {
                        ScRange aOldRange = pOldObj->GetOutRange();
                        SCsROW nDiff = aOldRange.aStart.Row()-aNewOut.aStart.Row();
                        aNewOut.aStart.SetRow( aOldRange.aStart.Row() );
                        aNewOut.aEnd.SetRow( aNewOut.aEnd.Row()+nDiff );
                        if( !ValidRow( aNewOut.aStart.Row() ) || !ValidRow( aNewOut.aEnd.Row() ) )
                            bOverflow = TRUE;
                    }
                }

                if ( bOverflow )
                {
                    //	like with STR_PROTECTIONERR, use undo to reverse everything
                    DBG_ASSERT( bRecord, "DataPilotUpdate: can't undo" );
                    bUndoSelf = TRUE;
                    nErrId = STR_PIVOT_ERROR;
                }
                else
                {
                    ScEditableTester aTester( pDoc, aNewOut );
                    if ( !aTester.IsEditable() )
                    {
                        //	destination area isn't editable
                        //!	reverse everything done so far, don't proceed

                        //	quick solution: proceed to end, use undo action
                        //	to reverse everything:
                        DBG_ASSERT( bRecord, "DataPilotUpdate: can't undo" );
                        bUndoSelf = TRUE;
                        nErrId = aTester.GetMessageId();
                    }
                }

                //	test if new output area is empty except for old area
                if ( !bApi )
                {
                    BOOL bEmpty;
                    if ( pOldObj )	// OutRange of pOldObj (pDestObj) is still old area
                        bEmpty = lcl_EmptyExcept( pDoc, aNewOut, pOldObj->GetOutRange() );
                    else
                        bEmpty = pDoc->IsBlockEmpty( aNewOut.aStart.Tab(),
                                            aNewOut.aStart.Col(), aNewOut.aStart.Row(),
                                            aNewOut.aEnd.Col(), aNewOut.aEnd.Row() );

                    if ( !bEmpty )
                    {
                        QueryBox aBox( rDocShell.GetActiveDialogParent(), WinBits(WB_YES_NO | WB_DEF_YES),
                                         ScGlobal::GetRscString(STR_PIVOT_NOTEMPTY) );
                        if (aBox.Execute() == RET_NO)
                        {
                            //!	like above (not editable), use undo to reverse everything
                            DBG_ASSERT( bRecord, "DataPilotUpdate: can't undo" );
                            bUndoSelf = TRUE;
                        }
                    }
                }

                if ( bRecord )
                {
                    SCTAB nTab = aNewOut.aStart.Tab();
                    pNewUndoDoc = new ScDocument( SCDOCMODE_UNDO );
                    pNewUndoDoc->InitUndo( pDoc, nTab, nTab );
                    pDoc->CopyToDocument( aNewOut, IDF_ALL, FALSE, pNewUndoDoc );
                }

                pDestObj->Output( aNewOut.aStart );

                rDocShell.PostPaintGridAll();			//! only necessary parts
                bDone = TRUE;
            }
        }
        // else nothing (no old, no new)
    }

    if ( bRecord && bDone )
    {
        SfxUndoAction* pAction = new ScUndoDataPilot( &rDocShell,
                                    pOldUndoDoc, pNewUndoDoc, pUndoDPObj, pDestObj, bAllowMove );
        pOldUndoDoc = NULL;
        pNewUndoDoc = NULL;		// pointers are used in undo action
        // pUndoDPObj is copied

        if (bUndoSelf)
        {
            //	use undo action to restore original state
            //!	prevent setting the document modified? (ScDocShellModificator)

            pAction->Undo();
            delete pAction;
            bDone = FALSE;
        }
        else
            rDocShell.GetUndoManager()->AddUndoAction( pAction );
    }

    delete pOldUndoDoc;		// if not used for undo
    delete pNewUndoDoc;
    delete pUndoDPObj;

    if (bDone)
        aModificator.SetDocumentModified();

    if ( nErrId && !bApi )
        rDocShell.ErrorMessage( nErrId );

    return bDone;
}

//==================================================================
//
//		Datenbank-Import...

void ScDBDocFunc::UpdateImport( const String& rTarget, const String& rDBName,
        const String& rTableName, const String& rStatement, BOOL bNative,
        BYTE nType, const ::com::sun::star::uno::Reference<
        ::com::sun::star::sdbc::XResultSet >& xResultSet,
        const SbaSelectionList* pSelection )
{
    //	Target ist jetzt einfach der Bereichsname

    ScDocument* pDoc = rDocShell.GetDocument();
    ScDBCollection& rDBColl = *pDoc->GetDBCollection();
    ScDBData* pData = NULL;
    ScImportParam aImportParam;
    BOOL bFound = FALSE;
    USHORT nCount = rDBColl.GetCount();
    for (USHORT i=0; i<nCount && !bFound; i++)
    {
        pData = rDBColl[i];
        if (pData->GetName() == rTarget)
            bFound = TRUE;
    }
    if (!bFound)
    {
        InfoBox aInfoBox(rDocShell.GetActiveDialogParent(),
                    ScGlobal::GetRscString( STR_TARGETNOTFOUND ) );
        aInfoBox.Execute();
        return;
    }

    SCTAB nTab;
    SCCOL nDummyCol;
    SCROW nDummyRow;
    pData->GetArea( nTab, nDummyCol,nDummyRow,nDummyCol,nDummyRow );
    pData->GetImportParam( aImportParam );

    BOOL bSql = ( rStatement.Len() != 0 );

    aImportParam.aDBName	= rDBName;
    aImportParam.bSql		= bSql;
    aImportParam.aStatement = bSql ? rStatement : rTableName;
    aImportParam.bNative	= bNative;
    aImportParam.nType		= nType;
    aImportParam.bImport	= TRUE;
    BOOL bContinue = DoImport( nTab, aImportParam, xResultSet, pSelection, TRUE );

    //	DB-Operationen wiederholen

    ScTabViewShell* pViewSh = rDocShell.GetBestViewShell();
    if (pViewSh)
    {
        ScRange aRange;
        pData->GetArea(aRange);
        pViewSh->MarkRange(aRange);			// selektieren

        if ( bContinue )		// #41905# Fehler beim Import -> Abbruch
        {
            //	interne Operationen, wenn welche gespeichert

            if ( pData->HasQueryParam() || pData->HasSortParam() || pData->HasSubTotalParam() )
                pViewSh->RepeatDB();

            //	Pivottabellen die den Bereich als Quelldaten haben

            rDocShell.RefreshPivotTables(aRange);
        }
    }
}