Raised This Month: $12 Target: $400
 3% 

Solved SQL switching between local and remote database


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
georgik57
Veteran Member
Join Date: Oct 2008
Location: 🎧Music World
Old 02-26-2017 , 13:14   SQL switching between local and remote database
Reply With Quote #1

EDIT3: Solved. Code updated. Any help is appreciated with the to-do list.

EDIT2: Everything (hopefully) solved. Code updated.
Need help with being able to select between local and remote database by code on map start.
I'm currently forcing it to save locally by enabling sqlite in modules.ini, which forces all the other SQL plugins to do the same and is very inconvenient.
Is it possible to have a SQL plugin use a local database while another uses a remote one?

EDIT: It worked using the SQL_Connect handle return as first parameter, but it only inserts a single database entry with NULL values on Name, AuthID and Address. Code updated.

PS: The database structure for everyone that doesn't want to figure it out by reading the code.




So I'm having some trouble using this native.

As far as I understood, it replaces any characters that could mess up our query code.
Quote:
Originally Posted by sqlx.inc
/**
* Back-quotes characters in a string for database querying.
* Note: The buffer's maximum size should be 2*strlen(string) to catch
* all scenarios.
*
* @param db Database handle for localization, or Empty_Handle
* for when a handle is not available.
* @param buffer Buffer to copy to.
* @param buflen Maximum size of the buffer.
* @param string String to backquote (should not overlap buffer).
* @return Length of new string, or -1 on failure.
*/
native SQL_QuoteString(Handle:db, buffer[], buflen, const string[]);
I've tried using it with Empty_Handle and got this error(even if the native documentation clearly states that you can use it):
Quote:
Originally Posted by error_20170226.log
L 02/26/2017 - 20:01:59: [SQLITE] Invalid database handle: 0
L 02/26/2017 - 20:01:59: [AMXX] Displaying debug trace (plugin "zpnm_gp_stats_save_sql.amxx")
L 02/26/2017 - 20:01:59: [AMXX] Run time error 10: native error (native "SQL_QuoteString")
L 02/26/2017 - 20:01:59: [AMXX] [0] zpnm_gp_stats_save_sql.sma::fwTaskSQLQueryAcc Find (line 529)
I've also tried using it with the connection handle and got this error:
Quote:
Originally Posted by error_20170226.log
L 02/26/2017 - 20:04:27: [SQLITE] Invalid database handle: 1
L 02/26/2017 - 20:04:27: [AMXX] Displaying debug trace (plugin "zpnm_gp_stats_save_sql.amxx")
L 02/26/2017 - 20:04:27: [AMXX] Run time error 10: native error (native "SQL_QuoteString")
L 02/26/2017 - 20:04:27: [AMXX] [0] zpnm_gp_stats_save_sql.sma::fwTaskSQLQueryAcc Find (line 529)
Here is the code.
Note that in order for it to work, sqlite module must be uncommented inside modules.ini.

The plug-in is intended for use with Zombie Plague Nightmare Mode.

bitsums.inc
D7Debug.inc

PHP Code:
/*
To do:

T = needs testing
X = done
- = cancelled

[T] make sure the user hasn't disconnected before the query has been executed
[T] make sure the user hasn't been replaced before the account load or biggest line query has been executed
    [T] support name changing bots
[T] make sure the user doesn't already have the account loaded when the account load or biggest line query is executed
[T] remove_task for account load and biggest line queries after confirming same user to avoid unnecessary extra query threads
[T] don't allow any more queries to be threaded after map end
v0.0.9
[T] save all data for all player in a single thread on round end
v0.1.0
[T] disconnect support
[T] individual query for each player on events with tasks for query spamming avoid
[T] change md5 key too along with the query
v0.1.3
[T] fix new lines still having null data
[T] last online time user and system friendly
[T] force local/remote saving without having to modify modules.ini
v0.1.6
[T] local/remote switching support
[T] cvars for connection data
[T] save previously connected player's data from the same server slot even if the task wasn't running
    (to support upcoming player/global event save choosing)
[T] delay players' account queries until last line id is retrieved
[T] make sure we only save a disconnected account once
v0.2.1
[T] instantly load accounts on putinserver if the database is done creating and connecting
v0.2.2
[ ] extend map time on time end to allow all queries to be executed and then change it
[ ] don't allow any more queries to be threaded after map time end
[ ] fix error when class is removed
[ ] see why some queries are threaded twice
[ ] optimize
[ ] cvar to choose between player and global event saving
[ ] find a way to cover all disconnects
[ ] adapt the query code to make sure it succesfully executes on the currently used module
[ ] only execute queries if at least one data part has changed
[ ] auto modify the table if same name one exists and differs from ours
[ ] add (single player) data resetting or removing time or command based
[ ] 
*/

#include <amxmodx>
#include <fakemeta>
#include <sqlx>

#include <zombieplaguenightmare>

#include <bitsums>
#include <D7Debug>



#pragma reqlib sqlite
#pragma reqlib mysql

#pragma loadlib sqlite
#pragma loadlib mysql



enum (+= 32)
{
    
g_iIDTaskAccountLoad 99999,
    
g_iIDTaskAccountSave
}

new const 
g_szSQLTableName[] = "PlayerData";

enum _:g_iEnumTableColumns
{
    
g_iIDClName,
    
g_iIDClAuthID,
    
g_iIDClAddress,
    
g_iIDClLastOnline,
    
g_iIDClAmmoPacks,
    
g_iIDClClassZombie,
    
g_iIDClClassHuman,
    
g_iIDClLineID,
    
g_iIDClMD5Key,
    
g_iIDClLastOnlineSys
//    KeyType,
}

