[go: up one dir, main page]

File: tooracleconnection.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 (990 lines) | stat: -rw-r--r-- 26,181 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
//***************************************************************************
/*
 * 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"

#ifdef WIN32
#  include "windows/cregistry.h"
#endif

#define OTL_STL
#define OTL_STREAM_POOLING_ON

#include "otlv4.h"

#include "toconf.h"
#include "toconnection.h"
#include "tomain.h"
#include "tosql.h"
#include "totool.h"

#include <stdio.h>

#include <qcheckbox.h>
#include <qfile.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qspinbox.h>
#include <qvalidator.h>

#include "tooraclesettingui.h"
#include "tooraclesettingui.moc"

#define CONF_OPEN_CURSORS	"OpenCursors"
#define DEFAULT_OPEN_CURSORS	"40"  // Defined to be able to update tuning view
#define CONF_MAX_LONG		"MaxLong"

// Must be larger than max long size in otl.

#ifndef DEFAULT_MAX_LONG
#define DEFAULT_MAX_LONG 30000 
#endif

static int toMaxLong=DEFAULT_MAX_LONG;

static toSQL SQLComment("toOracleConnection:Comments",
			"SELECT Column_name,Comments FROM sys.All_Col_Comments\n"
			" WHERE Owner = :f1<char[100]>\n"
			"   AND Table_Name = :f2<char[100]>",
			"Display column comments");

static toSQL SQLMembers("toOracleConnection:Members",
			"SELECT object_name,overload,argument_name,data_type\n"
			"  FROM sys.All_Arguments\n"
			" WHERE Owner = :f1<char[100]>\n"
			"   AND Package_Name = :f2<char[100]>\n"
			" ORDER BY object_name,overload,sequence",
			"Get list of package members");

static toSQL SQLListObjects("toOracleConnection:ListObjects",
			    "select a.owner,a.object_name,a.object_type,b.comments\n"
			    "  from sys.all_objects a,\n"
			    "       sys.all_tab_comments b\n"
			    " where a.owner = b.owner(+) and a.object_name = b.table_name(+)\n"
			    "   and a.object_type = b.table_type(+) and a.object_type != 'SYNONYM'",
			    "List the objects to cache for a connection, should have same "
			    "columns and binds");

static toSQL SQLListSynonyms("toOracleConnection:ListSynonyms",
			     "select synonym_name,table_owner,table_name\n"
			     "  from sys.all_synonyms\n"
			     " where owner = :usr<char[101]> or owner = 'PUBLIC'\n"
			     " order by table_owner,table_name",
			     "List the synonyms available to a user, should have same columns and binds");

static void ThrowException(const otl_exception &exc)
{
  toConnection::exception ret=QString::fromUtf8((const char *)exc.msg);
#if 1
  if (exc.stm_text&&strlen(exc.stm_text)) {
    ret+="\n";
    QString sql=QString::fromUtf8((const char *)exc.stm_text);
    if (exc.errorofs>=0) {
      QString t=QString::fromUtf8((const char *)exc.stm_text,exc.errorofs);
      ret.setOffset(t.length());
      sql.insert(t.length(),"<ERROR>");
    }
    ret+=sql;
  }
#endif
  throw ret;
}

class toOracleProvider : public toConnectionProvider {
public:
  class connectionDeleter : public toTask {
    otl_connect *Connection;
  public:
    connectionDeleter(otl_connect *connect)
      : Connection(connect)
    { }
    virtual void run(void)
    {
      delete Connection;
    }
  };
  class oracleSub : public toConnectionSub {
  public:
    toSemaphore Lock;
    otl_connect *Connection;
    oracleSub(otl_connect *conn)
      : Lock(1)
    { Connection=conn; }
    ~oracleSub()
    { toThread *thread=new toThread(new connectionDeleter(Connection)); thread->start(); }
    virtual void cancel(void)
    { Connection->cancel(); }
  };

  class oracleQuery : public toQuery::queryImpl {
    bool Cancel;
    bool Running;
    otl_stream *Query;
  public:
    oracleQuery(toQuery *query,oracleSub *conn)
      : toQuery::queryImpl(query)
    {
      Running=Cancel=false;
      Query=NULL;
    }
    virtual ~oracleQuery()
    { delete Query; }
    virtual void execute(void);

    virtual toQValue readValue(void)
    {
      char *buffer=NULL;
      otl_var_desc *dsc=Query->describe_next_out_var();
      if (!dsc)
	throw QString("Couldn't get description of next column to read");

      oracleSub *conn=dynamic_cast<oracleSub *>(query()->connectionSub());
      if (!conn)
	throw QString("Internal error, not oracle sub connection");
      conn->Lock.down();
      if (Cancel)
	throw QString("Cancelled while waiting to read value");
      Running=true;
      try {
	toQValue null;
	switch (dsc->ftype) {
	case otl_var_double:
	case otl_var_float:
	  {
	    double d;
	    (*Query)>>d;
	    Running=false;
	    conn->Lock.up();
	    if (Query->is_null())
	      return null;
	    return toQValue(d);
	  }
	  break;
	case otl_var_int:
	case otl_var_unsigned_int:
	case otl_var_short:
	case otl_var_long_int:
	  {
	    int i;
	    (*Query)>>i;
	    Running=false;
	    conn->Lock.up();
	    if (Query->is_null())
	      return null;
	    return toQValue(i);
	  }
	  break;
	case otl_var_varchar_long:
	case otl_var_raw_long:
	  {
	    int len=toMaxLong;
	    if (toMaxLong<0)
	      len=DEFAULT_MAX_LONG;
	    buffer=new char[len+1];
	    buffer[len]=0;
	    otl_long_string str(buffer,len);
	    (*Query)>>str;
	    Running=false;
	    conn->Lock.up();
	    if (!str.len())
	      return null;
	    QString buf(QString::fromUtf8(buffer));
	    delete buffer;
	    return buf;
	  }
	case otl_var_clob:
	case otl_var_blob:
	  {
	    otl_lob_stream lob;
	    (*Query)>>lob;
	    if (lob.len()==0) {
	      Running=false;
	      conn->Lock.up();
	      return null;
	    }
	    int len=lob.len();
	    if (toMaxLong>=0&&len>toMaxLong)
	      len=toMaxLong;
	    if (dsc->ftype==otl_var_clob)
	      len*=5;
	    else
	      len*=2;
	    buffer=new char[len+1];
	    buffer[0]=0;
	    otl_long_string data(buffer,len);
	    lob>>data;
	    if (!lob.eof()) {
	      otl_long_string sink(10000);
	      while(!lob.eof())
		lob>>sink;
	      if (toThread::mainThread())
		toStatusMessage("Data exists past length of LOB");
	      else
		printf("Data exists past length of LOB in thread\n");
	    }
	    buffer[data.len()]=0;
	    QString buf(QString::fromUtf8(buffer));
	    delete buffer;
	    Running=false;
	    conn->Lock.up();
	    return buf;
	  }
	  break;
	default:  // Try using char if all else fails
	  {
	    // The *5 is for raw columns or UTF expanded data, also dates and numbers
	    // are a bit tricky but if someone specifies a dateformat longer than 100 bytes he
	    // deserves everything he gets!
	    buffer=new char[max(dsc->elem_size*5+1,100)];
	    buffer[0]=0;
	    (*Query)>>buffer;
	    Running=false;
	    conn->Lock.up();
	    if (Query->is_null()) {
	      delete buffer;
	      return null;
	    }
	    QString buf(QString::fromUtf8(buffer));
	    delete buffer;
	    return buf;
	  }
	  break;
	}
      } catch (const otl_exception &exc) {
	Running=false;
	conn->Lock.up();
	delete buffer;
	ThrowException(exc);
      } catch (...) {
	Running=false;
	conn->Lock.up();
	delete buffer;
	throw;
      }
      // Never get here
      return QString::null;
    }
    virtual void cancel(void);
    virtual bool eof(void)
    {
      if (!Query)
	return true;
      return Query->eof();
    }
    virtual int rowsProcessed(void)
    {
      if (!Query)
	return 0;
      return Query->get_rpc();
    }
    virtual int columns(void)
    {
      int descriptionLen;
      Query->describe_select(descriptionLen);
      return descriptionLen;
    }
    virtual std::list<toQuery::queryDescribe> describe(void)
    {
      std::list<toQuery::queryDescribe> ret;
      int descriptionLen;
      otl_column_desc *description=Query->describe_select(descriptionLen);

      for (int i=0;i<descriptionLen;i++) {
	toQuery::queryDescribe desc;
	desc.AlignRight=false;
	desc.Name=QString::fromUtf8(description[i].name);

	switch(description[i].dbtype) {
	case 1:
	case 5:
	case 9:
	case 155:
	  desc.Datatype="VARCHAR2";
	  break;
	case 2:
	case 3:
	case 4:
	case 6:
	case 68:
	  desc.AlignRight=true;
	  desc.Datatype="NUMBER";
	  break;
	case 8:
	case 94:
	case 95:
	  desc.Datatype="LONG";
	  break;
	case 11:
	case 104:
	  desc.Datatype="ROWID";
	  break;
	case 12:
	case 156:
	  desc.AlignRight=true;
	  desc.Datatype="DATE";
	  break;
	case 15:
	case 23:
	case 24:
	  desc.Datatype="RAW";
	  break;
	case 96:
	case 97:
	  desc.Datatype="CHAR";
	  break;
	case 108:
	  desc.Datatype="NAMED DATA TYPE";
	  break;
	case 110:
	  desc.Datatype="REF";
	  break;
	case 112:
	  desc.Datatype="CLOB";
	  break;
	case 113:
	case 114:
	  desc.Datatype="BLOB";
	  break;
	default:
	  desc.Datatype="UNKNOWN";
          break;
	}

	if (desc.Datatype=="NUMBER") {
	  if (description[i].prec) {
	    desc.Datatype.append(" (");
	    desc.Datatype.append(QString::number(description[i].prec));
	    if (description[i].scale!=0) {
	      desc.Datatype.append(",");
	      desc.Datatype.append(QString::number(description[i].scale));
	    }
	    desc.Datatype.append(")");
	  }
	} else {
	  desc.Datatype.append(" (");
	  desc.Datatype.append(QString::number(description[i].dbsize));
	  desc.Datatype.append(")");
	}
	desc.Null=description[i].nullok;

	ret.insert(ret.end(),desc);
      }
      return ret;
    }
  };

  class oracleConnection : public toConnection::connectionImpl {
    QCString connectString(void)
    {
      QCString ret;
      ret=connection().user().utf8();
      ret+="/";
      ret+=connection().password().utf8();
      if (!connection().host().isEmpty()) {
	ret+="@";
	ret+=connection().database().utf8();
      }
      return ret;
    }
    oracleSub *oracleConv(toConnectionSub *sub)
    {
      oracleSub *conn=dynamic_cast<oracleSub *>(sub);
      if (!conn)
	throw QString("Internal error, not oracle sub connection");
      return conn;
    }
  public:
    oracleConnection(toConnection *conn)
      : toConnection::connectionImpl(conn)
    { }

    /** Return a string representation to address an object.
     * @param name The name to be quoted.
     * @return String addressing table.
     */
    virtual QString quote(const QString &name)
    {
      if (name.upper()==name)
	return name.lower();
      else
	return "\""+name+"\"";
    }
    virtual 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();
    }

    virtual std::list<toConnection::objectName> objectNames(void)
    {
      std::list<toConnection::objectName> ret;

      std::list<toQValue> par;
      toQuery objects(connection(),toQuery::Long,
		      SQLListObjects,par);
      toConnection::objectName cur;
      while(!objects.eof()) {
	cur.Owner=objects.readValueNull();
	cur.Name=objects.readValueNull();
	cur.Type=objects.readValueNull();
	cur.Comment=objects.readValueNull();
	ret.insert(ret.end(),cur);
      }

      return ret;
    }
    virtual std::map<QString,toConnection::objectName> synonymMap(std::list<toConnection::objectName> &objects)
    {
      std::map<QString,toConnection::objectName> ret;

      toConnection::objectName cur;
      cur.Type="A";
      std::list<toQValue> par;
      par.insert(par.end(),toQValue(connection().user().upper()));
      toQuery synonyms(connection(),toQuery::Long,
		       SQLListSynonyms,par);
      std::list<toConnection::objectName>::iterator i=objects.begin();
      while(!synonyms.eof()) {
	QString synonym=synonyms.readValueNull();
	cur.Owner=synonyms.readValueNull();
	cur.Name=synonyms.readValueNull();
	while(i!=objects.end()&&(*i)<cur)
	  i++;
	if (i==objects.end())
	  break;
	if (cur.Name==(*i).Name&&cur.Owner==(*i).Owner)
	  ret[synonym]=(*i);
      }

      return ret;
    }
    virtual toQDescList columnDesc(const toConnection::objectName &table)
    {
      toBusy busy;
      if(table.Type=="PACKAGE") {
	toQDescList ret;
	try {
	  toQuery::queryDescribe desc;
	  desc.Datatype="MEMBER";
	  desc.Null=false;
	  QString lastName;
	  QString lastOver;
	  toQuery member(connection(),SQLMembers,table.Owner,table.Name);
	  while(!member.eof()) {
	    QString name = member.readValue();
	    QString overld = member.readValue();
	    QString arg = member.readValueNull();
	    QString type = member.readValueNull();
	    if (lastName!=name||overld!=lastOver) {
	      if (desc.Name.contains("("))
		desc.Name+=")";
	      if (!desc.Name.isEmpty())
		ret.insert(ret.end(),desc);
	      desc.Name=name;
	      lastName=name;
	      lastOver=overld;
	      if (!arg.isEmpty())
		desc.Name+=" (";
	    } else
	      desc.Name+=", ";
	    desc.Name+=arg;
	    desc.Name+=" ";
	    desc.Name+=type;
	  }
	  if (desc.Name.contains("("))
	    desc.Name+=")";
	  if (!desc.Name.isEmpty())
	    ret.insert(ret.end(),desc);
	} catch (...) {
	}
	return ret;
      }

      std::map<QString,QString> comments;
      try {
	toQuery comment(connection(),SQLComment,table.Owner,table.Name);
	while(!comment.eof()) {
	  QString col=comment.readValue();
	  comments[col]=comment.readValueNull();
	}
      } catch (...) {
      }

      try {
	QString SQL="SELECT * FROM \"";
	SQL+=table.Owner;
	SQL+="\".\"";
	SQL+=table.Name;
	SQL+="\" WHERE NULL=NULL";
	toQuery query(connection(),SQL);
	toQDescList desc=query.describe();
	for(toQDescList::iterator j=desc.begin();j!=desc.end();j++)
	  (*j).Comment=comments[(*j).Name];

	return desc;
      } catch(...) {
      }

      toQDescList ret;
      return ret;
    }

    virtual void commit(toConnectionSub *sub)
    {
      oracleSub *conn=oracleConv(sub);
      try {
	conn->Connection->commit();
      } catch (const otl_exception &exc) {
	ThrowException(exc);
      }
    }
    virtual void rollback(toConnectionSub *sub)
    {
      oracleSub *conn=oracleConv(sub);
      try {
	conn->Connection->rollback();
      } catch (const otl_exception &exc) {
	ThrowException(exc);
      }
    }

    virtual toConnectionSub *createConnection(void);

    void closeConnection(toConnectionSub *conn)
    {
      delete conn;
    }

    virtual QString version(toConnectionSub *sub)
    {
      oracleSub *conn=oracleConv(sub);
      try {
	otl_stream version(1,
			   "SELECT banner FROM v$version",
			   *(conn->Connection));
	QRegExp verre("[0-9]\\.[0-9\\.]+[0-9]");
	QRegExp orare("^oracle",false);
	while(!version.eof()) {
	  char buffer[1024];
	  version>>buffer;
	  QString ver=QString::fromUtf8(buffer);
	  if (orare.match(ver)>=0) {
	    int pos;
	    int len;
	    pos=verre.match(ver,0,&len);
	    if (pos>=0)
	      return ver.mid(pos,len);
	  }
	}
      } catch (...) {
	// Ignore any errors here
      }
      return QString::null;
    }

    virtual toQuery::queryImpl *createQuery(toQuery *query,toConnectionSub *sub)
    { return new oracleQuery(query,oracleConv(sub)); }
    virtual void execute(toConnectionSub *sub,const QCString &sql,toQList &params)
    {
      oracleSub *conn=oracleConv(sub);

      if (params.size()==0) {
	try {
	  otl_cursor::direct_exec(*(conn->Connection),sql);
	} catch (const otl_exception &exc) {
	  ThrowException(exc);
	}
      } else
	toQuery query(connection(),sql,params);
    }
  };

  toOracleProvider(void)
    : toConnectionProvider("Oracle")
  {
    toMaxLong=toTool::globalConfig(CONF_MAX_LONG,
				   QString::number(DEFAULT_MAX_LONG)).toInt();
    otl_connect::otl_initialize(1);
  }

  virtual toConnection::connectionImpl *provideConnection(const QString &,toConnection *conn)
  { return new oracleConnection(conn); }
  virtual std::list<QString> providedModes(const QString &)
  {
    std::list<QString> ret;
    ret.insert(ret.end(),"Normal");
    ret.insert(ret.end(),"SYS_OPER");
    ret.insert(ret.end(),"SYS_DBA");
    return ret;
  }
  virtual std::list<QString> providedHosts(const QString &)
  {
    std::list<QString> ret;
    ret.insert(ret.end(),QString::null);
    ret.insert(ret.end(),"SQL*Net");
    return ret;
  }
  virtual std::list<QString> providedDatabases(const QString &,const QString &host,const QString &,const QString &)
  {
    QString str;
#ifdef WIN32
    CRegistry registry;
    DWORD siz=1024;
    char buffer[1024];
    try {
      if (registry.GetStringValue(HKEY_LOCAL_MACHINE,
				  "SOFTWARE\\ORACLE\\HOME0",
				  "TNS_ADMIN",
				  buffer,siz)) {
	if (siz>0)
	  str=buffer;
	else
	  throw 0;
      } else
	throw 0;
    } catch(...) {
      try {
	if (registry.GetStringValue(HKEY_LOCAL_MACHINE,
				    "SOFTWARE\\ORACLE\\HOME0",
				    "ORACLE_HOME",
				    buffer,siz)) {
	  if (siz>0) {
	    str=buffer;
	    str+="\\network\\admin";
	  }
	}
      } catch(...) {
      }
    }
#else
    if (!getenv("ORACLE_HOME"))
      throw QString("ORACLE_HOME environment variable not set");
    if (getenv("TNS_ADMIN")) {
      str=getenv("TNS_ADMIN");
    } else {
      str=getenv("ORACLE_HOME");
      str.append("/network/admin");
    }
#endif
    str.append("/tnsnames.ora");


    std::list<QString> ret;

    QFile file(str);
    if (!file.open(IO_ReadOnly))
      return ret;
	    
    int size=file.size();
	    
    char *buf=new char[size+1];
    if (file.readBlock(buf,size)==-1) {
      delete[] buf;
      return ret;
    }

    buf[size]=0;

    int begname=-1;
    int parambeg=-1;
    int pos=0;
    int param=0;
    while(pos<size) {
      if (buf[pos]=='#') {
	while(pos<size&&buf[pos]!='\n')
	  pos++;
      } else if (buf[pos]=='=') {
	if (param==0) {
	  if (begname>=0&&!host.isEmpty())
	    ret.insert(ret.end(),QString::fromLatin1(buf+begname,pos-begname));
	}
      } else if (buf[pos]=='(') {
	begname=-1;
	parambeg=pos+1;
	param++;
      } else if (buf[pos]==')') {
	if (parambeg>=0&&host.isEmpty()) {
	  QString tmp=QString::fromLatin1(buf+parambeg,pos-parambeg);
	  tmp.replace(QRegExp("\\s+"),"");
	  if (tmp.lower().startsWith("sid="))
	    ret.insert(ret.end(),tmp.mid(4));
	}
	begname=-1;
	parambeg=-1;
	param--;
      } else if (!isspace(buf[pos])&&begname<0) {
	begname=pos;
      }
      pos++;
    }
    delete[] buf;
    return ret;
  }
  virtual QWidget *providerConfigurationTab(const QString &provider,QWidget *parent);
};

