[go: up one dir, main page]

File: toworksheet.cpp

package info (click to toggle)
tora 1.3.4-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 8,632 kB
  • ctags: 7,487
  • sloc: cpp: 68,518; perl: 1,475; ansic: 291; sh: 173; makefile: 51
file content (1584 lines) | stat: -rw-r--r-- 44,386 bytes parent folder | download
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
1577
1578
1579
1580
1581
1582
1583
1584
//***************************************************************************
/*
 * TOra - An Oracle Toolkit for DBA's and developers
 * Copyright (C) 2000-2001,2001 Underscore AB
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation;  only version 2 of
 * the License is valid for this program.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *      As a special exception, you have permission to link this program
 *      with the Oracle Client libraries and distribute executables, as long
 *      as you follow the requirements of the GNU GPL in regard to all of the
 *      software in the executable aside from Oracle client libraries.
 *
 *      Specifically you are not permitted to link this program with the
 *      Qt/UNIX, Qt/Windows or Qt Non Commercial products of TrollTech.
 *      And you are not permitted to distribute binaries compiled against
 *      these libraries without written consent from Underscore AB. Observe
 *      that this does not disallow linking to the Qt Free Edition.
 *
 * All trademarks belong to their respective owners.
 *
 ****************************************************************************/

#include "utils.h"

#include "tochangeconnection.h"
#include "toconf.h"
#include "tohighlightedtext.h"
#include "tomain.h"
#include "toparamget.h"
#include "toresultbar.h"
#include "toresultcols.h"
#include "toresultlong.h"
#include "toresultplan.h"
#include "toresultresources.h"
#include "toresultstats.h"
#include "toresultview.h"
#include "tosession.h"
#include "totool.h"
#include "tovisualize.h"
#include "toworksheet.h"
#include "toworksheetsetupui.h"
#include "toworksheetstatistic.h"

#ifdef TO_KDE
#include <kfiledialog.h>
#include <kmenubar.h>
#endif

#include <qcheckbox.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qfiledialog.h>
#include <qfileinfo.h>
#include <qgrid.h>
#include <qgroupbox.h>
#include <qheader.h>
#include <qinputdialog.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qlistview.h>
#include <qmenubar.h>
#include <qmessagebox.h>
#include <qmultilineedit.h>
#include <qnamespace.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qsplitter.h>
#include <qtabwidget.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qtooltip.h>
#include <qworkspace.h>

#include "toworksheet.moc"
#include "toworksheetsetupui.moc"

#include "icons/clock.xpm"
#include "icons/compile.xpm"
#include "icons/describe.xpm"
#include "icons/eraselog.xpm"
#include "icons/execute.xpm"
#include "icons/executeall.xpm"
#include "icons/executestep.xpm"
#include "icons/filesave.xpm"
#include "icons/previous.xpm"
#include "icons/refresh.xpm"
#include "icons/stop.xpm"
#include "icons/toworksheet.xpm"

#define TO_ID_STATISTICS		(toMain::TO_TOOL_MENU_ID+ 0)
#define TO_ID_STOP			(toMain::TO_TOOL_MENU_ID+ 1)

#define CONF_AUTO_SAVE   "AutoSave"
#define CONF_CHECK_SAVE  "CheckSave"
#define CONF_AUTO_LOAD   "AutoLoad"
#define CONF_LOG_AT_END  "LogAtEnd"
#define CONF_LOG_MULTI   "LogMulti"
#define CONF_PLSQL_PARSE "PLSQLParse"
#define CONF_STATISTICS	 "Statistics"
#define CONF_TIMED_STATS "TimedStats"
#define CONF_NUMBER	 "Number"
#define CONF_MOVE_TO_ERR "MoveToError"
#define CONF_HISTORY	 "History"

static struct {
  int Pos;
  char *Start;
  bool WantEnd;
  bool WantSemi;
  bool CloseBlock;
  bool Comment;
  bool BeforeCode;
  bool StartCode;
  bool NoBinds;
  bool SingleLine;
} Blocks[] = { { 0,"begin",	true ,false,false,false,true ,true ,false,false},
	       { 0,"if",	true ,false,false,false,false,false,false,false},
	       { 0,"loop",	true ,false,false,false,false,false,false,false},
	       { 0,"while",	true ,false,false,false,false,false,false,false},
	       { 0,"declare",	false,false,false,false,true ,true ,false,false},
	       { 0,"create",	false,false,false,false,true ,false,false,false},
	       { 0,"package",	true ,false,false,false,false,true ,false,false},
	       { 0,"procedure",	false,false,false,false,false,true ,false,false},
	       { 0,"function",	false,false,false,false,false,true ,false,false},
	       { 0,"trigger",   false,false,false,false,false,true ,false,false},
	       { 0,"end",	false,true ,true ,false,false,false,false,false},
	       { 0,"rem",	false,false,false,true ,false,false,false,false},
	       { 0,"store",	false,false,false,true ,false,false,false,false},
	       { 0,"spool",	false,false,false,true ,false,false,false,false},
	       { 0,"prompt",	false,false,false,true ,false,false,false,false},
	       { 0,"set",	false,false,false,false,false,false,false,true },
	       { 0,"assign",	false,false,false,true ,false,false,false,false},
	       { 0,NULL,	false,false,false,false,false,false,false,false}
};