new const 
g_szSQLTableColumnNames[g_iEnumTableColumns][] =
{
    
"Name",
    
"AuthID",
    
"Address",
    
"LastOnline",
    
"AmmoPacks",
    
"ClassZombie",
    
"ClassHuman",
    
"LineID",
    
"MD5Key",
    
"LastOnlineSys"
//    "KeyType",
}

new const 
g_szSQLTableColumnProperties[g_iEnumTableColumns][] =
{
    
"TEXT",
    
"TEXT",
    
"TEXT",
    
"TEXT",
    
"INTEGER DEFAULT -1",
    
"INTEGER DEFAULT -1",
    
"INTEGER DEFAULT -1",
    
"INTEGER PRIMARY KEY UNIQUE AUTOINCREMENT",//
    
"TEXT",
    
"INTEGER"
//    "INTEGER",// DEFAULT -1
}

enum _:g_iEnumKeys
{
    
KeyAuthID,
    
KeyAddress,
    
KeyName
}

enum _:g_iEnumTypeConnection
{
    
ConnectionSQLite,
    
ConnectionMySQL
}

//4 32-bit limited numbers
//SQL Query code and other characters
//Players
/* + sizeof g_szSQLTableColumnNames[MD5Key] + sizeof g_szSQLTableColumnNames[KeyType]*/
//const g_iSizeSzQuery = (sizeof g_szSQLTableName + sizeof g_szSQLTableColumnNames[LineID] + sizeof g_szSQLTableColumnNames[AmmoPacks] + sizeof g_szSQLTableColumnNames[ClassZombie] + sizeof g_szSQLTableColumnNames[ClassHuman] + (11 * 4) + 44) * 32;

new Handle:g_iIDSQLTuple,
Handle:g_iIDSQLConnection,
g_szSQLHandle[32],
g_szSQLQuery[1024],//g_iSizeSzQuery
g_szSQLHandleData[50],
Float:g_fDelayTaskExecuting,
g_bRoundEnded,
g_iIDPCVarKey,
g_iIDPCVarDBAddress,
g_iIDPCVarDBUser,
g_iIDPCVarDBPassword,
g_iIDPCVarDBName,
g_szName[33][32],
g_szAuthID[33][35],
//255.255.255.255:65535
g_szAddress[33][22],
g_szNameSQL[33][sizeof g_szName[] * 2],
g_szAuthIDSQL[33][sizeof g_szAuthID[] * 2],
g_szAddressSQL[33][sizeof g_szAddress[] * 2],
g_iAmmoPacks[33],
g_iIDClassZombie[33],
g_iIDClassHuman[33],
g_iIDLine[33],
g_szMD5Key[33][g_iEnumKeys][34],
g_iCacheCVarKey,
g_iLastLineID,
g_iTypeConnection//,
//g_iCountQueries;

new g_iBsAuthorizedg_iBsBotg_iBsConnectedg_iBsAccountLoaded;

//new g_iSQLQueryData[g_iEnumTableColumns][99],
//g_szSQLQueryDataMD5Key[99][34],

//g_iSQLQuerySlot[33];

new g_iMaxPlayers;

#define is_user_valid(%0) (1 <= %0 <= g_iMaxPlayers)

public plugin_init()
{
    
register_plugin("[ZPNM] Data save SQL""0.2.2""rider, D i 5 7 i n c T")
    
    
register_event("HLTV""fwEvHltvRoundStart""a""1=0""2=0")
    
register_event("TextMsg""fwEvRoundEnd""a""2=#Game_Commencing")
    
register_event("TextMsg""fwEvRoundEnd""a""2=#Game_will_restart_in")
    
    
register_logevent("fwEvRoundEnd"2"1=Round_End")
    
    
register_forward(FM_ClientUserInfoChanged"fwFmClientUserInfoChanged"1)
    
    new 
szKey[2];
    
num_to_str(KeyNameszKeycharsmax(szKey))
    
    
g_iIDPCVarKey register_cvar("ZPNMDataKey"szKey);
    
g_iIDPCVarDBAddress register_cvar("ZPNMDataDBAddress""127.0.0.1");
    
g_iIDPCVarDBUser register_cvar("ZPNMDataDBUser""");
    
g_iIDPCVarDBPassword register_cvar("ZPNMDataDBPassword""");
    
g_iIDPCVarDBName register_cvar("ZPNMDataDBName""ZPNMData");
    
    
g_iMaxPlayers get_maxplayers();
    
    
g_fDelayTaskExecuting 0.1;
    
    
set_task(g_fDelayTaskExecuting"fwTaskSQLInitCreateTable")
    
    
register_clcmd("say /save""fwClCMDSaySave")
}

public 
fwFmClientUserInfoChanged(const iID)//, const iIDBuffer
{
    if (!
is_user_connected(iID) || !bitsum_get(g_iBsAccountLoadediID))
        return;
    
    static 
szName[sizeof g_szName[]];
    
    
get_user_name(iIDszNamecharsmax(szName))
    
    if (
equali(szNameg_szName[iID]))
        return;
    
    
g_szName[iID] = szName;
    
    
formatex(g_szNameSQL[iID], charsmax(g_szNameSQL[]), "%s"g_szName[iID])
    
strtolower(g_szNameSQL[iID])
    
    if (
bitsum_get(g_iBsBotiID))
    {
        
format(g_szNameSQL[iID], charsmax(g_szNameSQL[]), "^"%s^""g_szNameSQL[iID])
    }
    
    
md5(g_szNameSQL[iID], g_szMD5Key[iID][KeyName])
    
    
SQL_QuoteString(g_iIDSQLConnectiong_szNameSQL[iID], charsmax(g_szNameSQL[]), g_szName[iID])
    
    
remove_task(iID g_iIDTaskAccountSave)
    
set_task(5.0"fwTaskSQLQueryAccSave"iID g_iIDTaskAccountSave)
}

public 
fwClCMDSaySave(const iID)
{
    
fwEvRoundEnd()
}