static toOracleProvider OracleProvider;

void toOracleProvider::oracleQuery::execute(void)
{
  oracleSub *conn=dynamic_cast<oracleSub *>(query()->connectionSub());
  if (!conn)
    throw QString("Internal error, not oracle sub connection");
  try {
    delete Query;
    Query=NULL;

    while (conn->Lock.getValue()>1) {
      conn->Lock.down();
      toStatusMessage("Too high value on connection lock semaphore");
    }

    conn->Lock.down();
    if (Cancel)
      throw QString("Query aborted before started");
    Running=true;
    try {
      Query=new otl_stream;
      Query->set_commit(0);
      Query->set_all_column_types(otl_all_num2str|otl_all_date2str);
      Query->open(1,
		  query()->sql(),
		  *(conn->Connection));
    } catch(...) {
      conn->Lock.up();
      throw;
    }
  } catch (const otl_exception &exc) {
    Running=false;
    ThrowException(exc);
  }
  try {
    otl_null null;
    for(toQList::iterator i=query()->params().begin();i!=query()->params().end();i++) {
      if ((*i).isNull())
	(*Query)<<null;
      else {
	otl_var_desc *next=Query->describe_next_in_var();
	switch(next->ftype) {
	case otl_var_double:
	case otl_var_float:
	  (*Query)<<(*i).toDouble();
	  break;
	case otl_var_int:
	case otl_var_unsigned_int:
	case otl_var_short:
	case otl_var_long_int:
	  (*Query)<<(*i).toInt();
	  break;
	default:
	  (*Query)<<QString(*i).utf8();
	  break;
	}
      }
    }
    Running=false;
    conn->Lock.up();
  } catch (const otl_exception &exc) {
    Running=false;
    conn->Lock.up();
    ThrowException(exc);
  }
}

