Lua script to stop firing a query in mysql via mysql proxy - mysql

I am a beginner to lua language.The main concept is when a user fire the DROP TABLE command in mysql it should not be executed.But he can fire all other commands as usual in mysql.But i don't want to use GRANTS for this.Is there any luaScript to perform this action via mysql-proxy?
For example:
mysql> DROP TABLE T1;
Please wait for authentication
Also is LuaSql helpful to perform this task via mysql-proxy?
Hope i made the idea clear.Someone help me solve out this issue.Thanks in advance.

Yes, you can do that. The idea here is to check a query whether or not it fulfills the requirements you want to filter and if so NOT sending it to the server
function read_query(packet)
if string.byte(packet) == proxy.COM_QUERY then
query = packet:sub(2)
if condition(query) then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
return proxy.PROXY_SEND_RESULT
end
end
end
This checks each query the proxy receives for condition and if it matches it will just return a SUCCESS to the client without delivering the query. Thus effectively dropping the query.

Related

Rails6 how to do `XXX.update_all` with mysql function

I would like to use update_all in order to update all records in a database.
Let me assume that the name of the attribute to be update is price.
I succeeded command A.
A
MyModel.update_all(price: "$500")
However, I would like to mysql function(e.g. IF, CONCAT, arithmetic...) in updating.
so I tried command B, but failed and the string value CONCAT('$', 500) was stored.
B
MyModel.update_all(price: "CONCAT('$', 500)")
I succeeded when I tried C, but I don't want use it because of the SQL injection risks.
C
MyModel.update_all("price = CONCAT('$', 500)")
How can I do that without any risk of SQL injection attacks?
Here, I have to use sql function here for some reasons.
Thank you in advance.
You need to create methods corresponding to allowable sql functions that take the params as input. So if you want to provide "CONCAT(..,...)" then user should be able to call a method like this. You can extent it to check type of arguments are allowed and add checks there as well.
def allowed_functions(func_name, all_args_here)
case func_name
when 'concat' then "CONCAT(#{all_args_here})"
end
end

MySQL executes sleep command when UPDATE query is used

I have created a discord bot that interacts with a mysql database but when you run a command that uses the UPDATE query it doesnt execute the update query but executes sleep , meaning the data in the DB isnt chnaged.
(from comment)
#client.command()
async def SetJob(ctx, uid: str, rank: str):
disout = exec("UPDATE users SET 'job'='{0}' WHERE identifier='{1}'".format(rank,uid))
if ctx.message.author == client.user:
return
if ctx.message.author.id not in whitelisted:
await ctx.send(embed=discord.Embed(title="You are not authorized to use this bot", description='Please contact Not Soviet Bear to add you to the whitelisted members list', color=discord.Color.red()))
return
else:
await ctx.send(embed=discord.Embed(title="Job Change", description="Job changed to '{0}' for Identifier'{1}'".format(rank,uid), color=discord.Color.blue()))
I assume your "bot" is periodically doing SHOW PROCESSLIST? Well, the UPDATE probably finished so fast that it did not see the query.
The Sleep says that the connection is still sitting there, but doing nothing. (There is no "sleep command"; "Sleep" indicates that no query is running at the instant.)
So, perhaps the question is "why did my update not do anything?". In order to debug that (or get help from us),
Check for errors after running the update. (You should always do this.)
Figure out the exact text of the generated SQL. (Sometimes there is an obvious syntax error or failure to escape, say, quotes.)

Prestashop 1.4 - How to execute an initial MySQL query on every request