public 
fwSQLHandleLogFree(const iFailstate, const Handle:iIDHandleQuery, const szError[], const iIDError)//, const szData[], const iSizeData, const Float:fTimeQueue
{
    if (
iFailstate == TQUERY_CONNECT_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleLogFree] Load - Could not connect to SQL database. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    else if (
iFailstate == TQUERY_QUERY_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleLogFree] Load Query failed. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    
/*    new iID = str_to_num(szData);
    
    if (!is_user_valid(iID) || !bitsum_get(g_iBsConnected, iID))
    {
        //log_error(AMX_ERR_GENERAL, "[fwSQLHandleLogFree] User disconnected before the query could be completed.")
        
        goto GoToFreeHandle;
    }
    */
    
GoToFreeHandle:
    
    
SQL_FreeHandle(iIDHandleQuery)
}

public 
fwTaskSQLInitCreateTable()
{
    new 
szDBAddress[64],
    
szDBUser[32],
    
szDBPassword[32],
    
szDBName[128];
    
    
get_pcvar_string(g_iIDPCVarDBAddressszDBAddresscharsmax(szDBAddress))
    
get_pcvar_string(g_iIDPCVarDBUserszDBUsercharsmax(szDBUser))
    
get_pcvar_string(g_iIDPCVarDBPasswordszDBPasswordcharsmax(szDBPassword))
    
get_pcvar_string(g_iIDPCVarDBNameszDBNamecharsmax(szDBName))
    
    if (!
szDBAddress[0] || equali(szDBAddress"127.0.0.1"))
    {
        if (!
szDBAddress[0])
            
formatex(szDBAddresscharsmax(szDBAddress), "127.0.0.1")
        
        
SQL_SetAffinity("sqlite");
        
        
g_iTypeConnection ConnectionSQLite;
    }
    else
    {
        
SQL_SetAffinity("mysql");
        
        
g_iTypeConnection ConnectionMySQL;
    }
    
    
ftD7Log(__"[fwTaskSQLInitCreateTable] Making DB Tuple: ^"%s^", ^"%s^", ^"%s^", ^"%s^". g_iTypeConnection: ^"%s^".",
    
szDBAddressszDBUserszDBPasswordszDBName, (g_iTypeConnection == ConnectionSQLite) ? "SQLite" "MySQL")
    
    
g_iIDSQLTuple SQL_MakeDbTuple(szDBAddressszDBUserszDBPasswordszDBName);
/*    
    // I have no idea what I'm doing
    if (g_iIDSQLTuple == Empty_Handle)
    {
        //SQL_FreeHandle(g_iIDSQLTuple)
        
        set_fail_state("SQL_MakeDbTuple FAILED!")
        
        return;
    }*/
    
    
new iTempszError[512];
    
    
g_iIDSQLConnection SQL_Connect(g_iIDSQLTupleiTempszErrorcharsmax(szError));
    
    if (
g_iIDSQLConnection == Empty_Handle)
    {
        
//SQL_FreeHandle(g_iIDSQLConnection)
        
        
set_fail_state(szError)
        
        
//goto GoToFreeHandle;
        
return;
    }
    
    
formatex(g_szSQLHandlecharsmax(g_szSQLHandle), "fwSQLHandleLogFree")
    
    
iTemp 0;
    
    
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"CREATE TABLE IF NOT EXISTS `%s` ("g_szSQLTableName);
    
    for (new 
iID 0iID g_iEnumTableColumnsiID++)
    {
        if (!
g_szSQLTableColumnNames[iID][0])// || !g_szSQLTableColumnProperties[iID][0]
            
continue;
        
        
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"%s`%s` %s", (g_szSQLQuery[iTemp 1] != '(') ? ", " ""g_szSQLTableColumnNames[iID], g_szSQLTableColumnProperties[iID]);
    }
    
    
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp")");
    
    if (
g_iTypeConnection == ConnectionSQLite)
    {
        
replace_all(g_szSQLQuerycharsmax(g_szSQLQuery), "AUTOINCREMENT""")
        
        
trim(g_szSQLQuery)
        
        
replace_all(g_szSQLQuerycharsmax(g_szSQLQuery), "  "" ")
        
replace_all(g_szSQLQuerycharsmax(g_szSQLQuery), " ,"",")
    }
    
    
g_szSQLHandleData "";
    
    
fwTaskSQLThreadQuery()
    
    
g_fDelayTaskExecuting 0.0;
    
    
formatex(g_szSQLHandlecharsmax(g_szSQLHandle), "fwSQLHandleGetBiggestLineID")
    
    
formatex(g_szSQLQuerycharsmax(g_szSQLQuery), "SELECT `%s` FROM `%s` ORDER BY `%s` DESC LIMIT 1"g_szSQLTableColumnNames[g_iIDClLineID], g_szSQLTableNameg_szSQLTableColumnNames[g_iIDClLineID])
    
    
g_szSQLHandleData "";
    
    
fwTaskSQLThreadQuery();
/*    
    g_fDelayTaskExecuting = 0.1;
    
    set_task(g_fDelayTaskExecuting, "fwTaskSQLThreadQuery")
    
    GoToFreeHandle:
    
    SQL_FreeHandle(g_iIDSQLConnection)*/
}

public 
fwTaskSQLThreadQuery()
{
/*    if (g_iIDSQLTuple == Empty_Handle)
        return;
    */
    
SQL_ThreadQuery(g_iIDSQLTupleg_szSQLHandleg_szSQLQueryg_szSQLHandleDatacharsmax(g_szSQLHandleData))
    
    static 
Float:fGameTimeLast;
    
    
replace_all(g_szSQLQuerycharsmax(g_szSQLQuery), ";"";^n")
    
    
ftD7Log(__"[fwTaskSQLThreadQuery] g_szSQLQuery:^n\
    %s.^n\
    g_szSQLHandleData: ^"
%s^".^n\
    Time since last query: %f."
g_szSQLQueryg_szSQLHandleDataget_gametime() - fGameTimeLast)
    
    
fGameTimeLast get_gametime();
    
    
//g_fDelayTaskExecuting = 0.0;
}
/*
public fwClCmdSaySave(const iID)
{
    SaveAccount(iID)
}

public fwClCmdSayLoad(const iID)
{
    fwTaskSQLQueryAccFind(iID + g_iIDTaskAccountLoad)
}*/