void toOracleProvider::oracleQuery::cancel(void)
{
  oracleSub *conn=dynamic_cast<oracleSub *>(query()->connectionSub());
  if (!conn)
    throw QString("Internal error, not oracle sub connection");
  if (Running)
    conn->Connection->cancel();
  else {
    Cancel=true;
    conn->Lock.up();
  }
}

toConnectionSub *toOracleProvider::oracleConnection::createConnection(void)
{
  QString oldSid;
  bool sqlNet=!connection().host().isEmpty();
  if (!sqlNet) {
    oldSid=getenv("ORACLE_SID");
    toSetEnv("ORACLE_SID",connection().database().utf8());
  }
  otl_connect *conn=NULL;
  try {
    QString mode=connection().mode();
    int session_mode=OCI_DEFAULT;
    if (mode=="SYS_OPER")
      session_mode=OCI_SYSOPER;
    else if (mode=="SYS_DBA")
      session_mode=OCI_SYSDBA;
    conn=new otl_connect;
    conn->set_stream_pool_size(max(toTool::globalConfig(CONF_OPEN_CURSORS,
							DEFAULT_OPEN_CURSORS).toInt(),1));
    if(!sqlNet)
      conn->server_attach();
    else
      conn->server_attach(connection().database().utf8());
    QCString user=connection().user().utf8();
    QCString pass=connection().password().utf8();
    conn->session_begin(user.isEmpty()?"":(const char *)user,pass.isEmpty()?"":(const char *)pass,0,session_mode);
  } catch (const otl_exception &exc) {
    if (!sqlNet) {
      if (oldSid.isNull())
	toUnSetEnv("ORACLE_SID");
      else
	toSetEnv("ORACLE_SID",oldSid.latin1());
    }
    delete conn;
    ThrowException(exc);
  }
  if (!sqlNet) {
    if (oldSid.isNull())
      toUnSetEnv("ORACLE_SID");
    else {
      toSetEnv("ORACLE_SID",oldSid.latin1());
    }
  }
  
  try {
    {
      QString str="ALTER SESSION SET NLS_DATE_FORMAT = '";
      str+=toTool::globalConfig(CONF_DATE_FORMAT,DEFAULT_DATE_FORMAT);
      str+="'";
      otl_stream date(1,str.utf8(),*conn);
    }
    {
      otl_stream info(1,
		      "BEGIN\n"
		      "  SYS.DBMS_APPLICATION_INFO.SET_CLIENT_INFO('TOra (http://www.globecom.se/tora)');\n"
		      "END;",
		      *conn);
    }
  } catch(...) {
    toStatusMessage("Failed to set new default date format for session");
  }
  return new oracleSub(conn);
}

