Raised This Month: $32 Target: $400
 8% 

Solved Optimized Code?


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
ThatKidWhoGames
Veteran Member
Join Date: Jun 2013
Location: IsValidClient()
Old 11-29-2018 , 11:00   Optimized Code?
Reply With Quote #1

Hey all,

I just wanted to know if what I coded is the most efficient way of stat tracking with MySQL.

PHP Code:
#include <sourcemod>
#include <tf2_stocks>

Database g_hDatabase;

public 
void OnPluginStart()
{
    
Database.Connect(DB_OnConnection"stats");

    
HookEvent("player_death"Event_PlayerDeath);
}

/*===================================================
=                    C L I E N T S                    =
===================================================*/

public void OnClientPostAdminCheck(int client)
{
    
InsertClientIntoDB(client);
}

/*=================================================
=                    E V E N T S                      =
=================================================*/

public void Event_PlayerDeath(Event event, const char[] namebool dontBroadcast)
{
    if (
g_hDatabase && GameRules_GetRoundState() == RoundState_RoundRunning && !(event.GetInt("death_flags") & TF_DEATHFLAG_DEADRINGER))
    {
        
char steamid[21], query[256];
        
int victim_userid event.GetInt("userid");
        
int victim           GetClientOfUserId(victim_userid);
        if (
victim && IsClientInGame(victim))
        {
            if (!
GetClientAuthId(victimAuthId_Steam2steamidsizeof(steamid)))
            {
                
LogError("Failure retrieving the SteamID of victim %N (UserID: %i) Callback: Event_PlayerDeath()"victimvictim_userid);
            } else {
                
g_hDatabase.Format(querysizeof(query), "UPDATE `stats` SET `deaths` = `deaths` + '1', `points` = `points` - '1' WHERE `steamid` = '%s';"steamid);
                
g_hDatabase.Query(DB_OnUpdateClientqueryvictim_userid);
            }
        }

        
int attacker_userid event.GetInt("attacker");
        
int attacker        GetClientOfUserId(attacker_userid);
        if (
attacker && IsClientInGame(attacker))
        {
            if (!
GetClientAuthId(attackerAuthId_Steam2steamidsizeof(steamid)))
            {
                
LogError("Failure retrieving the SteamID of attacker %N (UserID: %i) Callback: Event_PlayerDeath()"attackerattacker_userid);
            } else {
                
g_hDatabase.Format(querysizeof(query), "UPDATE `stats` SET `kills` = `kills` + '1', `points` = `points` + '2' WHERE `steamid` = '%s';"steamid);
                
g_hDatabase.Query(DB_OnUpdateClientqueryattacker_userid);
            }
        }

        
int assister_userid event.GetInt("assister");
        
int assister        GetClientOfUserId(assister_userid);
        if (
assister && IsClientInGame(assister))
        {
            if (!
GetClientAuthId(assisterAuthId_Steam2steamidsizeof(steamid)))
            {
                
LogError("Failure retrieving the SteamID of assister %N (UserID: %i) Callback: Event_PlayerDeath()"assisterassister_userid);
            } else {
                
g_hDatabase.Format(querysizeof(query), "UPDATE `stats` SET `assists` = `assists` + '1', `points` = `points` + '1' WHERE `steamid` = '%s';"steamid);
                
g_hDatabase.Query(DB_OnUpdateClientqueryassister_userid);
            }
        }
    }
}

/*===============================================
=                    M Y S Q L                      =
===============================================*/

public void DB_OnConnection(Database db, const char[] errorany data)
{
    if (!
db)
    {
        
SetFailState("Failure establishing a connection to the database! Error: %s"error);
    } else {
        
g_hDatabase db;
        
CreateTable();
    }
}

void CreateTable()
{
    
char[] query "CREATE TABLE IF NOT EXISTS `stats` ("
                
..."`steamid` varchar(21) NOT NULL PRIMARY KEY, "
                
..."`name` varchar(32) NOT NULL, "
                
..."`kills` int(11) NOT NULL DEFAULT '0', "
                
..."`deaths` int(11) NOT NULL DEFAULT '0', "
                
..."`assists` int(11) NOT NULL DEFAULT '0', "
                
..."`points` int(11) NOT NULL DEFAULT '0');";
    
g_hDatabase.Query(DB_OnCreateTablequery);
}

public 
void DB_OnCreateTable(Database dbDBResultSet results, const char[] errorany data)
{
    if (!
results)
    {
        
delete g_hDatabase;
        
SetFailState("Failure creating the database table! Error: %s"error);
    } else if (
GetClientCount()) {
        
InsertAllIntoDB();
    }
}

public 
void DB_OnInsertClient(Database dbDBResultSet results, const char[] errorint userid)
{
    
int client GetClientOfUserId(userid);
    if (
client && IsClientInGame(client))
    {
        if (!
results)
        {
            
LogError("Failure inserting client %N (UserID: %i) into the database! Error: %s"clientuserid);
        }
    }
}

public 
void DB_OnUpdateClient(Database dbDBResultSet results, const char[] errorint userid)
{
    
int client GetClientOfUserId(userid);
    if (
client && IsClientInGame(client) && !results)
    {
        
LogError("Failure updating the stats of client %N (UserID: %i) in the database! Error: %s"clientuseriderror);
    }
}

