1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <memory>
#include <strings.hrc>
#include <strings.hxx>
#include <core_resource.hxx>
#include <WCopyTable.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/sdb/application/XCopyTableWizard.hpp>
#include <com/sun/star/sdb/application/CopyTableContinuation.hpp>
#include <com/sun/star/sdb/application/CopyTableOperation.hpp>
#include <com/sun/star/ucb/AlreadyInitializedException.hpp>
#include <com/sun/star/lang/NotInitializedException.hpp>
#include <com/sun/star/sdbc/XDataSource.hpp>
#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/task/InteractionHandler.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/sdb/DatabaseContext.hpp>
#include <com/sun/star/sdb/XDocumentDataSource.hpp>
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#include <com/sun/star/sdb/CommandType.hpp>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#include <com/sun/star/sdbc/XParameters.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbcx/XRowLocate.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <com/sun/star/sdb/SQLContext.hpp>
#include <com/sun/star/sdbc/DriverManager.hpp>
#include <com/sun/star/sdbc/ConnectionPool.hpp>
#include <comphelper/processfactory.hxx>
#include <comphelper/interaction.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <comphelper/proparrhlp.hxx>
#include <connectivity/dbexception.hxx>
#include <connectivity/dbtools.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/implbase.hxx>
#include <comphelper/interfacecontainer3.hxx>
#include <o3tl/safeint.hxx>
#include <rtl/ustrbuf.hxx>
#include <sal/log.hxx>
#include <svtools/genericunodialog.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <comphelper/diagnose_ex.hxx>
#include <unotools/sharedunocomponent.hxx>
#include <vcl/svapp.hxx>
namespace dbaui
{
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::UNO_SET_THROW;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::beans::Property;
using ::com::sun::star::sdb::application::XCopyTableWizard;
using ::com::sun::star::sdb::application::XCopyTableListener;
using ::com::sun::star::sdb::application::CopyTableRowEvent;
using ::com::sun::star::beans::Optional;
using ::com::sun::star::lang::IllegalArgumentException;
using ::com::sun::star::ucb::AlreadyInitializedException;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::lang::NotInitializedException;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::sdbc::XConnection;
using ::com::sun::star::sdbc::XDataSource;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XChild;
using ::com::sun::star::task::InteractionHandler;
using ::com::sun::star::task::XInteractionHandler;
using ::com::sun::star::frame::XModel;
using ::com::sun::star::sdb::DatabaseContext;
using ::com::sun::star::sdb::XDatabaseContext;
using ::com::sun::star::sdb::XDocumentDataSource;
using ::com::sun::star::sdb::XCompletedConnection;
using ::com::sun::star::lang::WrappedTargetException;
using ::com::sun::star::sdbcx::XTablesSupplier;
using ::com::sun::star::sdb::XQueriesSupplier;
using ::com::sun::star::lang::DisposedException;
using ::com::sun::star::sdbc::XPreparedStatement;
using ::com::sun::star::sdb::XSingleSelectQueryComposer;
using ::com::sun::star::sdbc::XDatabaseMetaData;
using ::com::sun::star::sdbcx::XColumnsSupplier;
using ::com::sun::star::sdbc::XParameters;
using ::com::sun::star::sdbc::XResultSet;
using ::com::sun::star::sdbc::XRow;
using ::com::sun::star::sdbcx::XRowLocate;
using ::com::sun::star::sdbc::XResultSetMetaDataSupplier;
using ::com::sun::star::sdbc::XResultSetMetaData;
using ::com::sun::star::sdbc::SQLException;
using ::com::sun::star::sdb::SQLContext;
using ::com::sun::star::sdbc::ConnectionPool;
using ::com::sun::star::sdbc::XDriverManager;
using ::com::sun::star::sdbc::DriverManager;
using ::com::sun::star::beans::PropertyValue;
namespace CopyTableOperation = ::com::sun::star::sdb::application::CopyTableOperation;
namespace CopyTableContinuation = ::com::sun::star::sdb::application::CopyTableContinuation;
namespace CommandType = ::com::sun::star::sdb::CommandType;
namespace DataType = ::com::sun::star::sdbc::DataType;
typedef ::utl::SharedUNOComponent< XConnection > SharedConnection;
// CopyTableWizard
typedef ::svt::OGenericUnoDialog CopyTableWizard_DialogBase;
typedef ::cppu::ImplInheritanceHelper< CopyTableWizard_DialogBase
, XCopyTableWizard
> CopyTableWizard_Base;
namespace {
class CopyTableWizard
:public CopyTableWizard_Base
,public ::comphelper::OPropertyArrayUsageHelper< CopyTableWizard >
{
public:
// XServiceInfo
virtual OUString SAL_CALL getImplementationName() override;
virtual css::uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() override;
// XCopyTableWizard
virtual ::sal_Int16 SAL_CALL getOperation() override;
virtual void SAL_CALL setOperation( ::sal_Int16 _operation ) override;
virtual OUString SAL_CALL getDestinationTableName() override;
virtual void SAL_CALL setDestinationTableName( const OUString& _destinationTableName ) override;
virtual Optional< OUString > SAL_CALL getCreatePrimaryKey() override;
virtual void SAL_CALL setCreatePrimaryKey( const Optional< OUString >& _newPrimaryKey ) override;
virtual sal_Bool SAL_CALL getUseHeaderLineAsColumnNames() override;
virtual void SAL_CALL setUseHeaderLineAsColumnNames( sal_Bool _bUseHeaderLineAsColumnNames ) override;
virtual void SAL_CALL addCopyTableListener( const Reference< XCopyTableListener >& Listener ) override;
virtual void SAL_CALL removeCopyTableListener( const Reference< XCopyTableListener >& Listener ) override;
// XCopyTableWizard::XExecutableDialog
virtual void SAL_CALL setTitle( const OUString& aTitle ) override;
virtual ::sal_Int16 SAL_CALL execute( ) override;
// XInitialization
virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) override;
// XPropertySet
virtual Reference< XPropertySetInfo > SAL_CALL getPropertySetInfo() override;
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() override;
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const override;
public:
::osl::Mutex& getMutex() { return m_aMutex; }
bool isInitialized() const { return m_xSourceConnection.is() && m_pSourceObject && m_xDestConnection.is(); }
explicit CopyTableWizard( const Reference< XComponentContext >& _rxORB );
virtual ~CopyTableWizard() override;
protected:
// OGenericUnoDialog overridables
virtual std::unique_ptr<weld::DialogController> createDialog(const css::uno::Reference<css::awt::XWindow>& rParent) override;
virtual void executedDialog( sal_Int16 _nExecutionResult ) override;
private:
/// ensures our current attribute values are reflected in the dialog
void impl_attributesToDialog_nothrow( OCopyTableWizard& _rDialog ) const;
/// ensures the current dialog settings are reflected in our attributes
void impl_dialogToAttributes_nothrow( const OCopyTableWizard& _rDialog );
/** returns our typed dialog
@throws css::uno::RuntimeException
if we don't have a dialog at the moment the method is called
*/
OCopyTableWizard&
impl_getDialog_throw();
/** ensures the given argument sequence contains a valid data access descriptor at the given position
@param _rAllArgs
the arguments as passed to ->initialize
@param _nArgPos
the position within ->_rAllArgs which contains the data access descriptor
@param _out_rxConnection
will, upon successful return, contain the connection for the data source
@param _out_rxDocInteractionHandler
will, upon successful return, contain the interaction handler which could
be deduced from database document described by the descriptor, if any.
(It is possible that the descriptor does not allow to deduce a database document,
in which case <code>_out_rxDocInteractionHandler</code> will be <NULL/>.)
@return the data access descriptor
*/
Reference< XPropertySet >
impl_ensureDataAccessDescriptor_throw(
const Sequence< Any >& _rAllArgs,
const sal_Int16 _nArgPos,
SharedConnection& _out_rxConnection,
Reference< XInteractionHandler >& _out_rxDocInteractionHandler
) const;
/** extracts the source object (table or query) described by the given descriptor,
relative to m_xSourceConnection
*/
std::unique_ptr< ICopyTableSourceObject >
impl_extractSourceObject_throw(
const Reference< XPropertySet >& _rxDescriptor,
sal_Int32& _out_rCommandType
) const;
/** extracts the result set to copy records from, and the selection-related aspects, if any.
Effectively, this method extracts m_xSourceResultSet, m_aSourceSelection, and m_bSourceSelectionBookmarks.
If an inconsistent/insufficient sub set of those properties is present in the descriptor, and exception
is thrown.
*/
void impl_extractSourceResultSet_throw(
const Reference< XPropertySet >& i_rDescriptor
);
/** checks whether the given copy source descriptor contains settings which are not
supported (yet)
Throws an IllegalArgumentException if the descriptor contains a valid setting, which is
not yet supported.
*/
void impl_checkForUnsupportedSettings_throw(
const Reference< XPropertySet >& _rxSourceDescriptor ) const;
/** obtains the connection described by the given data access descriptor
If needed and possible, the method will ask the user, using the interaction
handler associated with the database described by the descriptor.
All errors are handled with the InteractionHandler associated with the data source,
if there is one. Else, they will be silenced (but asserted in non-product builds).
@param _rxDataSourceDescriptor
the data access descriptor describing the data source whose connection
should be obtained. Must not be <NULL/>.
@param _out_rxDocInteractionHandler
the interaction handler which could be deduced from the descriptor
@throws RuntimeException
if anything goes seriously wrong.
*/
SharedConnection
impl_extractConnection_throw(
const Reference< XPropertySet >& _rxDataSourceDescriptor,
Reference< XInteractionHandler >& _out_rxDocInteractionHandler
) const;
/** actually copies the table
This method is called after the dialog has been successfully executed.
*/
void impl_doCopy_nothrow();
/** creates the INSERT INTO statement
@param _xTable The destination table.
*/
OUString impl_getServerSideCopyStatement_throw( const Reference< XPropertySet >& _xTable );
/** creates the statement which, when executed, will produce the source data to copy
If the source object refers to a query which contains parameters, those parameters
are filled in, using an interaction handler.
*/
::utl::SharedUNOComponent< XPreparedStatement >
impl_createSourceStatement_throw() const;
/** copies the data rows from the given source result set to the given destination table
*/
void impl_copyRows_throw(
const Reference< XResultSet >& _rxSourceResultSet,
const Reference< XPropertySet >& _rxDestTable
);
/** processes an error which occurred during copying
First, all listeners are ask. If a listener tells to cancel or continue copying, this is reported to the
method's caller. If a listener tells to ask the user, this is done, and the user's decision is
reported to the method's caller.
@return
<TRUE/> if and only if copying should be continued.
*/
bool impl_processCopyError_nothrow(
const CopyTableRowEvent& _rEvent );
private:
Reference<XComponentContext> m_xContext;
// attributes
sal_Int16 m_nOperation;
OUString m_sDestinationTable;
Optional< OUString > m_aPrimaryKeyName;
bool m_bUseHeaderLineAsColumnNames;
// source
SharedConnection m_xSourceConnection;
sal_Int32 m_nCommandType;
std::unique_ptr< ICopyTableSourceObject >
m_pSourceObject;
Reference< XResultSet > m_xSourceResultSet;
Sequence< Any > m_aSourceSelection;
bool m_bSourceSelectionBookmarks;
// destination
SharedConnection m_xDestConnection;
// other
Reference< XInteractionHandler > m_xInteractionHandler;
::comphelper::OInterfaceContainerHelper3<XCopyTableListener>
m_aCopyTableListeners;
sal_Int16 m_nOverrideExecutionResult;
};
// MethodGuard
class CopyTableAccessGuard
{
public:
explicit CopyTableAccessGuard( CopyTableWizard& _rWizard )
:m_rWizard( _rWizard )
{
m_rWizard.getMutex().acquire();
if ( !m_rWizard.isInitialized() )
throw NotInitializedException();
}
~CopyTableAccessGuard()
{
m_rWizard.getMutex().release();
}
private:
CopyTableWizard& m_rWizard;
};
}
CopyTableWizard::CopyTableWizard( const Reference< XComponentContext >& _rxORB )
:CopyTableWizard_Base( _rxORB )
,m_xContext( _rxORB )
,m_nOperation( CopyTableOperation::CopyDefinitionAndData )
,m_aPrimaryKeyName( false, "ID" )
,m_bUseHeaderLineAsColumnNames( true )
,m_nCommandType( CommandType::COMMAND )
,m_bSourceSelectionBookmarks( true )
,m_aCopyTableListeners( m_aMutex )
,m_nOverrideExecutionResult( -1 )
{
}
CopyTableWizard::~CopyTableWizard()
{
acquire();
// protect some members whose dtor might potentially throw
try { m_xSourceConnection.clear(); }
catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION("dbaccess"); }
try { m_xDestConnection.clear(); }
catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION("dbaccess"); }
// TODO: shouldn't we have explicit disposal support? If a listener is registered
// at our instance, and perhaps holds this our instance by a hard ref, then we'll never
// be destroyed.
// However, adding XComponent support to the GenericUNODialog probably requires
// some thinking - would it break existing clients which do not call a dispose, then?
}
OUString SAL_CALL CopyTableWizard::getImplementationName()
{
return "org.openoffice.comp.dbu.CopyTableWizard";
}
css::uno::Sequence<OUString> SAL_CALL CopyTableWizard::getSupportedServiceNames()
{
return { "com.sun.star.sdb.application.CopyTableWizard" };
}
Reference< XPropertySetInfo > SAL_CALL CopyTableWizard::getPropertySetInfo()
{
Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
::sal_Int16 SAL_CALL CopyTableWizard::getOperation()
{
CopyTableAccessGuard aGuard( *this );
return m_nOperation;
}
void SAL_CALL CopyTableWizard::setOperation( ::sal_Int16 _operation )
{
CopyTableAccessGuard aGuard( *this );
if ( ( _operation != CopyTableOperation::CopyDefinitionAndData )
&& ( _operation != CopyTableOperation::CopyDefinitionOnly )
&& ( _operation != CopyTableOperation::CreateAsView )
&& ( _operation != CopyTableOperation::AppendData )
)
throw IllegalArgumentException( OUString(), *this, 1 );
if ( ( _operation == CopyTableOperation::CreateAsView )
&& !OCopyTableWizard::supportsViews( m_xDestConnection )
)
throw IllegalArgumentException(
DBA_RES( STR_CTW_NO_VIEWS_SUPPORT ),
*this,
1
);
m_nOperation = _operation;
}
OUString SAL_CALL CopyTableWizard::getDestinationTableName()
{
CopyTableAccessGuard aGuard( *this );
return m_sDestinationTable;
}
void SAL_CALL CopyTableWizard::setDestinationTableName( const OUString& _destinationTableName )
{
CopyTableAccessGuard aGuard( *this );
m_sDestinationTable = _destinationTableName;
}
Optional< OUString > SAL_CALL CopyTableWizard::getCreatePrimaryKey()
{
CopyTableAccessGuard aGuard( *this );
return m_aPrimaryKeyName;
}
void SAL_CALL CopyTableWizard::setCreatePrimaryKey( const Optional< OUString >& _newPrimaryKey )
{
CopyTableAccessGuard aGuard( *this );
if ( _newPrimaryKey.IsPresent && !OCopyTableWizard::supportsPrimaryKey( m_xDestConnection ) )
throw IllegalArgumentException(
DBA_RES( STR_CTW_NO_PRIMARY_KEY_SUPPORT ),
*this,
1
);
m_aPrimaryKeyName = _newPrimaryKey;
}
sal_Bool SAL_CALL CopyTableWizard::getUseHeaderLineAsColumnNames()
{
CopyTableAccessGuard aGuard( *this );
return m_bUseHeaderLineAsColumnNames;
}
void SAL_CALL CopyTableWizard::setUseHeaderLineAsColumnNames( sal_Bool _bUseHeaderLineAsColumnNames )
{
CopyTableAccessGuard aGuard( *this );
m_bUseHeaderLineAsColumnNames = _bUseHeaderLineAsColumnNames;
}
void SAL_CALL CopyTableWizard::addCopyTableListener( const Reference< XCopyTableListener >& _rxListener )
{
CopyTableAccessGuard aGuard( *this );
if ( _rxListener.is() )
m_aCopyTableListeners.addInterface( _rxListener );
}
void SAL_CALL CopyTableWizard::removeCopyTableListener( const Reference< XCopyTableListener >& _rxListener )
{
CopyTableAccessGuard aGuard( *this );
if ( _rxListener.is() )
m_aCopyTableListeners.removeInterface( _rxListener );
}
void SAL_CALL CopyTableWizard::setTitle( const OUString& _rTitle )
{
CopyTableAccessGuard aGuard( *this );
CopyTableWizard_DialogBase::setTitle( _rTitle );
}
::sal_Int16 SAL_CALL CopyTableWizard::execute( )
{
CopyTableAccessGuard aGuard( *this );
m_nOverrideExecutionResult = -1;
sal_Int16 nExecutionResult = CopyTableWizard_DialogBase::execute();
if ( m_nOverrideExecutionResult )
nExecutionResult = m_nOverrideExecutionResult;
return nExecutionResult;
}
OCopyTableWizard& CopyTableWizard::impl_getDialog_throw()
{
OCopyTableWizard* pWizard = dynamic_cast<OCopyTableWizard*>(m_xDialog.get());
if ( !pWizard )
throw DisposedException( OUString(), *this );
return *pWizard;
}
void CopyTableWizard::impl_attributesToDialog_nothrow( OCopyTableWizard& _rDialog ) const
{
// primary key column
_rDialog.setCreatePrimaryKey( m_aPrimaryKeyName.IsPresent, m_aPrimaryKeyName.Value );
_rDialog.setUseHeaderLine(m_bUseHeaderLineAsColumnNames);
// everything else was passed at construction time already
}
void CopyTableWizard::impl_dialogToAttributes_nothrow( const OCopyTableWizard& _rDialog )
{
m_aPrimaryKeyName.IsPresent = _rDialog.shouldCreatePrimaryKey();
if ( m_aPrimaryKeyName.IsPresent )
m_aPrimaryKeyName.Value = _rDialog.getPrimaryKeyName();
else
m_aPrimaryKeyName.Value.clear();
m_sDestinationTable = _rDialog.getName();
m_nOperation = _rDialog.getOperation();
m_bUseHeaderLineAsColumnNames = _rDialog.UseHeaderLine();
}
namespace
{
/** tries to obtain the InteractionHandler associated with a given data source
If the data source is a sdb-level data source, it will have a DatabaseDocument associated
with it. This document may have an InteractionHandler used while loading it.
@throws RuntimeException
if it occurs during invoking any of the data source's methods, or if any of the involved
components violates its contract by not providing the required interfaces
*/
Reference< XInteractionHandler > lcl_getInteractionHandler_throw( const Reference< XDataSource >& _rxDataSource, const Reference< XInteractionHandler >& _rFallback )
{
Reference< XInteractionHandler > xHandler( _rFallback );
// try to obtain the document model
Reference< XModel > xDocumentModel;
Reference< XDocumentDataSource > xDocDataSource( _rxDataSource, UNO_QUERY );
if ( xDocDataSource.is() )
xDocumentModel.set( xDocDataSource->getDatabaseDocument(), UNO_QUERY_THROW );
// see whether the document model can provide a handler
if ( xDocumentModel.is() )
{
xHandler = ::comphelper::NamedValueCollection::getOrDefault( xDocumentModel->getArgs(), u"InteractionHandler", xHandler );
}
return xHandler;
}
/** tries to obtain the InteractionHandler associated with a given connection
If the connection belongs to a sdb-level data source, then this data source
is examined for an interaction handler. Else, <NULL/> is returned.
@throws RuntimeException
if it occurs during invoking any of the data source's methods, or if any of the involved
components violates its contract by not providing the required interfaces
*/
Reference< XInteractionHandler > lcl_getInteractionHandler_throw( const Reference< XConnection >& _rxConnection, const Reference< XInteractionHandler >& _rFallback )
{
// try whether there is a data source which the connection belongs to
Reference< XDataSource > xDataSource;
Reference< XChild > xAsChild( _rxConnection, UNO_QUERY );
if ( xAsChild.is() )
xDataSource.set(xAsChild->getParent(), css::uno::UNO_QUERY);
if ( xDataSource.is() )
return lcl_getInteractionHandler_throw( xDataSource, _rFallback );
return _rFallback;
}
}
Reference< XPropertySet > CopyTableWizard::impl_ensureDataAccessDescriptor_throw(
const Sequence< Any >& _rAllArgs, const sal_Int16 _nArgPos, SharedConnection& _out_rxConnection,
Reference< XInteractionHandler >& _out_rxDocInteractionHandler ) const
{
Reference< XPropertySet > xDescriptor;
_rAllArgs[ _nArgPos ] >>= xDescriptor;
// the descriptor must be non-NULL, of course
bool bIsValid = xDescriptor.is();
// it must support the proper service
if ( bIsValid )
{
Reference< XServiceInfo > xSI( xDescriptor, UNO_QUERY );
bIsValid = ( xSI.is()
&& xSI->supportsService( "com.sun.star.sdb.DataAccessDescriptor" ) );
}
// it must be able to provide a connection
if ( bIsValid )
{
_out_rxConnection = impl_extractConnection_throw( xDescriptor, _out_rxDocInteractionHandler );
bIsValid = _out_rxConnection.is();
}
if ( !bIsValid )
{
throw IllegalArgumentException(
DBA_RES( STR_CTW_INVALID_DATA_ACCESS_DESCRIPTOR ),
*const_cast< CopyTableWizard* >( this ),
_nArgPos + 1
);
}
return xDescriptor;
}
namespace
{
bool lcl_hasNonEmptyStringValue_throw( const Reference< XPropertySet >& _rxDescriptor,
const Reference< XPropertySetInfo >& rxPSI, const OUString& _rPropertyName )
{
OUString sValue;
if ( rxPSI->hasPropertyByName( _rPropertyName ) )
{
OSL_VERIFY( _rxDescriptor->getPropertyValue( _rPropertyName ) >>= sValue );
}
return !sValue.isEmpty();
}
}
void CopyTableWizard::impl_checkForUnsupportedSettings_throw( const Reference< XPropertySet >& _rxSourceDescriptor ) const
{
OSL_PRECOND( _rxSourceDescriptor.is(), "CopyTableWizard::impl_checkForUnsupportedSettings_throw: illegal argument!" );
Reference< XPropertySetInfo > xPSI( _rxSourceDescriptor->getPropertySetInfo(), UNO_SET_THROW );
OUString sUnsupportedSetting;
const OUString aSettings[] = {
PROPERTY_FILTER, PROPERTY_ORDER, PROPERTY_HAVING_CLAUSE, PROPERTY_GROUP_BY
};
for (const auto & aSetting : aSettings)
{
if ( lcl_hasNonEmptyStringValue_throw( _rxSourceDescriptor, xPSI, aSetting ) )
{
sUnsupportedSetting = aSetting;
break;
}
}
if ( !sUnsupportedSetting.isEmpty() )
{
OUString sMessage(
DBA_RES(STR_CTW_ERROR_UNSUPPORTED_SETTING).
replaceFirst("$name$", sUnsupportedSetting));
throw IllegalArgumentException(
sMessage,
*const_cast< CopyTableWizard* >( this ),
1
);
}
}
std::unique_ptr< ICopyTableSourceObject > CopyTableWizard::impl_extractSourceObject_throw( const Reference< XPropertySet >& _rxDescriptor, sal_Int32& _out_rCommandType ) const
{
OSL_PRECOND( _rxDescriptor.is() && m_xSourceConnection.is(), "CopyTableWizard::impl_extractSourceObject_throw: illegal arguments!" );
Reference< XPropertySetInfo > xPSI( _rxDescriptor->getPropertySetInfo(), UNO_SET_THROW );
if ( !xPSI->hasPropertyByName( PROPERTY_COMMAND )
|| !xPSI->hasPropertyByName( PROPERTY_COMMAND_TYPE )
)
throw IllegalArgumentException("Expecting a table or query specification.",
// TODO: resource
*const_cast< CopyTableWizard* >( this ), 1);
OUString sCommand;
_out_rCommandType = CommandType::COMMAND;
OSL_VERIFY( _rxDescriptor->getPropertyValue( PROPERTY_COMMAND ) >>= sCommand );
OSL_VERIFY( _rxDescriptor->getPropertyValue( PROPERTY_COMMAND_TYPE ) >>= _out_rCommandType );
std::unique_ptr< ICopyTableSourceObject > pSourceObject;
Reference< XNameAccess > xContainer;
switch ( _out_rCommandType )
{
case CommandType::TABLE:
{
Reference< XTablesSupplier > xSuppTables( m_xSourceConnection.getTyped(), UNO_QUERY );
if ( xSuppTables.is() )
xContainer.set( xSuppTables->getTables(), UNO_SET_THROW );
}
break;
case CommandType::QUERY:
{
Reference< XQueriesSupplier > xSuppQueries( m_xSourceConnection.getTyped(), UNO_QUERY );
if ( xSuppQueries.is() )
xContainer.set( xSuppQueries->getQueries(), UNO_SET_THROW );
}
break;
default:
throw IllegalArgumentException(
DBA_RES( STR_CTW_ONLY_TABLES_AND_QUERIES_SUPPORT ),
*const_cast< CopyTableWizard* >( this ),
1
);
}
if ( xContainer.is() )
{
pSourceObject.reset( new ObjectCopySource( m_xSourceConnection,
Reference< XPropertySet >( xContainer->getByName( sCommand ), UNO_QUERY_THROW ) ) );
}
else
{
// our source connection is an SDBC level connection only, not a SDBCX level one
// Which means it cannot provide the to-be-copied object as component.
if ( _out_rCommandType == CommandType::QUERY )
// we cannot copy a query if the connection cannot provide it ...
throw IllegalArgumentException(
DBA_RES( STR_CTW_ERROR_NO_QUERY ),
*const_cast< CopyTableWizard* >( this ),
1
);
pSourceObject.reset( new NamedTableCopySource( m_xSourceConnection, sCommand ) );
}
return pSourceObject;
}
void CopyTableWizard::impl_extractSourceResultSet_throw( const Reference< XPropertySet >& i_rDescriptor )
{
Reference< XPropertySetInfo > xPSI( i_rDescriptor->getPropertySetInfo(), UNO_SET_THROW );
// extract relevant settings
if ( xPSI->hasPropertyByName( PROPERTY_RESULT_SET ) )
m_xSourceResultSet.set( i_rDescriptor->getPropertyValue( PROPERTY_RESULT_SET ), UNO_QUERY );
if ( xPSI->hasPropertyByName( PROPERTY_SELECTION ) )
OSL_VERIFY( i_rDescriptor->getPropertyValue( PROPERTY_SELECTION ) >>= m_aSourceSelection );
if ( xPSI->hasPropertyByName( PROPERTY_BOOKMARK_SELECTION ) )
OSL_VERIFY( i_rDescriptor->getPropertyValue( PROPERTY_BOOKMARK_SELECTION ) >>= m_bSourceSelectionBookmarks );
// sanity checks
const bool bHasResultSet = m_xSourceResultSet.is();
const bool bHasSelection = m_aSourceSelection.hasElements();
if ( bHasSelection && !bHasResultSet )
throw IllegalArgumentException("A result set is needed when specifying a selection to copy.",
// TODO: resource
*this, 1);
if ( bHasSelection && m_bSourceSelectionBookmarks )
{
Reference< XRowLocate > xRowLocate( m_xSourceResultSet, UNO_QUERY );
if ( !xRowLocate.is() )
{
::dbtools::throwGenericSQLException(
DBA_RES(STR_CTW_COPY_SOURCE_NEEDS_BOOKMARKS),
*this
);
}
}
}
SharedConnection CopyTableWizard::impl_extractConnection_throw( const Reference< XPropertySet >& _rxDataSourceDescriptor,
Reference< XInteractionHandler >& _out_rxDocInteractionHandler ) const
{
SharedConnection xConnection;
OSL_PRECOND( _rxDataSourceDescriptor.is(), "CopyTableWizard::impl_extractConnection_throw: no descriptor!" );
if ( !_rxDataSourceDescriptor.is() )
return xConnection;
Reference< XInteractionHandler > xInteractionHandler;
do
{
Reference< XPropertySetInfo > xPSI( _rxDataSourceDescriptor->getPropertySetInfo(), UNO_SET_THROW );
// if there's an ActiveConnection, use it
if ( xPSI->hasPropertyByName( PROPERTY_ACTIVE_CONNECTION ) )
{
Reference< XConnection > xPure;
OSL_VERIFY( _rxDataSourceDescriptor->getPropertyValue( PROPERTY_ACTIVE_CONNECTION ) >>= xPure );
xConnection.reset( xPure, SharedConnection::NoTakeOwnership );
}
if ( xConnection.is() )
{
xInteractionHandler = lcl_getInteractionHandler_throw( xConnection.getTyped(), m_xInteractionHandler );
SAL_WARN_IF( !xInteractionHandler.is(), "dbaccess.ui", "CopyTableWizard::impl_extractConnection_throw: lcl_getInteractionHandler_throw returned nonsense!" );
break;
}
// there could be a DataSourceName or a DatabaseLocation, describing the css.sdb.DataSource
OUString sDataSource, sDatabaseLocation;
if ( xPSI->hasPropertyByName( PROPERTY_DATASOURCENAME ) )
OSL_VERIFY( _rxDataSourceDescriptor->getPropertyValue( PROPERTY_DATASOURCENAME ) >>= sDataSource );
if ( xPSI->hasPropertyByName( PROPERTY_DATABASE_LOCATION ) )
OSL_VERIFY( _rxDataSourceDescriptor->getPropertyValue( PROPERTY_DATABASE_LOCATION ) >>= sDatabaseLocation );
// need a DatabaseContext for loading the data source
Reference< XDatabaseContext > xDatabaseContext = DatabaseContext::create( m_xContext );
Reference< XDataSource > xDataSource;
if ( !sDataSource.isEmpty() )
xDataSource.set( xDatabaseContext->getByName( sDataSource ), UNO_QUERY_THROW );
if ( !xDataSource.is() && !sDatabaseLocation.isEmpty() )
xDataSource.set( xDatabaseContext->getByName( sDatabaseLocation ), UNO_QUERY_THROW );
if ( xDataSource.is() )
{
// first, try connecting with completion
xInteractionHandler = lcl_getInteractionHandler_throw( xDataSource, m_xInteractionHandler );
SAL_WARN_IF( !xInteractionHandler.is(), "dbaccess.ui", "CopyTableWizard::impl_extractConnection_throw: lcl_getInteractionHandler_throw returned nonsense!" );
if ( xInteractionHandler.is() )
{
Reference< XCompletedConnection > xInteractiveConnection( xDataSource, UNO_QUERY );
if ( xInteractiveConnection.is() )
xConnection.reset( xInteractiveConnection->connectWithCompletion( xInteractionHandler ), SharedConnection::TakeOwnership );
}
// interactively connecting was not successful or possible -> connect without interaction
if ( !xConnection.is() )
{
xConnection.reset( xDataSource->getConnection( OUString(), OUString() ), SharedConnection::TakeOwnership );
}
}
if ( xConnection.is() )
break;
// finally, there could be a ConnectionResource/ConnectionInfo
OUString sConnectionResource;
Sequence< PropertyValue > aConnectionInfo;
if ( xPSI->hasPropertyByName( PROPERTY_CONNECTION_RESOURCE ) )
OSL_VERIFY( _rxDataSourceDescriptor->getPropertyValue( PROPERTY_CONNECTION_RESOURCE ) >>= sConnectionResource );
if ( xPSI->hasPropertyByName( PROPERTY_CONNECTION_INFO ) )
OSL_VERIFY( _rxDataSourceDescriptor->getPropertyValue( PROPERTY_CONNECTION_INFO ) >>= aConnectionInfo );
Reference< XDriverManager > xDriverManager;
try {
xDriverManager.set( ConnectionPool::create( m_xContext ), UNO_QUERY_THROW );
} catch( const Exception& ) { }
if ( !xDriverManager.is() )
// no connection pool installed
xDriverManager.set( DriverManager::create( m_xContext ), UNO_QUERY_THROW );
if ( aConnectionInfo.hasElements() )
xConnection.set( xDriverManager->getConnectionWithInfo( sConnectionResource, aConnectionInfo ), UNO_SET_THROW );
else
xConnection.set( xDriverManager->getConnection( sConnectionResource ), UNO_SET_THROW );
}
while ( false );
if ( xInteractionHandler != m_xInteractionHandler )
_out_rxDocInteractionHandler = xInteractionHandler;
return xConnection;
}
::utl::SharedUNOComponent< XPreparedStatement > CopyTableWizard::impl_createSourceStatement_throw() const
{
OSL_PRECOND( m_xSourceConnection.is(), "CopyTableWizard::impl_createSourceStatement_throw: illegal call!" );
if ( !m_xSourceConnection.is() )
throw RuntimeException( "CopyTableWizard::impl_createSourceStatement_throw: illegal call!", *const_cast< CopyTableWizard* >( this ));
::utl::SharedUNOComponent< XPreparedStatement > xStatement;
switch ( m_nCommandType )
{
case CommandType::TABLE:
xStatement.set( m_pSourceObject->getPreparedSelectStatement(), UNO_SET_THROW );
break;
case CommandType::QUERY:
{
OUString sQueryCommand( m_pSourceObject->getSelectStatement() );
xStatement.set( m_pSourceObject->getPreparedSelectStatement(), UNO_SET_THROW );
// check whether we have to fill in parameter values
// create and fill a composer
Reference< XMultiServiceFactory > xFactory( m_xSourceConnection, UNO_QUERY );
::utl::SharedUNOComponent< XSingleSelectQueryComposer > xComposer;
if ( xFactory.is() )
// note: connections below the sdb-level are allowed to not support the XMultiServiceFactory interface
xComposer.set( xFactory->createInstance( SERVICE_NAME_SINGLESELECTQUERYCOMPOSER ), UNO_QUERY );
if ( xComposer.is() )
{
xComposer->setQuery( sQueryCommand );
Reference< XParameters > xStatementParams( xStatement, UNO_QUERY );
OSL_ENSURE( xStatementParams.is(), "CopyTableWizard::impl_createSourceStatement_throw: no access to the statement's parameters!" );
// the statement should be a css.sdbc.PreparedStatement (this is what
// we created), and a prepared statement is required to support XParameters
if ( xStatementParams.is() )
{
OSL_ENSURE( m_xInteractionHandler.is(),
"CopyTableWizard::impl_createSourceStatement_throw: no interaction handler for the parameters request!" );
// we should always have an interaction handler - as last fallback, we create an own one in ::initialize
if ( m_xInteractionHandler.is() )
::dbtools::askForParameters( xComposer, xStatementParams, m_xSourceConnection, m_xInteractionHandler );
}
}
}
break;
default:
// this should not have survived initialization phase
throw RuntimeException("No case matched, this should not have survived the initialization phase", *const_cast< CopyTableWizard* >( this ));
}
return xStatement;
}
namespace
{
class ValueTransfer
{
public:
ValueTransfer( std::vector< sal_Int32 > _rColTypes,
const Reference< XRow >& _rxSource, const Reference< XParameters >& _rxDest )
:m_ColTypes( std::move(_rColTypes) )
,m_xSource( _rxSource )
,m_xDest( _rxDest )
{
}
template< typename VALUE_TYPE >
void transferValue( sal_Int32 _nSourcePos, sal_Int32 _nDestPos,
VALUE_TYPE ( SAL_CALL XRow::*_pGetter )( sal_Int32 ),
void (SAL_CALL XParameters::*_pSetter)( sal_Int32, VALUE_TYPE ) )
{
VALUE_TYPE value( (m_xSource.get()->*_pGetter)( _nSourcePos ) );
if ( m_xSource->wasNull() )
m_xDest->setNull( _nDestPos, m_ColTypes[ _nSourcePos ] );
else
(m_xDest.get()->*_pSetter)( _nDestPos, value );
}
template< typename VALUE_TYPE >
void transferComplexValue( sal_Int32 _nSourcePos, sal_Int32 _nDestPos,
VALUE_TYPE ( SAL_CALL XRow::*_pGetter )( sal_Int32 ),
void (SAL_CALL XParameters::*_pSetter)( sal_Int32, const VALUE_TYPE& ) )
{
const VALUE_TYPE value( (m_xSource.get()->*_pGetter)( _nSourcePos ) );
if ( m_xSource->wasNull() )
m_xDest->setNull( _nDestPos, m_ColTypes[ _nSourcePos ] );
else
(m_xDest.get()->*_pSetter)( _nDestPos, value );
}
private:
const std::vector< sal_Int32 > m_ColTypes;
const Reference< XRow > m_xSource;
const Reference< XParameters > m_xDest;
};
}
bool CopyTableWizard::impl_processCopyError_nothrow( const CopyTableRowEvent& _rEvent )
{
try
{
::comphelper::OInterfaceIteratorHelper3 aIter( m_aCopyTableListeners );
while ( aIter.hasMoreElements() )
{
Reference< XCopyTableListener > xListener( aIter.next() );
sal_Int16 nListenerChoice = xListener->copyRowError( _rEvent );
switch ( nListenerChoice )
{
case CopyTableContinuation::Proceed: return true; // continue copying
case CopyTableContinuation::CallNextHandler: continue; // continue the loop, ask next listener
case CopyTableContinuation::Cancel: return false; // cancel copying
case CopyTableContinuation::AskUser: break; // stop asking the listeners, ask the user
default:
SAL_WARN("dbaccess.ui", "CopyTableWizard::impl_processCopyError_nothrow: invalid listener response!" );
// ask next listener
continue;
}
}
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION("dbaccess");
}
// no listener felt responsible for the error, or a listener told to ask the user
try
{
css::uno::Any next;
::dbtools::SQLExceptionInfo aInfo( _rEvent.Error );
if ( aInfo.isValid() )
next = _rEvent.Error;
else
{
// a non-SQL exception happened
Exception aException;
OSL_VERIFY( _rEvent.Error >>= aException );
SQLContext aContext(aException.Message, aException.Context, {}, 0, {},
_rEvent.Error.getValueTypeName());
next <<= aContext;
}
SQLContext aError(DBA_RES(STR_ERROR_OCCURRED_WHILE_COPYING), *this, {}, 0, next, {});
::rtl::Reference< ::comphelper::OInteractionRequest > xRequest( new ::comphelper::OInteractionRequest( Any( aError ) ) );
::rtl::Reference< ::comphelper::OInteractionApprove > xYes = new ::comphelper::OInteractionApprove;
xRequest->addContinuation( xYes );
xRequest->addContinuation( new ::comphelper::OInteractionDisapprove );
OSL_ENSURE( m_xInteractionHandler.is(),
"CopyTableWizard::impl_processCopyError_nothrow: we always should have an interaction handler!" );
if ( m_xInteractionHandler.is() )
m_xInteractionHandler->handle( xRequest );
if ( xYes->wasSelected() )
// continue copying
return true;
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION("dbaccess");
}
// cancel copying
return false;
}
void CopyTableWizard::impl_copyRows_throw( const Reference< XResultSet >& _rxSourceResultSet,
const Reference< XPropertySet >& _rxDestTable )
{
OSL_PRECOND( m_xDestConnection.is(), "CopyTableWizard::impl_copyRows_throw: illegal call!" );
if ( !m_xDestConnection.is() )
throw RuntimeException( "m_xDestConnection is set to null, CopyTableWizard::impl_copyRows_throw: illegal call!", *this );
Reference< XDatabaseMetaData > xDestMetaData( m_xDestConnection->getMetaData(), UNO_SET_THROW );
const OCopyTableWizard& rWizard = impl_getDialog_throw();
ODatabaseExport::TPositions aColumnPositions = rWizard.GetColumnPositions();
const bool bShouldCreatePrimaryKey = rWizard.shouldCreatePrimaryKey();
Reference< XRow > xRow ( _rxSourceResultSet, UNO_QUERY_THROW );
Reference< XRowLocate > xRowLocate ( _rxSourceResultSet, UNO_QUERY_THROW );
Reference< XResultSetMetaDataSupplier > xSuppResMeta( _rxSourceResultSet, UNO_QUERY_THROW );
Reference< XResultSetMetaData> xMeta( xSuppResMeta->getMetaData() );
// we need a vector which all types
sal_Int32 nCount = xMeta->getColumnCount();
std::vector< sal_Int32 > aSourceColTypes;
aSourceColTypes.reserve( nCount + 1 );
aSourceColTypes.push_back( -1 ); // just to avoid an every time i-1 call
std::vector< sal_Int32 > aSourcePrec;
aSourcePrec.reserve( nCount + 1 );
aSourcePrec.push_back( -1 ); // just to avoid an every time i-1 call
for ( sal_Int32 k=1; k <= nCount; ++k )
{
aSourceColTypes.push_back( xMeta->getColumnType( k ) );
aSourcePrec.push_back( xMeta->getPrecision( k ) );
}
// now create, fill and execute the prepared statement
Reference< XPreparedStatement > xStatement( ODatabaseExport::createPreparedStatement( xDestMetaData, _rxDestTable, aColumnPositions ), UNO_SET_THROW );
Reference< XParameters > xStatementParams( xStatement, UNO_QUERY_THROW );
const bool bSelectedRecordsOnly = m_aSourceSelection.hasElements();
const Any* pSelectedRow = m_aSourceSelection.begin();
const Any* pSelEnd = m_aSourceSelection.end();
sal_Int32 nRowCount = 0;
bool bContinue = false;
CopyTableRowEvent aCopyEvent;
aCopyEvent.Source = *this;
aCopyEvent.SourceData = _rxSourceResultSet;
do // loop as long as there are more rows or the selection ends
{
bContinue = false;
if ( bSelectedRecordsOnly )
{
if ( pSelectedRow != pSelEnd )
{
if ( m_bSourceSelectionBookmarks )
{
bContinue = xRowLocate->moveToBookmark( *pSelectedRow );
}
else
{
sal_Int32 nPos = 0;
OSL_VERIFY( *pSelectedRow >>= nPos );
bContinue = _rxSourceResultSet->absolute( nPos );
}
++pSelectedRow;
}
}
else
bContinue = _rxSourceResultSet->next();
if ( !bContinue )
{
break;
}
++nRowCount;
aCopyEvent.Error.clear();
try
{
bool bInsertedPrimaryKey = false;
// notify listeners
m_aCopyTableListeners.notifyEach( &XCopyTableListener::copyingRow, aCopyEvent );
sal_Int32 nSourceColumn( 1 );
ValueTransfer aTransfer( aSourceColTypes, xRow, xStatementParams );
for ( auto const& rColumnPos : aColumnPositions )
{
sal_Int32 nDestColumn = rColumnPos.first;
if ( nDestColumn == COLUMN_POSITION_NOT_FOUND )
{
++nSourceColumn;
// otherwise we don't get the correct value when only the 2nd source column was selected
continue;
}
if ( bShouldCreatePrimaryKey && !bInsertedPrimaryKey )
{
xStatementParams->setInt( 1, nRowCount );
++nSourceColumn;
bInsertedPrimaryKey = true;
continue;
}
if ( ( nSourceColumn < 1 ) || ( o3tl::make_unsigned(nSourceColumn) >= aSourceColTypes.size() ) )
{ // ( we have to check here against 1 because the parameters are 1 based)
::dbtools::throwSQLException("Internal error: invalid column type index.",
::dbtools::StandardSQLState::INVALID_DESCRIPTOR_INDEX, *this);
}
switch ( aSourceColTypes[ nSourceColumn ] )
{
case DataType::DOUBLE:
case DataType::REAL:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getDouble, &XParameters::setDouble );
break;
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::LONGVARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getString, &XParameters::setString );
break;
case DataType::BIGINT:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getLong, &XParameters::setLong );
break;
case DataType::FLOAT:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getFloat, &XParameters::setFloat );
break;
case DataType::LONGVARBINARY:
case DataType::BINARY:
case DataType::VARBINARY:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getBytes, &XParameters::setBytes );
break;
case DataType::DATE:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getDate, &XParameters::setDate );
break;
case DataType::TIME:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getTime, &XParameters::setTime );
break;
case DataType::TIMESTAMP:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getTimestamp, &XParameters::setTimestamp );
break;
case DataType::BIT:
if ( aSourcePrec[nSourceColumn] > 1 )
{
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getBytes, &XParameters::setBytes );
break;
}
[[fallthrough]];
case DataType::BOOLEAN:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getBoolean, &XParameters::setBoolean );
break;
case DataType::TINYINT:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getByte, &XParameters::setByte );
break;
case DataType::SMALLINT:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getShort, &XParameters::setShort );
break;
case DataType::INTEGER:
aTransfer.transferValue( nSourceColumn, nDestColumn, &XRow::getInt, &XParameters::setInt );
break;
case DataType::BLOB:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getBlob, &XParameters::setBlob );
break;
case DataType::CLOB:
aTransfer.transferComplexValue( nSourceColumn, nDestColumn, &XRow::getClob, &XParameters::setClob );
break;
default:
{
OUString aMessage( DBA_RES( STR_CTW_UNSUPPORTED_COLUMN_TYPE ) );
aMessage = aMessage.replaceFirst( "$type$", OUString::number( aSourceColTypes[ nSourceColumn ] ) );
aMessage = aMessage.replaceFirst( "$pos$", OUString::number( nSourceColumn ) );
::dbtools::throwSQLException(
aMessage,
::dbtools::StandardSQLState::INVALID_SQL_DATA_TYPE,
*this
);
}
}
++nSourceColumn;
}
xStatement->executeUpdate();
// notify listeners
m_aCopyTableListeners.notifyEach( &XCopyTableListener::copiedRow, aCopyEvent );
}
catch( const Exception& )
{
TOOLS_WARN_EXCEPTION("dbaccess", "");
aCopyEvent.Error = ::cppu::getCaughtException();
}
if ( aCopyEvent.Error.hasValue() )
bContinue = impl_processCopyError_nothrow( aCopyEvent );
}
while( bContinue );
}
void CopyTableWizard::impl_doCopy_nothrow()
{
Any aError;
try
{
OCopyTableWizard& rWizard( impl_getDialog_throw() );
weld::WaitObject aWO(rWizard.getDialog());
Reference< XPropertySet > xTable;
switch ( rWizard.getOperation() )
{
case CopyTableOperation::CopyDefinitionOnly:
case CopyTableOperation::CopyDefinitionAndData:
{
xTable = rWizard.createTable();
if( !xTable.is() )
{
SAL_WARN("dbaccess.ui", "CopyTableWizard::impl_doCopy_nothrow: createTable should throw here, shouldn't it?" );
break;
}
if( CopyTableOperation::CopyDefinitionOnly == rWizard.getOperation() )
break;
[[fallthrough]];
}
case CopyTableOperation::AppendData:
{
// note that the CopyDefinitionAndData case falls through to here.
assert((rWizard.getOperation() == CopyTableOperation::CopyDefinitionAndData) ||
(rWizard.getOperation() == CopyTableOperation::AppendData));
assert((rWizard.getOperation() == CopyTableOperation::CopyDefinitionAndData) == xTable.is());
if ( !xTable.is() )
{
assert(rWizard.getOperation() == CopyTableOperation::AppendData);
xTable = rWizard.getTable();
if ( !xTable.is() )
{
SAL_WARN("dbaccess.ui", "CopyTableWizard::impl_doCopy_nothrow: getTable should throw here, shouldn't it?" );
break;
}
}
::utl::SharedUNOComponent< XPreparedStatement > xSourceStatement;
::utl::SharedUNOComponent< XResultSet > xSourceResultSet;
if ( m_xSourceResultSet.is() )
{
xSourceResultSet.reset( m_xSourceResultSet, ::utl::SharedUNOComponent< XResultSet >::NoTakeOwnership );
}
else
{
const bool bIsSameConnection = ( m_xSourceConnection.getTyped() == m_xDestConnection.getTyped() );
const bool bIsTable = ( CommandType::TABLE == m_nCommandType );
bool bDone = false;
if ( bIsSameConnection && bIsTable )
{
// try whether the server supports copying via SQL
try
{
m_xDestConnection->createStatement()->executeUpdate( impl_getServerSideCopyStatement_throw(xTable) );
bDone = true;
}
catch( const Exception& )
{
// this is allowed.
}
}
if ( !bDone )
{
xSourceStatement.set( impl_createSourceStatement_throw(), UNO_SET_THROW );
xSourceResultSet.set( xSourceStatement->executeQuery(), UNO_SET_THROW );
}
}
if ( xSourceResultSet.is() )
impl_copyRows_throw( xSourceResultSet, xTable );
// tdf#119962
const Reference< XDatabaseMetaData > xDestMetaData( m_xDestConnection->getMetaData(), UNO_SET_THROW );
OUString sDatabaseDest = xDestMetaData->getDatabaseProductName().toAsciiLowerCase();
// If we created a new primary key, then it won't necessarily be an IDENTITY column
const bool bShouldCreatePrimaryKey = rWizard.shouldCreatePrimaryKey();
if ( !bShouldCreatePrimaryKey && (sDatabaseDest.indexOf("firebird") != -1) )
{
const OUString sComposedTableName = ::dbtools::composeTableName( xDestMetaData, xTable, ::dbtools::EComposeRule::InDataManipulation, true );
OUString aSchema,aTable;
xTable->getPropertyValue("SchemaName") >>= aSchema;
xTable->getPropertyValue("Name") >>= aTable;
Any aCatalog = xTable->getPropertyValue("CatalogName");
const Reference< XResultSet > xResultPKCL(xDestMetaData->getPrimaryKeys(aCatalog,aSchema,aTable));
Reference< XRow > xRowPKCL(xResultPKCL, UNO_QUERY_THROW);
OUString sPKCL;
if ( xRowPKCL.is() )
{
if (xResultPKCL->next())
{
sPKCL = xRowPKCL->getString(4);
}
}
if (!sPKCL.isEmpty())
{
OUString strSql = "SELECT MAX(\"" + sPKCL + "\") FROM " + sComposedTableName;
Reference< XResultSet > xResultMAXNUM(m_xDestConnection->createStatement()->executeQuery(strSql));
Reference< XRow > xRow(xResultMAXNUM, UNO_QUERY_THROW);
sal_Int64 maxVal = -1L;
if (xResultMAXNUM->next())
{
maxVal = xRow->getLong(1);
}
if (maxVal > 0L)
{
strSql = "ALTER TABLE " + sComposedTableName + " ALTER \"" + sPKCL + "\" RESTART WITH " + OUString::number(maxVal + 1);
m_xDestConnection->createStatement()->execute(strSql);
}
}
}
}
break;
case CopyTableOperation::CreateAsView:
rWizard.createView();
break;
default:
SAL_WARN("dbaccess.ui", "CopyTableWizard::impl_doCopy_nothrow: What operation, please?" );
break;
}
}
catch( const Exception& )
{
aError = ::cppu::getCaughtException();
SAL_WARN("dbaccess", exceptionToString(aError));
// silence the error of the user cancelling the parameter's dialog
SQLException aSQLError;
if ( ( aError >>= aSQLError ) && ( aSQLError.ErrorCode == ::dbtools::ParameterInteractionCancelled ) )
{
aError.clear();
m_nOverrideExecutionResult = RET_CANCEL;
}
}
if ( aError.hasValue() && m_xInteractionHandler.is() )
{
try
{
::rtl::Reference< ::comphelper::OInteractionRequest > xRequest( new ::comphelper::OInteractionRequest( aError ) );
m_xInteractionHandler->handle( xRequest );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION("dbaccess");
}
}
}
OUString CopyTableWizard::impl_getServerSideCopyStatement_throw(const Reference< XPropertySet >& _xTable)
{
const Reference<XColumnsSupplier> xDestColsSup(_xTable,UNO_QUERY_THROW);
const Sequence< OUString> aDestColumnNames = xDestColsSup->getColumns()->getElementNames();
const Reference< XDatabaseMetaData > xDestMetaData( m_xDestConnection->getMetaData(), UNO_SET_THROW );
const OUString sQuote = xDestMetaData->getIdentifierQuoteString();
OUStringBuffer sColumns;
// 1st check if the columns matching
for ( auto const & rColumnPositionPair : impl_getDialog_throw().GetColumnPositions() )
{
if ( COLUMN_POSITION_NOT_FOUND != rColumnPositionPair.second )
{
if ( !sColumns.isEmpty() )
sColumns.append(",");
sColumns.append(sQuote + aDestColumnNames[rColumnPositionPair.second - 1] + sQuote);
}
}
const OUString sComposedTableName = ::dbtools::composeTableName( xDestMetaData, _xTable, ::dbtools::EComposeRule::InDataManipulation, true );
OUString sSql("INSERT INTO " + sComposedTableName + " ( " + sColumns + " ) " + m_pSourceObject->getSelectStatement());
return sSql;
}
void SAL_CALL CopyTableWizard::initialize( const Sequence< Any >& _rArguments )
{
::osl::MutexGuard aGuard( m_aMutex );
if ( isInitialized() )
throw AlreadyInitializedException( OUString(), *this );
sal_Int32 nArgCount( _rArguments.getLength() );
if ( ( nArgCount != 2 ) && ( nArgCount != 3 ) )
throw IllegalArgumentException(
DBA_RES( STR_CTW_ILLEGAL_PARAMETER_COUNT ),
*this,
1
);
try
{
if ( nArgCount == 3 )
{ // ->createWithInteractionHandler
if ( !( _rArguments[2] >>= m_xInteractionHandler ) )
throw IllegalArgumentException(
DBA_RES( STR_CTW_ERROR_INVALID_INTERACTIONHANDLER ),
*this,
3
);
}
if ( !m_xInteractionHandler.is() )
m_xInteractionHandler = InteractionHandler::createWithParent(m_xContext, nullptr);
Reference< XInteractionHandler > xSourceDocHandler;
Reference< XPropertySet > xSourceDescriptor( impl_ensureDataAccessDescriptor_throw( _rArguments, 0, m_xSourceConnection, xSourceDocHandler ) );
impl_checkForUnsupportedSettings_throw( xSourceDescriptor );
m_pSourceObject = impl_extractSourceObject_throw( xSourceDescriptor, m_nCommandType );
impl_extractSourceResultSet_throw( xSourceDescriptor );
Reference< XInteractionHandler > xDestDocHandler;
impl_ensureDataAccessDescriptor_throw( _rArguments, 1, m_xDestConnection, xDestDocHandler );
if ( xDestDocHandler.is() && !m_xInteractionHandler.is() )
m_xInteractionHandler = xDestDocHandler;
Reference< XPropertySet > xInteractionHandler(m_xInteractionHandler, UNO_QUERY);
if (xInteractionHandler.is())
{
Any aParentWindow(xInteractionHandler->getPropertyValue("ParentWindow"));
aParentWindow >>= m_xParent;
}
}
catch( const RuntimeException& ) { throw; }
catch( const SQLException& ) { throw; }
catch( const Exception& )
{
throw WrappedTargetException(
DBA_RES( STR_CTW_ERROR_DURING_INITIALIZATION ),
*this,
::cppu::getCaughtException()
);
}
}
::cppu::IPropertyArrayHelper& CopyTableWizard::getInfoHelper()
{
return *getArrayHelper();
}
::cppu::IPropertyArrayHelper* CopyTableWizard::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties( aProps );
return new ::cppu::OPropertyArrayHelper( aProps );
}
std::unique_ptr<weld::DialogController> CopyTableWizard::createDialog(const css::uno::Reference<css::awt::XWindow>& rParent)
{
OSL_PRECOND( isInitialized(), "CopyTableWizard::createDialog: not initialized!" );
// this should have been prevented in ::execute already
auto xWizard = std::make_unique<OCopyTableWizard>(
Application::GetFrameWeld(rParent),
m_sDestinationTable,
m_nOperation,
*m_pSourceObject,
m_xSourceConnection.getTyped(),
m_xDestConnection.getTyped(),
m_xContext,
m_xInteractionHandler);
impl_attributesToDialog_nothrow(*xWizard);
return xWizard;
}
void CopyTableWizard::executedDialog( sal_Int16 _nExecutionResult )
{
CopyTableWizard_DialogBase::executedDialog( _nExecutionResult );
if ( _nExecutionResult == RET_OK )
impl_doCopy_nothrow();
// do this after impl_doCopy_nothrow: The attributes may change during copying, for instance
// if the user entered an unqualified table name
impl_dialogToAttributes_nothrow( impl_getDialog_throw() );
}
} // namespace dbaui
extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
org_openoffice_comp_dbu_CopyTableWizard_get_implementation(
css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const& )
{
return cppu::acquire(new ::dbaui::CopyTableWizard(context));
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|