3
* TOra - An Oracle Toolkit for DBA's and developers
4
* Copyright (C) 2003-2005 Quest Software, Inc
5
* Portions Copyright (C) 2005 Other Contributors
7
* This program is free software; you can redistribute it and/or
8
* modify it under the terms of the GNU General Public License
9
* as published by the Free Software Foundation; only version 2 of
10
* the License is valid for this program.
12
* This program is distributed in the hope that it will be useful,
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
* GNU General Public License for more details.
17
* You should have received a copy of the GNU General Public License
18
* along with this program; if not, write to the Free Software
19
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21
* As a special exception, you have permission to link this program
22
* with the Oracle Client libraries and distribute executables, as long
23
* as you follow the requirements of the GNU GPL in regard to all of the
24
* software in the executable aside from Oracle client libraries.
26
* Specifically you are not permitted to link this program with the
27
* Qt/UNIX, Qt/Windows or Qt Non Commercial products of TrollTech.
28
* And you are not permitted to distribute binaries compiled against
29
* these libraries without written consent from Quest Software, Inc.
30
* Observe that this does not disallow linking to the Qt Free Edition.
32
* You may link this product with any GPL'd Qt library such as Qt/Free
34
* All trademarks belong to their respective owners.
40
#include "tochangeconnection.h"
42
#include "tohighlightedtext.h"
44
#include "toparamget.h"
45
#include "toresultbar.h"
46
#include "toresultcols.h"
47
#include "toresultcombo.h"
48
#include "toresultlong.h"
49
#include "toresultplan.h"
50
#include "toresultresources.h"
51
#include "toresultstats.h"
52
#include "toresultview.h"
53
#include "tosession.h"
54
#include "tosgatrace.h"
55
#include "totabwidget.h"
57
#include "totabwidget.h"
58
#include "tovisualize.h"
59
#include "toworksheet.h"
60
#include "toworksheetsetupui.h"
61
#include "toworksheetstatistic.h"
64
#include <kfiledialog.h>
69
#include <qcheckbox.h>
70
#include <qcheckbox.h>
71
#include <qcombobox.h>
72
#include <qfiledialog.h>
73
#include <qfileinfo.h>
75
#include <qgroupbox.h>
77
#include <qinputdialog.h>
79
#include <qlineedit.h>
80
#include <qlistview.h>
82
#include <qmessagebox.h>
83
#include <qmultilineedit.h>
84
#include <qnamespace.h>
86
#include <qprogressdialog.h>
87
#include <qpushbutton.h>
89
#include <qsplitter.h>
90
#include <qtabwidget.h>
92
#include <qtoolbutton.h>
94
#include <qworkspace.h>
96
#include "toworksheet.moc"
97
#include "toworksheetsetupui.moc"
99
#include "icons/clock.xpm"
100
#include "icons/recall.xpm"
101
#include "icons/describe.xpm"
102
#include "icons/eraselog.xpm"
103
#include "icons/execute.xpm"
104
#include "icons/executeall.xpm"
105
#include "icons/executestep.xpm"
106
#include "icons/explainplan.xpm"
107
#include "icons/filesave.xpm"
108
#include "icons/insertsaved.xpm"
109
#include "icons/previous.xpm"
110
#include "icons/refresh.xpm"
111
#include "icons/stop.xpm"
112
#include "icons/toworksheet.xpm"
113
#include "icons/up.xpm"
114
#include "icons/down.xpm"
116
#ifdef TO_KDE_KACCELMANAGER
117
# include <kaccelmanager.h>
120
#define TO_ID_STATISTICS (toMain::TO_TOOL_MENU_ID+ 0)
121
#define TO_ID_STOP (toMain::TO_TOOL_MENU_ID+ 1)
122
#define TO_ID_PLAN (toMain::TO_TOOL_MENU_ID+ 2)
124
#define CONF_AUTO_SAVE "AutoSave"
125
#define CONF_CHECK_SAVE "CheckSave"
126
#define CONF_AUTO_LOAD "AutoLoad"
127
#define CONF_LOG_AT_END "LogAtEnd"
128
#define CONF_LOG_MULTI "LogMulti"
129
#define CONF_STATISTICS "Statistics"
130
#define CONF_TIMED_STATS "TimedStats"
131
#define CONF_NUMBER "Number"
132
#define CONF_MOVE_TO_ERR "MoveToError"
133
#define CONF_HISTORY "History"
134
#define CONF_EXEC_LOG "ExecLog"
135
#define CONF_TOPLEVEL_DESCRIBE "ToplevelDescribe"
137
class toWorksheetSetup : public toWorksheetSetupUI, public toSettingTab
142
toWorksheetSetup(toTool *tool, QWidget* parent = 0, const char* name = 0)
143
: toWorksheetSetupUI(parent, name), toSettingTab("worksheet.html#preferences"), Tool(tool)
145
if (!tool->config(CONF_AUTO_SAVE, "").isEmpty())
146
AutoSave->setChecked(true);
147
if (!tool->config(CONF_CHECK_SAVE, "Yes").isEmpty())
148
CheckSave->setChecked(true);
149
if (!tool->config(CONF_LOG_AT_END, "Yes").isEmpty())
150
LogAtEnd->setChecked(true);
151
if (!tool->config(CONF_LOG_MULTI, "Yes").isEmpty())
152
LogMulti->setChecked(true);
153
MoveToError->setChecked(!tool->config(CONF_MOVE_TO_ERR, "Yes").isEmpty());
154
if (!tool->config(CONF_STATISTICS, "").isEmpty())
155
Statistics->setChecked(true);
156
TimedStatistics->setChecked(!tool->config(CONF_TIMED_STATS, "Yes").isEmpty());
157
History->setChecked(!tool->config(CONF_HISTORY, "").isEmpty());
158
if (!tool->config(CONF_NUMBER, "Yes").isEmpty())
159
DisplayNumber->setChecked(true);
160
if (!tool->config(CONF_TOPLEVEL_DESCRIBE, "Yes").isEmpty())
161
ToplevelDescribe->setChecked(true);
162
DefaultFile->setText(tool->config(CONF_AUTO_LOAD, ""));
163
ExecLog->setChecked(!tool->config(CONF_EXEC_LOG, "").isEmpty());
166
TimedStatistics->hide();
172
virtual void saveSetting(void)
174
if (AutoSave->isChecked())
175
Tool->setConfig(CONF_AUTO_SAVE, "Yes");
177
Tool->setConfig(CONF_AUTO_SAVE, "");
178
if (CheckSave->isChecked())
179
Tool->setConfig(CONF_CHECK_SAVE, "Yes");
181
Tool->setConfig(CONF_CHECK_SAVE, "");
182
if (LogAtEnd->isChecked())
183
Tool->setConfig(CONF_LOG_AT_END, "Yes");
185
Tool->setConfig(CONF_LOG_AT_END, "");
186
if (LogMulti->isChecked())
187
Tool->setConfig(CONF_LOG_MULTI, "Yes");
189
Tool->setConfig(CONF_LOG_MULTI, "");
190
Tool->setConfig(CONF_TOPLEVEL_DESCRIBE, ToplevelDescribe->isChecked() ? "Yes" : "");
191
Tool->setConfig(CONF_MOVE_TO_ERR, MoveToError->isChecked() ? "Yes" : "");
192
Tool->setConfig(CONF_STATISTICS, Statistics->isChecked() ? "Yes" : "");
193
Tool->setConfig(CONF_HISTORY, History->isChecked() ? "Yes" : "");
194
Tool->setConfig(CONF_TIMED_STATS, TimedStatistics->isChecked() ? "Yes" : "");
195
Tool->setConfig(CONF_NUMBER, DisplayNumber->isChecked() ? "Yes" : "");
196
Tool->setConfig(CONF_EXEC_LOG, ExecLog->isChecked() ? "Yes" : "");
197
Tool->setConfig(CONF_AUTO_LOAD, DefaultFile->text());
200
void chooseFile(void)
202
QString str = toOpenFilename(DefaultFile->text(), QString::null, this);
204
DefaultFile->setText(str);
208
class toWorksheetTool : public toTool
211
virtual const char **pictureXPM(void)
213
return const_cast<const char**>(toworksheet_xpm);
217
: toTool(10, "SQL Editor")
219
virtual const char *menuItem()
223
virtual QWidget *toolWindow(QWidget *main, toConnection &connection)
225
return new toWorksheet(main, connection);
227
virtual QWidget *configurationTab(QWidget *parent)
229
return new toWorksheetSetup(this, parent);
231
virtual bool canHandle(toConnection &)
235
virtual void closeWindow(toConnection &connection){};
238
static toWorksheetTool WorksheetTool;
240
class toWorksheetText : public toHighlightedText
242
toWorksheet *Worksheet;
244
toWorksheetText(toWorksheet *worksheet, QWidget *parent, const char *name = NULL)
245
: toHighlightedText(parent, name), Worksheet(worksheet)
247
/** Reimplemented for internal reasons.
249
virtual void keyPressEvent(QKeyEvent *e)
251
if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "Ctrl+Return", "Worksheet|Execute current"))))
253
Worksheet->execute();
256
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "F8", "Worksheet|Execute all"))))
258
Worksheet->executeAll();
261
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "F9", "Worksheet|Execute next"))))
263
Worksheet->executeStep();
266
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "Shift+F9", "Worksheet|Execute newline separated"))))
268
Worksheet->executeNewline();
271
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "F7", "Worksheet|Execute saved SQL"))))
273
Worksheet->executeSaved();
276
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "Shift+F7", "Worksheet|Insert saved SQL"))))
278
Worksheet->insertSaved();
281
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "F4", "Worksheet|Describe under cursor"))))
283
Worksheet->describe();
286
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "Alt+Up", "Worksheet|Previous log entry"))))
288
Worksheet->executePreviousLog();
291
else if (toCheckKeyEvent(e, QKeySequence(qApp->translate("toWorksheet", "Alt+Down", "Worksheet|Next log entry"))))
293
Worksheet->executeNextLog();
298
toHighlightedText::keyPressEvent(e);
301
virtual bool editSave(bool askfile)
303
bool ret = toHighlightedText::editSave(askfile);
304
Worksheet->setCaption();
307
virtual bool editOpen(QString suggestedFile)
312
ret = TOMessageBox::information(this,
313
qApp->translate("toWorksheetText", "Save changes?"),
314
qApp->translate("toWorksheetText", "The editor has been changed. Do you want to save them,\n"
315
"discard changes or open file in new worksheet?"),
316
qApp->translate("toWorksheetText", "&Save"),
317
qApp->translate("toWorksheetText", "&Discard"),
318
qApp->translate("toWorksheetText", "&New worksheet"), 0);
323
if (!editSave(false))
329
if (suggestedFile != QString::null)
330
fname = suggestedFile;
333
QFileInfo file(filename());
334
fname = toOpenFilename(file.dirPath(), QString::null, this);
341
toWorksheet::fileWorksheet(fname);
345
Worksheet->setCaption();
355
void toWorksheet::viewResources(void)
359
QString address = toSQLToAddress(connection(), QueryString);
361
Resources->changeParams(address);
363
QString sql = toSQL::string(TOSQL_LONGOPS, connection());
364
sql += " AND b.SQL_Address||':'||b.SQL_Hash_Value = :addr<char[100]>";
365
LongOps->setSQL(sql);
366
LongOps->clearParams();
367
LongOps->changeParams(address);
372
#define TOWORKSHEET "toWorksheet:"
374
void toWorksheet::setup(bool autoLoad)
376
QToolBar *toolbar = toAllocBar(this, tr("SQL worksheet"));
378
new QToolButton(QPixmap(const_cast<const char**>(execute_xpm)),
379
tr("Execute current statement"),
380
tr("Execute current statement"),
381
this, SLOT(execute(void)),
383
new QToolButton(QPixmap(const_cast<const char**>(executestep_xpm)),
384
tr("Step through statements"),
385
tr("Step through statements"),
386
this, SLOT(executeStep(void)),
388
new QToolButton(QPixmap(const_cast<const char**>(executeall_xpm)),
389
tr("Execute all statements"),
390
tr("Execute all statements"),
391
this, SLOT(executeAll(void)),
393
toolbar->addSeparator();
394
new QToolButton(QPixmap(const_cast<const char**>(refresh_xpm)),
395
tr("Reexecute Last Statement"),
396
tr("Reexecute Last Statement"),
397
this, SLOT(refreshSetup(void)),
400
connect(&RefreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
402
LastLine = LastOffset = -1;
407
Editor = new toWorksheetText(this, this);
408
#ifdef TO_KDE_KACCELMANAGER
409
KAcceleratorManager::setNoAccel( Editor );
411
Current = Result = new toResultLong(this);
413
connect(Result, SIGNAL(done(void)), this, SLOT(queryDone(void)));
414
connect(Result, SIGNAL(firstResult(const QString &, const toConnection::exception &, bool)),
415
this, SLOT(addLog(const QString &, const toConnection::exception &, bool)));
423
StatisticButton = NULL;
429
WaitChart = IOChart = NULL;
430
toolbar->addSeparator();
431
StopButton = new QToolButton(QPixmap(const_cast<const char**>(stop_xpm)),
432
tr("Stop execution"),
433
tr("Stop execution"),
434
Result, SLOT(stop(void)),
436
StopButton->setEnabled(false);
437
toolbar->setStretchableWidget(Started = new QLabel(toolbar, TO_KDE_TOOLBAR_WIDGET));
438
Started->setAlignment(AlignRight | AlignVCenter | ExpandTabs);
442
QSplitter *splitter = new QSplitter(Vertical, this);
444
Editor = new toWorksheetText(this, splitter);
445
#ifdef TO_KDE_KACCELMANAGER
446
KAcceleratorManager::setNoAccel( Editor );
448
ResultTab = new toTabWidget(splitter);
449
QVBox *box = new QVBox(ResultTab);
450
ResultTab->addTab(box, tr("&Result"));
452
Current = Result = new toResultLong(box);
453
connect(Result, SIGNAL(done(void)), this, SLOT(queryDone(void)));
454
connect(Result, SIGNAL(firstResult(const QString &, const toConnection::exception &, bool)),
455
this, SLOT(addLog(const QString &, const toConnection::exception &, bool)));
457
bool toplevel = !WorksheetTool.config(CONF_TOPLEVEL_DESCRIBE, "Yes").isEmpty();
458
Columns = new toResultCols(box, "description", toplevel ? WType_TopLevel : 0);
461
ResultTab->setTabEnabled(Columns, false);
462
Plan = new toResultPlan(ResultTab);
463
ResultTab->addTab(Plan, tr("E&xecution plan"));
465
ResourceSplitter = new QSplitter(Vertical, ResultTab);
466
Resources = new toResultResources(ResourceSplitter);
468
LongOps = new toResultLong(ResourceSplitter);
470
Visualize = new toVisualize(Result, ResultTab);
471
ResultTab->addTab(Visualize, tr("&Visualize"));
472
ResultTab->addTab(ResourceSplitter, tr("&Information"));
473
ResultTab->setTabShown(ResourceSplitter, Resources->handled());
475
StatTab = new QVBox(ResultTab);
477
QToolBar *stattool = toAllocBar(StatTab, tr("Worksheet Statistics"));
478
new QToolButton(QPixmap(const_cast<const char**>(filesave_xpm)),
479
tr("Save statistics for later analysis"),
480
tr("Save statistics for later analysis"),
481
this, SLOT(saveStatistics(void)),
483
stattool->setStretchableWidget(new QLabel(stattool));
485
splitter = new QSplitter(Horizontal, StatTab);
486
Statistics = new toResultStats(true, splitter);
487
Statistics->setTabWidget(ResultTab);
488
WaitChart = new toResultBar(splitter);
491
WaitChart->setSQL(toSQL::sql(TO_SESSION_WAIT));
495
WaitChart->setTitle(tr("Wait states"));
496
WaitChart->setYPostfix(QString::fromLatin1("ms/s"));
497
WaitChart->setSamples( -1);
499
connect(Statistics, SIGNAL(sessionChanged(const QString &)),
500
WaitChart, SLOT(changeParams(const QString &)));
501
IOChart = new toResultBar(splitter);
504
IOChart->setSQL(toSQL::sql(TO_SESSION_IO));
508
IOChart->setTitle(tr("I/O"));
509
IOChart->setYPostfix(tr("blocks/s"));
510
IOChart->setSamples( -1);
512
connect(Statistics, SIGNAL(sessionChanged(const QString &)),
513
IOChart, SLOT(changeParams(const QString &)));
514
ResultTab->addTab(StatTab, tr("&Statistics"));
515
ResultTab->setTabEnabled(StatTab, false);
517
Logging = new toListView(ResultTab);
518
ResultTab->addTab(Logging, tr("&Logging"));
519
Logging->addColumn(tr("SQL"));
520
Logging->addColumn(tr("Result"));
521
Logging->addColumn(tr("Timestamp"));
522
Logging->addColumn(tr("Duration"));
523
Logging->setColumnAlignment(3, AlignRight);
524
Logging->setSelectionMode(QListView::Single);
525
connect(Logging, SIGNAL(selectionChanged(QListViewItem *)), this, SLOT(executeLog()));
528
toolbar->addSeparator();
529
new QToolButton(QPixmap(const_cast<const char**>(describe_xpm)),
530
tr("Describe under cursor"),
531
tr("Describe under cursor"),
532
this, SLOT(describe(void)),
534
PlanButton = new QToolButton(QPixmap(const_cast<const char**>(explainplan_xpm)),
535
tr("Explain plan of current statement"),
536
tr("Explain plan of current statement"),
537
this, SLOT(explainPlan(void)),
539
PlanButton->setEnabled(Plan->handled());
540
StopButton = new QToolButton(QPixmap(const_cast<const char**>(stop_xpm)),
541
tr("Stop execution"),
542
tr("Stop execution"),
543
this, SLOT(stop(void)),
545
StopButton->setEnabled(false);
546
toolbar->addSeparator();
547
new QToolButton(QPixmap(const_cast<const char**>(eraselog_xpm)),
548
tr("Clear execution log"),
549
tr("Clear execution log"),
550
this, SLOT(eraseLogButton(void)),
553
toolbar->addSeparator();
554
StatisticButton = new QToolButton(toolbar);
555
StatisticButton->setToggleButton(true);
556
StatisticButton->setIconSet(QIconSet(QPixmap(const_cast<const char**>(clock_xpm))));
557
connect(StatisticButton, SIGNAL(toggled(bool)), this, SLOT(enableStatistic(bool)));
559
(StatisticButton, tr("Gather session statistic of execution"));
564
new QLabel(tr("Refresh") + " ", toolbar, TO_KDE_TOOLBAR_WIDGET);
565
Refresh = toRefreshCreate(toolbar, TO_KDE_TOOLBAR_WIDGET);
572
toolbar->addSeparator();
575
connect(Refresh, SIGNAL(activated(const QString &)), this, SLOT(changeRefresh(const QString &)));
576
connect(StatisticButton, SIGNAL(toggled(bool)), Refresh, SLOT(setEnabled(bool)));
577
Refresh->setEnabled(false);
578
Refresh->setFocusPolicy(NoFocus);
580
new QToolButton(QPixmap(const_cast<const char**>(up_xpm)),
581
tr("Previous log entry"),
582
tr("Previous log entry"),
583
this, SLOT(executePreviousLog()),
585
new QToolButton(QPixmap(const_cast<const char**>(down_xpm)),
586
tr("Next log entry"),
587
tr("Next log entry"),
588
this, SLOT(executeNextLog()),
590
toolbar->addSeparator();
592
InsertSavedButton = new toPopupButton(QPixmap(const_cast<const char**>(insertsaved_xpm)),
593
tr("Insert current saved SQL"),
594
tr("Insert current saved SQL"),
596
InsertSavedMenu = new QPopupMenu(InsertSavedButton);
597
InsertSavedButton->setPopup(InsertSavedMenu);
598
connect(InsertSavedMenu, SIGNAL(aboutToShow()), this, SLOT(showInsertSaved()));
599
connect(InsertSavedMenu, SIGNAL(activated(int)), this, SLOT(insertSaved(int)));
601
SavedButton = new toPopupButton(QPixmap(const_cast<const char**>(recall_xpm)),
602
tr("Run current saved SQL"),
603
tr("Run current saved SQL"),
605
SavedMenu = new QPopupMenu(SavedButton);
606
SavedButton->setPopup(SavedMenu);
607
connect(SavedMenu, SIGNAL(aboutToShow()), this, SLOT(showSaved()));
608
connect(SavedMenu, SIGNAL(activated(int)), this, SLOT(executeSaved(int)));
610
new QToolButton(QPixmap(const_cast<const char**>(previous_xpm)),
613
this, SLOT(saveLast(void)),
616
toolbar->setStretchableWidget(Started = new QLabel(toolbar, TO_KDE_TOOLBAR_WIDGET));
617
Started->setAlignment(AlignRight | AlignVCenter | ExpandTabs);
619
Schema = new toResultCombo(toolbar);
620
Schema->setSQL(toSQL::sql(toSQL::TOSQL_USERLIST));
621
if (toIsMySQL(connection()))
622
Schema->setSelected(connection().database());
623
else if (toIsOracle(connection()) || toIsSapDB(connection()))
624
Schema->setSelected(connection().user().upper());
626
Schema->setSelected(connection().user());
627
connect(Schema, SIGNAL(activated(int)), this, SLOT(changeSchema()));
635
new toChangeConnection(toolbar, TO_KDE_TOOLBAR_WIDGET);
637
connect(ResultTab, SIGNAL(currentChanged(QWidget *)),
638
this, SLOT(changeResult(QWidget *)));
642
Editor->setFilename(WorksheetTool.config(CONF_AUTO_LOAD, ""));
643
if (!Editor->filename().isEmpty())
647
QCString data = toReadFile(Editor->filename());
648
Editor->setText(QString::fromLocal8Bit(data));
649
Editor->setModified(false);
656
connect(toMainWidget()->workspace(), SIGNAL(windowActivated(QWidget *)),
657
this, SLOT(windowActivated(QWidget *)));
661
if (connection().provider() == "Oracle")
663
if (!WorksheetTool.config(CONF_STATISTICS, "").isEmpty())
666
StatisticButton->setOn(true);
671
StatisticButton->setShown(false);
676
connect(this, SIGNAL(connectionChange()), this, SLOT(connectionChanged()));
678
Editor->setAnalyzer(connection().analyzer());
679
connect(Editor, SIGNAL(displayMenu(QPopupMenu *)), this, SLOT(displayMenu(QPopupMenu *)));
681
connect(&Poll, SIGNAL(timeout()), this, SLOT(poll()));
682
setFocusProxy(Editor);
685
toWorksheet::toWorksheet(QWidget *main, toConnection &connection, bool autoLoad)
686
: toToolWidget(WorksheetTool, "worksheet.html", main, connection), Light(false)
691
toWorksheet::toWorksheet(QWidget *main, const char *name, toConnection &connection)
692
: toToolWidget(WorksheetTool, "worksheetlight.html", main, connection, name), Light(true)
697
void toWorksheet::changeRefresh(const QString &str)
701
if (!Light && StopButton->isEnabled() && StatisticButton->isOn())
702
toRefreshParse(timer(), str);
707
void toWorksheet::windowActivated(QWidget *widget)
713
while (w && w != widget)
715
w = w->parentWidget();
722
ToolMenu = new QPopupMenu(this);
723
ToolMenu->insertItem(QPixmap(const_cast<const char**>(execute_xpm)),
724
tr("&Execute Current"), this, SLOT(execute(void)),
725
toKeySequence(tr("Ctrl+Return", "Worksheet|Execute current")));
726
ToolMenu->insertItem(QPixmap(const_cast<const char**>(executestep_xpm)),
727
tr("Execute &Next"), this, SLOT(executeStep(void)),
728
toKeySequence(tr("F9", "Worksheet|Execute next")));
729
ToolMenu->insertItem(QPixmap(const_cast<const char**>(executeall_xpm)),
730
tr("Execute &All"), this, SLOT(executeAll(void)),
731
toKeySequence(tr("F8", "Worksheet|Execute all")));
732
ToolMenu->insertItem(tr("Execute &Newline Separated"), this,
733
SLOT(executeNewline(void)),
734
toKeySequence(tr("Shift+F9", "Worksheet|Execute newline separated")));
735
ToolMenu->insertItem(QPixmap(const_cast<const char**>(refresh_xpm)),
736
tr("&Reexecute Last Statement"), this, SLOT(refresh(void)),
737
toKeySequence(tr("F5", "Worksheet|Reexecute last statement")));
738
if (connection().provider() == "Oracle")
739
ToolMenu->insertItem(tr("Check syntax of buffer"),
740
this, SLOT(parseAll()),
741
toKeySequence(tr("Ctrl+F9", "Worksheet|Check syntax of buffer")));
742
ToolMenu->insertSeparator();
743
ToolMenu->insertItem(QPixmap(const_cast<const char**>(describe_xpm)),
744
tr("&Describe Under Cursor"), this, SLOT(describe(void)),
745
toKeySequence(tr("F4", "Worksheet|Describe under cursor")));
746
ToolMenu->insertItem(tr("&Explain current statement"), this, SLOT(explainPlan(void)),
747
toKeySequence(tr("F3", "Worksheet|Explain plan")), TO_ID_PLAN);
748
if (connection().provider() == "Oracle")
749
ToolMenu->insertItem(tr("&Enable Statistics"), this, SLOT(toggleStatistic(void)),
750
0, TO_ID_STATISTICS);
751
ToolMenu->insertItem(QPixmap(const_cast<const char**>(stop_xpm)),
752
tr("&Stop Execution"), Result, SLOT(stop(void)),
754
ToolMenu->insertSeparator();
755
ToolMenu->insertItem(tr("Execute Saved SQL"),
756
this, SLOT(executeSaved()),
757
toKeySequence(tr("F7", "Worksheet|Execute saved SQL")));
758
ToolMenu->insertItem(tr("Select Saved SQL"),
759
this, SLOT(selectSaved()),
760
toKeySequence(tr("Ctrl+Shift+S", "Worksheet|Select saved SQL")));
761
ToolMenu->insertItem(QPixmap(const_cast<const char**>(previous_xpm)),
763
this, SLOT(saveLast()));
764
ToolMenu->insertItem(tr("Edit Saved SQL..."),
765
this, SLOT(editSaved()));
766
ToolMenu->insertSeparator();
767
ToolMenu->insertItem(tr("Previous Log Entry"), this, SLOT(executePreviousLog()),
768
toKeySequence(tr("Alt+Up", "Worksheet|Previous log entry")));
769
ToolMenu->insertItem(tr("Next Log Entry"), this, SLOT(executeNextLog()),
770
toKeySequence(tr("Alt+Down", "Worksheet|Next log entry")));
771
ToolMenu->insertItem(QPixmap(const_cast<const char**>(eraselog_xpm)),
772
tr("Erase &Log"), this, SLOT(eraseLogButton(void)));
775
toMainWidget()->menuBar()->insertItem(tr("Edit&or"), ToolMenu, -1, toToolMenuIndex());
776
ToolMenu->setItemEnabled(TO_ID_STOP, StopButton->isEnabled());
777
ToolMenu->setItemChecked(TO_ID_STATISTICS, StatisticButton->isOn());
778
ToolMenu->setItemEnabled(TO_ID_PLAN, Plan->handled());
788
void toWorksheet::connectionChanged(void)
792
StatisticButton->setShown(connection().provider() == "Oracle");
793
ResultTab->setTabShown(ResourceSplitter, Resources->handled());
794
Editor->setAnalyzer(connection().analyzer());
795
PlanButton->setEnabled(Plan->handled());
798
windowActivated(this);
803
bool toWorksheet::checkSave(bool input)
807
if (Editor->isModified())
809
if (WorksheetTool.config(CONF_AUTO_SAVE, "").isEmpty() ||
810
Editor->filename().isEmpty())
812
if (!WorksheetTool.config(CONF_CHECK_SAVE, "Yes").isEmpty())
819
conn = connection().description();
823
conn += QString::fromLatin1("unknown connection");
825
QString str = tr("Save changes to editor for %1").arg(conn);
826
if (!Editor->filename().isEmpty())
827
str += QString::fromLatin1("\n(") + Editor->filename() + QString::fromLatin1(")");
828
int ret = TOMessageBox::information(this,
831
tr("&Yes"), tr("&No"), tr("Cancel"), 0, 2);
842
if (Editor->filename().isEmpty() && input)
843
Editor->setFilename(toSaveFilename(Editor->filename(), QString::null, this));
844
if (Editor->filename().isEmpty())
847
if (!toWriteFile(Editor->filename(), Editor->text()))
849
Editor->setModified(false);
854
bool toWorksheet::close(bool del)
859
return QVBox::close(del);
864
toWorksheet::~toWorksheet()
870
#define LARGE_BUFFER 4096
872
void toWorksheet::changeResult(QWidget *widget)
875
if (QueryString.length())
877
if (CurrentTab == Plan)
878
Plan->query(QueryString);
879
else if (CurrentTab == ResourceSplitter)
881
else if (CurrentTab == Statistics && Result->running())
882
Statistics->refreshStats(false);
886
void toWorksheet::refresh(void)
888
if (!QueryString.isEmpty())
889
query(QueryString, Normal);
890
if (RefreshSeconds > 0)
891
RefreshTimer.start(RefreshSeconds*1000, true);
894
static QString unQuote(const QString &str)
896
if (str.at(0).latin1() == '\"' && str.at(str.length() - 1).latin1() == '\"')
897
return str.left(str.length() - 1).right(str.length() - 2);
901
bool toWorksheet::describe(const QString &query)
905
QRegExp white(QString::fromLatin1("[ \r\n\t.]+"));
906
QStringList part = QStringList::split(white, query);
907
if (part[0].upper() == QString::fromLatin1("DESC") ||
908
part[0].upper() == QString::fromLatin1("DESCRIBE"))
912
if (toIsOracle(connection()))
914
if (part.count() == 2)
916
Columns->changeParams(unQuote(part[1]));
918
else if (part.count() == 3)
920
Columns->changeParams(unQuote(part[1]), unQuote(part[2]));
923
throw tr("Wrong number of parameters for describe");
925
else if (connection().provider() == "MySQL")
927
if (part.count() == 2)
929
Columns->changeParams(part[1]);
932
throw tr("Wrong number of parameters for describe");
943
QWidget *curr = ResultTab->currentPage();
948
ResultTab->showPage(Result);
956
void toWorksheet::query(const QString &str, execType type)
961
QRegExp strq(QString::fromLatin1("'[^']*'"));
962
QString chk = str.lower();
963
chk.replace(strq, QString::fromLatin1(" "));
965
static QRegExp codere(QString::fromLatin1("[^a-z0-9]end\\s+[a-z0-9_-]*;$"), true);
966
static QRegExp codere2(QString::fromLatin1("[^a-z0-9]end;"), true);
968
if (codere.match(chk) >= 0 || codere2.match(chk) >= 0)
972
if (!code && QueryString.length() > 0 && QueryString.at(QueryString.length() - 1) == ';')
973
QueryString.truncate(QueryString.length() - 1);
975
bool nobinds = false;
977
chk.replace(strq, QString::fromLatin1(" "));
978
chk = chk.simplifyWhiteSpace();
979
chk.replace(QRegExp(QString::fromLatin1(" or replace ")), QString::fromLatin1(" "));
980
if (chk.startsWith(QString::fromLatin1("create trigger ")))
983
if (type == OnlyPlan)
985
ResultTab->showPage(Plan);
988
else if (!describe(QueryString))
991
toSQLParse::stringTokenizer tokens(str);
992
QString first = tokens.getToken(true).upper();
993
if (first == QString::fromLatin1("REM") ||
994
first == QString::fromLatin1("ASSIGN") ||
995
first == QString::fromLatin1("PROMPT") ||
996
first == QString::fromLatin1("COLUMN") ||
997
first == QString::fromLatin1("SPOOL") ||
998
first == QString::fromLatin1("STORE"))
1000
QString t = tr("Ignoring SQL*Plus command");
1002
addLog(QueryString, toConnection::exception(t), false);
1003
toStatusMessage(t, true);
1011
param = toParamGet::getParam(connection(), this, QueryString);
1017
toStatusMessage(tr("Processing query"), true);
1025
connection().parse(QueryString);
1027
catch (const QString &exc)
1029
addLog(QueryString, exc, true);
1032
else if (type == Direct)
1039
if (WorksheetTool.config(CONF_HISTORY, "").isEmpty() && !Light)
1041
toQuery query(connection(), toQuery::Long, QueryString, param);
1042
if (query.rowsProcessed() > 0)
1043
buffer = tr("%1 rows processed").arg((int)query.rowsProcessed());
1045
buffer = tr("Query executed");
1049
toResultView *query = new toResultView(Current->parentWidget());
1053
query->query(QueryString, param);
1054
if (query->query() && query->query()->rowsProcessed() > 0)
1055
buffer = tr("%1 rows processed").arg((int)query->query()->rowsProcessed());
1057
buffer = tr("Query executed");
1069
addLog(QueryString, toConnection::exception(buffer), false);
1071
catch (const QString &exc)
1073
addLog(QueryString, exc, true);
1080
StopButton->setEnabled(true);
1083
(Started, tr("Duration while query has been running\n\n") + QueryString);
1085
ToolMenu->setItemEnabled(TO_ID_STOP, true);
1086
Result->setNumberColumn(!WorksheetTool.config(CONF_NUMBER, "Yes").isEmpty());
1090
Result->setSQL(QString::null);
1091
Result->query(QueryString, param);
1094
if (CurrentTab == Visualize)
1095
Visualize->display();
1096
else if (CurrentTab == Plan)
1097
Plan->query(QueryString);
1098
else if (CurrentTab == ResourceSplitter)
1101
catch (const toConnection::exception &exc)
1103
addLog(QueryString, exc, true);
1105
catch (const QString &exc)
1107
addLog(QueryString, exc, true);
1113
if (StatisticButton->isOn())
1114
toRefreshParse(timer(), Refresh->currentText());
1118
Result->setSQLName(QueryString.simplifyWhiteSpace().left(40));
1123
void toWorksheet::saveHistory(void)
1125
if (WorksheetTool.config(CONF_HISTORY, "").isEmpty())
1127
if (Result->firstChild() && Current == Result && !Light)
1129
History[LastID] = Result;
1132
disconnect(Result, SIGNAL(done(void)), this, SLOT(queryDone(void)));
1133
disconnect(Result, SIGNAL(firstResult(const QString &, const toConnection::exception &, bool)),
1134
this, SLOT(addLog(const QString &, const toConnection::exception &, bool)));
1135
disconnect(StopButton, SIGNAL(clicked(void)), Result, SLOT(stop(void)));
1137
Result = new toResultLong(Result->parentWidget());
1138
if (StatisticButton->isOn())
1139
enableStatistic(true);
1142
connect(StopButton, SIGNAL(clicked(void)), Result, SLOT(stop(void)));
1143
connect(Result, SIGNAL(done(void)), this, SLOT(queryDone(void)));
1144
connect(Result, SIGNAL(firstResult(const QString &, const toConnection::exception &, bool)),
1145
this, SLOT(addLog(const QString &, const toConnection::exception &, bool)));
1149
QString toWorksheet::duration(int dur, bool hundreds)
1155
sprintf(buf, "%d:%02d:%02d.%02d", dur / 3600000, (dur / 60000) % 60, (dur / 1000) % 60, (dur / 10) % 100);
1157
sprintf(buf, "%d:%02d:%02d", dur / 3600000, (dur / 60000) % 60, (dur / 1000) % 60);
1162
sprintf(buf, "%d:%02d.%02d", dur / 60000, (dur / 1000) % 60, (dur / 10) % 100);
1164
sprintf(buf, "%d:%02d", dur / 60000, (dur / 1000) % 60);
1166
return QString::fromLatin1(buf);
1169
void toWorksheet::addLog(const QString &sql, const toConnection::exception &result, bool error)
1174
now = toNow(connection());
1178
now = QString::fromLatin1("Unknown");
1180
toResultViewItem *item = NULL;
1185
if (!Timer.isNull())
1186
dur = Timer.elapsed();
1191
if (WorksheetTool.config(CONF_LOG_MULTI, "Yes").isEmpty())
1193
if (WorksheetTool.config(CONF_LOG_AT_END, "Yes").isEmpty())
1194
item = new toResultViewItem(Logging, NULL);
1196
item = new toResultViewItem(Logging, LastLogItem);
1198
else if (WorksheetTool.config(CONF_LOG_AT_END, "Yes").isEmpty())
1199
item = new toResultViewMLine(Logging, NULL);
1201
item = new toResultViewMLine(Logging, LastLogItem);
1202
item->setText(0, sql);
1205
item->setText(1, result);
1206
item->setText(2, now);
1207
if (!WorksheetTool.config(CONF_HISTORY, "").isEmpty())
1208
item->setText(4, QString::number(LastID));
1209
item->setText(5, QString::number(result.offset()));
1212
if (result.offset() >= 0 && LastLine >= 0 && LastOffset >= 0 &&
1213
!WorksheetTool.config(CONF_MOVE_TO_ERR, "Yes").isEmpty())
1218
for (int i = 0;i < result.offset();i++)
1220
if (sql.at(i) == cmp)
1227
Editor->setCursorPosition(LastLine + lines, LastOffset + result.offset() - lastnl);
1228
LastLine = LastOffset = -1;
1231
QString buf = duration(dur);
1235
item->setText(3, buf);
1237
QListViewItem *last = Logging->currentItem();
1238
toResultViewItem *citem = NULL;
1240
citem = dynamic_cast<toResultViewItem *>(last);
1241
if (!citem || citem->allText(0) != sql)
1243
disconnect(Logging, SIGNAL(selectionChanged(QListViewItem *)), this, SLOT(executeLog()));
1244
Logging->setSelected(item, true);
1245
connect(Logging, SIGNAL(selectionChanged(QListViewItem *)), this, SLOT(executeLog()));
1246
Logging->ensureItemVisible(item);
1251
QString str = result;
1252
str += "\n" + tr("(Duration %1)").arg(buf);
1255
toStatusMessage(str);
1257
toStatusMessage(str, false, false);
1259
if (!Light && !error)
1260
changeResult(CurrentTab);
1262
static QRegExp re(QString::fromLatin1("^[1-9]\\d* rows processed$"));
1265
if (result.contains(re))
1267
if (!toConfigurationSingle::Instance().globalConfig(CONF_AUTO_COMMIT, "").isEmpty())
1268
connection().commit();
1270
toMainWidget()->setNeedCommit(connection());
1277
void toWorksheet::execute(toSQLParse::tokenizer &tokens, int line, int pos, execType type)
1282
if(Editor->lines()<=tokens.line()){
1283
endLine=Editor->lines()-1;
1284
endCol=Editor->lineLength(Editor->lines()-1);
1286
endLine=tokens.line();
1287
if(Editor->lineLength(tokens.line())<=tokens.offset())
1288
endCol=Editor->lineLength(tokens.line());
1290
endCol=tokens.offset();
1293
Editor->setSelection(line, pos, endLine,endCol);
1294
QString t = Editor->selectedText();
1296
bool comment = false;
1297
bool multiComment = false;
1302
for (i = 0;i < t.length() - 1;i++)
1306
if (t.at(i).latin1() == '\n')
1309
else if (multiComment)
1311
if (t.at(i).latin1() == '*' &&
1312
t.at(i + 1).latin1() == '/')
1314
multiComment = false;
1318
else if (t.at(i).latin1() == '-' &&
1319
t.at(i + 1).latin1() == '-')
1321
else if (t.at(i).latin1() == '/' &&
1322
t.at(i + 1).latin1() == '/')
1324
else if (t.at(i).latin1() == '/' &&
1325
t.at(i + 1).latin1() == '*')
1326
multiComment = true;
1327
else if (!t.at(i).isSpace() && t.at(i) != '/')
1330
if (t.at(i).latin1() == '\n')
1339
if (line != oline ||
1344
Editor->setSelection(line, pos, endLine, endCol);
1351
void toWorksheet::execute()
1353
if (Editor->hasSelectedText())
1355
query(Editor->selectedText(), Normal);
1359
toSQLParse::editorTokenizer tokens(Editor);
1362
Editor->getCursorPosition(&cline, &cpos);
1368
line = tokens.line();
1369
pos = tokens.offset();
1370
toSQLParse::parseStatement(tokens);
1372
while (tokens.line() < cline ||
1373
(tokens.line() == cline && tokens.offset() < cpos));
1375
execute(tokens, line, pos, Normal);
1378
void toWorksheet::explainPlan()
1380
if (Editor->hasSelectedText())
1382
query(Editor->selectedText(), OnlyPlan);
1386
toSQLParse::editorTokenizer tokens(Editor);
1389
Editor->getCursorPosition(&cline, &cpos);
1395
line = tokens.line();
1396
pos = tokens.offset();
1397
toSQLParse::parseStatement(tokens);
1399
while (tokens.line() < cline ||
1400
(tokens.line() == cline && tokens.offset() < cpos));
1402
execute(tokens, line, pos, OnlyPlan);
1405
void toWorksheet::executeStep()
1407
toSQLParse::editorTokenizer tokens(Editor);
1410
Editor->getCursorPosition(&cline, &cpos);
1416
line = tokens.line();
1417
pos = tokens.offset();
1418
toSQLParse::parseStatement(tokens);
1420
while (tokens.line() < cline ||
1421
(tokens.line() == cline && tokens.offset() <= cpos));
1423
execute(tokens, line, pos, Normal);
1426
void toWorksheet::executeAll()
1428
toSQLParse::editorTokenizer tokens(Editor);
1431
Editor->getCursorPosition(&cline, &cpos);
1433
QProgressDialog dialog(tr("Executing all statements"),
1444
line = tokens.line();
1445
pos = tokens.offset();
1446
dialog.setProgress(line);
1447
qApp->processEvents();
1448
if (dialog.wasCancelled())
1450
toSQLParse::parseStatement(tokens);
1452
if (ignore && (tokens.line() > cline ||
1453
(tokens.line() == cline &&
1454
tokens.offset() >= cpos)))
1461
if (tokens.line() < Editor->lines() && !ignore)
1463
execute(tokens, line, pos, Direct);
1466
toResultView *last = dynamic_cast<toResultView *>(Current);
1467
if (!WorksheetTool.config(CONF_HISTORY, "").isEmpty() &&
1468
last && last->firstChild())
1469
History[LastID] = last;
1473
while (tokens.line() < Editor->lines());
1475
Editor->setSelection(cline, cpos, tokens.line(), tokens.offset());
1478
void toWorksheet::parseAll()
1480
toSQLParse::editorTokenizer tokens(Editor);
1483
Editor->getCursorPosition(&cline, &cpos);
1485
QProgressDialog dialog(tr("Parsing all statements"),
1496
line = tokens.line();
1497
pos = tokens.offset();
1498
dialog.setProgress(line);
1499
qApp->processEvents();
1500
if (dialog.wasCancelled())
1502
toSQLParse::parseStatement(tokens);
1504
if (ignore && (tokens.line() > cline ||
1505
(tokens.line() == cline &&
1506
tokens.offset() >= cpos)))
1513
if (tokens.line() < Editor->lines() && !ignore)
1515
execute(tokens, line, pos, Parse);
1518
toResultView *last = dynamic_cast<toResultView *>(Current);
1519
if (!WorksheetTool.config(CONF_HISTORY, "").isEmpty() &&
1520
last && last->firstChild())
1521
History[LastID] = last;
1525
while (tokens.line() < Editor->lines());
1527
Editor->setSelection(cline, cpos, tokens.line(), tokens.offset());
1530
void toWorksheet::eraseLogButton()
1536
for (std::map<int, QWidget *>::iterator i = History.begin();i != History.end();i++)
1541
void toWorksheet::queryDone(void)
1543
if (!First && !QueryString.isEmpty())
1544
addLog(QueryString, toConnection::exception(tr("Aborted")), false);
1552
StopButton->setEnabled(false);
1555
ToolMenu->setItemEnabled(TO_ID_STOP, false);
1559
void toWorksheet::saveDefaults(void)
1561
QListViewItem *item = Result->firstChild();
1564
QHeader *head = Result->header();
1565
for (int i = 0;i < Result->columns();i++)
1567
toResultViewItem *resItem = dynamic_cast<toResultViewItem *>(item);
1570
str = resItem->allText(i);
1572
str = item->text(i);
1576
toParamGet::setDefault(connection(), head->label(i).lower(), toUnnull(toQValue(str)));
1583
#define ENABLETIMED "ALTER SESSION SET TIMED_STATISTICS = TRUE"
1585
void toWorksheet::enableStatistic(bool ena)
1589
Result->setStatistics(Statistics);
1590
ResultTab->setTabEnabled(StatTab, true);
1592
ToolMenu->setItemChecked(TO_ID_STATISTICS, true);
1593
Statistics->clear();
1594
if (!WorksheetTool.config(CONF_TIMED_STATS, "Yes").isEmpty())
1598
connection().allExecute(QString::fromLatin1(ENABLETIMED));
1599
connection().addInit(QString::fromLatin1(ENABLETIMED));
1608
connection().delInit(QString::fromLatin1(ENABLETIMED));
1612
Result->setStatistics(NULL);
1613
ResultTab->setTabEnabled(StatTab, false);
1615
ToolMenu->setItemChecked(TO_ID_STATISTICS, false);
1619
void toWorksheet::executeNewline(void)
1623
Editor->getCursorPosition(&cline, &epos);
1629
QString data = Editor->text(cline).simplifyWhiteSpace();
1630
if (data.length() == 0 || data == QString::fromLatin1(" "))
1638
while (cline < Editor->lines())
1640
QString data = Editor->text(cline).simplifyWhiteSpace();
1641
if (data.length() != 0 && data != QString::fromLatin1(" "))
1648
while (eline < Editor->lines())
1650
QString data = Editor->text(eline).simplifyWhiteSpace();
1651
if (data.length() == 0 || data == QString::fromLatin1(" "))
1656
epos = Editor->text(eline).length();
1659
Editor->setSelection(cline, 0, eline, epos);
1662
if (Editor->hasSelectedText())
1663
query(Editor->selectedText(), Normal);
1666
void toWorksheet::describe(void)
1671
QString owner, table;
1672
Editor->tableAtCursor(owner, table);
1675
Columns->changeParams(table);
1677
Columns->changeParams(owner, table);
1678
if (!Columns->isTopLevel())
1684
void toWorksheet::executeSaved(void)
1689
LastLine = LastOffset = -1;
1691
if (SavedLast.length() > 0)
1695
query(toSQL::string(SavedLast, connection()), Normal);
1701
void toWorksheet::insertSaved(void)
1706
LastLine = LastOffset = -1;
1708
if (InsertSavedLast.length() > 0)
1712
Editor->setText(toSQL::string(InsertSavedLast, connection()));
1718
void toWorksheet::executeSaved(int id)
1720
std::list<QCString> def = toSQL::range(TOWORKSHEET);
1721
for (std::list<QCString>::iterator i = def.begin();i != def.end();i++)
1733
void toWorksheet::insertSaved(int id)
1735
std::list<QCString> def = toSQL::range(TOWORKSHEET);
1736
for (std::list<QCString>::iterator i = def.begin();i != def.end();i++)
1741
InsertSavedLast = *i;
1748
void toWorksheet::showSaved(void)
1750
static QRegExp colon(QString::fromLatin1(":"));
1751
std::list<QCString> def = toSQL::range(TOWORKSHEET);
1753
std::map<QString, QPopupMenu *> menues;
1755
for (std::list<QCString>::iterator sql = def.begin();sql != def.end();sql++)
1760
QStringList spl = QStringList::split(colon, QString::fromLatin1(*sql));
1761
spl.remove(spl.begin());
1763
if (spl.count() > 0)
1765
QString name = spl.last();
1766
spl.remove(spl.fromLast());
1769
if (spl.count() == 0)
1773
QStringList exs = spl;
1774
while (exs.count() > 0 && menues.find(exs.join(QString::fromLatin1(":"))) == menues.end())
1775
exs.remove(exs.fromLast());
1776
if (exs.count() == 0)
1779
menu = menues[exs.join(QString::fromLatin1(":"))];
1780
QString subname = exs.join(QString::fromLatin1(":"));
1781
for (unsigned int i = exs.count();i < spl.count();i++)
1783
QPopupMenu *next = new QPopupMenu(this);
1784
connect(next, SIGNAL(activated(int)), this, SLOT(executeSaved(int)));
1786
subname += QString::fromLatin1(":");
1788
menu->insertItem(spl[i], next);
1790
menues[subname] = menu;
1793
menu->insertItem(name, id);
1798
void toWorksheet::showInsertSaved(void)
1800
static QRegExp colon(QString::fromLatin1(":"));
1801
std::list<QCString> def = toSQL::range(TOWORKSHEET);
1802
InsertSavedMenu->clear();
1803
std::map<QString, QPopupMenu *> menues;
1805
for (std::list<QCString>::iterator sql = def.begin();sql != def.end();sql++)
1810
QStringList spl = QStringList::split(colon, QString::fromLatin1(*sql));
1811
spl.remove(spl.begin());
1813
if (spl.count() > 0)
1815
QString name = spl.last();
1816
spl.remove(spl.fromLast());
1819
if (spl.count() == 0)
1820
menu = InsertSavedMenu;
1823
QStringList exs = spl;
1824
while (exs.count() > 0 && menues.find(exs.join(QString::fromLatin1(":"))) == menues.end())
1825
exs.remove(exs.fromLast());
1826
if (exs.count() == 0)
1827
menu = InsertSavedMenu;
1829
menu = menues[exs.join(QString::fromLatin1(":"))];
1830
QString subname = exs.join(QString::fromLatin1(":"));
1831
for (unsigned int i = exs.count();i < spl.count();i++)
1833
QPopupMenu *next = new QPopupMenu(this);
1834
connect(next, SIGNAL(activated(int)), this, SLOT(insertSaved(int)));
1836
subname += QString::fromLatin1(":");
1838
menu->insertItem(spl[i], next);
1840
menues[subname] = menu;
1843
menu->insertItem(name, id);
1849
void toWorksheet::editSaved(void)
1851
QCString sql = TOWORKSHEET;
1853
toMainWidget()->editSQL(QString::fromLatin1(sql));
1856
void toWorksheet::selectSaved()
1858
SavedMenu->popup(SavedButton->mapToGlobal(QPoint(0, SavedButton->height())));
1861
void toWorksheet::insertStatement(const QString &str)
1863
QString txt = Editor->text();
1865
int i = txt.find(str);
1869
int startCol, endCol;
1870
int startRow, endRow;
1872
Editor->findPosition(i, startRow, startCol);
1873
Editor->findPosition(i + str.length(), endRow, endCol);
1875
if (Editor->text(endRow).at(endCol) == ';')
1877
Editor->setSelection(startRow, startCol, endRow, endCol);
1882
if (str.right(1) != ";")
1887
Editor->insert(t, true);
1891
void toWorksheet::executePreviousLog(void)
1898
LastLine = LastOffset = -1;
1901
QListViewItem *item = Logging->currentItem();
1904
QListViewItem *pt = Logging->firstChild();
1905
while (pt && pt->nextSibling() != item)
1906
pt = pt->nextSibling();
1909
Logging->setSelected(pt, true);
1913
void toWorksheet::executeLog(void)
1920
LastLine = LastOffset = -1;
1923
QListViewItem *ci = Logging->currentItem();
1924
toResultViewItem *item = dynamic_cast<toResultViewItem *>(ci);
1927
insertStatement(item->allText(0));
1929
if (item->text(4).isEmpty())
1931
if (!WorksheetTool.config(CONF_EXEC_LOG, "").isEmpty())
1932
query(item->allText(0), Normal);
1936
std::map<int, QWidget *>::iterator i = History.find(item->text(4).toInt());
1937
QueryString = item->allText(0);
1938
changeResult(ResultTab->currentPage());
1939
if (i != History.end() && (*i).second)
1942
Current = (*i).second;
1949
void toWorksheet::executeNextLog(void)
1956
LastLine = LastOffset = -1;
1959
QListViewItem *item = Logging->currentItem();
1960
if (item && item->nextSibling())
1962
toResultViewItem *next = dynamic_cast<toResultViewItem *>(item->nextSibling());
1964
Logging->setSelected(next, true);
1968
void toWorksheet::poll(void)
1970
Started->setText(duration(Timer.elapsed(), false));
1973
void toWorksheet::saveLast(void)
1975
if (QueryString.isEmpty())
1977
TOMessageBox::warning(this, tr("No SQL to save"),
1978
tr("You haven't executed any SQL yet"),
1983
QCString name = QInputDialog::getText(tr("Enter title"),
1984
tr("Enter the title in the menu of the saved SQL,\n"
1985
"submenues are separated by a ':' character."),
1986
QLineEdit::Normal, QString::null, &ok, this).latin1();
1987
if (ok && !name.isEmpty())
1991
toSQL::updateSQL(TOWORKSHEET + name,
1995
connection().provider());
1996
toSQL::saveSQL(toConfigurationSingle::Instance().globalConfig(CONF_SQL_FILE, DEFAULT_SQL_FILE));
2002
void toWorksheet::saveStatistics(void)
2004
std::map<QCString, QString> stat;
2006
Statistics->exportData(stat, "Stat");
2007
IOChart->exportData(stat, "IO");
2008
WaitChart->exportData(stat, "Wait");
2009
if (Plan->firstChild())
2010
Plan->exportData(stat, "Plan");
2012
toStatusMessage(tr("No plan available to save"), false, false);
2013
stat["Description"] = QueryString;
2015
toWorksheetStatistic::saveStatistics(stat);
2018
void toWorksheet::exportData(std::map<QCString, QString> &data, const QCString &prefix)
2020
Editor->exportData(data, prefix + ":Edit");
2021
if (StatisticButton->isOn())
2022
data[prefix + ":Stats"] = Refresh->currentText();
2023
toToolWidget::exportData(data, prefix);
2026
void toWorksheet::importData(std::map<QCString, QString> &data, const QCString &prefix)
2028
Editor->importData(data, prefix + ":Edit");
2029
QString stat = data[prefix + ":Stats"];
2032
for (int i = 0;i < Refresh->count();i++)
2034
if (Refresh->text(i) == stat)
2036
Refresh->setCurrentItem(i);
2040
StatisticButton->setOn(true);
2043
StatisticButton->setOn(false);
2045
toToolWidget::importData(data, prefix);
2049
void toWorksheet::setCaption(void)
2051
QString name = WorksheetTool.name();
2052
if (! Editor->filename().isEmpty())
2054
QFileInfo file(Editor->filename());
2055
name += QString::fromLatin1(" ") + file.fileName();
2057
toToolCaption(this, name);
2060
toWorksheet *toWorksheet::fileWorksheet(const QString &file)
2062
toWorksheet *worksheet = new toWorksheet(toMainWidget()->workspace(),
2063
toMainWidget()->currentConnection(),
2065
worksheet->editor()->openFilename(file);
2066
worksheet->setCaption();
2068
toMainWidget()->windowsMenu();
2072
void toWorksheet::refreshSetup(void)
2075
int num = QInputDialog::getInteger(tr("Enter refreshrate"),
2076
tr("Refresh rate of query in seconds"),
2077
RefreshSeconds, 0, 1000000, 1, &ok, this);
2080
RefreshSeconds = num;
2081
RefreshTimer.start(num*1000);
2084
RefreshTimer.stop();
2087
void toWorksheet::stop(void)
2089
RefreshTimer.stop();
2093
void toWorksheet::displayMenu(QPopupMenu *menu)
2095
menu->insertSeparator(0);
2098
menu->insertItem(tr("&Explain current statement"), this, SLOT(explainPlan(void)),
2099
toKeySequence(tr("F3", "Worksheet|Explain plan")), TO_ID_PLAN, 0);
2100
menu->insertItem(QPixmap(const_cast<const char**>(describe_xpm)),
2101
tr("&Describe Under Cursor"), this, SLOT(describe(void)),
2102
toKeySequence(tr("F4", "Worksheet|Describe under cursor")), 0, 0);
2103
menu->insertSeparator(0);
2105
if (connection().provider() == "Oracle")
2106
menu->insertItem(tr("Check syntax of buffer"),
2107
this, SLOT(parseAll()),
2108
toKeySequence(tr("Ctrl+F9", "Worksheet|Check syntax of buffer")), 0, 0);
2109
menu->insertItem(QPixmap(const_cast<const char**>(refresh_xpm)),
2110
tr("&Reexecute Last Statement"), this, SLOT(refresh(void)),
2111
toKeySequence(tr("F5", "Worksheet|Reexecute last statement")), 0, 0);
2112
menu->insertItem(tr("Execute &Newline Separated"), this,
2113
SLOT(executeNewline(void)),
2114
toKeySequence(tr("Shift+F9", "Worksheet|Execute newline separated")), 0, 0);
2115
menu->insertItem(QPixmap(const_cast<const char**>(executeall_xpm)),
2116
tr("Execute &All"), this, SLOT(executeAll(void)),
2117
toKeySequence(tr("F8", "Worksheet|Execute all")), 0, 0);
2118
menu->insertItem(QPixmap(const_cast<const char**>(executestep_xpm)),
2119
tr("Execute &Next"), this, SLOT(executeStep(void)),
2120
toKeySequence(tr("F9", "Worksheet|Execute next")), 0, 0);
2121
menu->insertItem(QPixmap(const_cast<const char**>(execute_xpm)),
2122
tr("&Execute Current"), this, SLOT(execute(void)),
2123
toKeySequence(tr("Ctrl+Return", "Worksheet|Execute current")), 0, 0);
2125
menu->insertSeparator();
2128
if (connection().provider() == "Oracle")
2129
menu->insertItem(tr("&Enable Statistics"), this, SLOT(toggleStatistic(void)),
2130
0, TO_ID_STATISTICS);
2132
menu->insertItem(QPixmap(const_cast<const char**>(stop_xpm)),
2133
tr("&Stop Execution"), Result, SLOT(stop(void)),
2137
menu->insertSeparator();
2138
menu->insertItem(tr("Execute Saved SQL"),
2139
this, SLOT(executeSaved()),
2140
toKeySequence(tr("F7", "Worksheet|Execute saved SQL")));
2141
menu->insertItem(tr("Insert Saved SQL"),
2142
this, SLOT(insertSaved()),
2143
toKeySequence(tr("Shift+F7", "Worksheet|Insert saved SQL")));
2144
menu->insertItem(tr("Select Saved SQL"),
2145
this, SLOT(selectSaved()),
2146
toKeySequence(tr("Ctrl+Shift+S", "Worksheet|Select saved SQL")));
2147
menu->insertItem(QPixmap(const_cast<const char**>(previous_xpm)),
2148
tr("Save last SQL"),
2149
this, SLOT(saveLast()));
2153
#define CHANGE_CURRENT_SCHEMA QString("ALTER SESSION SET CURRENT_SCHEMA = ")
2155
void toWorksheet::changeSchema(void)
2159
QString schema = Schema->selected();
2160
toConnection &conn = connection();
2161
if (toIsOracle(conn))
2163
QString sql = CHANGE_CURRENT_SCHEMA + schema;
2164
conn.allExecute(sql);
2165
for (std::list<QString>::const_iterator i = conn.initStrings().begin();i != conn.initStrings().end();i++)
2167
if ((*i).startsWith(CHANGE_CURRENT_SCHEMA))
2175
else if (toIsMySQL(conn))
2177
conn.allExecute(QString("USE %1").arg(schema));
2178
conn.setDatabase(schema);
2181
throw QString("No support for changing schema for this database");