class toWorksheetSetup : public toWorksheetSetupUI, public toSettingTab
{ 
  toTool *Tool;

public:
  toWorksheetSetup(toTool *tool,QWidget* parent = 0,const char* name = 0)
    : toWorksheetSetupUI(parent,name),toSettingTab("worksheet.html#preferences"),Tool(tool)
  {
    if (!tool->config(CONF_AUTO_SAVE,"").isEmpty())
      AutoSave->setChecked(true);
    if (!tool->config(CONF_CHECK_SAVE,"Yes").isEmpty())
      CheckSave->setChecked(true);
    if (!tool->config(CONF_LOG_AT_END,"Yes").isEmpty())
      LogAtEnd->setChecked(true);
    if (!tool->config(CONF_LOG_MULTI,"Yes").isEmpty())
      LogMulti->setChecked(true);
    if (!tool->config(CONF_PLSQL_PARSE,"Yes").isEmpty())
      PLSQLParse->setChecked(true);
    MoveToError->setChecked(!tool->config(CONF_MOVE_TO_ERR,"Yes").isEmpty());
    if (!tool->config(CONF_STATISTICS,"").isEmpty())
      Statistics->setChecked(true);
    TimedStatistics->setChecked(!tool->config(CONF_TIMED_STATS,"Yes").isEmpty());
    History->setChecked(!tool->config(CONF_HISTORY,"").isEmpty());
    if (!tool->config(CONF_NUMBER,"Yes").isEmpty())
      DisplayNumber->setChecked(true);
    DefaultFile->setText(tool->config(CONF_AUTO_LOAD,""));
  }
  virtual void saveSetting(void)
  {
    if (AutoSave->isChecked())
      Tool->setConfig(CONF_AUTO_SAVE,"Yes");
    else
      Tool->setConfig(CONF_AUTO_SAVE,"");
    if (CheckSave->isChecked())
      Tool->setConfig(CONF_CHECK_SAVE,"Yes");
    else
      Tool->setConfig(CONF_CHECK_SAVE,"");
    if (LogAtEnd->isChecked())
      Tool->setConfig(CONF_LOG_AT_END,"Yes");
    else
      Tool->setConfig(CONF_LOG_AT_END,"");
    if (LogMulti->isChecked())
      Tool->setConfig(CONF_LOG_MULTI,"Yes");
    else
      Tool->setConfig(CONF_LOG_MULTI,"");
    if (PLSQLParse->isChecked())
      Tool->setConfig(CONF_PLSQL_PARSE,"Yes");
    else
      Tool->setConfig(CONF_PLSQL_PARSE,"");
    Tool->setConfig(CONF_MOVE_TO_ERR,MoveToError->isChecked()?"Yes":"");
    Tool->setConfig(CONF_STATISTICS,Statistics->isChecked()?"Yes":"");
    Tool->setConfig(CONF_HISTORY,History->isChecked()?"Yes":"");
    Tool->setConfig(CONF_TIMED_STATS,TimedStatistics->isChecked()?"Yes":"");
    Tool->setConfig(CONF_NUMBER,DisplayNumber->isChecked()?"Yes":"");
    Tool->setConfig(CONF_AUTO_LOAD,DefaultFile->text());
  }
public slots:
  void chooseFile(void)
  {
    QString str=toOpenFilename(DefaultFile->text(),QString::null,this);
    if (!str.isEmpty())
      DefaultFile->setText(str);
  }
};

class toWorksheetTool : public toTool {
protected:
  virtual char **pictureXPM(void)
  { return toworksheet_xpm; }
public:
  toWorksheetTool()
    : toTool(10,"SQL Worksheet")
  { }
  virtual const char *menuItem()
  { return "SQL Worksheet"; }
  virtual QWidget *toolWindow(QWidget *main,toConnection &connection)
  {
    return new toWorksheet(main,connection);
  }
  virtual QWidget *configurationTab(QWidget *parent)
  {
    return new toWorksheetSetup(this,parent);
  }
  virtual bool canHandle(toConnection &conn)
  { return true; }
};

static toWorksheetTool WorksheetTool;

class toWorksheetText : public toHighlightedText {
  toWorksheet *Worksheet;
public:
  toWorksheetText(toWorksheet *worksheet,QWidget *parent,const char *name=NULL)
    : toHighlightedText(parent,name),Worksheet(worksheet)
  { }
  /** Reimplemented for internal reasons.
   */
  virtual void keyPressEvent(QKeyEvent *e)
  {
    if (e->state()==ControlButton&&
	e->key()==Key_Return) {
      Worksheet->execute();
      e->accept();
    } else if (e->state()==0&&
	       e->key()==Key_F8) {
      Worksheet->executeAll();
      e->accept();
    } else if (e->state()==0&&
	       e->key()==Key_F9) {
      Worksheet->executeStep();
      e->accept();
    } else if (e->state()==ShiftButton&&
	       e->key()==Key_F9) {
      Worksheet->executeNewline();
      e->accept();
    } else if (e->state()==0&&
	       e->key()==Key_F7) {
      Worksheet->executeSaved();
      e->accept();
    } else if (e->state()==0&&
	       e->key()==Key_F4) {
      Worksheet->describe();
      e->accept();
    } else if (e->state()==AltButton&&
	       e->key()==Key_Up) {
      Worksheet->executePreviousLog();
      e->accept();
    } else if (e->state()==AltButton&&
	       e->key()==Key_Down) {
      Worksheet->executeNextLog();
      e->accept();
    } else {
      toHighlightedText::keyPressEvent(e);
    }
  }
  virtual bool editOpen(void)
  {
    bool ret=toHighlightedText::editOpen();
    QFileInfo file(filename());
    toToolCaption(Worksheet,WorksheetTool.name()+" "+file.fileName());
    return ret;
  }
};

void toWorksheet::viewResources(void)
{
  try {
    QString address=toSQLToAddress(connection(),QueryString);

    Resources->changeParams(address);
  } TOCATCH
}

#define TOWORKSHEET "toWorksheet:"