Kind of old version of Prestashop, I know, but I need to execute an initial MySQL query on every request.
Where do I need to put the logic to be always executed?
Sort of initialization point the application always executes, no matter what URL is requested.
Thanks in advance.
Finally found the solution (and smartly, I think).
And I also think this approach could be applicable to other versions of Prestashop (1.5, 1.6, 1.7...).
In classes/MySQL.php file, within the connect function, I add my query just before returning $this->_link:
public function connect()
{
if (!defined('_PS_DEBUG_SQL_'))
define('_PS_DEBUG_SQL_', false);
if ($this->_link = mysql_connect($this->_server, $this->_user, $this->_password))
{
if (!$this->set_db($this->_database))
die('The database selection cannot be made.');
}
else
die('Link to database cannot be established.');
/* UTF-8 support */
if (!mysql_query('SET NAMES \'utf8\'', $this->_link))
die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
// removed SET GLOBAL SQL_MODE : we can't do that (see PSCFI-1548)
/** MY QUERY IS INSERTED HERE, USING $this->_link BY THE WAY **/
mysql_query('...', $this->_link);
return $this->_link;
}
In this way, 2 advantages arise:
I do not have to maintain a copy of database credentials other than Prestashop's
The query is executed in every request, both shop frontoffice and backoffice user interfaces.
I hope this can help anyone.

Calling MySQL stored procedure in ROR 4

There are few example out there but non of them are very clarified (or on old version).
I want to call MySQL procedure and check the return status (in rails 4.2). The most common method I saw is to call result = ActiveRecord::Base.connection.execute("call example_proc()"), but in some places people wrote there is prepared method result = ActiveRecord::Base.connection.execute_procedure("Stored Procedure Name", arg1, arg2) (however it didn't compiled).
So what is the correct way to call and get the status for MySQL procedure?
Edit:
And how to send parameters safly, where the first parameter is integer, second string and third boolean?
Rails 4 ActiveRecord::Base doesn't support execute_procedure method, though result = ActiveRecord::Base.connection still works. ie
result = ActiveRecord::Base.connection.execute("call example_proc('#{arg1}','#{arg2}')")
You can try Vishnu approach below
or
You can also try
ActiveRecord::Base.connections.exec_query("call example_proc('#{arg1}','#{arg2}')")
here is the document
In general, you should be able to call stored procedures in a regular where or select method for a given model:
YourModel.where("YOUR_PROC(?, ?)", var1, var2)
As for your comment "Bottom line I want the most correct approach with procedure validation afterwards (for warnings and errors)", I guess it always depends on what you actually want to implement and how readable you want your code to be.
For example, if you want to return rows of YourModel attributes, then it probably would be better if you use the above statement with where method. On the other hand, if you write some sql adapter then you might want to go down to the ActiveRecord::Base.connection.execute level.
BTW, there is something about stored proc performance that should be mentioned here. In several databases, database does stored proc optimization on the first run of the stored proc. However, the parameters that you pass to that first run might not be those that will be running on it more frequently later on. As a result, your stored-proc might be auto-optimized in a "none-optimal" way for your case. It may or may not happen this way, but it is something that you should consider while using stored procs with dynamic params.
I believe you have tried many other solutions and got some or other errors mostly "out of sync" or "closed connection" errors. These errors occur every SECOND time you try to execute the queries. We need to workaround like the connection is new every time to overcome this. Here is my solution that didn't throw any errors.
#checkout a connection for Model
conn = ModelName.connection_pool.checkout
#use the new connection to execute the query
#records = conn.execute("call proc_name('params')")
#checkout the connection
ModelName.connection_pool.checkin(conn)
The other approaches failed for me, possibly because ActiveRecord connections are automatically handled to checkout and checking for each thread. When our method tries to checkout a connection just to execute the SP, it might conflict since there will be an active connection just when the method started.
So the idea is to manually #checkout a connection for the model instead of for thread/function from the pool and #checkin once the work is done. This worked great for me.

Perform select and multiple inserts as transaction using C Connector?

I am using MySQL. I have a select statement followed by a number of insert statement done using the C Connector. I would like to know how to put them all under one transaction and finally commit then.
I have gone through the MySQL 5.0 Reference Manual and C API Function Overview it have this function mysql_commit()? I must have a start transaction (how to set this is it by just turning off the autocommit()) and finally only commit right?
As far as I understand, there is no mysql_starttransaction() or something similar; so you're stuck with something like:
mysql_autocommit(conn, 0);
//Do stuff here
mysql_commit(conn); //...or mysql_rollback(conn);
I would rather use the "query" method for all these calls:
mysql_query(conn, "START TRANSACTION");
//Do stuff here
mysql_query(conn, "COMMIT"); //...or mysql_query(conn, "ROLLBACK");
Also see this documentation.