views:

151

answers:

4

I'm trying to find out if a specific MySQL User is still in use in our system (and what queries it is executing).

So I thought of writing a trigger that would kick in anytime user X executes a query, and it would log the query in a log table.

How can I do that? I know how to write a query for a specific table, but not for a specific user (any table).

Thanks

+2  A: 

The easiest would be to have the trigger always fire, but only logs if the user is X.

IPX Ares
how do you trigger for ANY table ANY action?
nute
@nute: You don't - with MySQL, you have to trigger for each table and event separately; also, you can only trigger on INSERT,UPDATE,or DELETE. (REPLACE = DELETE+INSERT)
Piskvor
oh, that's not gonna work then, too many tables
nute
Is there then a way to enable MySQL logs but just for ONE user?
nute
I do not think you can enable it just for one user, but you could do logs for everything, then parse the log. I agree though, there should be a way. If the user is really using a mySQL user ID rather than an application user ID... couldn't you just disable that ID?
IPX Ares
I want to disable that ID, but I'm afraid to break some existing code. Which is why I first want to see if anything is still using that identifier.
nute
I see, hmmmm, then I think you are stuck doing triggers for everything (you could script the creation SQL for them to do all the tables at once), or parsing the log file.
IPX Ares
+2  A: 

You could branch your trigger function on USER().

cmptrgeekken
This makes the most sense. Now the only problem is the part where I need to have that trigger for ALL tables, ALL actions. For the entire database...
nute
A: 

Yeah, fire away, but use whatever system you have to see what user it is (cookies, session) to log only if the specific user (userID, class) matches your credentials.

Olsson
We're talking about core MySQL users, not application users.
nute
A: 

There are also other ways you could approach this problem, for example using MySQL proxy

In the proxy you could do interesting things - from logging to transforming queries, pattern matching (check this link also for details on how to test/develop the scripts)

-- set the username
local log_user = 'username'

function read_query( packet )
    if proxy.connection.client.username == log_user and string.byte(packet) == proxy.COM_QUERY then
        local log_file = '/var/log/mysql-proxy/mysql-' .. log_user .. '.log'
        local fh = io.open(log_file, "a+")
        local query = string.sub(packet, 2)
        fh:write( string.format("%s %6d -- %s \n",
            os.date('%Y-%m-%d %H:%M:%S'),
            proxy.connection.server["thread_id"],
            query))
        fh:flush()
    end
end

The above has been tested and it does what it is supposed to (although this is a simple variant, does not log success or failure and only logs proxy.COM_QUERY, see the list of all constants to see what is skipped and adjust for your needs)

Unreason