static toSQL SQLCreatePlanTable(toSQL::TOSQL_CREATEPLAN,
				"CREATE TABLE %1 (\n"
				"    STATEMENT_ID    VARCHAR2(30),\n"
				"    TIMESTAMP       DATE,\n"
				"    REMARKS         VARCHAR2(80),\n"
				"    OPERATION       VARCHAR2(30),\n"
				"    OPTIONS         VARCHAR2(30),\n"
				"    OBJECT_NODE     VARCHAR2(128),\n"
				"    OBJECT_OWNER    VARCHAR2(30),\n"
				"    OBJECT_NAME     VARCHAR2(30),\n"
				"    OBJECT_INSTANCE NUMERIC,\n"
				"    OBJECT_TYPE     VARCHAR2(30),\n"
				"    OPTIMIZER       VARCHAR2(255),\n"
				"    SEARCH_COLUMNS  NUMBER,\n"
				"    ID              NUMERIC,\n"
				"    PARENT_ID       NUMERIC,\n"
				"    POSITION        NUMERIC,\n"
				"    COST            NUMERIC,\n"
				"    CARDINALITY     NUMERIC,\n"
				"    BYTES           NUMERIC,\n"
				"    OTHER_TAG       VARCHAR2(255),\n"
				"    PARTITION_START VARCHAR2(255),\n"
				"    PARTITION_STOP  VARCHAR2(255),\n"
				"    PARTITION_ID    NUMERIC,\n"
				"    OTHER           LONG,\n"
				"    DISTRIBUTION    VARCHAR2(30)\n"
				")",
				"Create plan table, must have same % signs");