public client_authorized(iID)
{
    
bitsum_add(g_iBsAuthorizediID)
    
    if (
is_user_bot(iID))
        
bitsum_add(g_iBsBotiID)
    
    if (
bitsum_get(g_iBsConnectediID))
        if (
g_fDelayTaskExecuting)
            
set_task(g_fDelayTaskExecuting"fwTaskSQLQueryAccFind"iID g_iIDTaskAccountLoad)
        else
            
fwTaskSQLQueryAccFind(iID g_iIDTaskAccountLoad)
}

public 
client_putinserver(iID)
{
    
bitsum_add(g_iBsConnectediID)
    
    
remove_task(iID g_iIDTaskAccountSave)
    
fwTaskSQLQueryAccSave(iID g_iIDTaskAccountSave)
    
    
bitsum_del(g_iBsAccountLoadediID)
    
    
g_iCacheCVarKey clamp(get_pcvar_num(g_iIDPCVarKey), 13);
    
    if (
bitsum_get(g_iBsAuthorizediID))
        if (
g_fDelayTaskExecuting)
            
set_task(g_fDelayTaskExecuting"fwTaskSQLQueryAccFind"iID g_iIDTaskAccountLoad)
        else
            
fwTaskSQLQueryAccFind(iID g_iIDTaskAccountLoad)
}

public 
client_disconnect(iID)
{
    
bitsum_del(g_iBsAuthorizediID)
    
bitsum_del(g_iBsConnectediID)
    
bitsum_del(g_iBsBotiID)
    
    
remove_task(iID g_iIDTaskAccountLoad)
}

public 
fwEvHltvRoundStart()
{
    
g_bRoundEnded 0;
}

public 
fwEvRoundEnd()
{
    if (
g_bRoundEnded)
        return;
    
    
g_bRoundEnded 1;
    
    
formatex(g_szSQLHandlecharsmax(g_szSQLHandle), "fwSQLHandleAccUpdate")
    
    for (new 
iID 1iID <= g_iMaxPlayersiID++)
    {
        
//if (!bitsum_get(g_iBsAccountLoaded, iID) && !task_exists(iID + g_iIDTaskAccountSave))
            //continue;
        
        
remove_task(iID g_iIDTaskAccountSave)
        
fwTaskSQLQueryAccSave(iID g_iIDTaskAccountSave)
    }
    
    
g_szSQLHandleData "";
    
    
fwTaskSQLThreadQuery();
}

public 
zpnm_user_spawn_post(iID)
{
    new 
iTemp zpnm_get_user_next_hclass(iID);
    
    if (
iTemp > -1)
        
g_iIDClassHuman[iID] = iTemp;
    else
        
g_iIDClassHuman[iID] = zpnm_get_user_human_class(iID);
    
    
remove_task(iID g_iIDTaskAccountSave)
    
set_task(5.0"fwTaskSQLQueryAccSave"iID g_iIDTaskAccountSave)
}

public 
zp_user_infected_post(iID)
{
    new 
iTemp zp_get_user_next_class(iID);
    
    if (
iTemp > -1)
        
g_iIDClassZombie[iID] = iTemp;
    else
        
g_iIDClassZombie[iID] = zp_get_user_zombie_class(iID);
    
    
remove_task(iID g_iIDTaskAccountSave)
    
set_task(5.0"fwTaskSQLQueryAccSave"iID g_iIDTaskAccountSave)
}

public 
zp_user_humanized_post(iID)
{
    
zpnm_user_spawn_post(iID)
}

public 
zpnm_extra_item_buy_attempt(iIDiItemIDbIgnoreCostiCost)
{
    if (
bitsum_get(g_iBsAccountLoadediID))
        return 
PLUGIN_CONTINUE;
    
    return 
ZP_PLUGIN_HANDLED;
}

public 
zpnm_extra_item_selected_post(iIDiItemIDbIgnoreCostiCost)
{
    if (
bIgnoreCost || !iCost || !bitsum_get(g_iBsAccountLoadediID))
        return;
    
    
g_iAmmoPacks[iID] -= iCost;
    
    
remove_task(iID g_iIDTaskAccountSave)
    
set_task(5.0"fwTaskSQLQueryAccSave"iID g_iIDTaskAccountSave)
}

public 
zpnm_user_get_ammo_packs(iID)//, iAmount, iFrom
{
    if (!
bitsum_get(g_iBsAccountLoadediID))//!iAmount || 
        
return;
    
    
g_iAmmoPacks[iID] = zp_get_user_ammo_packs(iID);
    
    
remove_task(iID g_iIDTaskAccountSave)
    
set_task(5.0"fwTaskSQLQueryAccSave"iID g_iIDTaskAccountSave)
}

public 
fwTaskSQLQueryAccSave(iID)
{
    
iID -= g_iIDTaskAccountSave;
    
    if (!
bitsum_get(g_iBsAccountLoadediID))
        return;
/*    else if (!g_iIDLine[iID])
    {
        remove_task(iID + g_iIDTaskAccountSave)
        set_task(5.0, "fwTaskSQLQueryAccSave", iID + g_iIDTaskAccountSave)
        
        return;
    }*/
    
    
if (!bitsum_get(g_iBsConnectediID))
    {
        
bitsum_del(g_iBsAccountLoadediID)
    }
    
    
formatex(g_szSQLHandlecharsmax(g_szSQLHandle), "fwSQLHandleAccUpdate")
    
    static 
szLastOnline[1]
    
get_time("%Y.%m.%d %H:%M:%S"szLastOnlinecharsmax(szLastOnline))
    
    
formatex(g_szSQLQuerycharsmax(g_szSQLQuery), "UPDATE `%s` SET `%s` = '%s', `%s` = '%s', `%s` = '%s', `%s` = '%s', `%s` = '%d', `%s` = '%d', `%s` = '%d', `%s` = '%s', `%s` = '%d' WHERE `%s` = '%d'",
    
g_szSQLTableName,
    
g_szSQLTableColumnNames[g_iIDClName], g_szNameSQL[iID],
    
g_szSQLTableColumnNames[g_iIDClAuthID], g_szAuthIDSQL[iID],
    
g_szSQLTableColumnNames[g_iIDClAddress], g_szAddressSQL[iID],
    
g_szSQLTableColumnNames[g_iIDClLastOnline], szLastOnline,
    
g_szSQLTableColumnNames[g_iIDClAmmoPacks], g_iAmmoPacks[iID],
    
g_szSQLTableColumnNames[g_iIDClClassZombie], g_iIDClassZombie[iID],
    
g_szSQLTableColumnNames[g_iIDClClassHuman], g_iIDClassHuman[iID],
    
g_szSQLTableColumnNames[g_iIDClMD5Key], g_szMD5Key[iID][g_iCacheCVarKey],
    
g_szSQLTableColumnNames[g_iIDClLastOnlineSys], get_systime(),
    
g_szSQLTableColumnNames[g_iIDClLineID], g_iIDLine[iID]);
    
    
g_szSQLHandleData "";
    
    
fwTaskSQLThreadQuery();
}

public 
fwTaskSQLQueryAccFind(iID)
{
    
iID -= g_iIDTaskAccountLoad;
    
    if (!
g_iLastLineID)
    {
        
set_task(1.0"fwTaskSQLQueryAccFind"iID g_iIDTaskAccountLoad)
        
        return;
    }
    
    static 
szAuthID[sizeof g_szAuthID[]], szAddress[sizeof g_szAddress[]], szName[sizeof g_szName[]],
    
szKey[40],
    
szKeyMD5AuthID[34], szKeyMD5Address[34], szKeyMD5Name[34];
    
    new 
iTemp;
    
    
get_user_authid(iIDszAuthIDcharsmax(szAuthID))
    
formatex(szKeycharsmax(szKey), "%s"szAuthID)
    
strtolower(szKey)
    
md5(szKeyszKeyMD5AuthID)
    
    
get_user_ip(iIDszAddresscharsmax(szAddress))
    
formatex(szKeycharsmax(szKey), "%s"szAddress)
    
strtolower(szKey)
    
md5(szKeyszKeyMD5Address)
    
    
get_user_name(iIDszNamecharsmax(szName))
    
formatex(szKeycharsmax(szKey), "%s"szName)
    
strtolower(szKey)
    
    
//ftD7Log(_, _, "[fwTaskSQLQueryAccFind] szAuthID: ^"%s^". szAddress: ^"%s^". szName: ^"%s^".", szAuthID, szAddress, szName)
    
    
if (bitsum_get(g_iBsBotiID))
    {
        
format(szKeycharsmax(szKey), "^"%s^""szKey)
    }
    
    
md5(szKeyszKeyMD5Name)
    
    for (
iTemp 1iTemp <= g_iMaxPlayersiTemp++)
    {
        if (
bitsum_get(g_iBsConnectediTemp))
            continue;
        
        if (!
bitsum_get(g_iBsBotiID))
        {
            if ((!
g_szMD5Key[iTemp][KeyAuthID][0] || !equal(g_szMD5Key[iTemp][KeyAuthID], szKeyMD5AuthID))
            && (!
g_szMD5Key[iTemp][KeyAddress][0] || !equal(g_szMD5Key[iTemp][KeyAddress], szKeyMD5Address))
            && (!
g_szMD5Key[iTemp][KeyName][0] || !equal(g_szMD5Key[iTemp][KeyName], szKeyMD5Name)))
                continue;
        }
        else
        {
            if (!
g_szMD5Key[iTemp][KeyName][0] || !equal(g_szMD5Key[iTemp][KeyName], szKeyMD5Name))
                continue;
        }
        
        
ftD7Log(__"[fwTaskSQLQueryAccFind] Found same recently disconnected account. ^"%s^" - ^"%s^". ^"%s^" - ^"%s^". ^"%s^" - ^"%s^".",
        
szAuthIDg_szAuthID[iTemp], szAddressg_szAddress[iTemp], szNameg_szName[iTemp])
        
        if (
iID != iTemp)
        {
            
g_iIDLine[iID] = g_iIDLine[iTemp];
            
g_iAmmoPacks[iID] = g_iAmmoPacks[iTemp];
            
g_iIDClassHuman[iID] = g_iIDClassHuman[iTemp];
            
g_iIDClassZombie[iID] = g_iIDClassZombie[iTemp];
            
            
g_iIDLine[iTemp] = 0;
            
g_szMD5Key[iTemp][KeyAuthID] = "";
            
g_szMD5Key[iTemp][KeyAddress] = "";
            
g_szMD5Key[iTemp][KeyName] = "";
        }
        
        if (
g_iAmmoPacks[iID] != -1)
            
zp_set_user_ammo_packs(iIDg_iAmmoPacks[iID])
        
        if (
g_iIDClassHuman[iID] > -1)
            
zpnm_set_user_human_class(iIDg_iIDClassHuman[iID])
        
        if (
g_iIDClassZombie[iID] > -1)
            
zp_set_user_zombie_class(iIDg_iIDClassZombie[iID])
        
        
bitsum_add(g_iBsAccountLoadediID)
        
        break;
    }
    
    
g_szAuthID[iID] = szAuthID;
    
g_szAddress[iID] = szAddress;
    
g_szName[iID] = szName;
    
    
SQL_QuoteString(g_iIDSQLConnectiong_szAuthIDSQL[iID], charsmax(g_szAuthIDSQL[]), g_szAuthID[iID])
    
SQL_QuoteString(g_iIDSQLConnectiong_szAddressSQL[iID], charsmax(g_szAddressSQL[]), g_szAddress[iID])
    
SQL_QuoteString(g_iIDSQLConnectiong_szNameSQL[iID], charsmax(g_szNameSQL[]), g_szName[iID])
    
    
g_szMD5Key[iID][KeyAuthID] = szKeyMD5AuthID;
    
g_szMD5Key[iID][KeyAddress] = szKeyMD5Address;
    
g_szMD5Key[iID][KeyName] = szKeyMD5Name;
    
    if (
bitsum_get(g_iBsAccountLoadediID))
        return;
    
    
formatex(g_szSQLHandlecharsmax(g_szSQLHandle), "fwSQLHandleAccLoadCreate")
    
    if (!
bitsum_get(g_iBsBotiID))
    {
        
formatex(g_szSQLQuerycharsmax(g_szSQLQuery), "SELECT * FROM `%s` WHERE `%s` = '%s' OR `%s` = '%s' OR `%s` = '%s'",
        
g_szSQLTableNameg_szSQLTableColumnNames[g_iIDClMD5Key], g_szMD5Key[iID][KeyAuthID],
        
g_szSQLTableColumnNames[g_iIDClMD5Key], g_szMD5Key[iID][KeyAddress],
        
g_szSQLTableColumnNames[g_iIDClMD5Key], g_szMD5Key[iID][KeyName]);
    }
    else
    {
        
formatex(g_szSQLQuerycharsmax(g_szSQLQuery), "SELECT * FROM `%s` WHERE `%s` = '%s'",
        
g_szSQLTableNameg_szSQLTableColumnNames[g_iIDClMD5Key], g_szMD5Key[iID][KeyName])
    }
    
    
formatex(g_szSQLHandleDatacharsmax(g_szSQLHandleData), "%d %s"iIDftUserGetAddress(iID))
    
    
fwTaskSQLThreadQuery();
}
/*
ftMD5String(const szString[])
{
    static szStringMD5[34];
    
    md5(szString, szStringMD5)
    
    return szStringMD5;
}

ftKeyGet(const iID)
{
    static szKey[40];
    
    if (g_iCacheCVarKey == KeyAuthID)
    {
        get_user_authid(iID, szKey, charsmax(szKey))
    }
    else if (g_iCacheCVarKey == KeyAddress)
    {
        get_user_ip(iID, szKey, charsmax(szKey))
    }
    else if (g_iCacheCVarKey == KeyName)
    {
        get_user_name(iID, szKey, charsmax(szKey))
    }
    
    strtolower(szKey)
    
    return szKey;
}*/

