def _create_database(self, key): """Create database if it doesn't exist.""" conn_string = self.test_databases[key] conn_pieces = urlparse.urlparse(conn_string) if conn_string.startswith('mysql'): (user, password, database, host) = \ get_mysql_connection_info(conn_pieces) sql = "create database if not exists %s;" % database cmd = ("mysql -u \"%(user)s\" %(password)s -h %(host)s " "-e \"%(sql)s\"" % { 'user': user, 'password': password, 'host': host, 'sql': sql }) self.execute_cmd(cmd) elif conn_string.startswith('postgresql'): (user, password, database, host) = \ get_pgsql_connection_info(conn_pieces) os.environ['PGPASSWORD'] = password os.environ['PGUSER'] = user sqlcmd = ("psql -w -U %(user)s -h %(host)s -c" " '%(sql)s' -d template1") sql = ("create database if not exists %s;") % database createtable = sqlcmd % {'user': user, 'host': host, 'sql': sql} # 0 means databases is created # 256 means it already exists (which is fine) # otherwise raise an error out, err = processutils.trycmd(createtable, shell=True, check_exit_code=[0, 256], discard_warnings=True) output = out or err if err != '': self.fail("Failed to run: %s\n%s" % (createtable, output)) os.unsetenv('PGPASSWORD') os.unsetenv('PGUSER')
def _create_database(self, key): """Create database if it doesn't exist.""" conn_string = self.test_databases[key] conn_pieces = urlparse.urlparse(conn_string) if conn_string.startswith('mysql'): (user, password, database, host) = \ get_mysql_connection_info(conn_pieces) sql = "create database if not exists %s;" % database cmd = ("mysql -u \"%(user)s\" %(password)s -h %(host)s " "-e \"%(sql)s\"" % {'user': user, 'password': password, 'host': host, 'sql': sql}) self.execute_cmd(cmd) elif conn_string.startswith('postgresql'): (user, password, database, host) = \ get_pgsql_connection_info(conn_pieces) os.environ['PGPASSWORD'] = password os.environ['PGUSER'] = user sqlcmd = ("psql -w -U %(user)s -h %(host)s -c" " '%(sql)s' -d template1") sql = ("create database if not exists %s;") % database createtable = sqlcmd % {'user': user, 'host': host, 'sql': sql} # 0 means databases is created # 256 means it already exists (which is fine) # otherwise raise an error out, err = processutils.trycmd(createtable, shell=True, check_exit_code=[0, 256], discard_warnings=True) output = out or err if err != '': self.fail("Failed to run: %s\n%s" % (createtable, output)) os.unsetenv('PGPASSWORD') os.unsetenv('PGUSER')
def execute_cmd(self, cmd=None): out, err = processutils.trycmd(cmd, shell=True, discard_warnings=True) output = out or err LOG.debug(output) self.assertEqual('', err, "Failed to run: %s\n%s" % (cmd, output))