From 29a5c79fc8844824a11100d129e95c96dac75607 Mon Sep 17 00:00:00 2001 From: Sandu Liviu Catalin Date: Tue, 17 Jul 2018 20:46:39 +0300 Subject: [PATCH] Implement an a method in the MySQL connection handle to escape strings of unwanted characters. --- modules/mysql/Connection.cpp | 18 ++++++++++++++++++ modules/mysql/Connection.hpp | 5 +++++ 2 files changed, 23 insertions(+) diff --git a/modules/mysql/Connection.cpp b/modules/mysql/Connection.cpp index 6675e5b4..4ebc5fa3 100644 --- a/modules/mysql/Connection.cpp +++ b/modules/mysql/Connection.cpp @@ -7,6 +7,7 @@ // ------------------------------------------------------------------------------------------------ #include +#include // ------------------------------------------------------------------------------------------------ namespace SqMod { @@ -348,6 +349,22 @@ SQInteger Connection::QueryF(HSQUIRRELVM vm) return 1; } +// ------------------------------------------------------------------------------------------------ +LightObj Connection::EscapeString(const StackStrF & str) +{ + // Is there even a string to escape? + if (str.mLen <= 0) + { + return LightObj(_SC(""), 0, str.mVM); // Default to empty string + } + // Allocate a buffer for the given string + std::vector< SQChar > buffer(str.mLen * 2 + 1); + // Attempt to ecape the specified string + const Ulong len = mysql_real_escape_string(m_Handle->mPtr, buffer.data(), str.mPtr, str.mLen); + // Return the resulted string + return LightObj(buffer.data(), static_cast< SQInteger >(len), str.mVM); +} + // ================================================================================================ void Register_Connection(Table & sqlns) { @@ -391,6 +408,7 @@ void Register_Connection(Table & sqlns) .Func(_SC("Query"), &Connection::Query) .Func(_SC("Statement"), &Connection::GetStatement) .Func(_SC("Transaction"), &Connection::GetTransaction) + .FmtFunc(_SC("EscapeString"), &Connection::EscapeString) // Squirrel Methods .SquirrelFunc(_SC("ExecuteF"), &Connection::ExecuteF) .SquirrelFunc(_SC("InsertF"), &Connection::InsertF) diff --git a/modules/mysql/Connection.hpp b/modules/mysql/Connection.hpp index d3932a1c..bd341a41 100644 --- a/modules/mysql/Connection.hpp +++ b/modules/mysql/Connection.hpp @@ -411,6 +411,11 @@ public: */ Transaction GetTransaction(); + /* -------------------------------------------------------------------------------------------- + * Escape unwanted characters from a given string. + */ + LightObj EscapeString(const StackStrF & str); + /* -------------------------------------------------------------------------------------------- * Attempt to execute the specified query. */