public fwSQLHandleGetBiggestLineID(const iFailstate, const Handle:iIDHandleQuery, const szError[], const iIDError, const szData[], const iSizeData, const Float:fTimeQueue)
{
    if (
iFailstate == TQUERY_CONNECT_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleGetBiggestLineID] Load - Could not connect to SQL database. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    else if (
iFailstate == TQUERY_QUERY_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleGetBiggestLineID] Load Query failed. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    
    
//if (!g_iLastLineID)
    //{
    
if (SQL_NumResults(iIDHandleQuery))
        
g_iLastLineID SQL_ReadResult(iIDHandleQuery0) + 1;
    else
        
g_iLastLineID 1;
    
//}
    //else
        //g_iLastLineID++;
    /*
    static szID[3];
    formatex(szID, charsmax(szID), szData)
    
    new iTemp = contain(szID, " ");
    
    if (iTemp != -1)
        replace(szID, charsmax(szID), szID[iTemp], "")
    else
        iTemp = 2;
    
    iTemp++;
    
    new iID = str_to_num(szID);
    
    //ftD7Log(_, _, "[fwSQLHandleGetBiggestLineID] szData: ^"%s^". iID: %d. Address: ^"%s^".", szData, iID, szData[iTemp])
    
    if (!is_user_valid(iID) || !bitsum_get(g_iBsConnected, iID) || !ftUserCheckSameAddress(iID, szData[iTemp]))// || bitsum_get(g_iBsAccountLoaded, iID)
    {
        //log_error(AMX_ERR_GENERAL, "[fwSQLHandleGetBiggestLineID] User disconnected and/or has been replaced before the query could be completed.")
        
        goto GoToFreeHandle;
    }
    
    remove_task(iID + g_iIDTaskAccountLoad)
    
    g_iIDLine[iID] = g_iLastLineID;*/
    
    
GoToFreeHandle:
    
    
SQL_FreeHandle(iIDHandleQuery)
}

public 
fwSQLHandleAccUpdate(const iFailstate, const Handle:iIDHandleQuery, const szError[], const iIDError, const szData[], const iSizeData, const Float:fTimeQueue)
{
    if (
iFailstate == TQUERY_CONNECT_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleAccUpdate] Load - Could not connect to SQL database. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    else if (
iFailstate == TQUERY_QUERY_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleAccUpdate] Load Query failed. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    
/*
    static Float:fGameTimeLast;
    
    replace_all(g_szSQLQuery, charsmax(g_szSQLQuery), ";", ";^n")
    
    ftD7Log(_, _, "[fwSQLHandleAccUpdate] Time since last info return: %f.", get_gametime() - fGameTimeLast)
    
    fGameTimeLast = get_gametime();
    
    //ftD7Log(_, _, "[fwSQLHandleAccUpdate] szData: ^"%s^". fTimeQueue: %f.", szData, fTimeQueue)
    
    new iID = str_to_num(szData);
    
    if (!is_user_valid(iID) || !bitsum_get(g_iBsConnected, iID))
    {
        //log_error(AMX_ERR_GENERAL, "[fwSQLHandleAccUpdate] User disconnected before the query could be completed.")
        
        goto GoToFreeHandle;
    }*/
    
    
GoToFreeHandle:
    
    
SQL_FreeHandle(iIDHandleQuery)
}

