1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <core_resource.hxx>
21 #include <directsql.hxx>
22 #include <sqledit.hxx>
23 #include <strings.hxx>
24 #include <strings.hrc>
25 #include <comphelper/types.hxx>
26 #include <osl/mutex.hxx>
27 #include <rtl/ustrbuf.hxx>
28 #include <comphelper/diagnose_ex.hxx>
29 #include <vcl/svapp.hxx>
30 #include <vcl/weld.hxx>
31 #include <com/sun/star/sdbc/SQLException.hpp>
32 #include <com/sun/star/sdbc/XRow.hpp>
33 #include <com/sun/star/beans/XPropertySet.hpp>
34 #include <com/sun/star/sdbc/XMultipleResults.hpp>
38 using namespace ::com::sun::star::uno
;
39 using namespace ::com::sun::star::sdbc
;
40 using namespace ::com::sun::star::lang
;
42 constexpr sal_Int32 g_nHistoryLimit
= 20;
45 DirectSQLDialog::DirectSQLDialog(weld::Window
* _pParent
, const Reference
< XConnection
>& _rxConn
)
46 : GenericDialogController(_pParent
, "dbaccess/ui/directsqldialog.ui", "DirectSQLDialog")
47 , m_xExecute(m_xBuilder
->weld_button("execute"))
48 , m_xSQLHistory(m_xBuilder
->weld_combo_box("sqlhistory"))
49 , m_xStatus(m_xBuilder
->weld_text_view("status"))
50 , m_xDirectSQL(m_xBuilder
->weld_check_button("directsql"))
51 , m_xShowOutput(m_xBuilder
->weld_check_button("showoutput"))
52 , m_xOutput(m_xBuilder
->weld_text_view("output"))
53 , m_xClose(m_xBuilder
->weld_button("close"))
54 , m_xSQL(new SQLEditView(m_xBuilder
->weld_scrolled_window("scrolledwindow", true)))
55 , m_xSQLEd(new weld::CustomWeld(*m_xBuilder
, "sql", *m_xSQL
))
57 , m_xConnection(_rxConn
)
58 , m_pClosingEvent(nullptr)
60 int nWidth
= m_xStatus
->get_approximate_digit_width() * 60;
61 int nHeight
= m_xStatus
->get_height_rows(7);
63 m_xSQLEd
->set_size_request(nWidth
, nHeight
);
64 m_xStatus
->set_size_request(-1, nHeight
);
65 m_xOutput
->set_size_request(-1, nHeight
);
69 m_xExecute
->connect_clicked(LINK(this, DirectSQLDialog
, OnExecute
));
70 m_xClose
->connect_clicked(LINK(this, DirectSQLDialog
, OnCloseClick
));
71 m_xSQLHistory
->connect_changed(LINK(this, DirectSQLDialog
, OnListEntrySelected
));
73 // add a dispose listener to the connection
74 Reference
< XComponent
> xConnComp(m_xConnection
, UNO_QUERY
);
75 OSL_ENSURE(xConnComp
.is(), "DirectSQLDialog::DirectSQLDialog: invalid connection!");
77 startComponentListening(xConnComp
);
79 m_xSQL
->SetModifyHdl(LINK(this, DirectSQLDialog
, OnStatementModified
));
80 OnStatementModified(nullptr);
83 DirectSQLDialog::~DirectSQLDialog()
85 ::osl::MutexGuard
aGuard(m_aMutex
);
87 Application::RemoveUserEvent(m_pClosingEvent
);
88 stopAllComponentListening();
91 void DirectSQLDialog::_disposing( const EventObject
& _rSource
)
93 SolarMutexGuard aSolarGuard
;
94 ::osl::MutexGuard
aGuard(m_aMutex
);
96 assert(!m_pClosingEvent
);
98 OSL_ENSURE(Reference
< XConnection
>(_rSource
.Source
, UNO_QUERY
).get() == m_xConnection
.get(),
99 "DirectSQLDialog::_disposing: where does this come from?");
102 OUString
sMessage(DBA_RES(STR_DIRECTSQL_CONNECTIONLOST
));
103 std::unique_ptr
<weld::MessageDialog
> xError(Application::CreateMessageDialog(m_xDialog
.get(),
104 VclMessageType::Warning
, VclButtonsType::Ok
,
109 m_pClosingEvent
= Application::PostUserEvent(LINK(this, DirectSQLDialog
, OnClose
));
112 sal_Int32
DirectSQLDialog::getHistorySize() const
116 const char* pError
= impl_CheckInvariants();
118 SAL_WARN("dbaccess.ui", "DirectSQLDialog::getHistorySize: " << pError
);
121 return m_aStatementHistory
.size();
124 void DirectSQLDialog::implEnsureHistoryLimit()
128 const char* pError
= impl_CheckInvariants();
130 SAL_WARN("dbaccess.ui", "DirectSQLDialog::implEnsureHistoryLimit: " << pError
);
134 if (getHistorySize() <= g_nHistoryLimit
)
138 sal_Int32 nRemoveEntries
= getHistorySize() - g_nHistoryLimit
;
139 while (nRemoveEntries
--)
141 m_aStatementHistory
.pop_front();
142 m_aNormalizedHistory
.pop_front();
143 m_xSQLHistory
->remove(0);
147 void DirectSQLDialog::implAddToStatementHistory(const OUString
& _rStatement
)
151 const char* pError
= impl_CheckInvariants();
153 SAL_WARN("dbaccess.ui", "DirectSQLDialog::implAddToStatementHistor: " << pError
);
157 // add the statement to the history
158 m_aStatementHistory
.push_back(_rStatement
);
160 // normalize the statement, and remember the normalized form, too
161 OUString sNormalized
= _rStatement
.replaceAll("\n", " ");
162 m_aNormalizedHistory
.push_back(sNormalized
);
164 // add the normalized version to the list box
165 m_xSQLHistory
->append_text(sNormalized
);
167 // ensure that we don't exceed the history limit
168 implEnsureHistoryLimit();
172 const char* DirectSQLDialog::impl_CheckInvariants() const
174 if (m_aStatementHistory
.size() != m_aNormalizedHistory
.size())
175 return "statement history is inconsistent!";
178 return "invalid listbox!";
180 if (m_aStatementHistory
.size() != static_cast<size_t>(m_xSQLHistory
->get_count()))
181 return "invalid listbox entry count!";
183 if (!m_xConnection
.is())
184 return "have no connection!";
190 void DirectSQLDialog::implExecuteStatement(const OUString
& _rStatement
)
194 const char* pError
= impl_CheckInvariants();
196 SAL_WARN("dbaccess.ui", "DirectSQLDialog::implExecuteStatement: " << pError
);
200 ::osl::MutexGuard
aGuard(m_aMutex
);
204 // clear the output box
205 m_xOutput
->set_text(OUString());
208 // create a statement
209 Reference
< XStatement
> xStatement
= m_xConnection
->createStatement();
211 if (m_xDirectSQL
->get_active())
213 Reference
< com::sun::star::beans::XPropertySet
> xStatementProps(xStatement
, UNO_QUERY_THROW
);
216 xStatementProps
->setPropertyValue(PROPERTY_ESCAPE_PROCESSING
, Any(false));
218 catch( const Exception
& )
220 DBG_UNHANDLED_EXCEPTION("dbaccess");
224 Reference
<XDatabaseMetaData
> xMeta
= m_xConnection
->getMetaData();
225 css::uno::Reference
< css::sdbc::XMultipleResults
> xMR ( xStatement
, UNO_QUERY
);
227 if (xMeta
.is() && xMeta
->supportsMultipleResultSets() && xMR
.is())
229 bool hasRS
= xStatement
->execute(_rStatement
);
232 css::uno::Reference
< css::sdbc::XResultSet
> xRS (xMR
->getResultSet());
233 if (m_xShowOutput
->get_active())
238 Concat2View(OUString::number(xMR
->getUpdateCount()) + " rows updated\n"));
241 hasRS
= xMR
->getMoreResults();
242 if (!hasRS
&& xMR
->getUpdateCount() == -1)
246 css::uno::Reference
< css::sdbc::XResultSet
> xRS (xMR
->getResultSet());
247 if (m_xShowOutput
->get_active())
254 const OUString upperStatement
= _rStatement
.toAsciiUpperCase();
255 if (upperStatement
.startsWith("UPDATE"))
257 sal_Int32 resultCount
= xStatement
->executeUpdate(_rStatement
);
258 addOutputText(Concat2View(OUString::number(resultCount
) + " rows updated\n"));
260 else if (upperStatement
.startsWith("INSERT"))
262 sal_Int32 resultCount
= xStatement
->executeUpdate(_rStatement
);
263 addOutputText(Concat2View(OUString::number(resultCount
) + " rows inserted\n"));
265 else if (upperStatement
.startsWith("DELETE"))
267 sal_Int32 resultCount
= xStatement
->executeUpdate(_rStatement
);
268 addOutputText(Concat2View(OUString::number(resultCount
) + " rows deleted\n"));
270 else if (upperStatement
.startsWith("CREATE"))
272 xStatement
->executeUpdate(_rStatement
);
273 addOutputText(u
"Command executed\n");
275 else if (upperStatement
.startsWith("SELECT") || m_xShowOutput
->get_active())
277 css::uno::Reference
< css::sdbc::XResultSet
> xRS
= xStatement
->executeQuery(_rStatement
);
278 if (m_xShowOutput
->get_active())
283 sal_Int32 resultCount
= xStatement
->executeUpdate(_rStatement
);
284 addOutputText(Concat2View(OUString::number(resultCount
) + " rows updated\n"));
288 sStatus
= DBA_RES(STR_COMMAND_EXECUTED_SUCCESSFULLY
);
290 // dispose the statement
291 ::comphelper::disposeComponent(xStatement
);
293 catch(const SQLException
& e
)
297 catch( const Exception
& )
299 DBG_UNHANDLED_EXCEPTION("dbaccess");
302 // add the status text
303 addStatusText(sStatus
);
306 void DirectSQLDialog::display(const css::uno::Reference
< css::sdbc::XResultSet
>& xRS
)
308 // get a handle for the rows
309 css::uno::Reference
< css::sdbc::XRow
> xRow( xRS
, css::uno::UNO_QUERY
);
310 // work through each of the rows
313 // initialise the output line for each row
315 // work along the columns until that are none left
321 // be dumb, treat everything as a string unless below
322 // tdf#153317, at least "Bit" type in Mysql/MariaDB gives: "\000" or "\001"
323 // so retrieve Sequence from getBytes, test if it has a length of 1 (so we avoid BLOB/CLOB or other complex types)
324 // and test if the value of first byte is one of those.
325 // In this case, there's a good chance it's a "Bit" field
326 // remark: for unknown reason, getByte(i) gives "\000" even if the bit is at 1.
327 auto seq
= xRow
->getBytes(i
);
328 if ((seq
.getLength() == 1) && (seq
[0] >= 0) && (seq
[0] <= 1))
330 out
.append(OUString::number(static_cast<int>(seq
[0])) + ",");
334 out
.append(xRow
->getString(i
) + ",");
339 // trap for when we fall off the end of the row
340 catch (const SQLException
&)
348 void DirectSQLDialog::addStatusText(std::u16string_view _rMessage
)
350 OUString sAppendMessage
= OUString::number(m_nStatusCount
++) + ": " + _rMessage
+ "\n\n";
352 OUString sCompleteMessage
= m_xStatus
->get_text() + sAppendMessage
;
353 m_xStatus
->set_text(sCompleteMessage
);
355 m_xStatus
->select_region(sCompleteMessage
.getLength(), sCompleteMessage
.getLength());
358 void DirectSQLDialog::addOutputText(std::u16string_view _rMessage
)
360 OUString sAppendMessage
= OUString::Concat(_rMessage
) + "\n";
362 OUString sCompleteMessage
= m_xOutput
->get_text() + sAppendMessage
;
363 m_xOutput
->set_text(sCompleteMessage
);
366 void DirectSQLDialog::executeCurrent()
370 const char* pError
= impl_CheckInvariants();
372 SAL_WARN("dbaccess.ui", "DirectSQLDialog::executeCurrent: " << pError
);
376 OUString sStatement
= m_xSQL
->GetText();
379 implExecuteStatement(sStatement
);
381 // add the statement to the history
382 implAddToStatementHistory(sStatement
);
387 void DirectSQLDialog::switchToHistory(sal_Int32 _nHistoryPos
)
391 const char* pError
= impl_CheckInvariants();
393 SAL_WARN("dbaccess.ui", "DirectSQLDialog::switchToHistory: " << pError
);
397 if ((_nHistoryPos
>= 0) && (_nHistoryPos
< getHistorySize()))
399 // set the text in the statement editor
400 OUString sStatement
= m_aStatementHistory
[_nHistoryPos
];
401 m_xSQL
->SetTextAndUpdate(sStatement
);
402 OnStatementModified(nullptr);
407 OSL_FAIL("DirectSQLDialog::switchToHistory: invalid position!");
410 IMPL_LINK_NOARG( DirectSQLDialog
, OnStatementModified
, LinkParamNone
*, void )
412 m_xExecute
->set_sensitive(!m_xSQL
->GetText().isEmpty());
415 IMPL_LINK_NOARG( DirectSQLDialog
, OnCloseClick
, weld::Button
&, void )
417 m_xDialog
->response(RET_OK
);
420 IMPL_LINK_NOARG( DirectSQLDialog
, OnClose
, void*, void )
422 assert(m_pClosingEvent
);
423 Application::RemoveUserEvent(m_pClosingEvent
);
424 m_pClosingEvent
= nullptr;
426 m_xDialog
->response(RET_OK
);
429 IMPL_LINK_NOARG( DirectSQLDialog
, OnExecute
, weld::Button
&, void )
434 IMPL_LINK_NOARG( DirectSQLDialog
, OnListEntrySelected
, weld::ComboBox
&, void )
436 const sal_Int32 nSelected
= m_xSQLHistory
->get_active();
438 switchToHistory(nSelected
);
443 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */