]> scripts.mit.edu Git - wizard.git/blobdiff - wizard/install/__init__.py
Revamp database infrastructure.
[wizard.git] / wizard / install / __init__.py
index e7bf46bb7e92f2109fdb99f448e027d823e11302..666fcf9d3640548dbffbe79ef36ff42229435ecb 100644 (file)
@@ -22,10 +22,15 @@ allow applications to refer to them as a single name.
 
 import os
 import logging
+import sqlalchemy
 
 import wizard
 from wizard import scripts, shell, util
 
+def dsn_callback(options):
+    if not isinstance(options.dsn, sqlalchemy.engine.url.URL):
+        options.dsn = sqlalchemy.engine.url.make_url(options.dsn)
+
 # XXX: This is in the wrong place
 def fetch(options, path, post=None):
     """
@@ -43,7 +48,7 @@ def preloads():
     """
     return {
             'web': WebArgSet(),
-            'mysql': MysqlArgSet(),
+            'db': DbArgSet(),
             'admin': AdminArgSet(),
             'email': EmailArgSet(),
             'title': TitleArgSet(),
@@ -126,13 +131,17 @@ class ScriptsMysqlStrategy(Strategy):
     may create an appropriate database for the user.
     """
     side_effects = True
-    provides = frozenset(["mysql_host", "mysql_user", "mysql_password", "mysql_db"])
-    def __init__(self, dir):
+    provides = frozenset(["dsn"])
+    def __init__(self, application, dir):
+        self.application = application
         self.dir = dir
     def prepare(self):
         """Uses :func:`wizard.scripts.get_sql_credentials`"""
-        self._triplet = scripts.get_sql_credentials()
-        if not self._triplet:
+        if self.application.database != "mysql":
+            raise StrategyFailed
+        try:
+            self._triplet = shell.Shell().eval("/mit/scripts/sql/bin/get-password").split()
+        except shell.CallError:
             raise StrategyFailed
         self._username = os.getenv('USER')
         if self._username is None:
@@ -140,10 +149,11 @@ class ScriptsMysqlStrategy(Strategy):
     def execute(self, options):
         """Creates a new database for the user using ``get-next-database`` and ``create-database``."""
         sh = shell.Shell()
-        options.mysql_host, options.mysql_user, options.mysql_password = self._triplet
+        host, username, password = self._triplet
         # race condition
-        options.mysql_db = self._username + '+' + sh.eval("/mit/scripts/sql/bin/get-next-database", os.path.basename(self.dir))
-        sh.call("/mit/scripts/sql/bin/create-database", options.mysql_db)
+        database = self._username + '+' + sh.eval("/mit/scripts/sql/bin/get-next-database", os.path.basename(self.dir))
+        sh.call("/mit/scripts/sql/bin/create-database", name)
+        options.dsn = sqlalchemy.engine.url.URL("mysql", username=username, password=password, host=host, database=database)
 
 class ScriptsEmailStrategy(Strategy):
     """Performs script specific guess for email."""
@@ -173,6 +183,8 @@ class Arg(object):
     type = None
     #: If true, is a password
     password = False
+    #: Callback that this argument wants to get run on options after finished
+    callback = None
     @property
     def envname(self):
         """Name of the environment variable containing this arg."""
@@ -196,6 +208,7 @@ class ArgSet(object):
     """
     #: The :class:`Arg` objects that compose this argument set.
     args = None
+    # XXX: probably could also use a callback attribute
     def __init__(self):
         self.args = []
 
@@ -207,14 +220,11 @@ class WebArgSet(ArgSet):
                 Arg("web_path", type="PATH", help="Relative path to your application root"),
                 ]
 
-class MysqlArgSet(ArgSet):
-    """Common arguments for applications that use a MySQL database."""
+class DbArgSet(ArgSet):
+    """Common arguments for applications that use a database."""
     def __init__(self):
         self.args = [
-                Arg("mysql_host", type="HOST", help="Host that your MySQL server lives on"),
-                Arg("mysql_db", type="DB", help="Name of the database to populate"),
-                Arg("mysql_user", type="USER", help="Name of user to access database with"),
-                Arg("mysql_password", type="PWD", password=True, help="Password of the database user"),
+                Arg("dsn", type="DSN", help="Database Source Name, i.e. mysql://user:pass@host/dbname", callback=dsn_callback),
                 ]
 
 class AdminArgSet(ArgSet):
@@ -282,7 +292,7 @@ class ArgSchema(object):
     def add(self, arg):
         """Adds an argument to our schema."""
         self.args[arg.name] = arg
-    def commit(self, dir):
+    def commit(self, application, dir):
         """Populates :attr:`strategies` and :attr:`provides`"""
         self.strategies = []
         self.provides = set()
@@ -290,7 +300,7 @@ class ArgSchema(object):
         raw_strategies = [
                 EnvironmentStrategy(self),
                 ScriptsWebStrategy(dir),
-                ScriptsMysqlStrategy(dir),
+                ScriptsMysqlStrategy(application, dir),
                 ScriptsEmailStrategy(),
                 ]
         for arg in self.args.values():
@@ -318,7 +328,8 @@ class ArgSchema(object):
         Load values from strategy.  Must be called after :meth:`commit`.  We
         omit strategies whose provided variables are completely specified
         already.  Will raise :exc:`MissingRequiredParam` if strategies aren't
-        sufficient to fill all options.
+        sufficient to fill all options.  It will then run any callbacks on
+        arguments.
         """
         unfilled = set(name for name in self.args if getattr(options, name) is None)
         missing = unfilled - self.provides
@@ -331,6 +342,10 @@ class ArgSchema(object):
                 if getattr(options, name) is not None:
                     logging.warning("Overriding pre-specified value for %s", name)
             strategy.execute(options)
+        for arg in self.args.values():
+            if arg.callback is None:
+                continue
+            arg.callback(options)
 
 class Error(wizard.Error):
     """Base error class for this module."""