public 
fwSQLHandleAccLoadCreate(const iFailstate, const Handle:iIDHandleQuery, const szError[], const iIDError, const szData[], const iSizeData, const Float:fTimeQueue)
{
    if (
iFailstate == TQUERY_CONNECT_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleAccLoadCreate] Load - Could not connect to SQL database. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    else if (
iFailstate == TQUERY_QUERY_FAILED)
    {
        
log_error(AMX_ERR_GENERAL"[fwSQLHandleAccLoadCreate] Load Query failed. [%d] %s"iIDErrorszError)
        
        goto 
GoToFreeHandle;
    }
    
    static 
szID[3];
    
formatex(szIDcharsmax(szID), szData)
    
    new 
iTemp contain(szID" ");
    
    if (
iTemp != -1)
        
replace(szIDcharsmax(szID), szID[iTemp], "")
    else
        
iTemp 2;
    
    
iTemp++;
    
    new 
iID str_to_num(szID);
    
    
ftD7Log(__"[fwSQLHandleAccLoadCreate] szData: ^"%s^". iID: %d. Address: ^"%s^"."szDataiIDszData[iTemp])
    
    if (!
is_user_valid(iID) || !bitsum_get(g_iBsConnectediID) || !ftUserCheckSameAddress(iIDszData[iTemp]))// || bitsum_get(g_iBsAccountLoaded, iID)
    
{
        
//log_error(AMX_ERR_GENERAL, "[fwSQLHandleAccLoadCreate] User disconnected and/or has been replaced before the query could be completed.")
        
        
goto GoToFreeHandle;
    }
    
    
remove_task(iID g_iIDTaskAccountLoad)
    
    if (
SQL_NumResults(iIDHandleQuery))// && SQL_MoreResults(iIDHandleQuery)
    
{
        
g_iIDLine[iID] = SQL_ReadResult(iIDHandleQueryg_iIDClLineID);
        
/*
        if (!bitsum_get(g_iBsBot, iID) && SQL_ReadResult(iIDHandleQuery, KeyType) != g_iCacheCVarKey)
        {
            formatex(g_szSQLHandle, charsmax(g_szSQLHandle), "fwSQLHandleAccUpdate")
            
            formatex(g_szSQLQuery, charsmax(g_szSQLQuery), "UPDATE `%s` SET `%s` = '%s', `%s` = '%d' WHERE `%s` = '%d'",
            g_szSQLTableName,
            g_szSQLTableColumnNames[g_iIDClMD5Key], ftMD5String(ftKeyGet(iID)),
            g_szSQLTableColumnNames[g_iIDClKeyType], g_iCacheCVarKey,
            g_szSQLTableColumnNames[g_iIDClLineID], g_iIDLine[iID])
            
            g_szSQLHandleData = "";
            
            fwTaskSQLThreadQuery();
        }*/
        
        
iTemp SQL_ReadResult(iIDHandleQueryg_iIDClAmmoPacks);
        
        if (
iTemp != -1)
        {
            
g_iAmmoPacks[iID] = iTemp;
            
            
zp_set_user_ammo_packs(iIDiTemp)
        }
        
        
iTemp SQL_ReadResult(iIDHandleQueryg_iIDClClassZombie);
        
        if (
iTemp > -1)
        {
            
g_iIDClassZombie[iID] = iTemp;
            
            
zp_set_user_zombie_class(iIDiTemp)
        }
        
        
iTemp SQL_ReadResult(iIDHandleQueryg_iIDClClassHuman);
        
        if (
iTemp > -1)
        {
            
g_iIDClassHuman[iID] = iTemp;
            
            
zpnm_set_user_human_class(iIDiTemp)
        }
        
        
bitsum_add(g_iBsAccountLoadediID)
    }
    else
    {
        
formatex(g_szSQLHandlecharsmax(g_szSQLHandle), "fwSQLHandleLogFree")
        
        
iTemp 0;
        
        
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"INSERT INTO `%s` ("g_szSQLTableName);
        
        new 
iID2;
        
        for (
iID2 0iID2 g_iEnumTableColumnsiID2++)
        {
            
// 
            
if (containi(g_szSQLTableColumnProperties[iID2], "PRIMARY KEY") != -1
            
|| containi(g_szSQLTableColumnProperties[iID2], "AUTOINCREMENT") != -1
            
|| containi(g_szSQLTableColumnProperties[iID2], "DEFAULT ") != -1)
                continue;
            
            
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"%s`%s`", (g_szSQLQuery[iTemp 1] != '(') ? ", " ""g_szSQLTableColumnNames[iID2]);
        }
        
        
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp") VALUES (");
        
        for (
iID2 0iID2 g_iEnumTableColumnsiID2++)
        {
            if (
containi(g_szSQLTableColumnProperties[iID2], "PRIMARY KEY") != -1
            
|| containi(g_szSQLTableColumnProperties[iID2], "AUTOINCREMENT") != -1
            
|| containi(g_szSQLTableColumnProperties[iID2], "DEFAULT ") != -1)
                continue;
            
            
//if (iID2 == g_iIDClMD5Key)
                //iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp, "%s'%s'", (g_szSQLQuery[iTemp - 1] != '(') ? ", " : "", ftMD5String(ftKeyGet(iID)))
            //else if (iID2 == KeyType)
                //iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp, "%s'%d'", (g_szSQLQuery[iTemp - 1] != '(') ? ", " : "", g_iCacheCVarKey)
            
if (containi(g_szSQLTableColumnProperties[iID2], "NOT NULL") != -|| g_iTypeConnection == ConnectionMySQL// NOT allowed to have NULL values
            
{
                if (
containi(g_szSQLTableColumnProperties[iID2], "INTEGER") != -|| containi(g_szSQLTableColumnProperties[iID2], "NUMERIC") != -1)
                    
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"%s'-1'", (g_szSQLQuery[iTemp 1] != '(') ? ", " "");
                else if (
containi(g_szSQLTableColumnProperties[iID2], "FLOAT") != -|| containi(g_szSQLTableColumnProperties[iID2], "REAL") != -1)
                    
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"%s'-1.0'", (g_szSQLQuery[iTemp 1] != '(') ? ", " "");
                else if (
containi(g_szSQLTableColumnProperties[iID2], "TEXT") != -|| containi(g_szSQLTableColumnProperties[iID2], "CHAR") != -1)
                    
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"%s' '", (g_szSQLQuery[iTemp 1] != '(') ? ", " "");
            }
            else
            {
                
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp"%s''", (g_szSQLQuery[iTemp 1] != '(') ? ", " "")
            }
        }
        
        if (
g_szSQLQuery[iTemp 1] != '(')
        {
            
iTemp += formatex(g_szSQLQuery[iTemp], charsmax(g_szSQLQuery) - iTemp")");
        }
        else
        {
            
//replace(g_szSQLQuery[iTemp - 9], charsmax(g_szSQLQuery) - iTemp - 9, " VALUES (", "")
            
g_szSQLQuery[iTemp 9] = EOS;
        }
        
        