void toWorksheet::setup(bool autoLoad)
{
  toConnection &connection=toWorksheet::connection();
  QToolBar *toolbar=toAllocBar(this,"SQL worksheet",connection.description());

  new QToolButton(QPixmap((const char **)execute_xpm),
		  "Execute current statement",
		  "Execute current statement",
		  this,SLOT(execute(void)),
		  toolbar);
  new QToolButton(QPixmap((const char **)executeall_xpm),
		  "Execute all statements",
		  "Execute all statements",
		  this,SLOT(executeAll(void)),
		  toolbar);
  new QToolButton(QPixmap((const char **)executestep_xpm),
		  "Step through statements",
		  "Step through statements",
		  this,SLOT(executeStep(void)),
		  toolbar);
  toolbar->addSeparator();
  new QToolButton(QPixmap((const char **)refresh_xpm),
		  "Reexecute Last Statement",
		  "Reexecute Last Statement",
		  this,SLOT(refresh(void)),
		  toolbar);

  LastLine=LastOffset=-1;
  LastID=0;

  if (Light) {
    Editor=new toWorksheetText(this,this);
    Current=Result=new toResultLong(this);
    Result->hide();
    connect(Result,SIGNAL(done(void)),this,SLOT(queryDone(void)));
    connect(Result,SIGNAL(firstResult(const QString &,const toConnection::exception &,bool)),
	    this,SLOT(addLog(const QString &,const toConnection::exception &,bool)));
    ResultTab=NULL;
    Plan=NULL;
    CurrentTab=NULL;
    Resources=NULL;
    Statistics=NULL;
    Logging=NULL;
    LastLogItem=NULL;
    StatisticButton=NULL;
    StatTab=NULL;
    Columns=NULL;
    Refresh=NULL;
    ToolMenu=NULL;
    Visualize=NULL;
    WaitChart=IOChart=NULL;
    toolbar->addSeparator();
    StopButton=new QToolButton(QPixmap((const char **)stop_xpm),
			       "Stop execution",
			       "Stop execution",
			       Result,SLOT(stop(void)),
			       toolbar);
    StopButton->setEnabled(false);
    toolbar->setStretchableWidget(Started=new QLabel(toolbar));
    Started->setAlignment(AlignRight|AlignVCenter|ExpandTabs);
  } else {
    QSplitter *splitter=new QSplitter(Vertical,this);

    Editor=new toWorksheetText(this,splitter);
    ResultTab=new QTabWidget(splitter);
    QVBox *box=new QVBox(ResultTab);
    ResultTab->addTab(box,"&Result");

    Current=Result=new toResultLong(box);
    connect(Result,SIGNAL(done(void)),this,SLOT(queryDone(void)));
    connect(Result,SIGNAL(firstResult(const QString &,const toConnection::exception &,bool)),
	    this,SLOT(addLog(const QString &,const toConnection::exception &,bool)));

    Columns=new toResultCols(box);
    Columns->hide();

    ResultTab->setTabEnabled(Columns,false);
    Plan=new toResultPlan(ResultTab);
    ResultTab->addTab(Plan,"E&xecution plan");
    Resources=new toResultResources(ResultTab);
    Visualize=new toVisualize(Result,ResultTab);
    ResultTab->addTab(Visualize,"&Visualize");
    ResultTab->addTab(Resources,"&Information");
    StatTab=new QVBox(ResultTab);
    {
      QToolBar *stattool=toAllocBar(StatTab,"Worksheet Statistics",connection.description());
      new QToolButton(QPixmap((const char **)filesave_xpm),
		      "Save statistics for later analysis",
		      "Save statistics for later analysis",
		      this,SLOT(saveStatistics(void)),
		      stattool);
      stattool->setStretchableWidget(new QLabel(stattool));
    }
    splitter=new QSplitter(Horizontal,StatTab);
    Statistics=new toResultStats(true,splitter);
    Statistics->setTabWidget(ResultTab);
    WaitChart=new toResultBar(splitter);
    try {
      toSQL sql=toSQL::sql(TO_SESSION_WAIT);
      WaitChart->setSQL(sql);
    } catch(...) {
    }
    WaitChart->setTitle("Wait states");
    WaitChart->setYPostfix("ms/s");
    WaitChart->setSamples(-1);
    WaitChart->start();
    connect(Statistics,SIGNAL(sessionChanged(const QString &)),
	    WaitChart,SLOT(changeParams(const QString &)));
    IOChart=new toResultBar(splitter);
    try {
      toSQL sql=toSQL::sql(TO_SESSION_IO);
      IOChart->setSQL(sql);
    } catch(...) {
    }
    IOChart->setTitle("I/O");
    IOChart->setYPostfix("blocks/s");
    IOChart->setSamples(-1);
    IOChart->start();
    connect(Statistics,SIGNAL(sessionChanged(const QString &)),
	    IOChart,SLOT(changeParams(const QString &)));
    ResultTab->addTab(StatTab,"&Statistics");
    ResultTab->setTabEnabled(StatTab,false);

    Logging=new toListView(ResultTab);
    ResultTab->addTab(Logging,"&Logging");
    Logging->addColumn("SQL");
    Logging->addColumn("Result");
    Logging->addColumn("Timestamp");
    Logging->addColumn("Duration");
    Logging->setColumnAlignment(3,AlignRight);
    LastLogItem=NULL;

    toolbar->addSeparator();
    new QToolButton(QPixmap((const char **)describe_xpm),
		    "Describe under cursor",
		    "Describe under cursor",
		    this,SLOT(describe(void)),
		    toolbar);
    StopButton=new QToolButton(QPixmap((const char **)stop_xpm),
			       "Stop execution",
			       "Stop execution",
			       Result,SLOT(stop(void)),
			       toolbar);
    StopButton->setEnabled(false);
    toolbar->addSeparator();
    new QToolButton(QPixmap((const char **)eraselog_xpm),
		    "Clear execution log",
		    "Clear execution log",
		    this,SLOT(eraseLogButton(void)),
		    toolbar);

    toolbar->addSeparator();
    StatisticButton=new QToolButton(toolbar);
    StatisticButton->setToggleButton(true);
    StatisticButton->setIconSet(QIconSet(QPixmap((const char **)clock_xpm)));
    connect(StatisticButton,SIGNAL(toggled(bool)),this,SLOT(enableStatistic(bool)));
    QToolTip::add(StatisticButton,"Gather session statistic of execution");
    new QLabel("Refresh ",toolbar);
    Refresh=toRefreshCreate(toolbar);
    connect(Refresh,SIGNAL(activated(const QString &)),this,SLOT(changeRefresh(const QString &)));
    connect(StatisticButton,SIGNAL(toggled(bool)),Refresh,SLOT(setEnabled(bool)));
    Refresh->setEnabled(false);
    Refresh->setFocusPolicy(NoFocus);

    toolbar->addSeparator();

    SavedButton=new toPopupButton(QPixmap((const char **)compile_xpm),
				  "Run current saved SQL",
				  "Run current saved SQL",
				  toolbar);
    SavedMenu=new QPopupMenu(SavedButton);
    SavedButton->setPopup(SavedMenu);
    connect(SavedMenu,SIGNAL(aboutToShow()),this,SLOT(showSaved()));
    connect(SavedMenu,SIGNAL(activated(int)),this,SLOT(executeSaved(int)));
    new QToolButton(QPixmap((const char **)previous_xpm),
		    "Save last SQL",
		    "Save last SQL",
		    this,SLOT(saveLast(void)),
		    toolbar);

    toolbar->setStretchableWidget(Started=new QLabel(toolbar));
    Started->setAlignment(AlignRight|AlignVCenter|ExpandTabs);
    new toChangeConnection(toolbar);

    connect(ResultTab,SIGNAL(currentChanged(QWidget *)),
	    this,SLOT(changeResult(QWidget *)));

    if (autoLoad) {
      Editor->setFilename(WorksheetTool.config(CONF_AUTO_LOAD,""));
      if (!Editor->filename().isEmpty()) {
	try {
	  QCString data=toReadFile(Editor->filename());
	  Editor->setText(QString::fromLocal8Bit(data));
	  Editor->setEdited(false);
	} TOCATCH
      }
    }

    ToolMenu=NULL;
    connect(toMainWidget()->workspace(),SIGNAL(windowActivated(QWidget *)),
	    this,SLOT(windowActivated(QWidget *)));

    if (connection.provider()=="Oracle") {
      if (!WorksheetTool.config(CONF_STATISTICS,"").isEmpty()) {
	show();
	StatisticButton->setOn(true);
      }
    } else {
      StatisticButton->setEnabled(false);
    }

#if 0
    setTabOrder(Editor,ResultTab);
    setTabOrder(ResultTab,Result);
    setTabOrder(Result,Columns);
    setTabOrder(Columns,Refresh);
#endif

    connect(this,SIGNAL(connectionChange()),this,SLOT(connectionChanged()));
  }
  connect(&Poll,SIGNAL(timeout()),this,SLOT(poll()));
  setFocusProxy(Editor);
}

toWorksheet::toWorksheet(QWidget *main,toConnection &connection,bool autoLoad)
  : toToolWidget(WorksheetTool,"worksheet.html",main,connection),Light(false)
{
  setup(autoLoad);
}

toWorksheet::toWorksheet(QWidget *main,const char *name,toConnection &connection)
  : toToolWidget(WorksheetTool,"worksheetlight.html",main,connection,name),Light(true)
{
  setup(false);
}

void toWorksheet::changeRefresh(const QString &str)
{
  if (!Light&&StopButton->isEnabled()&&StatisticButton->isOn())
    toRefreshParse(timer(),str);
}

void toWorksheet::windowActivated(QWidget *widget)
{
  if (Light)
    return;

  QWidget *w=this;
  while(w&&w!=widget) {
    w=w->parentWidget();
  }

  if (widget==w) {
    if (!ToolMenu) {
      ToolMenu=new QPopupMenu(this);
      ToolMenu->insertItem(QPixmap((const char **)execute_xpm),
			   "&Execute Current",this,SLOT(execute(void)),
			   CTRL+Key_Return);
      ToolMenu->insertItem(QPixmap((const char **)executeall_xpm),
			   "Execute &All",this,SLOT(executeAll(void)),
			   Key_F8);
      ToolMenu->insertItem(QPixmap((const char **)executestep_xpm),
			   "Execute &Next",this,SLOT(executeStep(void)),
			   Key_F9);
      ToolMenu->insertItem("Execute &Newline Separated",this,
			   SLOT(executeNewline(void)),SHIFT+Key_F9);
      ToolMenu->insertItem(QPixmap((const char **)refresh_xpm),
			   "&Reexecute Last Statement",this,SLOT(refresh(void)),
			   Key_F5);
      ToolMenu->insertSeparator();
      ToolMenu->insertItem(QPixmap((const char **)describe_xpm),
			   "&Describe Under Cursor",this,SLOT(describe(void)),
			   Key_F4);
      ToolMenu->insertItem("&Enable Statistics",this,SLOT(toggleStatistic(void)),
			   0,TO_ID_STATISTICS);
      ToolMenu->insertItem(QPixmap((const char **)stop_xpm),
			   "&Stop Execution",Result,SLOT(stop(void)),
			   0,TO_ID_STOP);
      ToolMenu->insertSeparator();
      ToolMenu->insertItem("Execute Saved SQL",
			   this,SLOT(executeSaved()),
			   Key_F7);
      ToolMenu->insertItem("Select Saved SQL",
			   this,SLOT(selectSaved()),
			   CTRL+SHIFT+Key_S);
      ToolMenu->insertItem(QPixmap((const char **)previous_xpm),
			   "Save last SQL",
			   this,SLOT(saveLast()));
      ToolMenu->insertItem("Edit Saved SQL...",
			   this,SLOT(editSaved()));
      ToolMenu->insertSeparator();
      ToolMenu->insertItem("Previous Log Entry",this,SLOT(executePreviousLog()),
			   ALT+Key_Up);
      ToolMenu->insertItem("Next Log Entry",this,SLOT(executeNextLog()),
			   ALT+Key_Down);
      ToolMenu->insertItem(QPixmap((const char **)eraselog_xpm),
			   "Erase &Log",this,SLOT(eraseLogButton(void)));

      toMainWidget()->menuBar()->insertItem("W&orksheet",ToolMenu,-1,toToolMenuIndex());
      toMainWidget()->menuBar()->setItemEnabled(TO_ID_STOP,StopButton->isEnabled());
      toMainWidget()->menuBar()->setItemChecked(TO_ID_STATISTICS,
						StatisticButton->isOn());
    }
  } else {
    delete ToolMenu;
    ToolMenu=NULL;
  }
}

void toWorksheet::connectionChanged(void)
{
  if (connection().provider()=="Oracle") {
    StatisticButton->setEnabled(true);
  } else {
    StatisticButton->setEnabled(false);
  }
}

bool toWorksheet::checkSave(bool input)
{
  if (Light)
    return true;
  if (Editor->edited()) {
    if(WorksheetTool.config(CONF_AUTO_SAVE,"").isEmpty()||
       Editor->filename().isEmpty()) {
      if (!WorksheetTool.config(CONF_CHECK_SAVE,"Yes").isEmpty()) {
	if (input) {
	  QString str("Save changes to worksheet for ");
	  str.append(connection().description());
	  int ret=TOMessageBox::information(this,
					    "Save file",
					    str,
					    "&Yes","&No","&Cancel",0,2);
	  if (ret==1)
	    return true;
	  else if (ret==2)
	    return false;
	} else
	  return true;
      } else
	return true;
      if (Editor->filename().isEmpty()&&input)
	Editor->setFilename(toSaveFilename(Editor->filename(),QString::null,this));
      if (Editor->filename().isEmpty())
	return false;	
    }
    if (!toWriteFile(Editor->filename(),Editor->text()))
      return false;
    Editor->setEdited(false);
  }
  return true;
}

bool toWorksheet::close(bool del)
{
  if (checkSave(true)) {
    Result->stop();
    return QVBox::close(del);
  }
  return false;
}

toWorksheet::~toWorksheet()
{
  checkSave(false);
  eraseLogButton();
}

#define LARGE_BUFFER 4096

void toWorksheet::changeResult(QWidget *widget)
{
  CurrentTab=widget;
  if (QueryString.length()) {
    if (CurrentTab==Plan)
      Plan->query(QueryString);
    else if (CurrentTab==Resources)
      viewResources();
    else if (CurrentTab==Statistics&&Result->running())
      Statistics->refreshStats(false);
  }
}

void toWorksheet::refresh(void)
{
  if (!QueryString.isEmpty()) {
    query(QueryString,false);
    StopButton->setEnabled(true);
    Poll.start(1000);
    toMainWidget()->menuBar()->setItemEnabled(TO_ID_STOP,true);
    if (Light)
      return;
    if (CurrentTab==Visualize)
      Visualize->display();
    else if (CurrentTab==Plan)
      Plan->query(QueryString);
    else if (CurrentTab==Resources)
      viewResources();
  }
}

