Exemplo n.º 1
0
int Connection::Query(char const* QueryStr, unsigned long Length, Result* ResultOut)
{
    MYSQL_RES* Result;
    my_ulonglong RetVal;
    if (mysql_real_query(MySQL, QueryStr, Length))
    {
        ShowMySQLError(MySQL, "mysql_real_query()");
        return -1;
    }

    Result = mysql_use_result(MySQL);
    if (Result)
    {
        if (ResultOut)
        {
            int RetVal = ResultOut->CreateResult(Result);

            if (RetVal == -1)
            {
                mysql_free_result(Result);
                return -1;
            }
        }

        if (mysql_errno(MySQL))
        {
            ShowMySQLError(MySQL, "mysql_fetch_row()");
            mysql_free_result(Result);
            return -1;
        }

        RetVal = mysql_num_rows(Result);
        mysql_free_result(Result);
    }
    else
    {
        if (mysql_errno(MySQL))
        {
            ShowMySQLError(MySQL, "mysql_store_result()");
            return -1;
        }

        RetVal = mysql_affected_rows(MySQL);
    }

    if (RetVal == ((my_ulonglong)-1)) return -1;
    return (int)RetVal;
}
void
TableMakerAdvProperties::InitCollationCombo()
{
    MDIWindow   *wnd = GetActiveWin();
    wyString    query, collationstr;
    MYSQL_ROW   myrow;
    MYSQL_RES   *myres;
    wyInt32     index;

    HWND        hwndcombo = GetDlgItem(m_hwnd, IDC_TABCOLLATION);

    query.SetAs("show collation");
    myres = ExecuteAndGetResult(wnd, wnd->m_tunnel, &wnd->m_mysql, query);
    if(!myres)
    {
        ShowMySQLError(m_hwnd, wnd->m_tunnel, &wnd->m_mysql, query.GetString());
        return;
    }
    while(myrow = wnd->m_tunnel->mysql_fetch_row(myres))
    {
        collationstr.SetAs(myrow[0]);
        SendMessage(hwndcombo , CB_ADDSTRING, 0,(LPARAM)collationstr.GetAsWideChar());
    }
    if((index = SendMessage(hwndcombo , CB_ADDSTRING, 0,(LPARAM)TEXT(STR_DEFAULT))) != CB_ERR)
        index = SendMessage(hwndcombo, CB_SETCURSEL, index, (LPARAM)TEXT(STR_DEFAULT));
}
wyBool 
ImportBatch::GetCurDatabase()
{
	wyInt32			ret;
    wyString        query;
	MYSQL_RES*		myres;
	MYSQL_ROW		myrow;
	wyString		myrowstr;
	MDIWindow		*wnd = GetActiveWin();
	wyBool			ismysql41 = wnd->m_ismysql41;

	query.Sprintf("select database()");

	wnd->SetThreadBusy(wyTrue);
	ret = my_query(wnd, m_tunnel, m_umysql, query.GetString(), query.GetLength());
	wnd->SetThreadBusy(wyFalse);
	if(ret)
	{
		ShowMySQLError(m_hwnd, m_tunnel, m_umysql, query.GetString());
		return wyFalse;
	}

	myres	=	m_tunnel->mysql_store_result(*m_umysql, false, false, GetActiveWin());
	if(!myres)
	{
		ShowMySQLError(m_hwnd, m_tunnel, m_umysql, query.GetString());
		return wyFalse;
	}

	myrow	=	m_tunnel->mysql_fetch_row(myres);
	if(myrow[0])
    {
		myrowstr.SetAs(myrow[0], ismysql41);
		strncpy(m_curdb, myrowstr.GetString(), myrowstr.GetLength());
    }
    else 
		m_curdb[0] = NULL;
	if( strlen(m_curdb) == 0)
		strcpy(m_curdb, "<None>");

        myrowstr.SetAs(m_curdb);
	SendMessage(GetDlgItem(m_hwnd, IDC_CURDATABASE), WM_SETTEXT, 0, (LPARAM)myrowstr.GetAsWideChar()); 		
	
	m_tunnel->mysql_free_result(myres);	

	return wyTrue;
}
wyBool
ConnectionCommunity::CreateTargetInstance(CopyDatabase *copydb)
{
	MYSQL *tempmysql, *newtargetmysql;
   
	copydb->m_newtargettunnel   = NULL;
	copydb->m_tgtprocess        = INVALID_HANDLE_VALUE;

	// create a tunnel and mysql object
    copydb->m_newtargettunnel = CreateTunnel((wyBool)copydb->m_targettunnel->IsTunnel());
		
	VERIFY(tempmysql = copydb->m_newtargettunnel->mysql_init((MYSQL*)0));
		
	SetMySQLOptions(copydb->m_tgtinfo, copydb->m_newtargettunnel, &tempmysql);

	newtargetmysql = copydb->m_newtargettunnel->mysql_real_connect(tempmysql, 
                             (*copydb->m_targetmysql)->host, (*copydb->m_targetmysql)->user, 
                             (*copydb->m_targetmysql)->passwd, NULL, 
                             (*copydb->m_targetmysql)->port, NULL, 
                             (*copydb->m_targetmysql)->client_flag | CLIENT_MULTI_RESULTS, NULL);

	if(!newtargetmysql)
    {
		ShowMySQLError(copydb->m_hwnddlg, copydb->m_newtargettunnel, &tempmysql, NULL, wyTrue);
		return wyFalse;
	}
	else
	{
		copydb->m_newtargetmysql=newtargetmysql;
	
	}

	if(!copydb->CreateTargetDB())
		return wyFalse;

	if(UseDatabase(copydb->m_targetdb, newtargetmysql, copydb->m_newtargettunnel) == wyFalse)
	{
		ShowMySQLError(copydb->m_hwnddlg, copydb->m_newtargettunnel, &tempmysql, NULL, wyTrue);
		return wyFalse;
	}
	copydb->m_newtargettunnel->SetServerInfo(newtargetmysql, 
                                copydb->m_targettunnel->mysql_get_server_info(*copydb->m_targetmysql));
	copydb->m_newtargetmysql = newtargetmysql;
	
	return wyTrue;
}
wyBool 
ConnectionCommunity::OnNewSameConnection(HWND hwndactive, MDIWindow *pcquerywnd, ConnectionInfo &conninfo)
{
    MYSQL       *mysqlnew, *mysqlold, *mysqltemp;
    Tunnel	    *oldtunnel, *newtunnel;	
    wyString    msg;

	if(hwndactive)
	{
		oldtunnel   = pcquerywnd->m_tunnel;
        newtunnel   = CreateTunnel(wyFalse);
        mysqlnew	= newtunnel->mysql_init((MYSQL*)0);
        mysqlold	= pcquerywnd->m_mysql;

		if(!mysqlnew)
		{
			yog_message(pGlobals->m_pcmainwin->m_hwndmain, _(L"Could not initialize a new window."), pGlobals->m_appname.GetAsWideChar(), MB_ICONERROR | MB_OK | MB_HELP);
			delete newtunnel;
			return wyFalse;
		}
		
		SetCursor(LoadCursor(NULL, IDC_WAIT	));
		ShowCursor(1);

        InitConInfo(pcquerywnd->m_conninfo, conninfo);

		//Get SQL_MODE info //following function remarked for issue #1654
		//GetAdvancedTabDetailsFromFile(&conninfo, (wyChar *)pcquerywnd->m_currentconn.GetString(), NULL);
	
		//post 8.01
		/*InvalidateRect(pcquerywnd->GetActiveTabEditor()->m_peditorbase->m_hwnd, NULL, FALSE);
		UpdateWindow(pcquerywnd->GetActiveTabEditor()->m_peditorbase->m_hwnd);*/
		
        if(conninfo.m_initcommand.GetLength())
            ExecuteInitCommands(mysqlnew, newtunnel, conninfo.m_initcommand);

		SetMySQLOptions(&pcquerywnd->m_conninfo, newtunnel, &mysqlnew);
		
        mysqltemp = newtunnel->mysql_real_connect(mysqlnew, mysqlold->host, mysqlold->user, 
                    mysqlold->passwd, NULL, mysqlold->port, NULL, 
                    mysqlold->client_flag | CLIENT_MULTI_RESULTS, NULL);
		
		if(!mysqltemp)
        {
			ShowMySQLError(pGlobals->m_pcmainwin->m_hwndmain, oldtunnel, &mysqlnew, NULL, wyTrue);
			newtunnel->mysql_close(mysqlnew);
			delete	newtunnel;
			return wyFalse;
		}

		/* change the conninfo things */
		conninfo.m_tunnel		= newtunnel;
		conninfo.m_mysql		= mysqlnew;
		conninfo.m_hprocess	    = INVALID_HANDLE_VALUE;
	}
    return wyTrue;
}
Exemplo n.º 6
0
bool Connection::SelectDatabase(char const* DatabaseName)
{
    int Failure = mysql_select_db(MySQL, DatabaseName);
    if (Failure)
    {
        ShowMySQLError(MySQL, "mysql_select_db()");
    }

    return Failure == 0;
}
Exemplo n.º 7
0
char const* Connection::GetStatus()
{
    char const* RetVal = mysql_stat(MySQL);
    if (!RetVal)
    {
        ShowMySQLError(MySQL, "mysql_stat()");
    }

    return RetVal;
}
Exemplo n.º 8
0
bool Connection::Ping()
{
    int Failure = mysql_ping(MySQL);
    if (Failure)
    {
        ShowMySQLError(MySQL, "mysql_ping()");
    }

    return Failure == 0;
}
wyBool
ConnectionCommunity::CreateSourceInstance(CopyDatabase *copydb)
{
	MYSQL *tempmysql, *newsrcmysql;

	copydb->m_newsrctunnel   = NULL;
	copydb->m_srcprocess     = INVALID_HANDLE_VALUE;

	// create a tunnel and mysql object
    copydb->m_newsrctunnel = CreateTunnel(wyFalse);

	VERIFY(tempmysql = copydb->m_newsrctunnel->mysql_init((MYSQL*)0));
	
	//if(IsMySQL41(copydb->m_newtargettunnel, &tempmysql))
		//VERIFY((copydb->m_newtargettunnel->mysql_options(tempmysql, MYSQL_SET_CHARSET_NAME, "utf8")));

	VERIFY(!(copydb->m_newsrctunnel->mysql_options(tempmysql, MYSQL_INIT_COMMAND, "/*40030 SET net_write_timeout=3600 */")));

	SetMySQLOptions(copydb->m_srcinfo, copydb->m_newsrctunnel, &tempmysql, wyTrue);

	newsrcmysql = copydb->m_newsrctunnel->mysql_real_connect(tempmysql, 
                             (*copydb->m_srcmysql)->host, (*copydb->m_srcmysql)->user, 
                             (*copydb->m_srcmysql)->passwd, NULL, 
                             (*copydb->m_srcmysql)->port, NULL, 
                             (*copydb->m_srcmysql)->client_flag | CLIENT_MULTI_RESULTS, NULL);

	if(!newsrcmysql)
    {
		ShowMySQLError(copydb->m_hwnddlg, copydb->m_newsrctunnel, &tempmysql, NULL, wyTrue);
		return wyFalse;
	}
	if(UseDatabase(copydb->m_srcdb, newsrcmysql, copydb->m_newsrctunnel) == wyFalse)
	{
		ShowMySQLError(copydb->m_hwnddlg, copydb->m_newsrctunnel, &tempmysql, NULL, wyTrue);
		return wyFalse;
	}
	copydb->m_newsrctunnel->SetServerInfo(newsrcmysql, 
                    copydb->m_srctunnel->mysql_get_server_info(*copydb->m_srcmysql));
	copydb->m_newsrcmysql = newsrcmysql;
	
	return wyTrue;
}
MYSQL* 
ConnectionCommunity::ConnectToMySQL(ConnectionInfo * coninfo)
{
	Tunnel			*tunnel = coninfo->m_tunnel;
	wyUInt32		client=0;
	MYSQL           *mysql, *temp;
    
	SetCursor(LoadCursor(NULL, IDC_WAIT));

	// FIRST initialize the object.
	VERIFY(mysql = tunnel->mysql_init((MYSQL*)0));
	temp = mysql;

	coninfo->m_hprocess      = INVALID_HANDLE_VALUE;
	coninfo->m_isssh         = wyFalse;
	coninfo->m_origmysqlport = 0;


	if(!tunnel->IsTunnel())
    {
        if(coninfo->m_initcommand.GetLength())
            ExecuteInitCommands(mysql, tunnel, coninfo->m_initcommand);
    }

	if(coninfo->m_isdeftimeout == wyTrue) 
	{	
		coninfo->m_strwaittimeout.SetAs(WAIT_TIMEOUT_SERVER);
	}
	else
	{
		if(!coninfo->m_strwaittimeout.GetLength())
		{
			coninfo->m_strwaittimeout.SetAs(WAIT_TIMEOUT_SERVER);
		}
	}

    SetMySQLOptions(coninfo, tunnel, &mysql);

	mysql	= tunnel->mysql_real_connect(mysql, coninfo->m_host.GetString(), coninfo->m_user.GetString(), coninfo->m_pwd.GetString(), NULL, coninfo->m_port, NULL, client | CLIENT_MULTI_RESULTS | CLIENT_REMEMBER_OPTIONS, coninfo->m_url.GetString());

	if(!mysql)
    {
		ShowMySQLError(NULL, tunnel, &temp, NULL, wyTrue);
		tunnel->mysql_close(temp);
		SetCursor(LoadCursor(NULL, IDC_ARROW));
		return NULL;
	}
		
	SetCursor(LoadCursor(NULL, IDC_ARROW));

	return mysql;
}
Exemplo n.º 11
0
bool Connection::Connect(char const* Host, char const* User, char const* Password, char const* DB, unsigned int Port)
{
    MySQL = mysql_init(NULL);
    if (!mysql_real_connect(MySQL, Host, User, Password, DB, Port, NULL, 0))
    {
        fprintf(stderr, "Error: Database Connection Refused\n");
        ShowMySQLError(MySQL, "mysql_real_connect()");
        mysql_close(MySQL);
        return false;
    }

    bIsConnected = true;
    return true;
}
void
TableMakerAdvProperties::ReInitRelatedCollations(HWND hwnd, wyWChar *charsetname)
{
    MDIWindow	*pcquerywnd = GetActiveWin();
    MYSQL_RES   *myres;
    MYSQL_ROW   myrow;
    wyWChar     *relcollation  = NULL;
    wyString    query, collationstr;
    wyInt32     ret, selcharsetlen  = 0;

    HWND    hwndcombo = GetDlgItem(hwnd, IDC_TABCOLLATION);

    query.SetAs("show collation");
    myres = ExecuteAndGetResult(pcquerywnd, pcquerywnd->m_tunnel, &pcquerywnd->m_mysql, query);
    if(!myres)
    {
        ShowMySQLError(hwnd, pcquerywnd->m_tunnel, &pcquerywnd->m_mysql, query.GetString());
        return;
    }

    VERIFY((hwndcombo, CB_RESETCONTENT, 0, 0));

    if(charsetname)
        selcharsetlen = wcslen(charsetname);

    while(myrow = pcquerywnd->m_tunnel->mysql_fetch_row(myres))
    {
        collationstr.SetAs(myrow[0]);
        ret = SendMessage(hwndcombo, CB_FINDSTRINGEXACT, -1,(LPARAM)collationstr.GetAsWideChar());
        if(ret != CB_ERR)
        {
            //delete the items which are not relevent
            if(wcsstr(collationstr.GetAsWideChar(), charsetname) == NULL)
                SendMessage(hwndcombo, CB_DELETESTRING, ret, 0);
        }
        else if((relcollation = wcsstr(collationstr.GetAsWideChar(), charsetname)) != NULL)
        {
            // Add the relevent items
            if(collationstr.GetCharAt(selcharsetlen) == '_')
                SendMessage(hwndcombo, CB_ADDSTRING, 0, (LPARAM)collationstr.GetAsWideChar());
        }
    }
    pcquerywnd->m_tunnel->mysql_free_result(myres);
    SendMessage(hwndcombo, CB_SETCURSEL, (WPARAM)0, 0);
}
void    
ConnectionCommunity::OnConnect(ConnectionInfo *dbname)
{
	Tunnel		*tunnel;
    MYSQL		*mysql;
	HWND		lastfocus = GetFocus();
	
    tunnel = CreateTunnel(wyFalse);

	if( ! tunnel )
	{
		return;
	}

	dbname->m_tunnel = tunnel;

    mysql = ConnectToMySQL(dbname);

	if(mysql == NULL)
    {
        delete tunnel;
		tunnel = NULL;
		SetFocus(lastfocus);
	}
    else if(dbname->m_db.GetLength() ==0 || (IsDatabaseValid(dbname->m_db, mysql, tunnel) == wyTrue))
    {
		dbname->m_mysql = mysql;
		dbname->m_tunnel = tunnel;
		if(!pGlobals->m_conrestore)
		{
			m_rgbobbkcolor = dbname->m_rgbconn;
			m_rgbobfgcolor = dbname->m_rgbfgconn;
		}
		pGlobals->m_isconnected = wyTrue;
	}
	else
	{
		ShowMySQLError(NULL, tunnel, &mysql, NULL, wyTrue);
		return;
	}

}
Exemplo n.º 14
0
//Getting databases from MySQL by executing show databases query
wyInt32  
DBListBuilder::GetDBFromServers(HWND hwnd, LPARAM lparam)
{
	HWND            hwndcombo;
	wyInt32         ret;
	MDIWindow		*pcquerywnd=NULL, *wnd=NULL;
	wyWChar         classname[SIZE_512] = {0};
	wyString        dbname, findvalue;
	LPDIFFCOMBOITEM	pdiffcombo = NULL;

	MYSQL_RES			*myres=NULL;
	MYSQL_ROW			myrow;
	wyString            query, database;

    hwndcombo =(HWND)lparam;
	
	VERIFY(GetClassName(hwnd, classname, SIZE_512 - 1));

	VERIFY(wnd = GetActiveWin());

	SetCursor(LoadCursor(NULL, IDC_WAIT));

	if((wcscmp(classname, QUERY_WINDOW_CLASS_NAME_STR)== 0))
    {
		VERIFY(pcquerywnd = (MDIWindow*)GetWindowLongPtr(hwnd, GWLP_USERDATA));
			
		// execute query to get all the database names.
		query.Sprintf("show databases");
        myres = ExecuteAndGetResult(pcquerywnd, pcquerywnd->m_tunnel, &pcquerywnd->m_mysql, query);

		if(!myres)
		{
			ShowMySQLError(hwnd, pcquerywnd->m_tunnel, &pcquerywnd->m_mysql, query.GetString());
			goto cleanup;
		}
		
		while(myrow = pcquerywnd->m_tunnel->mysql_fetch_row(myres))	
		{
			database.SetAs(myrow[0]);
			dbname.SetAs(database);
			/* starting from 4.1 BETA 4 we use connection name for unique values */
			findvalue.Sprintf("%s - %s", pcquerywnd->m_title.GetString(), dbname.GetString());

			// find it. if not found add it.
			ret = SendMessage(hwndcombo, CB_FINDSTRINGEXACT, -1,(LPARAM)findvalue.GetAsWideChar());

			if(ret == CB_ERR)
            {
				ret = SendMessage(hwndcombo, CB_ADDSTRING, 0,(LPARAM)findvalue.GetAsWideChar());

				pdiffcombo = new DIFFCOMBOITEM;
				
				//wcscpy(pdiffcombo->szDB, database.GetAsWideChar());
				wcsncpy(pdiffcombo->szDB, database.GetAsWideChar(), SIZE_128 - 1);
				pdiffcombo->szDB[SIZE_128 - 1] = '\0';
                
				pdiffcombo->wnd = pcquerywnd;
				
				pdiffcombo->mysql = &pcquerywnd->m_mysql;
				pdiffcombo->tunnel = pcquerywnd->m_tunnel;
				pdiffcombo->info = &pcquerywnd->m_conninfo;

				SendMessage(hwndcombo, CB_SETITEMDATA, ret, (LPARAM)pdiffcombo);
			}
		}

		pcquerywnd->m_tunnel->mysql_free_result(myres);
	}

	SetCursor(LoadCursor(NULL, IDC_ARROW));
	return wyTrue;

cleanup:
		SetCursor(LoadCursor(NULL, IDC_ARROW));
		return wyFalse;	
}
void
ConnectionCommunity::OnConnect(HWND hwnd, ConnectionInfo * dbname)
{
	Tunnel		*tunnel;
    MYSQL		*mysql;
	HWND		lastfocus = GetFocus();
	wyString	conn, temp, dirnamestr;
	wyWChar		directory[MAX_PATH + 1] = {0}, *lpfileport = 0, pass[MAX_PATH + 1] = {0};
	HWND		hwndcombo;
	wyInt32		count, storepwd, ret;

//	DEBUG_ENTER("clicked ok");

    tunnel = CreateTunnel(wyFalse);

//	DEBUG_LOG("created tunnel");

	// Call ConnectToMySQL function to initialize a new mySQL structure and connect to
	// mySQL server with the connection details. The function will return a valid mysql
	// pointer if connection successful and if not then it will return NULL.
	// If null then show the standard mySQL errors given by the mySQL API.
	/* set correct values for tunnel to use HTTP authentication */
	dbname->m_tunnel = tunnel;

    mysql = ConnectToMySQL(hwnd, dbname);
	if(mysql == NULL)
    {
        delete tunnel;
		SetFocus(lastfocus);
	} 
    else if(dbname->m_db.GetLength() ==0 ||(IsDatabaseValid(dbname->m_db, mysql, tunnel) == wyTrue))
    {
		// Successful so write the current details in connection .ini file 
		// so that when the user uses the software again it will show the same details.
		dbname->m_mysql = mysql;
		dbname->m_tunnel = tunnel;

		WriteConnDetails(hwnd);

		ret = SearchFilePath(L"sqlyog", L".ini", MAX_PATH, directory, &lpfileport);
		if(ret == 0)
        {
		    yog_enddialog(hwnd, (wyInt32)1);
			return;
		}
		
		/* if the user has changed any information then we ask him whether he wants to save */
		if(m_conndetaildirty == wyTrue)
		{
			if(ConfirmAndSaveConnection(hwnd, wyTrue) == wyFalse)
				return;
		}
		else 
        {
			/*	even if he has not selected to save, we need to check for password thing
				as the user might diable on the store_password first and then make
				modification to the password, in that case the state will not be dirty
				and the value will not be stored */
			VERIFY(hwndcombo = GetDlgItem(hwnd, IDC_DESC));

			count  = SendMessage(hwndcombo, CB_GETCOUNT, 0, 0);

			if(!count)
            {
				yog_enddialog(hwnd,(wyInt32)1);
				return;
			}

			VERIFY ((count = SendMessage(hwndcombo, CB_GETCURSEL, 0, 0))!= CB_ERR);
			count = SendMessage(hwndcombo, CB_GETITEMDATA, count, 0);
			conn.Sprintf("Connection %u", count);

			storepwd = Button_GetCheck(GetDlgItem(hwnd, IDC_DLGCONNECT_STOREPASSWORD));

			/* now we only save the password if the user has asked for otherwise we remove it only */
			/* feature implemented in v5.0 */
			dirnamestr.SetAs(directory);
            //WritePrivateProfileStringA(conn.GetString(), "Password01", NULL, dirnamestr.GetString());
			wyIni::IniDeleteKey(conn.GetString(), "Password01", dirnamestr.GetString());
			if(!storepwd)
            {
				//WritePrivateProfileStringA(conn.GetString(), "Password", NULL, dirnamestr.GetString());
				wyIni::IniDeleteKey(conn.GetString(), "Password", dirnamestr.GetString());
            }
            else
            {
                GetWindowText(GetDlgItem(hwnd, IDC_DLGCONNECT_PASSWORD), pass, MAX_PATH);
                temp.SetAs(pass);
                EncodePassword(temp);
                wyIni::IniWriteString(conn.GetString(), "Password", temp.GetString(), dirnamestr.GetString());
            }
			
			/* write the store password value too */
			temp.Sprintf("%d", storepwd);
			ret =	wyIni::IniWriteString (conn.GetString(), "StorePassword", temp.GetString(), dirnamestr.GetString());
		}

		m_rgbobbkcolor = m_rgbconnection;
		m_rgbobfgcolor = m_rgbconnectionfg;

		yog_enddialog(hwnd,(wyInt32)1);
	}
	else
	{
		ShowMySQLError(hwnd, tunnel, &mysql, NULL, wyTrue);

		//fix a bug, database neme was erasing on error
		//SendMessage(GetDlgItem(hwnd, IDC_DLGCONNECT_DATABASE), WM_SETTEXT, 0,(LPARAM)L"");

		SetFocus(GetDlgItem(hwnd,IDC_DLGCONNECT_DATABASE));
		return;
	}
}
// Connect to a mysql server with the given details and return a valid MYSQl* connection handle
// and if there is an error it return NULL
MYSQL *
ConnectionCommunity::ConnectToMySQL(HWND hdlg, ConnectionInfo *coninfo)
{
	Tunnel			*tunnel = coninfo->m_tunnel;
	wyUInt32		portno, client=0;
	wyInt32         ret;
    wyWChar         host[SIZE_512]={0}, user[SIZE_512]={0}, timeout[32] = {0};
	wyWChar			pwd[SIZE_512]={0}, port[10]={0};
	MYSQL           *mysql, *temp;
    wyString        strinitcommand;

	SetCursor(LoadCursor(NULL, IDC_WAIT));

	InitConnectionDetails(coninfo);

	// FIRST initialize the object.
	VERIFY(mysql = tunnel->mysql_init((MYSQL*)0));
	temp = mysql;

	// Get all the information.
	ret = SendMessage(GetDlgItem(hdlg, IDC_DLGCONNECT_HOST), WM_GETTEXT,(WPARAM)SIZE_512-1, (LPARAM)host);
	ret = SendMessage(GetDlgItem(hdlg, IDC_DLGCONNECT_USER), WM_GETTEXT,(WPARAM)SIZE_512-1, (LPARAM)user);
	ret = SendMessage(GetDlgItem(hdlg, IDC_DLGCONNECT_PORT), WM_GETTEXT,(WPARAM)9, (LPARAM)port);
	ret = SendMessage(GetDlgItem(hdlg, IDC_DLGCONNECT_PASSWORD), WM_GETTEXT,(WPARAM)SIZE_512-1, (LPARAM)pwd);

	portno = _wtoi(port);

	coninfo->m_host.SetAs(host);
	//to trim empty spaces from right, to avoid mysql errors
	coninfo->m_host.RTrim();

	coninfo->m_user.SetAs(user);
	//to trim empty spaces from right, to avoid mysql errors
	coninfo->m_user.RTrim();
	
	coninfo->m_pwd.SetAs(pwd); 
	coninfo->m_port = portno;
	coninfo->m_ishttp = wyFalse;
	coninfo->m_issslchecked = wyFalse;

	coninfo->m_hprocess      = INVALID_HANDLE_VALUE;
	coninfo->m_isssh         = wyFalse;
	coninfo->m_origmysqlport = 0;

	//Compress protocol settings
	ret =(SendMessage(GetDlgItem(hdlg, IDC_COMPRESS), BM_GETCHECK, 0, 0));
	(ret == BST_CHECKED) ? coninfo->m_iscompress = wyTrue : coninfo->m_iscompress = wyFalse;

	//send password in cleartext settings
	/*ret =(SendMessage(GetDlgItem(hdlg, IDC_ISCLEARTEXT), BM_GETCHECK, 0, 0));
	(ret == BST_CHECKED) ? coninfo->m_ispwdcleartext = wyTrue : coninfo->m_ispwdcleartext = wyFalse;*/	

	//Session wait_timeout settings
	ret =(SendMessage(GetDlgItem(hdlg, IDC_TIMEOUTDEF), BM_GETCHECK, 0, 0));
	if(ret == BST_CHECKED) 
	{
		coninfo->m_isdeftimeout = wyTrue;
		coninfo->m_strwaittimeout.SetAs("28800");
	}
	else
	{
		coninfo->m_isdeftimeout = wyFalse;	
		ret = SendMessage(GetDlgItem(hdlg, IDC_TIMEOUTEDIT), WM_GETTEXT,(WPARAM)32-1, (LPARAM)timeout);
		if(wcslen(timeout))
			coninfo->m_strwaittimeout.SetAs(timeout);
        
		else
			coninfo->m_strwaittimeout.SetAs("28800");
	}

	//Get SQL_Mode settings
	GetSqlModeSettings(hdlg, coninfo);

    //..Getting & Setting init_command if the connection is not http
    if(!tunnel->IsTunnel())
    {
		GetInitCommands(hdlg, coninfo);
		strinitcommand.SetAs("set names 'utf8';");
		strinitcommand.Add(coninfo->m_initcommand.GetString());
		ExecuteInitCommands(mysql, tunnel, coninfo->m_initcommand);
    }

    GetKeepAliveInterval(hdlg, coninfo);

	SetMySQLOptions(coninfo, tunnel, &mysql);

	mysql	= tunnel->mysql_real_connect(mysql, coninfo->m_host.GetString(), coninfo->m_user.GetString(), coninfo->m_pwd.GetString(), NULL, coninfo->m_port, NULL, client | CLIENT_MULTI_RESULTS | CLIENT_REMEMBER_OPTIONS, coninfo->m_url.GetString());

	if(!mysql)
    {
		ShowMySQLError(hdlg, tunnel, &temp, NULL, wyTrue);
		tunnel->mysql_close(temp);
		SetCursor(LoadCursor(NULL, IDC_WAIT));
		return NULL;
	}
		
	GetOtherValues(hdlg, coninfo);
    SetCursor(LoadCursor(NULL, IDC_WAIT));

	return mysql;	
}
/* Function just tests the connection and checks whether it is correct or not */
wyBool 
ConnectionCommunity::TestConnection(HWND hwnd, wyBool showmsg /*=wyTrue*/)
{
	ConnectionInfo	dbname; 
	MYSQL			*mysql;
	Tunnel			*tunnel;
    wyString	    query("select version()"), version;
	wyInt32         ret;
	MYSQL_RES	    *res;
	MYSQL_ROW	    row;
	wyString		myrowstr;

	InitConnectionDetails(&dbname);

    tunnel = CreateTunnel(wyFalse);
	dbname.m_tunnel = tunnel;

	// Call ConnectToMySQL function to initialize a new mySQL structure and connect to
	// mySQL server with the connection details. The function will return a valid mysql
	// pointer if connection successful and if not then it will return NULL.
	// If null then show the standard mySQL errors given by the mySQL API.
	//if database name is not correct, then throw error
	mysql = pGlobals->m_pcmainwin->m_connection->ConnectToMySQL(hwnd, &dbname);
	if(mysql == NULL)
    {
        if(tunnel)
            delete tunnel;
		return wyFalse;
	} 
	else if((dbname.m_db.GetLength() != 0) && (IsDatabaseValid(dbname.m_db, mysql, tunnel) == wyFalse))
	{
		query.Clear();
		goto cleanup;
	}

	/* now we send a test query "select version()", if everything is ok then we show a message
	   with the version number */
	ret = HandleMySQLRealQuery(tunnel, mysql, query.GetString(), query.GetLength(), false);

	if(ret)
		goto cleanup;

	res = tunnel->mysql_store_result(mysql);
	if(!res && mysql->affected_rows == -1)
		goto cleanup;

	row = tunnel->mysql_fetch_row(res);
	
	myrowstr.SetAs(row[0], IsMySQL41(dbname.m_tunnel, &mysql));
	version.Sprintf(_("Connection successful!\nMySQL version: %s"), myrowstr.GetString());

	if(showmsg)
		yog_message(hwnd, version.GetAsWideChar(), _(L"Connection Info"), MB_OK | MB_ICONINFORMATION);

	tunnel->mysql_free_result(res);
	tunnel->mysql_close(mysql);

	delete	tunnel;

	return wyTrue;

cleanup:
	if(query.GetLength())
		ShowMySQLError(hwnd, tunnel, &mysql, query.GetString());
	else
		ShowMySQLError(hwnd, tunnel, &mysql, NULL, wyTrue);
    delete tunnel;
	return wyFalse;
}