void InsertClientIntoDB(int client)
{
    if (!
IsFakeClient(client))
    {
        
int userid GetClientUserId(client);
        
char steamid[21];
        if (!
GetClientAuthId(clientAuthId_Steam2steamidsizeof(steamid)))
        {
            
LogError("Failure retrieving the SteamID of client %N (UserID: %i) Function: InsertClientIntoDB()"clientuserid);
        } else {
            
char query[256];
            
g_hDatabase.Format(querysizeof(query), "INSERT INTO `stats` (`steamid`, `name`) VALUES ('%s', '%N') ON DUPLICATE KEY UPDATE `name` = '%N';"steamidclientclient);
            
g_hDatabase.Query(DB_OnInsertClientqueryuserid);
        }
    }
}

void InsertAllIntoDB()
{
    for (
int i 1<= MaxClientsi++)
    {
        if (
IsClientInGame(i))
        {
            
InsertClientIntoDB(i);
        }
    }

Thanks,
Grant

Last edited by ThatKidWhoGames; 11-30-2018 at 07:58.
ThatKidWhoGames is offline
P4UL
AlliedModders Donor
Join Date: Apr 2017
Location: Netherlands
Old 11-29-2018 , 11:58   Re: Optimized Code?
Reply With Quote #2

I'm not that experienced with SQL but I think it is a lot more efficient to store the amount of deaths/kills etc locally until either the map ends or the player disconnects so it doesn't have to make a query to the database every single time
P4UL is offline
Bacardi
Veteran Member
Join Date: Jan 2010
Location: mom's basement
Old 11-29-2018 , 13:24   Re: Optimized Code?
Reply With Quote #3

Quote:
Originally Posted by P4UL View Post
I'm not that experienced with SQL but I think it is a lot more efficient to store the amount of deaths/kills etc locally until either the map ends or the player disconnects so it doesn't have to make a query to the database every single time
+1
__________________
Do not Private Message @me
Bacardi is offline
headline
SourceMod Moderator
Join Date: Mar 2015
Old 11-30-2018 , 01:04   Re: Optimized Code?
Reply With Quote #4

Apart from the previous comment; your code looks fine in terms of efficiency. Good work.

Last edited by headline; 11-30-2018 at 01:04.
headline is offline
Psyk0tik
Veteran Member
Join Date: May 2012
Location: Homeless
Old 11-30-2018 , 06:02   Re: Optimized Code?
Reply With Quote #5

A little off-topic but...

What does the "..." do in this function and what's the proper term for it?

PHP Code:
void CreateTable()
{
    
char[] query "CREATE TABLE IF NOT EXISTS `stats` ("
                
..."`steamid` varchar(21) NOT NULL PRIMARY KEY, "
                
..."`name` varchar(32) NOT NULL, "
                
..."`kills` int(11) NOT NULL DEFAULT '0', "
                
..."`deaths` int(11) NOT NULL DEFAULT '0', "
                
..."`assists` int(11) NOT NULL DEFAULT '0', "
                
..."`points` int(11) NOT NULL DEFAULT '0');";
    
g_hDatabase.Query(DB_OnCreateTablequery);

I've only seen the "..." used in function parameters for VFormat() usage before.
__________________
Psyk0tik is offline
headline
SourceMod Moderator
Join Date: Mar 2015
Old 11-30-2018 , 06:05   Re: Optimized Code?
Reply With Quote #6

Quote:
Originally Posted by Crasher_3637 View Post
A little off-topic but...

What does the "..." do in this function and what's the proper term for it?

PHP Code:
void CreateTable()
{
    
char[] query "CREATE TABLE IF NOT EXISTS `stats` ("
                
..."`steamid` varchar(21) NOT NULL PRIMARY KEY, "
                
..."`name` varchar(32) NOT NULL, "
                
..."`kills` int(11) NOT NULL DEFAULT '0', "
                
..."`deaths` int(11) NOT NULL DEFAULT '0', "
                
..."`assists` int(11) NOT NULL DEFAULT '0', "
                
..."`points` int(11) NOT NULL DEFAULT '0');";
    
g_hDatabase.Query(DB_OnCreateTablequery);

I've only seen the "..." used in function parameters for VFormat() usage before.
In sourcepawn, it’s a string concatenation operator. Similar to the + operator in languages like python and java. The limitation in sourcepawn is that it can only be used with string literals.

Last edited by headline; 11-30-2018 at 06:06.
headline is offline
ThatKidWhoGames
Veteran Member
Join Date: Jun 2013
Location: IsValidClient()
Old 11-30-2018 , 07:57   Re: Optimized Code?
Reply With Quote #7

Thanks guys!!
ThatKidWhoGames is offline
Psyk0tik
Veteran Member
Join Date: May 2012
Location: Homeless
Old 11-30-2018 , 18:30   Re: Optimized Code?
Reply With Quote #8

Quote:
Originally Posted by Headline View Post
In sourcepawn, it’s a string concatenation operator. Similar to the + operator in languages like python and java. The limitation in sourcepawn is that it can only be used with string literals.
That makes sense. Thanks!
__________________
Psyk0tik is offline
Impact123
Veteran Member
Join Date: Oct 2011
Location: Germany
Old 12-02-2018 , 09:56   Re: Optimized Code?
Reply With Quote #9

It's a bit late but don't forget to escape client names.
__________________
Impact123 is offline
headline
SourceMod Moderator
Join Date: Mar 2015
Old 12-02-2018 , 10:05   Re: Optimized Code?
Reply With Quote #10

Quote:
Originally Posted by Impact123 View Post
It's a bit late but don't forget to escape client names.
Database.Format escapes for you
headline is offline
Reply



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 13:38.


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