g_szSQLHandleData "";
        
        
fwTaskSQLThreadQuery();
        
        
g_iIDLine[iID] = g_iLastLineID;
        
        
g_iLastLineID++;
/*        
        if (g_iLastLineID)
        {
            g_iLastLineID++;
            
            g_iIDLine[iID] = g_iLastLineID;
        }
        else
        {
            formatex(g_szSQLHandle, charsmax(g_szSQLHandle), "fwSQLHandleGetBiggestLineID")
            
            formatex(g_szSQLQuery, charsmax(g_szSQLQuery), "SELECT `%s` FROM `%s` ORDER BY `%s` DESC LIMIT 1", g_szSQLTableColumnNames[g_iIDClLineID], g_szSQLTableName, g_szSQLTableColumnNames[g_iIDClLineID])
            
            formatex(g_szSQLHandleData, charsmax(g_szSQLHandleData), "%d %s", iID, ftUserGetAddress(iID))
            
            fwTaskSQLThreadQuery();
        }*/
        
        
g_iAmmoPacks[iID] = zp_get_user_ammo_packs(iID);
        
        
iTemp zpnm_get_user_next_hclass(iID);
        
        if (
iTemp > -1)
            
g_iIDClassHuman[iID] = iTemp;
        else
            
g_iIDClassHuman[iID] = zpnm_get_user_human_class(iID);
        
        
iTemp zp_get_user_next_class(iID);
        
        if (
iTemp > -1)
            
g_iIDClassZombie[iID] = iTemp;
        else
            
g_iIDClassZombie[iID] = zp_get_user_zombie_class(iID);
        
        
bitsum_add(g_iBsAccountLoadediID)
        
        
remove_task(iID g_iIDTaskAccountSave)
        
fwTaskSQLQueryAccSave(iID g_iIDTaskAccountSave)
    }
    
    
GoToFreeHandle:
    
    
SQL_FreeHandle(iIDHandleQuery)
}

ftUserGetAddress(const iID)
{
    static 
szAddress[32];
    
szAddress "";
    
    
//ftD7Log(_, _, "[ftUserGetAddress] szAddress(should be empty): ^"%s^".", szAddress)
    
    
if (!is_user_connected(iID))
        return 
szAddress;
    
    if (!
bitsum_get(g_iBsBotiID))
        
get_user_ip(iIDszAddresscharsmax(szAddress))
    else
        
get_user_name(iIDszAddresscharsmax(szAddress))
    
    
//if (bitsum_get(g_iBsBot, iID))
        //ftD7Log(_, _, "[ftUserGetAddress] szAddress(bots): ^"%s^".", szAddress)
    
    
return szAddress;
}

ftUserCheckSameAddress(const iID, const szAddressCheck[])
{
    if (!
is_user_connected(iID) || !equal(szAddressCheckftUserGetAddress(iID)))
    {
        
//ftD7Log(_, _, "[ftUserCheckSameAddress] iID: %d. szAddressCheck: ^"%s^". ftUserGetAddress: ^"%s^".", iID, szAddressCheck, ftUserGetAddress(iID))
        
        
return 0;
    }
    
    
//ftD7Log(_, _, "[ftUserCheckSameAddress] iID: %d. szAddressCheck: ^"%s^". ftUserGetAddress: ^"%s^".", iID, szAddressCheck, ftUserGetAddress(iID))
    
    
return 1;
}

public 
plugin_end()
{
    
fwEvRoundEnd()
    
    
SQL_FreeHandle(g_iIDSQLConnection)
    
SQL_FreeHandle(g_iIDSQLTuple)
    
    
//g_iIDSQLTuple = Empty_Handle;

Attached Thumbnails
Click image for larger version

Name:	table.png
Views:	334
Size:	72.3 KB
ID:	161142  
__________________

Last edited by georgik57; 02-27-2017 at 12:49.
georgik57 is offline
Send a message via MSN to georgik57 Send a message via Yahoo to georgik57 Send a message via Skype™ to georgik57
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 22:17.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode