1

A recent project update involved adding a massive amount of relatively (updates every 6-12 months) static data for the application. Because of its size (appx 1GB, including indexing), it was elected to include it in a separate database. The code has been updated to handle it all already, but now what was an easy one-off on the development machines would be a rather large headache to deploy with the update: namely, to add the application's user privileges to the new database.

Is there an easy way to copy the user that already exists on the main database to have access to the new one?

e.g. The user was originally created with the standard "GRANT ALL on main_db.* to user@localhost identified by 'XX';"

And I'm hoping to find a way to easily turn that into "GRANT ALL on static_db.* to user@localhost identified by 'XX';" without having to manually do it on every server the application is deployed on (and yes, they all have different values for "XX". :) )

Edit: Using Devart's advice as as starting point, I got what I needed. The table in question for database-wide permissions is mysql.db. Posting the query here (in generic form) in case it helps anyone else.

INSERT INTO mysql.db 
SELECT 
Host, 'New_DB', User, Select_priv, Insert_priv, Update_priv, Delete_priv, 
Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv, 
Create_tmp_table_priv, Lock_tables_priv, Create_view_priv, Show_view_priv,    
    Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv
    FROM mysql.db
WHERE
User='username' AND Host = 'hostname' AND Db='Old_Db';
GeminiDomino
  • 451
  • 1
  • 5
  • 19

1 Answers1

2

All granted privileges are stored in system tables, e.g. - mysql.tables_priv, mysql.columns_priv, mysql.db... You can write a script to copy all privileges you need.

Suppose we have user -

CREATE USER 'user1'@'%';
GRANT Insert ON TABLE database1.table1 TO 'user1'@'%';
GRANT Execute ON PROCEDURE database1.procedure1 TO 'user1'@'%';

Now, we will copy these privileges to have access to database 'database2' -

-- Copy table's privileges
INSERT INTO mysql.tables_priv SELECT host, 'database2', user, table_name, grantor, timestamp, table_priv, column_priv FROM mysql.tables_priv
  WHERE user = 'user1' AND host = '%' AND db = 'database1';

-- Copy routine's privileges
INSERT INTO mysql.procs_priv SELECT host, 'database2', user, routine_name, routine_type, grantor, proc_priv, timestamp FROM mysql.procs_priv
  WHERE user = 'user1' AND host = '%' AND db = 'database1';

-- Do not forget to apply changes ;-)
FLUSH PRIVILEGES;

Do the same for another system tables.

Devart
  • 119,203
  • 23
  • 166
  • 186