2 * Copyright (C) 2005-2013 Team XBMC
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, see
17 * <http://www.gnu.org/licenses/>.
25 #include "utils/log.h"
26 #include "system.h" // for GetLastError()
29 #include "mysqldataset.h"
30 #include "mysql/errmsg.h"
32 #pragma comment(lib, "mysqlclient.lib")
37 #define ER_BAD_DB_ERROR 1049
43 //************* MysqlDatabase implementation ***************
45 MysqlDatabase::MysqlDatabase() {
48 _in_transaction = false; // for transaction
50 error = "Unknown database error";//S_NO_CONNECTION;
60 MysqlDatabase::~MysqlDatabase() {
64 Dataset* MysqlDatabase::CreateDataset() const {
65 return new MysqlDataset((MysqlDatabase*)this);
68 int MysqlDatabase::status(void) {
69 if (active == false) return DB_CONNECTION_NONE;
70 return DB_CONNECTION_OK;
73 int MysqlDatabase::setErr(int err_code, const char * qry) {
77 error = "Successful result";
79 case CR_COMMANDS_OUT_OF_SYNC:
80 error = "Commands were executed in an improper order";
82 case CR_SERVER_GONE_ERROR:
83 error = "The MySQL server has gone away";
86 error = "The connection to the server was lost during this query";
88 case CR_UNKNOWN_ERROR:
89 error = "An unknown error occurred";
91 case 1146: /* ER_NO_SUCH_TABLE */
92 error = "The table does not exist";
96 snprintf(err, 256, "Undefined MySQL error: Code (%d)", err_code);
105 const char *MysqlDatabase::getErrorMsg() {
106 return error.c_str();
109 int MysqlDatabase::connect(bool create_new) {
110 if (host.empty() || db.empty())
111 return DB_CONNECTION_NONE;
113 //CLog::Log(LOGDEBUG, "Connecting to mysql:%s:%s", host.c_str(), db.c_str());
120 conn = mysql_init(conn);
122 // establish connection with just user credentials
123 if (mysql_real_connect(conn, host.c_str(),login.c_str(),passwd.c_str(), NULL, atoi(port.c_str()),NULL,0) != NULL)
125 // disable mysql autocommit since we handle it
126 //mysql_autocommit(conn, false);
128 // enforce utf8 charset usage
129 default_charset = mysql_character_set_name(conn);
130 if(mysql_set_character_set(conn, "utf8")) // returns 0 on success
132 CLog::Log(LOGERROR, "Unable to set utf8 charset: %s [%d](%s)",
133 db.c_str(), mysql_errno(conn), mysql_error(conn));
139 // nothing to see here
146 sprintf(sqlcmd, "CREATE DATABASE `%s`", db.c_str());
147 if ( (ret=query_with_reconnect(sqlcmd)) != MYSQL_OK )
149 throw DbErrors("Can't create new database: '%s' (%d)", db.c_str(), ret);
153 if (mysql_select_db(conn, db.c_str()) == 0)
156 return DB_CONNECTION_OK;
160 // if we failed above, either credentials were incorrect or the database didn't exist
161 if (mysql_errno(conn) == ER_BAD_DB_ERROR && create_new)
164 if (create() == MYSQL_OK)
168 return DB_CONNECTION_OK;
172 CLog::Log(LOGERROR, "Unable to open database: %s [%d](%s)",
173 db.c_str(), mysql_errno(conn), mysql_error(conn));
175 return DB_CONNECTION_NONE;
179 CLog::Log(LOGERROR, "Unable to open database: %s (%u)",
180 db.c_str(), GetLastError());
182 return DB_CONNECTION_NONE;
185 void MysqlDatabase::disconnect(void) {
195 int MysqlDatabase::create() {
196 return connect(true);
199 int MysqlDatabase::drop() {
201 throw DbErrors("Can't drop database: no active connection...");
204 sprintf(sqlcmd,"DROP DATABASE `%s`", db.c_str());
205 if ( (ret=query_with_reconnect(sqlcmd)) != MYSQL_OK )
207 throw DbErrors("Can't drop database: '%s' (%d)", db.c_str(), ret);
210 return DB_COMMAND_OK;
213 int MysqlDatabase::copy(const char *backup_name) {
214 if ( !active || conn == NULL)
215 throw DbErrors("Can't copy database: no active connection...");
220 // ensure we're connected to the db we are about to copy
221 if ( (ret=mysql_select_db(conn, db.c_str())) != MYSQL_OK )
222 throw DbErrors("Can't connect to source database: '%s'",db.c_str());
224 // grab a list of base tables only (no views)
225 sprintf(sql, "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'");
226 if ( (ret=query_with_reconnect(sql)) != MYSQL_OK )
227 throw DbErrors("Can't determine base tables for copy.");
229 // get list of all tables from old DB
230 MYSQL_RES* res = mysql_store_result(conn);
234 if (mysql_num_rows(res) == 0)
236 mysql_free_result(res);
237 throw DbErrors("The source database was unexpectedly empty.");
240 // create the new database
241 sprintf(sql, "CREATE DATABASE `%s`", backup_name);
242 if ( (ret=query_with_reconnect(sql)) != MYSQL_OK )
244 mysql_free_result(res);
245 throw DbErrors("Can't create database for copy: '%s' (%d)", db.c_str(), ret);
250 // duplicate each table from old db to new db
251 while ( (row=mysql_fetch_row(res)) != NULL )
253 // copy the table definition
254 sprintf(sql, "CREATE TABLE %s.%s LIKE %s",
255 backup_name, row[0], row[0]);
257 if ( (ret=query_with_reconnect(sql)) != MYSQL_OK )
259 mysql_free_result(res);
260 throw DbErrors("Can't copy schema for table '%s'\nError: %s", db.c_str(), ret);
263 // copy the table data
264 sprintf(sql, "INSERT INTO %s.%s SELECT * FROM %s",
265 backup_name, row[0], row[0]);
267 if ( (ret=query_with_reconnect(sql)) != MYSQL_OK )
269 mysql_free_result(res);
270 throw DbErrors("Can't copy data for table '%s'\nError: %s", row[0], ret);
273 mysql_free_result(res);
275 // after table are recreated and repopulated we can recreate views
276 // grab a list of views and their definitions
277 sprintf(sql, "SELECT TABLE_NAME, VIEW_DEFINITION FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = '%s'", db.c_str());
278 if ( (ret=query_with_reconnect(sql)) != MYSQL_OK )
279 throw DbErrors("Can't determine views to recreate.");
281 // get list of all views from old DB
282 MYSQL_RES* resViews = mysql_store_result(conn);
286 while ( (row=mysql_fetch_row(resViews)) != NULL )
288 sprintf(sql, "CREATE VIEW %s.%s AS %s",
289 backup_name, row[0], row[1]);
291 if ( (ret=query_with_reconnect(sql)) != MYSQL_OK )
293 mysql_free_result(resViews);
294 throw DbErrors("Can't create view '%s'\nError: %s", db.c_str(), ret);
297 mysql_free_result(resViews);
304 int MysqlDatabase::query_with_reconnect(const char* query) {
308 // try to reconnect if server is gone
309 while ( ((result = mysql_real_query(conn, query, strlen(query))) != MYSQL_OK) &&
310 ((result = mysql_errno(conn)) == CR_SERVER_GONE_ERROR || result == CR_SERVER_LOST) &&
313 CLog::Log(LOGINFO,"MYSQL server has gone. Will try %d more attempt(s) to reconnect.", attempts);
321 long MysqlDatabase::nextid(const char* sname) {
322 CLog::Log(LOGDEBUG,"MysqlDatabase::nextid for %s",sname);
323 if (!active) return DB_UNEXPECTED_RESULT;
324 const char* seq_table = "sys_seq";
325 int id;/*,nrow,ncol;*/
328 sprintf(sqlcmd,"select nextid from %s where seq_name = '%s'",seq_table, sname);
329 CLog::Log(LOGDEBUG,"MysqlDatabase::nextid will request");
330 if ((last_err = query_with_reconnect(sqlcmd)) != 0)
332 return DB_UNEXPECTED_RESULT;
334 res = mysql_store_result(conn);
335 if (mysql_num_rows(res) == 0)
338 sprintf(sqlcmd,"insert into %s (nextid,seq_name) values (%d,'%s')",seq_table,id,sname);
339 mysql_free_result(res);
340 if ((last_err = query_with_reconnect(sqlcmd)) != 0) return DB_UNEXPECTED_RESULT;
345 MYSQL_ROW row = mysql_fetch_row(res);
348 unsigned long *lengths;
349 lengths = mysql_fetch_lengths(res);
350 CLog::Log(LOGINFO,"Next id is [%.*s] ", (int) lengths[0], row[0]);
351 sprintf(sqlcmd,"update %s set nextid=%d where seq_name = '%s'",seq_table,id,sname);
352 mysql_free_result(res);
353 if ((last_err = query_with_reconnect(sqlcmd) != 0)) return DB_UNEXPECTED_RESULT;
356 return DB_UNEXPECTED_RESULT;
359 // methods for transactions
360 // ---------------------------------------------
361 void MysqlDatabase::start_transaction() {
364 CLog::Log(LOGDEBUG,"Mysql Start transaction");
365 _in_transaction = true;
369 void MysqlDatabase::commit_transaction() {
373 CLog::Log(LOGDEBUG,"Mysql commit transaction");
374 _in_transaction = false;
378 void MysqlDatabase::rollback_transaction() {
381 mysql_rollback(conn);
382 CLog::Log(LOGDEBUG,"Mysql rollback transaction");
383 _in_transaction = false;
387 bool MysqlDatabase::exists(void) {
390 if ( conn == NULL || mysql_ping(conn) )
392 CLog::Log(LOGERROR, "Not connected to database, test of existence is not possible.");
396 MYSQL_RES* result = mysql_list_dbs(conn, db.c_str());
399 CLog::Log(LOGERROR,"Database is not present, does the user has CREATE DATABASE permission");
403 ret = (mysql_num_rows(result) > 0);
404 mysql_free_result(result);
406 // Check if there is some tables ( to permit user with no create database rights
409 result = mysql_list_tables(conn, NULL);
411 ret = (mysql_num_rows(result) > 0);
413 mysql_free_result(result);
419 // methods for formatting
420 // ---------------------------------------------
421 string MysqlDatabase::vprepare(const char *format, va_list args)
423 string strFormat = format;
424 string strResult = "";
428 // %q is the sqlite format string for %s.
429 // Any bad character, like "'", will be replaced with a proper one
431 while ( (pos = strFormat.find("%s", pos)) != string::npos )
432 strFormat.replace(pos++, 2, "%q");
434 p = mysql_vmprintf(strFormat.c_str(), args);
440 // RAND() is the mysql form of RANDOM()
442 while ( (pos = strResult.find("RANDOM()", pos)) != string::npos )
444 strResult.replace(pos++, 8, "RAND()");
452 /* vsprintf() functionality is based on sqlite3.c functions */
455 ** Conversion types fall into various categories as defined by the
456 ** following enumeration.
458 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
459 #define etFLOAT 2 /* Floating point. %f */
460 #define etEXP 3 /* Exponentional notation. %e and %E */
461 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
462 #define etSIZE 5 /* Return number of characters processed so far. %n */
463 #define etSTRING 6 /* Strings. %s */
464 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
465 #define etPERCENT 8 /* Percent symbol. %% */
466 #define etCHARX 9 /* Characters. %c */
467 /* The rest are extensions, not normally found in printf() */
468 #define etSQLESCAPE 10 /* Strings with '\'' doubled. Stings with '\\' escaped. %q */
469 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
470 NULL pointers replaced by SQL NULL. %Q */
471 #define etPOINTER 14 /* The %p conversion */
472 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
474 #define etINVALID 0 /* Any unrecognized conversion type */
476 #define ARRAY_SIZE(X) ((int)(sizeof(X)/sizeof(X[0])))
479 ** An "etByte" is an 8-bit unsigned value.
481 typedef unsigned char etByte;
484 ** Each builtin conversion character (ex: the 'd' in "%d") is described
485 ** by an instance of the following structure
487 typedef struct et_info { /* Information about each format field */
488 char fmttype; /* The format field code letter */
489 etByte base; /* The base for radix conversion */
490 etByte flags; /* One or more of FLAG_ constants below */
491 etByte type; /* Conversion paradigm */
492 etByte charset; /* Offset into aDigits[] of the digits string */
493 etByte prefix; /* Offset into aPrefix[] of the prefix string */
497 ** An objected used to accumulate the text of a string where we
498 ** do not necessarily know how big the string will be in the end.
501 char *zBase; /* A base allocation. Not from malloc. */
502 char *zText; /* The string collected so far */
503 int nChar; /* Length of the string so far */
504 int nAlloc; /* Amount of space allocated in zText */
505 int mxAlloc; /* Maximum allowed string length */
506 bool mallocFailed; /* Becomes true if any memory allocation fails */
507 bool tooBig; /* Becomes true if string size exceeds limits */
511 ** Allowed values for et_info.flags
513 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
514 #define FLAG_INTERN 2 /* True if for internal use only */
515 #define FLAG_STRING 4 /* Allow infinity precision */
519 ** The following table is searched linearly, so it is good to put the
520 ** most frequently used conversion types first.
522 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
523 static const char aPrefix[] = "-x0\000X0";
524 static const et_info fmtinfo[] = {
525 { 'd', 10, 1, etRADIX, 0, 0 },
526 { 's', 0, 4, etSTRING, 0, 0 },
527 { 'g', 0, 1, etGENERIC, 30, 0 },
528 { 'z', 0, 4, etDYNSTRING, 0, 0 },
529 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
530 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
531 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
532 { 'c', 0, 0, etCHARX, 0, 0 },
533 { 'o', 8, 0, etRADIX, 0, 2 },
534 { 'u', 10, 0, etRADIX, 0, 0 },
535 { 'x', 16, 0, etRADIX, 16, 1 },
536 { 'X', 16, 0, etRADIX, 0, 4 },
537 { 'f', 0, 1, etFLOAT, 0, 0 },
538 { 'e', 0, 1, etEXP, 30, 0 },
539 { 'E', 0, 1, etEXP, 14, 0 },
540 { 'G', 0, 1, etGENERIC, 14, 0 },
541 { 'i', 10, 1, etRADIX, 0, 0 },
542 { 'n', 0, 0, etSIZE, 0, 0 },
543 { '%', 0, 0, etPERCENT, 0, 0 },
544 { 'p', 16, 0, etPOINTER, 0, 1 },
548 ** "*val" is a double such that 0.1 <= *val < 10.0
549 ** Return the ascii code for the leading digit of *val, then
550 ** multiply "*val" by 10.0 to renormalize.
553 ** input: *val = 3.14159
554 ** output: *val = 1.4159 function return = '3'
556 ** The counter *cnt is incremented each time. After counter exceeds
557 ** 16 (the number of significant digits in a 64-bit float) '0' is
560 char MysqlDatabase::et_getdigit(double *val, int *cnt) {
563 if( (*cnt)++ >= 16 ) return '0';
567 *val = (*val - d)*10.0;
572 ** Append N space characters to the given string buffer.
574 void MysqlDatabase::appendSpace(StrAccum *pAccum, int N) {
575 static const char zSpaces[] = " ";
576 while( N>=(int)sizeof(zSpaces)-1 ) {
577 mysqlStrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
578 N -= sizeof(zSpaces)-1;
581 mysqlStrAccumAppend(pAccum, zSpaces, N);
585 #ifndef MYSQL_PRINT_BUF_SIZE
586 # define MYSQL_PRINT_BUF_SIZE 350
589 #define etBUFSIZE MYSQL_PRINT_BUF_SIZE /* Size of the output buffer */
594 ** The maximum length of a TEXT or BLOB in bytes. This also
595 ** limits the size of a row in a table or index.
597 ** The hard limit is the ability of a 32-bit signed integer
598 ** to count the size: 2^31-1 or 2147483647.
600 #ifndef MYSQL_MAX_LENGTH
601 # define MYSQL_MAX_LENGTH 1000000000
605 ** The root program. All variations call this core.
608 ** func This is a pointer to a function taking three arguments
609 ** 1. A pointer to anything. Same as the "arg" parameter.
610 ** 2. A pointer to the list of characters to be output
611 ** (Note, this list is NOT null terminated.)
612 ** 3. An integer number of characters to be output.
613 ** (Note: This number might be zero.)
615 ** arg This is the pointer to anything which will be passed as the
616 ** first argument to "func". Use it for whatever you like.
618 ** fmt This is the format string, as in the usual print.
620 ** ap This is a pointer to a list of arguments. Same as in
624 ** The return value is the total number of characters sent to
625 ** the function "func". Returns -1 on a error.
627 ** Note that the order in which automatic variables are declared below
628 ** seems to make a big difference in determining how fast this beast
631 void MysqlDatabase::mysqlVXPrintf(
632 StrAccum *pAccum, /* Accumulate results here */
633 int useExtended, /* Allow extended %-conversions */
634 const char *fmt, /* Format string */
635 va_list ap /* arguments */
637 int c; /* Next character in the format string */
638 char *bufpt; /* Pointer to the conversion buffer */
639 int precision; /* Precision of the current field */
640 int length; /* Length of the field */
641 int idx; /* A general purpose loop counter */
642 int width; /* Width of the current field */
643 etByte flag_leftjustify; /* True if "-" flag is present */
644 etByte flag_plussign; /* True if "+" flag is present */
645 etByte flag_blanksign; /* True if " " flag is present */
646 etByte flag_alternateform; /* True if "#" flag is present */
647 etByte flag_altform2; /* True if "!" flag is present */
648 etByte flag_zeropad; /* True if field width constant starts with zero */
649 etByte flag_long; /* True if "l" flag is present */
650 etByte flag_longlong; /* True if the "ll" flag is present */
651 etByte done; /* Loop termination flag */
652 uint64_t longvalue; /* Value for integer types */
653 double realvalue; /* Value for real types */
654 const et_info *infop; /* Pointer to the appropriate info structure */
655 char buf[etBUFSIZE]; /* Conversion buffer */
656 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
657 etByte xtype = 0; /* Conversion paradigm */
658 char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
659 int exp, e2; /* exponent of real numbers */
660 double rounder; /* Used for rounding floating point values */
661 etByte flag_dp; /* True if decimal point should be shown */
662 etByte flag_rtz; /* True if trailing zeros should be removed */
663 etByte flag_exp; /* True to force display of the exponent */
664 int nsd; /* Number of significant digits returned */
668 for(; (c=(*fmt))!=0; ++fmt){
673 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
674 mysqlStrAccumAppend(pAccum, bufpt, amt);
677 if( (c=(*++fmt))==0 ){
678 mysqlStrAccumAppend(pAccum, "%", 1);
681 /* Find out what flags are present */
682 flag_leftjustify = flag_plussign = flag_blanksign = flag_alternateform = flag_altform2 = flag_zeropad = 0;
688 case '-': flag_leftjustify = 1; break;
689 case '+': flag_plussign = 1; break;
690 case ' ': flag_blanksign = 1; break;
691 case '#': flag_alternateform = 1; break;
692 case '!': flag_altform2 = 1; break;
693 case '0': flag_zeropad = 1; break;
694 default: done = 1; break;
696 } while( !done && (c=(*++fmt))!=0 );
697 /* Get the field width */
700 width = va_arg(ap,int);
702 flag_leftjustify = 1;
707 while( c>='0' && c<='9' ){
708 width = width*10 + c - '0';
712 if( width > etBUFSIZE-10 ){
713 width = etBUFSIZE-10;
715 /* Get the precision */
720 precision = va_arg(ap,int);
721 if( precision<0 ) precision = -precision;
724 while( c>='0' && c<='9' ){
725 precision = precision*10 + c - '0';
732 /* Get the conversion type modifier */
743 flag_long = flag_longlong = 0;
745 /* Fetch the info entry for the field */
748 for(idx=0; idx<ARRAY_SIZE(fmtinfo); idx++){
749 if( c==fmtinfo[idx].fmttype ){
750 infop = &fmtinfo[idx];
751 if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
762 /* Limit the precision to prevent overflowing buf[] during conversion */
763 if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
764 precision = etBUFSIZE-40;
768 ** At this point, variables are initialized as follows:
770 ** flag_alternateform TRUE if a '#' is present.
771 ** flag_altform2 TRUE if a '!' is present.
772 ** flag_plussign TRUE if a '+' is present.
773 ** flag_leftjustify TRUE if a '-' is present or if the
774 ** field width was negative.
775 ** flag_zeropad TRUE if the width began with 0.
776 ** flag_long TRUE if the letter 'l' (ell) prefixed
777 ** the conversion character.
778 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
779 ** the conversion character.
780 ** flag_blanksign TRUE if a ' ' is present.
781 ** width The specified field width. This is
782 ** always non-negative. Zero is the default.
783 ** precision The specified precision. The default
785 ** xtype The class of the conversion.
786 ** infop Pointer to the appropriate info struct.
790 flag_longlong = sizeof(char*)==sizeof(int64_t);
791 flag_long = sizeof(char*)==sizeof(long int);
792 /* Fall through into the next case */
794 if( infop->flags & FLAG_SIGNED ){
797 v = va_arg(ap,int64_t);
798 }else if( flag_long ){
799 v = va_arg(ap,long int);
808 if( flag_plussign ) prefix = '+';
809 else if( flag_blanksign ) prefix = ' ';
814 longvalue = va_arg(ap,uint64_t);
815 }else if( flag_long ){
816 longvalue = va_arg(ap,unsigned long int);
818 longvalue = va_arg(ap,unsigned int);
822 if( longvalue==0 ) flag_alternateform = 0;
823 if( flag_zeropad && precision<width-(prefix!=0) ){
824 precision = width-(prefix!=0);
826 bufpt = &buf[etBUFSIZE-1];
828 register const char *cset; /* Use registers for speed */
830 cset = &aDigits[infop->charset];
832 do{ /* Convert to ascii */
833 *(--bufpt) = cset[longvalue%base];
834 longvalue = longvalue/base;
835 }while( longvalue>0 );
837 length = (int)(&buf[etBUFSIZE-1]-bufpt);
838 for(idx=precision-length; idx>0; idx--){
839 *(--bufpt) = '0'; /* Zero pad */
841 if( prefix ) *(--bufpt) = prefix; /* Add sign */
842 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
845 pre = &aPrefix[infop->prefix];
846 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
848 length = (int)(&buf[etBUFSIZE-1]-bufpt);
854 realvalue = va_arg(ap,double);
855 if( precision<0 ) precision = 6; /* Set default precision */
856 if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
858 realvalue = -realvalue;
861 if( flag_plussign ) prefix = '+';
862 else if( flag_blanksign ) prefix = ' ';
865 if( xtype==etGENERIC && precision>0 ) precision--;
866 /* It makes more sense to use 0.5 */
867 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
868 if( xtype==etFLOAT ) realvalue += rounder;
869 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
872 if( mysqlIsNaN((double)realvalue) ){
879 while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
880 while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
881 while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
882 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
883 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
886 bufpt = (char *)"-Inf";
887 }else if( prefix=='+' ){
888 bufpt = (char *)"+Inf";
890 bufpt = (char *)"Inf";
892 length = strlen(bufpt);
898 ** If the field type is etGENERIC, then convert to either etEXP
899 ** or etFLOAT, as appropriate.
901 flag_exp = xtype==etEXP;
902 if( xtype!=etFLOAT ){
903 realvalue += rounder;
904 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
906 if( xtype==etGENERIC ){
907 flag_rtz = !flag_alternateform;
908 if( exp<-4 || exp>precision ){
911 precision = precision - exp;
923 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
924 /* The sign in front of the number */
928 /* Digits prior to the decimal point */
933 *(bufpt++) = et_getdigit(&realvalue,&nsd);
936 /* The decimal point */
940 /* "0" digits after the decimal point but before the first
941 ** significant digit of the number */
942 for(e2++; e2<0; precision--, e2++){
943 //ASSERT( precision>0 );
946 /* Significant digits after the decimal point */
947 while( (precision--)>0 ){
948 *(bufpt++) = et_getdigit(&realvalue,&nsd);
950 /* Remove trailing zeros and the "." if no digits follow the "." */
951 if( flag_rtz && flag_dp ){
952 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
953 //ASSERT( bufpt>buf );
954 if( bufpt[-1]=='.' ){
962 /* Add the "eNNN" suffix */
963 if( flag_exp || xtype==etEXP ){
964 *(bufpt++) = aDigits[infop->charset];
966 *(bufpt++) = '-'; exp = -exp;
971 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
974 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
975 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
979 /* The converted number is in buf[] and zero terminated. Output it.
980 ** Note that the number is in the usual order, not reversed as with
981 ** integer conversions. */
982 length = (int)(bufpt-buf);
985 /* Special case: Add leading zeros if the flag_zeropad flag is
986 ** set and we are not left justified */
987 if( flag_zeropad && !flag_leftjustify && length < width){
989 int nPad = width - length;
990 for(i=width; i>=nPad; i--){
991 bufpt[i] = bufpt[i-nPad];
994 while( nPad-- ) bufpt[i++] = '0';
999 *(va_arg(ap,int*)) = pAccum->nChar;
1011 for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
1020 bufpt = va_arg(ap,char*);
1023 }else if( xtype==etDYNSTRING ){
1027 for(length=0; length<precision && bufpt[length]; length++){}
1029 length = strlen(bufpt);
1034 case etSQLESCAPE3: {
1035 int i, j, k, n, isnull;
1038 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
1039 const char *escarg = va_arg(ap, char*);
1041 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
1043 for(i=0; k!=0 && (ch=escarg[i])!=0; i++, k--);
1044 needQuote = !isnull && xtype==etSQLESCAPE2;
1045 n = i*2 + 1 + needQuote*2;
1047 bufpt = zExtra = (char *)malloc(n);
1049 pAccum->mallocFailed = 1;
1056 if( needQuote ) bufpt[j++] = q;
1058 j += mysql_real_escape_string(conn, bufpt, escarg, k);
1059 if( needQuote ) bufpt[j++] = q;
1062 /* The precision in %q and %Q means how many input characters to
1063 ** consume, not the length of the output...
1064 ** if( precision>=0 && precision<length ) length = precision; */
1070 }/* End switch over the format type */
1072 ** The text of the conversion is pointed to by "bufpt" and is
1073 ** "length" characters long. The field width is "width". Do
1076 if( !flag_leftjustify ){
1077 register int nspace;
1078 nspace = width-length;
1080 appendSpace(pAccum, nspace);
1084 mysqlStrAccumAppend(pAccum, bufpt, length);
1086 if( flag_leftjustify ){
1087 register int nspace;
1088 nspace = width-length;
1090 appendSpace(pAccum, nspace);
1096 }/* End for loop over the format string */
1097 } /* End of function */
1100 ** Append N bytes of text from z to the StrAccum object.
1102 void MysqlDatabase::mysqlStrAccumAppend(StrAccum *p, const char *z, int N) {
1103 if( p->tooBig | p->mallocFailed ){
1112 if( p->nChar+N >= p->nAlloc ){
1114 int szNew = p->nChar;
1116 if( szNew > p->mxAlloc ){
1117 mysqlStrAccumReset(p);
1123 zNew = (char *)malloc(p->nAlloc);
1125 memcpy(zNew, p->zText, p->nChar);
1126 mysqlStrAccumReset(p);
1129 p->mallocFailed = 1;
1130 mysqlStrAccumReset(p);
1134 memcpy(&p->zText[p->nChar], z, N);
1139 ** Finish off a string by making sure it is zero-terminated.
1140 ** Return a pointer to the resulting string. Return a NULL
1141 ** pointer if any kind of error was encountered.
1143 char * MysqlDatabase::mysqlStrAccumFinish(StrAccum *p){
1145 p->zText[p->nChar] = 0;
1146 if( p->zText==p->zBase ){
1147 p->zText = (char *)malloc(p->nChar+1);
1149 memcpy(p->zText, p->zBase, p->nChar+1);
1151 p->mallocFailed = 1;
1159 ** Reset an StrAccum string. Reclaim all malloced memory.
1161 void MysqlDatabase::mysqlStrAccumReset(StrAccum *p){
1162 if( p->zText!=p->zBase ){
1169 ** Initialize a string accumulator
1171 void MysqlDatabase::mysqlStrAccumInit(StrAccum *p, char *zBase, int n, int mx){
1172 p->zText = p->zBase = zBase;
1177 p->mallocFailed = 0;
1181 ** Print into memory obtained from mysql_malloc(). Omit the internal
1182 ** %-conversion extensions.
1184 char *MysqlDatabase::mysql_vmprintf(const char *zFormat, va_list ap) {
1186 char zBase[MYSQL_PRINT_BUF_SIZE];
1189 mysqlStrAccumInit(&acc, zBase, sizeof(zBase), MYSQL_MAX_LENGTH);
1190 mysqlVXPrintf(&acc, 0, zFormat, ap);
1191 z = mysqlStrAccumFinish(&acc);
1196 //************* MysqlDataset implementation ***************
1198 MysqlDataset::MysqlDataset():Dataset() {
1202 autorefresh = false;
1206 MysqlDataset::MysqlDataset(MysqlDatabase *newDb):Dataset(newDb) {
1210 autorefresh = false;
1213 MysqlDataset::~MysqlDataset() {
1214 if (errmsg) free(errmsg);
1218 void MysqlDataset::set_autorefresh(bool val) {
1224 //--------- protected functions implementation -----------------//
1226 MYSQL* MysqlDataset::handle(){
1229 return static_cast<MysqlDatabase*>(db)->getHandle();
1235 void MysqlDataset::make_query(StringList &_sql) {
1238 if (db == NULL) throw DbErrors("No Database Connection");
1241 if (autocommit) db->start_transaction();
1243 for (list<string>::iterator i =_sql.begin(); i!=_sql.end(); i++)
1246 Dataset::parse_sql(query);
1247 if ((result = static_cast<MysqlDatabase *>(db)->query_with_reconnect(query.c_str())) != MYSQL_OK)
1249 throw DbErrors(db->getErrorMsg());
1253 if (db->in_transaction() && autocommit) db->commit_transaction();
1256 ds_state = dsSelect;
1262 if (db->in_transaction()) db->rollback_transaction();
1268 void MysqlDataset::make_insert() {
1269 make_query(insert_sql);
1273 void MysqlDataset::make_edit() {
1274 make_query(update_sql);
1278 void MysqlDataset::make_deletion() {
1279 make_query(delete_sql);
1282 void MysqlDataset::fill_fields() {
1283 if ((db == NULL) || (result.record_header.size() == 0) || (result.records.size() < (unsigned int)frecno)) return;
1285 if (fields_object->size() == 0) // Filling columns name
1287 const unsigned int ncols = result.record_header.size();
1288 fields_object->resize(ncols);
1289 for (unsigned int i = 0; i < ncols; i++)
1290 (*fields_object)[i].props = result.record_header[i];
1294 if (result.records.size() != 0)
1296 const sql_record *row = result.records[frecno];
1299 const unsigned int ncols = row->size();
1300 fields_object->resize(ncols);
1301 for (unsigned int i = 0; i < ncols; i++)
1302 (*fields_object)[i].val = row->at(i);
1306 const unsigned int ncols = result.record_header.size();
1307 fields_object->resize(ncols);
1308 for (unsigned int i = 0; i < ncols; i++)
1309 (*fields_object)[i].val = "";
1313 //------------- public functions implementation -----------------//
1314 bool MysqlDataset::dropIndex(const char *table, const char *index)
1317 string sql_prepared;
1319 sql = "SELECT * FROM information_schema.statistics WHERE TABLE_SCHEMA=DATABASE() AND table_name='%s' AND index_name='%s'";
1320 sql_prepared = static_cast<MysqlDatabase*>(db)->prepare(sql.c_str(), table, index);
1322 if (!query(sql_prepared))
1327 sql = "ALTER TABLE %s DROP INDEX %s";
1328 sql_prepared = static_cast<MysqlDatabase*>(db)->prepare(sql.c_str(), table, index);
1330 if (exec(sql_prepared) != MYSQL_OK)
1337 static bool ci_test(char l, char r)
1339 return tolower(l) == tolower(r);
1342 static size_t ci_find(const string& where, const string& what)
1344 std::string::const_iterator loc = std::search(where.begin(), where.end(), what.begin(), what.end(), ci_test);
1345 if (loc == where.end())
1346 return string::npos;
1348 return loc - where.begin();
1351 int MysqlDataset::exec(const string &sql) {
1352 if (!handle()) throw DbErrors("No Database Connection");
1357 // enforce the "auto_increment" keyword to be appended to "integer primary key"
1360 if ( (loc=ci_find(qry, "integer primary key")) != string::npos)
1362 qry = qry.insert(loc + 19, " auto_increment ");
1365 // force the charset and collation to UTF-8
1366 if ( ci_find(qry, "CREATE TABLE") != string::npos )
1368 qry += " CHARACTER SET utf8 COLLATE utf8_general_ci";
1371 CLog::Log(LOGDEBUG,"Mysql execute: %s", qry.c_str());
1373 if (db->setErr( static_cast<MysqlDatabase *>(db)->query_with_reconnect(qry.c_str()), qry.c_str()) != MYSQL_OK)
1375 throw DbErrors(db->getErrorMsg());
1379 // TODO: collect results and store in exec_res
1384 int MysqlDataset::exec() {
1388 const void* MysqlDataset::getExecRes() {
1393 bool MysqlDataset::query(const char *query) {
1394 if(!handle()) throw DbErrors("No Database Connection");
1395 std::string qry = query;
1396 int fs = qry.find("select");
1397 int fS = qry.find("SELECT");
1398 if (!( fs >= 0 || fS >=0))
1399 throw DbErrors("MUST be select SQL!");
1403 MYSQL_RES *stmt = NULL;
1405 if ( static_cast<MysqlDatabase*>(db)->setErr(static_cast<MysqlDatabase*>(db)->query_with_reconnect(query), query) != MYSQL_OK )
1406 throw DbErrors(db->getErrorMsg());
1408 MYSQL* conn = handle();
1409 stmt = mysql_store_result(conn);
1412 const unsigned int numColumns = mysql_num_fields(stmt);
1413 MYSQL_FIELD *fields = mysql_fetch_fields(stmt);
1415 result.record_header.resize(numColumns);
1416 for (unsigned int i = 0; i < numColumns; i++)
1417 result.record_header[i].name = fields[i].name;
1420 while ((row = mysql_fetch_row(stmt)))
1421 { // have a row of data
1422 sql_record *res = new sql_record;
1423 res->resize(numColumns);
1424 for (unsigned int i = 0; i < numColumns; i++)
1426 field_value &v = res->at(i);
1427 switch (fields[i].type)
1429 case MYSQL_TYPE_LONGLONG:
1430 case MYSQL_TYPE_DECIMAL:
1431 case MYSQL_TYPE_NEWDECIMAL:
1432 case MYSQL_TYPE_TINY:
1433 case MYSQL_TYPE_SHORT:
1434 case MYSQL_TYPE_INT24:
1435 case MYSQL_TYPE_LONG:
1438 v.set_asInt(atoi(row[i]));
1445 case MYSQL_TYPE_FLOAT:
1446 case MYSQL_TYPE_DOUBLE:
1449 v.set_asDouble(atof(row[i]));
1456 case MYSQL_TYPE_STRING:
1457 case MYSQL_TYPE_VAR_STRING:
1458 case MYSQL_TYPE_VARCHAR:
1459 if (row[i] != NULL) v.set_asString((const char *)row[i] );
1461 case MYSQL_TYPE_TINY_BLOB:
1462 case MYSQL_TYPE_MEDIUM_BLOB:
1463 case MYSQL_TYPE_LONG_BLOB:
1464 case MYSQL_TYPE_BLOB:
1465 if (row[i] != NULL) v.set_asString((const char *)row[i]);
1467 case MYSQL_TYPE_NULL:
1469 CLog::Log(LOGDEBUG,"MYSQL: Unknown field type: %u", fields[i].type);
1475 result.records.push_back(res);
1477 mysql_free_result(stmt);
1479 ds_state = dsSelect;
1484 bool MysqlDataset::query(const string &q) {
1485 return query(q.c_str());
1488 void MysqlDataset::open(const string &sql) {
1489 set_select_sql(sql);
1493 void MysqlDataset::open() {
1494 if (select_sql.size())
1496 query(select_sql.c_str());
1500 ds_state = dsInactive;
1504 void MysqlDataset::close() {
1507 edit_object->clear();
1508 fields_object->clear();
1509 ds_state = dsInactive;
1514 void MysqlDataset::cancel() {
1515 if ((ds_state == dsInsert) || (ds_state==dsEdit))
1517 if (result.record_header.size())
1518 ds_state = dsSelect;
1520 ds_state = dsInactive;
1525 int MysqlDataset::num_rows() {
1526 return result.records.size();
1530 bool MysqlDataset::eof() {
1535 bool MysqlDataset::bof() {
1540 void MysqlDataset::first() {
1542 this->fill_fields();
1545 void MysqlDataset::last() {
1550 void MysqlDataset::prev(void) {
1555 void MysqlDataset::next(void) {
1561 void MysqlDataset::free_row(void)
1563 if (frecno < 0 || (unsigned int)frecno >= result.records.size())
1566 sql_record *row = result.records[frecno];
1570 result.records[frecno] = NULL;
1574 bool MysqlDataset::seek(int pos) {
1575 if (ds_state == dsSelect)
1585 int64_t MysqlDataset::lastinsertid() {
1586 if (!handle()) DbErrors("No Database Connection");
1587 return mysql_insert_id(handle());
1590 long MysqlDataset::nextid(const char *seq_name) {
1592 return db->nextid(seq_name);
1594 return DB_UNEXPECTED_RESULT;
1597 void MysqlDataset::interrupt() {