[go: up one dir, main page]

File: tomysqlconnection.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 (494 lines) | stat: -rw-r--r-- 11,850 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
//***************************************************************************
/*
 * 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 <qfile.h>
#include <qregexp.h>

#ifdef WIN32
#include <winsock.h>
#endif
#include <mysql.h>

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

#define BUF_SIZE 102400

static toSQL SQLListTables("toMysqlConnection:ListTables",
			   "show tables",
			   "Get the available tables for a mysql connection",
			   "3.0",
			   "MySQL");

static QCString QueryParam(const QString &query,toQList &params,const QString &codec)
{
  QString ret;
  bool inString=false;
  toQList::iterator cpar=params.begin();

  std::map<QString,QString> binds;

  for(unsigned int i=0;i<query.length();i++) {
    QChar c=query.at(i);
    switch(char(c)) {
    case '\\':
      ret+=c;
      ret+=query.at(++i);
      break;
    case '\'':
      inString=!inString;
      ret+=c;
      break;
    case ':':
      if (!inString) {
	QString nam;
	for (i++;i<query.length();i++) {
	  c=query.at(i);
	  if (!c.isLetterOrNumber())
	    break;
	  nam+=c;
	}
	QString in;
	if (c=='<') {
	  for (i++;i<query.length();i++) {
	    c=query.at(i);
	    if (c=='>') {
	      i++;
	      break;
	    }
	    in+=c;
	  }
	}
	i--;
	
	if (nam.isEmpty())
	  throw QString("No bind name");

	if (binds.find(nam)!=binds.end()) {
	  ret+=binds[nam];
	  break;
	}
	if (cpar==params.end())
	  throw QString("Not all bind variables suplied");
	QString str;
	if ((*cpar).isNull()) {
	  str="NULL";
	} else if ((*cpar).isInt()||(*cpar).isDouble()) {
	  str=QString(*cpar);
	} else {
	  if (in!="noquote")
	    str+="'";
	  QString tmp=(*cpar);
	  for(unsigned int j=0;j<tmp.length();j++) {
	    QChar d=tmp.at(j);
	    switch(char(d)) {
	    case 0:
	      str+="\\0";
	      break;
	    case '\n':
	      str+="\\n";
	      break;
	    case '\t':
	      str+="\\t";
	      break;
	    case '\r':
	      str+="\\r";
	      break;
	    case '\'':
	      str+="\\\'";
	      break;
	    case '\"':
	      str+="\\\"";
	      break;
	    case '\\':
	      str+="\\\\";
	      break;
	    default:
	      str+=d;
	    }
	  }
	  if (in!="noquote")
	    str+="'";
	}
	binds[nam]=str;
	ret+=str;
	cpar++;
	break;
      }
    default:
      ret+=c;
    }
  }
  // More complex conversion here later
  //  printf("Parsed: %s\n",(const char *)ret);
  return ret.latin1();
}

class toMysqlProvider : public toConnectionProvider {
public:
  class mysqlConnection;
  struct mysqlSub : public toConnectionSub {
    mysqlConnection *Connection;
    mysqlSub(mysqlConnection *connection)
    { Connection=connection; }
  };
  class mysqlQuery : public toQuery::queryImpl {
    MYSQL_RES *Result;
    MYSQL_FIELD *Fields;
    MYSQL_ROW Row;
    int CurrentCol;
    int Columns;
    int AffectedRows;
    mysqlConnection *mysql(void);
  public:
    mysqlQuery(toQuery *query,toConnectionSub *conn)
      : toQuery::queryImpl(query)
    {
      Result=NULL;
      AffectedRows=Columns=0;
      Fields=NULL;
    }
    virtual ~mysqlQuery()
    {
      if (Result)
	mysql_free_result(Result);
    }
    virtual void execute(void);

    virtual toQValue readValue(void)
    {
      if (eof())
	throw QString("Tried to read past end of query");
      // More complex conversion here later
      QString ret(Row[CurrentCol]);
      CurrentCol++;
      if (CurrentCol==Columns) {
	CurrentCol=0;
	Row=mysql_fetch_row(Result);
      }
      return ret;
    }
    virtual void cancel(void)
    {
      // Not implemented
    }
    virtual bool eof(void)
    {
      if (!Result)
	return true;
      if (!Row)
	return true;
      return false;
    }
    virtual int rowsProcessed(void)
    { return AffectedRows; }
    virtual int columns(void)
    { return Columns; }
    virtual std::list<toQuery::queryDescribe> describe(void)
    {
      toQDescList ret;
      toQDescribe cur;
      for(int i=0;i<Columns;i++) {
	QString type;
	cur.AlignRight=true;
	cur.Name=Fields[i].name;
	if (IS_NUM(Fields[i].type)&&Fields[i].flags&UNSIGNED_FLAG)
	  type="UNSIGNED ";
	switch(Fields[i].type) {
	case FIELD_TYPE_TINY:
	  type+="TINYINT";
	  break;
	case FIELD_TYPE_SHORT:
	  type+="SMALLINT";
	  break;
	case FIELD_TYPE_LONG:
	  type+="INTEGER";
	  break;
	case FIELD_TYPE_INT24:
	  type+="MEDIUMINT";
	  break;
	case FIELD_TYPE_LONGLONG:
	  type+="BIGINT";
	  break;
	case FIELD_TYPE_DECIMAL:
	  type+="DECIMAL";
	  break;
	case FIELD_TYPE_FLOAT:
	  type+="FLOAT";
	  break;
	case FIELD_TYPE_DOUBLE:
	  type+="DOUBLE";
	  break;
	case FIELD_TYPE_TIMESTAMP:
	  type+="TIMESTAMP";
	  break;
	case FIELD_TYPE_DATETIME:
	  type+="DATETIME";
	  break;
	case FIELD_TYPE_DATE:
	  type+="DATE";
	  break;
	case FIELD_TYPE_TIME:
	  type+="TIME";
	  break;
	case FIELD_TYPE_YEAR:
	  type+="YEAR";
	  break;
	case FIELD_TYPE_VAR_STRING:
	  cur.AlignRight=false;
	  type+="VARCHAR(";
	  type+=QString::number(Fields[i].length);
	  type+=")";
	  break;
	case FIELD_TYPE_STRING:
	  cur.AlignRight=false;
	  type+="CHAR(";
	  type+=QString::number(Fields[i].length);
	  type+=")";
	  break;
	case FIELD_TYPE_TINY_BLOB:
	case FIELD_TYPE_MEDIUM_BLOB:
	case FIELD_TYPE_LONG_BLOB:
	case FIELD_TYPE_BLOB:
	  cur.AlignRight=false;
	  type+="BLOB";
	  break;
	case FIELD_TYPE_SET:
	  cur.AlignRight=false;
	  type+="SET";
	  break;
	case FIELD_TYPE_ENUM:
	  cur.AlignRight=false;
	  type+="ENUM";
	  break;
	default:
	  cur.AlignRight=false;
	  type+="UNKNOWN";
	  break;
	}
	cur.Datatype=type;
	cur.Null=!(Fields[i].flags&NOT_NULL_FLAG);
	ret.insert(ret.end(),cur);
      }
      return ret;
    }
  };

  class mysqlConnection : public toConnection::connectionImpl {
    toLock Lock;
    MYSQL *Connection;
    QString Codec;
  public:
    mysqlConnection(toConnection *conn)
      : toConnection::connectionImpl(conn)
    {
      Connection=mysql_init(NULL);
      if (!Connection)
	throw QString("Can't initialize MySQL connection");
      QString db=conn->database();
      int port=0;
      int pos=db.find(":");
      if (pos>=0) {
	port=db.mid(pos+1).toInt();
	db=db.mid(0,pos);
      }
      Connection=mysql_real_connect(Connection,
				    conn->host(),
				    conn->user(),
				    conn->password(),
				    db==QString::null?NULL:(const char *)db,
				    port,NULL,0);
      if (!Connection)
	throw QString("Couldn't open MySQL connection");
    }

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

      toQuery tables(connection(),SQLListTables);
      toConnection::objectName cur;
      cur.Type="TABLE";
      while(!tables.eof()) {
	cur.Name=tables.readValueNull();
	cur.Owner=connection().database();
	ret.insert(ret.end(),cur);
      }

      return ret;
    }
    virtual toQDescList columnDesc(const toConnection::objectName &table)
    {
      try {
	QString SQL="SELECT * FROM ";
	SQL+=table.Name;
	SQL+=" WHERE NULL=NULL";
	toQuery query(connection(),SQL);
	return query.describe();
      } catch(...) {
      }

      toQDescList ret;
      return ret;
    }

    virtual void commit(toConnectionSub *sub)
    {
      // Doesn't support transactions
    }
    virtual void rollback(toConnectionSub *sub)
    {
      // Doesn't support transactions
    }

    void throwError(const QString &sql=QString::null)
    {
      char *str=mysql_error(Connection);
      if (str) {
	if (!sql.isEmpty()) {
	  QString err=str;
	  err+="\n";
	  err+=sql;
	  throw QString(err);
	} else
	  throw QString(str);
      } else
	throw QString("Unknown error has occured in MySQL connection");
    }
    MYSQL *mysql(void)
    { return Connection; }
    const QString &codec(void) const
    { return Codec; }
    toLock &lock(void)
    { return Lock; }


    virtual toConnectionSub *createConnection(void)
    {
      return new mysqlSub(this);
    }
    void closeConnection(toConnectionSub *conn)
    {
      delete conn;
    }

    virtual QString version(toConnectionSub *sub)
    {
      char *version=mysql_get_server_info(Connection);
      if (!version)
	return "Unknown";
      return version;
    }

    virtual toQuery::queryImpl *createQuery(toQuery *query,toConnectionSub *sub)
    { return new mysqlQuery(query,sub); }
    virtual void execute(toConnectionSub *sub,const QCString &sql,toQList &params)
    {
      toLocker lock(Lock);
      QCString query=QueryParam(sql,params,Codec);
      if(mysql_real_query(Connection,query,query.length())!=0)
	throwError();
    }
  };

  toMysqlProvider(void)
    : toConnectionProvider("MySQL")
  {
  }

  virtual toConnection::connectionImpl *provideConnection(const QString &,toConnection *conn)
  { return new mysqlConnection(conn); }
  virtual std::list<QString> providedHosts(const QString &)
  {
    std::list<QString> ret;
    ret.insert(ret.end(),"localhost");
    return ret;
  }
  virtual std::list<QString> providedDatabases(const QString &,const QString &host,
					       const QString &user,const QString &pwd)
  {
    std::list<QString> ret;
    try {
      toConnection conn("MySQL",user,pwd,host,QString::null,"Normal",false);
      {
	toQuery query(conn,"SHOW DATABASES");
	while(!query.eof())
	  ret.insert(ret.end(),QString(query.readValue()));
      }
    } catch (...) {

    }
    return ret;
  }
};

static toMysqlProvider MysqlProvider;

void toMysqlProvider::mysqlQuery::execute(void)
{
  if (Result) {
    mysql_free_result(Result);
    Result=NULL;
  }
  QCString sql=QueryParam(QString::fromUtf8(query()->sql()),
			  query()->params(),mysql()->codec());
  toLocker lock(mysql()->lock());
  if(mysql_real_query(mysql()->mysql(),
		      sql,
		      sql.length())!=0)
    mysql()->throwError(sql);
  Result=mysql_store_result(mysql()->mysql());
  if (Result) {
    Columns=mysql_num_fields(Result);
    Fields=mysql_fetch_fields(Result);
    AffectedRows=0;
    CurrentCol=0;
    Row=mysql_fetch_row(Result);
  } else if (mysql_field_count(mysql()->mysql())==0) {
    AffectedRows=mysql_affected_rows(mysql()->mysql());
    Fields=NULL;
    Columns=0;
  } else
    mysql()->throwError(sql);
}

toMysqlProvider::mysqlConnection *toMysqlProvider::mysqlQuery::mysql(void)
{
  mysqlSub *conn=dynamic_cast<mysqlSub *>(query()->connectionSub());
  if (!conn)
    throw QString("Internal error MySQL query on non MySQL connection");
  return conn->Connection;
}