static QString unQuote(const QString &str)
{
  if (str.at(0)=='\"'&&str.at(str.length()-1)=='\"')
    return str.left(str.length()-1).right(str.length()-2);
  return str.upper();
}

bool toWorksheet::describe(const QString &query)
{
  QRegExp white("[ \r\n\t.]+");
  QStringList part=QStringList::split(white,query);
  if (part[0].upper()=="DESC"||
      part[0].upper()=="DESCRIBE") {
    if (Light)
      return true;
    if (toIsOracle(connection())) {
      if (part.count()==2) {
	Columns->changeParams(unQuote(part[1]));
      } else if (part.count()==3) {
	Columns->changeParams(unQuote(part[1]),unQuote(part[2]));
      } else
	throw QString("Wrong number of parameters for describe");
    } else if (connection().provider()=="MySQL") {
      if (part.count()==2) {
	Columns->changeParams(part[1]);
      } else
	throw QString("Wrong number of parameters for describe");
    }
    Current->hide();
    Columns->show();
    Current=Columns;
    return true;
  } else {
    if (Light)
      return false;
    QWidget *curr=ResultTab->currentPage();
    Current->hide();
    Result->show();
    Current=Result;
    if (curr==Columns)
      ResultTab->showPage(Result);
    return false;
  }
}

void toWorksheet::query(const QString &str,bool direct)
{
  Result->stop();

  QRegExp strq("'[^']*'");
  QString chk=str.lower();
  chk.replace(strq," ");
  bool code=false;
  static QRegExp codere("end\\s+[a-z0-9_-]*;$",true);
  static QRegExp codere2("end;",true);

  if (codere.match(chk)>=0||codere2.match(chk)>=0)
    code=true;

  QueryString=str;
  if (!code&&QueryString.length()>0&&QueryString.at(QueryString.length()-1)==';')
    QueryString.truncate(QueryString.length()-1);
  
  bool nobinds=false;
  chk=str.lower();
  chk.replace(strq," ");
  chk=chk.simplifyWhiteSpace();
  chk.replace(QRegExp(" or replace ")," ");
  if(chk.startsWith("create trigger "))
    nobinds=true;
  
  if (!describe(QueryString)) {
    toQList param;
    if (!nobinds)
      try {
	param=toParamGet::getParam(connection(),this,QueryString);
      } catch (...) {
	return;
      }
    toStatusMessage("Processing query",true);
    if (direct) {
      try {
	First=false;
	Timer.start();
	toQuery query(connection(),toQuery::Long,QueryString,param);

	char buffer[100];
	if (query.rowsProcessed()>0)
	  sprintf(buffer,"%d rows processed",(int)query.rowsProcessed());
	else
	  sprintf(buffer,"Query executed");
	addLog(QueryString,toConnection::exception(QString(buffer)),false);
      } catch (const QString &exc) {
	addLog(QueryString,exc,true);
      }
    } else {
      First=false;
      Timer.start();
      StopButton->setEnabled(true);
      Poll.start(1000);
      QToolTip::add(Started,"Duration while query has been running\n\n"+QueryString);
      toMainWidget()->menuBar()->setItemEnabled(TO_ID_STOP,true);
      Result->setNumberColumn(!WorksheetTool.config(CONF_NUMBER,"Yes").isEmpty());
      try {
	saveHistory();
	Result->setSQL(QString::null);
	Result->query(QueryString,param);
      } catch (const toConnection::exception &exc) {
	addLog(QueryString,exc,true);
      } catch (const QString &exc) {
	addLog(QueryString,exc,true);
      }
      if (!Light) {
	if (StatisticButton->isOn())
	  toRefreshParse(timer(),Refresh->currentText());
      }
      Result->setSQLName(QueryString.simplifyWhiteSpace().left(40));
    }
  }
}

void toWorksheet::saveHistory(void)
{
  if (WorksheetTool.config(CONF_HISTORY,"").isEmpty())
    return;
  if (Result->firstChild()&&Current==Result&&!Light) {
    History[LastID]=Result;
    Result->hide();
    Result->stop();
    disconnect(Result,SIGNAL(done(void)),this,SLOT(queryDone(void)));
    disconnect(Result,SIGNAL(firstResult(const QString &,const toConnection::exception &,true)),
	       this,SLOT(addLog(const QString &,const toConnection::exception &,true)));
    disconnect(StopButton,SIGNAL(clicked(void)),Result,SLOT(stop(void)));

    Result=new toResultLong(Result->parentWidget());
    if (StatisticButton->isOn())
      enableStatistic(true);
    Result->show();
    Current=Result;
    connect(StopButton,SIGNAL(clicked(void)),Result,SLOT(stop(void)));
    connect(Result,SIGNAL(done(void)),this,SLOT(queryDone(void)));
    connect(Result,SIGNAL(firstResult(const QString &,const toConnection::exception &,bool)),
	    this,SLOT(addLog(const QString &,const toConnection::exception &,bool)));
  }
}

QString toWorksheet::duration(int dur,bool hundreds)
{
  char buf[100];
  if (dur>=3600000) {
    if (hundreds)
      sprintf(buf,"%d:%02d:%02d.%02d",dur/3600000,(dur/60000)%60,(dur/1000)%60,(dur/10)%100);
    else
      sprintf(buf,"%d:%02d:%02d",dur/3600000,(dur/60000)%60,(dur/1000)%60);
  } else {
    if (hundreds)
      sprintf(buf,"%d:%02d.%02d",dur/60000,(dur/1000)%60,(dur/10)%100);
    else
      sprintf(buf,"%d:%02d",dur/60000,(dur/1000)%60);
  }
  return buf;
}