class toOracleSetting : public toOracleSettingUI, public toSettingTab
{
public:
  toOracleSetting(QWidget *parent)
    : toOracleSettingUI(parent),toSettingTab("database.html#oracle")
  {
    DefaultDate->setText(toTool::globalConfig(CONF_DATE_FORMAT,
					      DEFAULT_DATE_FORMAT));
    CheckPoint->setText(toTool::globalConfig(CONF_PLAN_CHECKPOINT,
					     DEFAULT_PLAN_CHECKPOINT));
    ExplainPlan->setText(toTool::globalConfig(CONF_PLAN_TABLE,
					      DEFAULT_PLAN_TABLE));
    OpenCursors->setValue(toTool::globalConfig(CONF_OPEN_CURSORS,
					       DEFAULT_OPEN_CURSORS).toInt());
    KeepPlans->setChecked(!toTool::globalConfig(CONF_KEEP_PLANS,"").isEmpty());
    int len=toTool::globalConfig(CONF_MAX_LONG,
				 QString::number(DEFAULT_MAX_LONG)).toInt();
    if (len>=0) {
      MaxLong->setText(QString::number(len));
      MaxLong->setValidator(new QIntValidator(MaxLong));
      Unlimited->setChecked(false);
    }
    try {
      // Check if connection exists
      toMainWidget()->currentConnection();
      CreatePlanTable->setEnabled(true);
    } catch (...) {
    }
  }
  virtual void saveSetting(void)
  {
    toTool::globalSetConfig(CONF_KEEP_PLANS,KeepPlans->isChecked()?"Yes":"");
    toTool::globalSetConfig(CONF_DATE_FORMAT,DefaultDate->text());
    toTool::globalSetConfig(CONF_PLAN_CHECKPOINT,CheckPoint->text());
    toTool::globalSetConfig(CONF_PLAN_TABLE,ExplainPlan->text());
    toTool::globalSetConfig(CONF_OPEN_CURSORS,QString::number(OpenCursors->value()));
    if (Unlimited->isChecked()) {
      toMaxLong=-1;
      toTool::globalSetConfig(CONF_MAX_LONG,"-1");
    } else {
      toTool::globalSetConfig(CONF_MAX_LONG,MaxLong->text());
      toMaxLong=MaxLong->text().toInt();
    }
  }
  virtual void createPlanTable(void)
  {
    try {
      toConnection &conn=toMainWidget()->currentConnection();
      conn.execute(toSQL::string(SQLCreatePlanTable,conn).
		   arg(ExplainPlan->text()));
    } TOCATCH
  }
};

QWidget *toOracleProvider::providerConfigurationTab(const QString &,QWidget *parent)
{
  return new toOracleSetting(parent);
}