Commits

Mikhail Korobov committed d1409a6

mysql module improvements: mysql user creation is handled, granting permissions is fixed, mysqldump no longer requires project dir to be created, missing import is added

  • Participants
  • Parent commits 9cc9926

Comments (0)

Files changed (1)

File fab_deploy/mysql.py

 from __future__ import with_statement
+import posixpath
 from datetime import datetime
 from fabric.api import *
 from fabric.operations import _handle_failure
+from fabric.utils import puts
 from fab_deploy import utils
 from fab_deploy import system
 
 MYSQL_CREATE_DB = """CREATE DATABASE %(db_name)s DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"""
 
 MYSQL_GRANT_PERMISSIONS = """
-GRANT ALL ON %(db_name)s.* TO '%(db_user}s'@'localhost';
+GRANT ALL ON %(db_name)s.* TO '%(db_user)s'@'localhost';
 FLUSH PRIVILEGES;
 """
 
+MYSQL_USER_EXISTS = "SHOW GRANTS FOR '%(db_user)s'@localhost"
+
 
 def _get_root_password():
     """Ask root password only once if needed"""
         output = run('mysql --version')
     return output.succeeded
 
-@utils.inside_project
+def _mysql_user_exists(db_user):
+    sql = MYSQL_USER_EXISTS % dict(db_user=db_user)
+    with settings(warn_only=True):
+        result = mysql_execute(sql, 'root')
+    return result.succeeded
+
 def mysqldump(dir=None, db_name=None, db_user=None, db_password=None):
     """ Runs mysqldump. Result is stored at <env>/var/backups/ """
     if dir is None:
     db_name, db_user, db_password = _credentials(db_name, db_user, db_password)
 
     now = datetime.now().strftime('%Y.%m.%d-%H.%M')
-    filename = '%s/%s%s.sql' % (dir, db_name, now)
+    filename = '%s%s.sql' % (db_name, now)
+
+    # if dir is absolute then PROJECT_DIR won't affect result path
+    # otherwise dir will be relative to PROJECT_DIR
+    full_name = posixpath.join(env.conf.PROJECT_DIR, dir, filename)
+
     run('mysqldump --user="%s" --password="%s" %s > %s' % (
-                        db_user, db_password, db_name, filename))
+                        db_user, db_password, db_name, full_name))
 
 def mysql_execute(sql, user=None, password=None):
     """ Executes passed sql command using mysql shell. """
         _handle_failure('MySQL root user can not be created')
         return
 
+    if _mysql_user_exists(db_user):
+        puts('User %s already exists' % db_user)
+        return
+
     sql = MYSQL_CREATE_USER % dict(db_user=db_user, db_password=db_password)
     mysql_execute(sql, 'root')
 
     mysql_execute(sql, 'root')
 
     if db_user != 'root':
+        mysql_create_user(db_user=db_user)
         mysql_grant_permissions(db_name=db_name, db_user=db_user)
 
 def mysql_grant_permissions(db_name=None, db_user=None):