void toWorksheet::addLog(const QString &sql,const toConnection::exception &result,bool error)
{
  QString now=toNow(connection());
  toResultViewItem *item;

  LastID++;

  int dur=0;
  if (!Timer.isNull())
    dur=Timer.elapsed();
  First=true;

  if (!Light) {
    if (WorksheetTool.config(CONF_LOG_MULTI,"Yes").isEmpty()) {
      if (WorksheetTool.config(CONF_LOG_AT_END,"Yes").isEmpty())
	item=new toResultViewItem(Logging,NULL);
      else
	item=new toResultViewItem(Logging,LastLogItem);
    } else if (WorksheetTool.config(CONF_LOG_AT_END,"Yes").isEmpty())
      item=new toResultViewMLine(Logging,NULL);
    else
      item=new toResultViewMLine(Logging,LastLogItem);
    item->setText(0,sql);
  
    LastLogItem=item;
    item->setText(1,result);
    item->setText(2,now);
    if (!WorksheetTool.config(CONF_HISTORY,"").isEmpty())
      item->setText(4,QString::number(LastID));
  }

  if (result.offset()>=0&&LastLine>=0&&LastOffset>=0&&
      !WorksheetTool.config(CONF_MOVE_TO_ERR,"Yes").isEmpty()) {
    QChar cmp='\n';
    int lastnl=0;
    int lines=0;
    for (int i=0;i<result.offset();i++) {
      if (sql.at(i)==cmp) {
	LastOffset=0;
	lastnl=i+1;
	lines++;
      }
    }
    Editor->setCursorPosition(LastLine+lines,LastOffset+result.offset()-lastnl,false);
    LastLine=LastOffset=-1;
  }

  QString buf=duration(dur);

  if (!Light) {
    item->setText(3,buf);

    QListViewItem *last=Logging->currentItem();
    toResultViewItem *citem=NULL;
    if (last)
      citem=dynamic_cast<toResultViewItem *>(last);
    if (!citem||citem->allText(0)!=sql) {
      Logging->setCurrentItem(item);
      Logging->ensureItemVisible(item);
    }
  }

  {
    QString str=result;
    str+="\n(Duration ";
    str+=buf;
    str+=")";
    if (error)
      toStatusMessage(str);
    else
      toStatusMessage(str,false,false);
  }
  if (!Light&&!error)
    changeResult(CurrentTab);

  static QRegExp re("^[1-9]\\d* rows processed$");
  if (result.contains(re)) {
    if (!toTool::globalConfig(CONF_AUTO_COMMIT,"").isEmpty())
      connection().commit();
    else
      toMainWidget()->setNeedCommit(connection());
  }
  saveDefaults();
}

static void NewStatement(void)
{
  for (int i=0;Blocks[i].Start;i++)
    Blocks[i].Pos=0;
}

void toWorksheet::execute(bool all,bool step)
{
  bool sqlparse;
  bool code=true;
  bool beforeCode=false;
  if(connection().provider()=="Oracle")
    sqlparse=!WorksheetTool.config(CONF_PLSQL_PARSE,"Yes").isEmpty();
  else
    sqlparse=false;
  TryStrip=true;
  if (!Editor->hasMarkedText()||all||step) {
    int cpos,cline,cbpos,cbline;
    if (!Editor->getMarkedRegion(&cbline,&cbpos,&cline,&cpos)) {
      Editor->getCursorPosition(&cline,&cpos);
      step=false;
    }
    enum {
      beginning,
      comment,
      multiComment,
      inStatement,
      inString,
      inCode,
      endCode,
      done
    } state,lastState;

    int startLine=-1,startPos=-1;
    int endLine=-1,endPos=-1;
    lastState=state=beginning;
    NewStatement();
    int BlockCount=0;
    beforeCode=code=TryStrip=false;
    QChar lastChar;
    QChar c=' ';
    QChar nc;

    for (int line=0;line<Editor->numLines()&&state!=done;line++) {
      QString data=Editor->textLine(line);
      c='\n'; // Set correct previous character
      for (int i=0;i<(int)data.length()&&state!=done;i++) {
	lastChar=c;
	c=data[i];
	if (i+1<int(data.length()))
	  nc=data[i+1];
	else
	  nc=' ';
	if (state==comment) {
	  state=lastState;
	  break;
	} else if (state==multiComment) {
	  if (c=='*'&&nc=='/')
	    state=lastState;
	} else if (state!=inString&&c=='\'') {
	  lastState=state;
	  state=inString;
	} else {
	  switch(state) {
	  case comment:
	  case multiComment:
	    throw QString("Internal error, comment shouldn't have gotten here.");
	  case endCode:
	    if (c==';')
	      state=inCode;
	    break;
	  case inCode:
	    if (c=='-'&&nc=='-') {
	      lastState=state;
	      state=comment;
	    } else if (c=='/'&&nc=='*') {
	      lastState=state;
	      state=multiComment;
	    } else {
	      for (int j=0;Blocks[j].Start;j++) {
		int &pos=Blocks[j].Pos;
		if (c.lower()==Blocks[j].Start[pos]&&!Blocks[j].Comment) {
		  if (pos>0||!toIsIdent(lastChar)) {
		    pos++;
		    if (!Blocks[j].Start[pos]) {
		      if (!toIsIdent(nc)) {
			if (Blocks[j].CloseBlock) {
			  BlockCount--;
			  if (BlockCount<=0)
			    state=inStatement;
			} else if (Blocks[j].WantEnd)
			  BlockCount++;
			NewStatement();
			if (state==inCode) {
			  if (Blocks[j].WantSemi)
			    state=endCode;
			  else
			    state=inCode;
			}
			break;
		      } else
			pos=0;
		    }
		  } else
		    pos=0;
		} else
		  pos=0;
	      }
	    }
	    break;
	  case beginning:
	    if (c=='@') {
	      lastState=state;
	      state=comment;
	      break;
	    } else if (c=='-'&&nc=='-') {
	      lastState=state;
	      state=comment;
	      break;
	    } else if (c=='/'&&nc=='*') {
	      lastState=state;
	      state=multiComment;
	      break;
	    } else if (!c.isSpace()&&(c!='/'||data.length()!=1)) {
	      QString rest=data.right(data.length()-i).lower();
	      if (((line==cline&&i>cpos)||(line>cline))&&!all&&!step&&startLine>=0&&startPos>=0) {
		state=done;
		break;
	      } else {
		for (int j=0;Blocks[j].Start;j++) {
		  if (Blocks[j].Comment) {
		    unsigned int len=strlen(Blocks[j].Start);
		    if (rest.lower().startsWith(Blocks[j].Start)&&(rest.length()<=len||!toIsIdent(rest.at(len)))) {
		      lastState=state;
		      state=comment;
		      break;
		    }
		  }
		}
		if (state==comment)
		  break;
		beforeCode=code=false;
	      }
	      startLine=line;
	      startPos=i;
	      endLine=-1;
	      endPos=-1;
	      state=inStatement;
	      for (int j=0;Blocks[j].Start;j++) {
		if (Blocks[j].SingleLine) {
		  unsigned int len=strlen(Blocks[j].Start);
		  if (rest.lower().startsWith(Blocks[j].Start)&&(rest.length()<=len||!toIsIdent(rest.at(len)))) {
		    endLine=line;
		    i=data.length()-1;
		    endPos=i+1;

		    state=beginning;
		    break;
		  }
		}
	      }
	    } else
	      break;
	  case inStatement:
	    {
	      if (!code&&sqlparse) {
		bool br=false;
		for (int j=0;Blocks[j].Start&&!br;j++) {
		  int &pos=Blocks[j].Pos;
		  if (c.lower()==Blocks[j].Start[pos]&&!Blocks[j].Comment) {
		    if (pos>0||(!toIsIdent(lastChar))) {
		      pos++;
		      if (!Blocks[j].Start[pos]) {
			if (!toIsIdent(nc)) {
			  if (Blocks[j].BeforeCode) {
			    beforeCode=true;
			    pos=0;
			    br=true;
			  }
			  if (beforeCode) {
			    if (Blocks[j].CloseBlock) {
			      toStatusMessage("Ending unstarted block");
			      return;
			    } else if (Blocks[j].StartCode) {
			      if (Blocks[j].WantEnd)
				BlockCount++;

			      code=true;
			      if (Blocks[j].WantSemi)
				state=endCode;
			      else
				state=inCode;
			      NewStatement();
			      br=true;
			    }
			  }
			} else
			  pos=0;
		      } 
		    } else
		      pos=0;
		  } else
		    pos=0;
		}
		if (br)
		  break;
		if (!toIsIdent(c)&&toIsIdent(nc)) {
		  int j=i-2;
		  while(j>=0&&toIsIdent(data[j]))
		    j--;
		  QString t=data.mid(j+1,i-j).upper();
		  if (t!="OR"&&t!="REPLACE")
		    beforeCode=false;
		}
	      }
	      if (c==';') {
		endLine=line;
		endPos=i+1;
		state=beginning;
		if (all) {
		  Editor->setCursorPosition(startLine,startPos,false);
		  Editor->setCursorPosition(endLine,endPos,true);
		  LastLine=LastOffset=-1;
		  if (Editor->hasMarkedText()) {
		    query(Editor->markedText(),true);
		    qApp->processEvents();
		    NewStatement();
		    beforeCode=code=false;
		  }
		} else if (step&&
			   ((line==cline&&i>cpos)||(line>cline))) {
		  state=done;
		  break;
		}
	      }
	    }
	    break;
	  case inString:
	    if (c=='\'') {
	      state=lastState;
	    }
	    break;
	  case done:
	    break;
	  }
	}
      }
    }
    if (endLine==-1) {
      endLine=Editor->numLines()-1;
      endPos=Editor->textLine(endLine).length();
      if (all&&endLine) {
	LastLine=startLine;
	LastOffset=startPos;
	Editor->setCursorPosition(startLine,startPos,false);
	Editor->setCursorPosition(endLine,endPos,true);
	if (Editor->hasMarkedText()) {
	  query(Editor->markedText(),false);
	}
      }
    }
    if (all) {
      Editor->setCursorPosition(0,0,false);
      Editor->setCursorPosition(endLine,endPos,true);
    } else {
      LastLine=startLine;
      LastOffset=startPos;
      Editor->setCursorPosition(startLine,startPos,false);
      Editor->setCursorPosition(endLine,endPos,true);
    }
  }
  if (Editor->hasMarkedText()&&!all) {
    query(Editor->markedText(),false);
    if (Light)
      return;
    else if (CurrentTab==Visualize)
      Visualize->display();
    else if (CurrentTab==Plan)
      Plan->query(QueryString);
    else if (CurrentTab==Resources)
      viewResources();
  }
}

void toWorksheet::eraseLogButton()
{
  if (Light)
    return;
  Logging->clear();
  LastLogItem=NULL;
  for(std::map<int,toResultLong *>::iterator i=History.begin();i!=History.end();i++)
    delete (*i).second;
  History.clear();
}

void toWorksheet::queryDone(void)
{
  if (!First&&!QueryString.isEmpty())
    addLog(QueryString,toConnection::exception("Aborted"),false);
  else
    emit executed();
  timer()->stop();
  StopButton->setEnabled(false);
  Poll.stop();
  toMainWidget()->menuBar()->setItemEnabled(TO_ID_STOP,false);
  saveDefaults();
}

void toWorksheet::saveDefaults(void)
{
  QListViewItem *item=Result->firstChild();
  if (item) {
    QHeader *head=Result->header();
    for (int i=0;i<Result->columns();i++) {
      toResultViewItem *resItem=dynamic_cast<toResultViewItem *>(item);
      QString str;
      if (resItem)
	str=resItem->allText(i);
      else if (item)
	str=item->text(i);

      toParamGet::setDefault(connection(),head->label(i).lower(),toUnnull(str));
    }
  }
}

#define ENABLETIMED "ALTER SESSION SET TIMED_STATISTICS = TRUE"

void toWorksheet::enableStatistic(bool ena)
{
  if (ena) {
    Result->setStatistics(Statistics);
    ResultTab->setTabEnabled(StatTab,true);
    toMainWidget()->menuBar()->setItemChecked(TO_ID_STATISTICS,true);
    Statistics->clear();
    if (!WorksheetTool.config(CONF_TIMED_STATS,"Yes").isEmpty()) {
      try {
	connection().allExecute(ENABLETIMED);
	connection().addInit(ENABLETIMED);
      } TOCATCH
    }
  } else {
    connection().delInit(ENABLETIMED);
    Result->setStatistics(NULL);
    ResultTab->setTabEnabled(StatTab,false);
    toMainWidget()->menuBar()->setItemChecked(TO_ID_STATISTICS,false);
  }
}

void toWorksheet::executeNewline(void)
{
  int cline,epos;

  Editor->getCursorPosition(&cline,&epos);

  if (cline>0)
    cline--;
  while(cline>0) {
    QString data=Editor->textLine(cline).simplifyWhiteSpace();
    if (data.length()==0||data==" ") {
      cline++;
      break;
    }
    cline--;
  }

  while(cline<Editor->numLines()) {
    QString data=Editor->textLine(cline).simplifyWhiteSpace();
    if (data.length()!=0&&data!=" ")
      break;
    cline++;
  }

  int eline=cline;

  while(eline<Editor->numLines()) {
    QString data=Editor->textLine(eline).simplifyWhiteSpace();
    if (data.length()==0||data==" ") {
      eline--;
      break;
    }
    epos=Editor->textLine(eline).length();
    eline++;
  }
  Editor->setCursorPosition(cline,0,false);
  Editor->setCursorPosition(eline,epos,true);
  LastLine=cline;
  LastOffset=0;
  if (Editor->hasMarkedText())
    query(Editor->markedText(),false);
}

void toWorksheet::describe(void)
{
  if (Light)
    return;

  QString owner,table;
  Editor->tableAtCursor(owner,table);

  if (owner.isNull())
    Columns->changeParams(table);
  else
    Columns->changeParams(owner,table);
  Current->hide();
  Columns->show();
  Current=Columns;
}

void toWorksheet::executeSaved(void)
{
  if (Light)
    return;

  LastLine=LastOffset=-1;

  if (SavedLast.length()>0) {
    try {
      query(toSQL::string(SavedLast,connection()),false);
    } TOCATCH
  }
}

void toWorksheet::executeSaved(int id)
{
  std::list<QString> def=toSQL::range(TOWORKSHEET);
  for(std::list<QString>::iterator i=def.begin();i!=def.end();i++) {
    id--;
    if (id==0) {
      SavedLast=(*i);
      executeSaved();
      break;
    }
  }
}

void toWorksheet::showSaved(void)
{
  static QRegExp colon(":");
  std::list<QString> def=toSQL::range(TOWORKSHEET);
  SavedMenu->clear();
  std::map<QString,QPopupMenu *> menues;
  int id=0;
  for(std::list<QString>::iterator sql=def.begin();sql!=def.end();sql++) {

    id++;

    QStringList spl=QStringList::split(colon,*sql);
    spl.remove(spl.begin());

    if (spl.count()>0) {
      QString name=spl.last();
      spl.remove(spl.fromLast());

      QPopupMenu *menu;
      if (spl.count()==0)
	menu=SavedMenu;
      else {
	QStringList exs=spl;
	while (exs.count()>0&&menues.find(exs.join(":"))==menues.end())
	  exs.remove(exs.fromLast());
	if (exs.count()==0)
	  menu=SavedMenu;
	else
	  menu=menues[exs.join(":")];
	QString subname=exs.join(":");
	for (unsigned int i=exs.count();i<spl.count();i++) {
	  QPopupMenu *next=new QPopupMenu(this);
	  if (i!=0)
	    subname+=":";
	  subname+=spl[i];
	  menu->insertItem(spl[i],next);
	  menu=next;
	  menues[subname]=menu;
	}
      }
      menu->insertItem(name,id);
    }
  }
}

void toWorksheet::editSaved(void)
{
  QString sql=TOWORKSHEET;
  sql+="Untitled";
  toMainWidget()->editSQL(sql);
}

void toWorksheet::selectSaved()
{
  SavedMenu->popup(SavedButton->mapToGlobal(QPoint(0,SavedButton->height())));
}

void toWorksheet::executePreviousLog(void)
{
  if (Light)
    return;

  LastLine=LastOffset=-1;
  saveHistory();

  QListViewItem *item=Logging->currentItem();
  if (item) {
    QListViewItem *prev=Logging->firstChild();
    while(prev&&prev->nextSibling()!=item)
      prev=prev->nextSibling();
    toResultViewItem *item=dynamic_cast<toResultViewItem *>(prev);
    if (item) {
      Logging->setCurrentItem(item);
      if (item->text(4).isEmpty())
	query(item->allText(0),false);
      else {
	std::map<int,toResultLong *>::iterator i=History.find(item->text(4).toInt());
	if (i!=History.end()&&(*i).second) {
	  Current->hide();
	  Current=(*i).second;
	  Current->show();
	}
      }
    }
  }
}

void toWorksheet::executeNextLog(void)
{
  if (Light)
    return;

  LastLine=LastOffset=-1;
  saveHistory();

  QListViewItem *item=Logging->currentItem();
  if (item&&item->nextSibling()) {
    toResultViewItem *next=dynamic_cast<toResultViewItem *>(item->nextSibling());
    if (next) {
      Logging->setCurrentItem(next);

      if (next->text(4).isEmpty())
	query(next->allText(0),false);
      else {
	std::map<int,toResultLong *>::iterator i=History.find(next->text(4).toInt());
	if (i!=History.end()&&(*i).second) {
	  Current->hide();
	  Current=(*i).second;
	  Current->show();
	}
      }
    }
  }
}

void toWorksheet::poll(void)
{
  Started->setText(duration(Timer.elapsed(),false));
}

void toWorksheet::saveLast(void)
{
  if (QueryString.isEmpty()) {
    TOMessageBox::warning(this,"No SQL to save",
			  "You haven't executed any SQL yet",
			  "&Ok");
    return;
  }
  bool ok=false;
  QString name=QInputDialog::getText("Enter title",
				     "Enter the title in the menu of the saved SQL,\n"
				     "submenues are separated by a ':' character.",
				     QLineEdit::Normal,QString::null,&ok,this);
  if (ok&&!name.isEmpty()) {
    toSQL::updateSQL(TOWORKSHEET+name,
		     QueryString,
		     "Undescribed",
		     "Any",
		     connection().provider());
    toSQL::saveSQL(toTool::globalConfig(CONF_SQL_FILE,DEFAULT_SQL_FILE));
  }
}

void toWorksheet::saveStatistics(void)
{
  std::map<QString,QString> stat;

  Statistics->exportData(stat,"Stat");
  IOChart->exportData(stat,"IO");
  WaitChart->exportData(stat,"Wait");
  if (Plan->firstChild())
    Plan->exportData(stat,"Plan");
  else
    toStatusMessage("No plan available to save",false,false);
  stat["Description"]=QueryString;
  
  toWorksheetStatistic::saveStatistics(stat);
}

void toWorksheet::exportData(std::map<QString,QString> &data,const QString &prefix)
{
  Editor->exportData(data,prefix+":Edit");
  if (StatisticButton->isOn())
    data[prefix+":Stats"]=Refresh->currentText();
  toToolWidget::exportData(data,prefix);
}

void toWorksheet::importData(std::map<QString,QString> &data,const QString &prefix)
{
  Editor->importData(data,prefix+":Edit");
  QString stat=data[prefix+":Stats"];
  if (stat) {
    for (int i=0;i<Refresh->count();i++) {
      if (Refresh->text(i)==stat) {
	Refresh->setCurrentItem(i);
	break;
      }
    }
    StatisticButton->setOn(true);
  } else
    StatisticButton->setOn(false);

  toToolWidget::importData(data,prefix);
}

toWorksheet *toWorksheet::fileWorksheet(const QString &file)
{
  toWorksheet *worksheet=new toWorksheet(toMainWidget()->workspace(),
					 toMainWidget()->currentConnection(),
					 false);
  worksheet->editor()->openFilename(file);
  worksheet->show();
  toToolCaption(worksheet,WorksheetTool.name());
  toMainWidget()->windowsMenu();
  return worksheet;
}