commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnue] r9986 - in trunk/gnue-common/src: apps base datasources


From: reinhard
Subject: [gnue] r9986 - in trunk/gnue-common/src: apps base datasources
Date: Sun, 18 Oct 2009 12:59:44 -0500 (CDT)

Author: reinhard
Date: 2009-10-18 12:59:43 -0500 (Sun, 18 Oct 2009)
New Revision: 9986

Added:
   trunk/gnue-common/src/base/config.py
   trunk/gnue-common/src/datasources/backends.py
Removed:
   trunk/gnue-common/src/base/utils.py
Modified:
   trunk/gnue-common/src/apps/GBaseApp.py
   trunk/gnue-common/src/base/log.py
   trunk/gnue-common/src/datasources/ConnectionTriggerObj.py
   trunk/gnue-common/src/datasources/GConnections.py
   trunk/gnue-common/src/datasources/GDataSource.py
Log:
Use new configuration management module for backends.conf (formerly known as
connections.conf).

issue146 testing


Modified: trunk/gnue-common/src/apps/GBaseApp.py
===================================================================
--- trunk/gnue-common/src/apps/GBaseApp.py      2009-10-18 17:51:05 UTC (rev 
9985)
+++ trunk/gnue-common/src/apps/GBaseApp.py      2009-10-18 17:59:43 UTC (rev 
9986)
@@ -43,7 +43,7 @@
 from gnue.common.base.i18n import utranslate as u_
 
 from gnue.common.apps import GConfig, GDebug
-from gnue.common.datasources import GConnections
+from gnue.common.datasources import backends, GConnections
 from gnue.common.apps.CommandOption import CommandOption
 
 
@@ -381,32 +381,19 @@
                     lhOptions['_password'] = self.OPTIONS['password']
 
             if self.OPTIONS['connections']:
-                self.connections_file = self.OPTIONS['connections']
+                connections_file = self.OPTIONS['connections']
             elif os.environ.has_key('GNUE_CONNECTIONS'):
-                self.connections_file = os.environ['GNUE_CONNECTIONS']
+                connections_file = os.environ['GNUE_CONNECTIONS']
             else:
-                self.connections_file = os.path.join(paths.config,
+                connections_file = os.path.join(paths.config,
                         "connections.conf")
 
-            assert log.debug('Connection Definition: "%s"' %
-                    self.connections_file)
+            backends.initialize_backends(connections_file)
 
-            try:
-                self.connections = GConnections.GConnections( \
-                        self.connections_file, loginOptions = lhOptions)
+            self.connections = GConnections.GConnections(
+                    connections_file, loginOptions = lhOptions)
 
-            except GConnections.InvalidFormatError, msg:
-                raise errors.AdminError, \
-                    u_("Unable to load the connections definition file.\n\n"
-                       "The connections file is in an invalid format.\n%s") \
-                               % msg
 
-            except IOError:
-                raise StartupError, \
-                    u_("Unable to load the connections definition file: %s.") \
-                    % self.connections_file
-
-
     # -------------------------------------------------------------------------
     # Run the program
     # -------------------------------------------------------------------------

Copied: trunk/gnue-common/src/base/config.py (from rev 9984, 
trunk/gnue-common/src/base/utils.py)
===================================================================
--- trunk/gnue-common/src/base/config.py                                (rev 0)
+++ trunk/gnue-common/src/base/config.py        2009-10-18 17:59:43 UTC (rev 
9986)
@@ -0,0 +1,171 @@
+# GNU Enterprise Common Library - Configuration file management
+#
+# Copyright 2001-2009 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 3, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+
+"""
+Configuration file management.
+"""
+
+import ConfigParser
+import os.path
+import urllib
+
+from gnue import paths
+from gnue.common.base import errors
+
+__all__ = ['Config', 'config_files', 'ConfigParserError']
+
+
+# =============================================================================
+# Configuration file
+# =============================================================================
+
+class Config(ConfigParser.ConfigParser):
+    """
+    The configuration for a configuration realm.
+
+    The configuration realm can be understood as the configuration file name
+    without the .conf ending.  However, for each configuration realm, several
+    files are scanned sequentially according to the L{config_files} function.
+
+    As an improvement to the standard Python ConfigParser module, this parser
+    can also handle network URLs instead of local files.
+
+    All errors happening during configuration file parsing are considered to be
+    of group 'admin'.
+    """
+
+    def __init__(self, realm, additional_url=None):
+        """
+        Scan the configuration for the given realm.
+
+        @param realm: Configuration realm (the name of the configuration file
+            without the .conf ending).
+        @type realm: string
+        """
+        # We may not import log at the beginning of this file since log imports
+        # this module.
+        from gnue.common.base import log
+
+        url_list = config_files(realm)
+
+        # TODO: location of old configuration file (gnue.conf,
+        # connections.conf), deprecate with 0.8, remove with 0.9
+        if additional_url is not None:
+            url_list.insert(0, additional_url)
+
+        ConfigParser.ConfigParser.__init__(self)
+
+        for url in url_list:
+            log.info("Reading configuration for %(realm)s from %(url)s" % {
+                'realm': realm,
+                'url':   url})
+            try:
+                handle = urllib.urlopen(url)
+                self.readfp (handle)
+            except StandardError:
+                (group, name, message, detail) = errors.get_exception()
+                group = 'admin'         # Redirect exceptions to 'admin' group.
+                raise ConfigParserError(group, name, message, detail)
+
+
+# =============================================================================
+# Global functions
+# =============================================================================
+
+# -----------------------------------------------------------------------------
+# Return a list of config files to use
+# -----------------------------------------------------------------------------
+
+def config_files(realm):
+    """
+    Return a list of filenames to parse for a specific configuration realm.
+
+    The list contains all existing config files in the following order of
+    directories searched:
+        1. system configuration file (usually /etc/gnue/*.conf)
+        2. system configuration directory (usually /etc/gnue/*.d/)
+        3. user configuration (~/.gnue/*.conf)
+        4. local configuration (etc/*.conf)
+        5. environment variable location ($GNUE_*_CONF)
+        6. fixed system configuration (/etc/gnue/*.conf.fixed)
+    The practical use for 6. is to define configuration entries that cannot be
+    overwritten by normal users.
+
+    For example, if realm is C{backends}, on a standard install on a POSIX
+    system, the file would be searched in:
+        1. C{/etc/gnue/backends.conf}
+        2. C{/etc/gnue/backends.d/*}
+        3. C{~/.gnue/backends.conf}
+        4. C{etc/backends.conf} (from the current directory)
+        5. the content of the C{GNUE_BACKENDS_CONF} environment variable
+        6. C{/etc/gnue/backends.conf.fixed}
+
+    @param realm: name of the configuration file without the .conf ending
+    @type realm: string
+    @return: list of full path names of configuration files to parse
+    @rtype: string
+    """
+
+    files = []
+
+    # 1. system configuration file (usually /etc/gnue/*.conf)
+    files.append(os.path.join(paths.config, realm + '.conf'))
+
+    # 2. system configuration directory (usually /etc/gnue/*.d/)
+    confdir = os.path.join(paths.config, realm + '.d')
+    if os.path.isdir(confdir):
+        indir = os.listdir(confdir)
+        indir.sort()
+        files.extend([os.path.join(confdir, f) for f in indir])
+
+    # 3. user configuration (~/.gnue/*.conf)
+    if os.environ.has_key('HOME'):
+        files.append(os.path.join(os.environ['HOME'], '.gnue', realm + 
'.conf'))
+
+    # 4. local configuration (etc/*.conf)
+    files.append(os.path.join('etc', realm + '.conf'))
+
+    # 5. environment variable location ($GNUE_*)
+    if os.environ.has_key('GNUE_' + realm.upper() + '_CONF'):
+        files.append(os.environ['GNUE_' + realm.upper() + '_CONF'])
+
+    # 6. fixed system configuration (/etc/gnue/*.conf.fixed)
+    files.append(os.path.join(paths.config, realm + '.conf.fixed'))
+
+    return [f for f in files if os.path.isfile(f)]
+
+
+# =============================================================================
+# Exceptions
+# =============================================================================
+
+# -----------------------------------------------------------------------------
+# Error in configuration file
+# -----------------------------------------------------------------------------
+
+class ConfigParserError(errors.RemoteError):
+    """
+    Error parsing configuration file.
+    """
+
+    pass

Modified: trunk/gnue-common/src/base/log.py
===================================================================
--- trunk/gnue-common/src/base/log.py   2009-10-18 17:51:05 UTC (rev 9985)
+++ trunk/gnue-common/src/base/log.py   2009-10-18 17:59:43 UTC (rev 9986)
@@ -102,7 +102,7 @@
 import traceback
 
 from gnue.common.lib import modules
-from gnue.common.base import errors, utils
+from gnue.common.base import config, errors
 
 __all__ = ['logged_f', 'deprecated_f',
         'logged_f_n', 'deprecated_f_n',
@@ -759,7 +759,7 @@
 
     # Configure logging through configuration files, or use standard 
configuration
     # if no configuration files available.
-    config_files = utils.config_files('log')
+    config_files = config.config_files('log')
     if config_files:
         logging.config.fileConfig(config_files)
     else:

Deleted: trunk/gnue-common/src/base/utils.py
===================================================================
--- trunk/gnue-common/src/base/utils.py 2009-10-18 17:51:05 UTC (rev 9985)
+++ trunk/gnue-common/src/base/utils.py 2009-10-18 17:59:43 UTC (rev 9986)
@@ -1,96 +0,0 @@
-# GNU Enterprise Common Library - Basic Utilities
-#
-# Copyright 2001-2009 Free Software Foundation
-#
-# This file is part of GNU Enterprise
-#
-# GNU Enterprise is free software; you can redistribute it
-# and/or modify it under the terms of the GNU General Public
-# License as published by the Free Software Foundation; either
-# version 3, or (at your option) any later version.
-#
-# GNU Enterprise is distributed in the hope that it will be
-# useful, but WITHOUT ANY WARRANTY; without even the implied
-# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-# PURPOSE. See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public
-# License along with program; see the file COPYING. If not,
-# write to the Free Software Foundation, Inc., 59 Temple Place
-# - Suite 330, Boston, MA 02111-1307, USA.
-#
-# $Id$
-
-"""
-The C{utils} module provides some very basic although GNU Enterprise specific
-utility functions.
-"""
-
-import os.path
-
-from gnue import paths
-
-__all__ = ['config_files']
-
-
-# -----------------------------------------------------------------------------
-# Return a list of config files to use
-# -----------------------------------------------------------------------------
-
-def config_files(name):
-    """
-    Return a list of filenames to parse for a specific configuration file.
-
-    The list contains all existing config files in the following order of
-    directories searched:
-        1. system configuration file (usually /etc/gnue/*.conf)
-        2. system configuration directory (usually /etc/gnue/*.d/)
-        3. user configuration (~/.gnue/*.conf)
-        4. local configuration (etc/*.conf)
-        5. environment variable location ($GNUE_*_CONF)
-        6. fixed system configuration (/etc/gnue/*.conf.fixed)
-    The practical use for 6. is to define configuration entries that cannot be
-    overwritten by normal users.
-
-    For example, if name is C{backends}, on a standard install on a POSIX
-    system, the file would be searched in:
-        1. C{/etc/gnue/backends.conf}
-        2. C{/etc/gnue/backends.d/*}
-        3. C{~/.gnue/backends.conf}
-        4. C{etc/backends.conf} (from the current directory)
-        5. the content of the C{GNUE_BACKENDS_CONF} environment variable
-        6. C{/etc/gnue/backends.conf.fixed}
-
-    @param name: name of the configuration file without the .conf ending
-    @type name: string
-    @return: list of full path names of configuration files to parse
-    @rtype: string
-    """
-
-    files = []
-
-    # 1. system configuration file (usually /etc/gnue/*.conf)
-    files.append(os.path.join(paths.config, name + '.conf'))
-
-    # 2. system configuration directory (usually /etc/gnue/*.d/)
-    confdir = os.path.join(paths.config, name + '.d')
-    if os.path.isdir(confdir):
-        indir = os.listdir(confdir)
-        indir.sort()
-        files.extend([os.path.join(confdir, f) for f in indir])
-
-    # 3. user configuration (~/.gnue/*.conf)
-    if os.environ.has_key('HOME'):
-        files.append(os.path.join(os.environ['HOME'], '.gnue', name + '.conf'))
-
-    # 4. local configuration (etc/*.conf)
-    files.append(os.path.join('etc', name + '.conf'))
-
-    # 5. environment variable location ($GNUE_*)
-    if os.environ.has_key('GNUE_' + name.upper() + '_CONF'):
-        files.append(os.environ['GNUE_' + name.upper() + '_CONF'])
-
-    # 6. fixed system configuration (/etc/gnue/*.conf.fixed)
-    files.append(os.path.join(paths.config, name + '.conf.fixed'))
-
-    return [f for f in files if os.path.isfile(f)]

Modified: trunk/gnue-common/src/datasources/ConnectionTriggerObj.py
===================================================================
--- trunk/gnue-common/src/datasources/ConnectionTriggerObj.py   2009-10-18 
17:51:05 UTC (rev 9985)
+++ trunk/gnue-common/src/datasources/ConnectionTriggerObj.py   2009-10-18 
17:59:43 UTC (rev 9986)
@@ -32,7 +32,9 @@
 
 from gnue.common.definitions import GObjects
 
+from gnue.common.datasources import backends
 
+
 # =============================================================================
 # Connection wrapper object
 # =============================================================================
@@ -89,7 +91,7 @@
     namespace, because they will be handled like XML elements defined within
     the root element.
     """
-    for name in connections.getConnectionNames(): 
+    for name in backends.BACKENDS.sections(): 
         try: 
             conn = connections.getConnection(name)
         except: 
@@ -105,7 +107,7 @@
   Adds all the connection names to the global trigger namespace. DEPRECIATED.
   """
 
-  for name in connections.getConnectionNames (): 
+  for name in connections.backends.BACKENDS.sections(): 
     try: 
       conn = connections.getConnection (name)
     except: 

Modified: trunk/gnue-common/src/datasources/GConnections.py
===================================================================
--- trunk/gnue-common/src/datasources/GConnections.py   2009-10-18 17:51:05 UTC 
(rev 9985)
+++ trunk/gnue-common/src/datasources/GConnections.py   2009-10-18 17:59:43 UTC 
(rev 9986)
@@ -24,19 +24,14 @@
 Connection manager system.
 """
 
-from ConfigParser import *
-from ConfigParser import RawConfigParser # is not in __all__
-
 import copy
 import locale
 import netrc
 
 from gnue.common.base import errors, log, plugin
 from gnue.common.utils.FileUtils import openResource, dyn_import
-from gnue.common.datasources import Exceptions, GLoginHandler
+from gnue.common.datasources import backends, Exceptions, GLoginHandler
 
-import warnings
-
 # =============================================================================
 # Exceptions
 # =============================================================================
@@ -46,10 +41,8 @@
   Connection name not found in connections.conf.
   """
   def __init__ (self, name, file):
-    msg = u_("The connections file does not contain a definition "
-             "for \"%(connection)s\".\n\nFile: %(file)s") \
-           % {'connection': name,
-              'file'      : file}
+    msg = u_("No backend definition for '%(connection)s'.") % {
+            'connection': name}
     errors.AdminError.__init__ (self, msg)
 
 # -----------------------------------------------------------------------------
@@ -85,17 +78,13 @@
   """
   Class that loads connection definition files and maintains
   database connections.
-
-  If you pass GConnections an "eventHandler" instance, it will generate a
-  Connections:Connect(name, base) when a new connection is created.
   """
 
   # ---------------------------------------------------------------------------
   # Constructor
   # ---------------------------------------------------------------------------
 
-  def __init__ (self, location, loginHandler = None, loginOptions = {},
-                eventhandler = None):
+  def __init__ (self, location, loginHandler = None, loginOptions = {}):
     """
     Create a new GConnections instance.
 
@@ -103,7 +92,6 @@
     @param loginHandler: Instance of a L{GLoginHandler.LoginHandler}
       descendant to ask the user for login data.
     @param loginOptions: Default data for the login handler.
-    @param eventhandler: Event handler to notify about new connections.
     """
 
     # These 4 may not be private as they are used by appserver to clone the
@@ -111,67 +99,14 @@
     self._location     = location
     self._loginHandler = loginHandler
     self._loginOptions = loginOptions
-    self._eventHandler = eventhandler
 
-    # Primary connection names and their parameters
-    self.__primaries = {}
-
-    # Alias connection names and their parameters
-    self.__aliases = {}
-
-    # All connection names and their parameters
-    self.__definitions = {}
-
     # Dictionary of authenticated users per connection name.
     self.__authenticatedUsers = {}
 
     # Dictionary of open connections (GConnection objects) per connection name.
     self.__openConnections = {}
 
-    # Parse the connections.conf file
-    parser = RawConfigParser ()
 
-    if len (self._location):
-      fileHandle = openResource (self._location)
-
-      try:
-        parser.readfp (fileHandle)
-
-      except DuplicateSectionError:
-        tmsg =  u_("The connections file has duplicate source definitions."
-                   "\n\nFile: %s") % location
-        raise InvalidFormatError, tmsg
-      except MissingSectionHeaderError:
-        tmsg = u_("The connections file has no source definitions."
-                  "\n\nFile: %s") % location
-        raise InvalidFormatError, tmsg
-      except Exception:
-        tmsg =  u_("The connections file cannot be parsed."
-                   "\n\nFile: %s") % location
-        raise InvalidFormatError, tmsg
-
-    # Read all the sections into a dict
-    # and make a note of all alias names
-    for section in parser.sections ():
-       self.__primaries [section] = {}
-       for att in parser.options (section):
-         if att == 'aliases':
-           for alias in ((parser.get (section,att)).lower ()).split ():
-             self.__aliases [alias] = section
-         else:
-           self.__primaries [section] [att] = parser.get (section, att)
-
-    # Fill in any aliases with their parameters
-    for alias in self.__aliases.keys():
-      section = self.__aliases [alias]
-      self.__aliases [alias] = copy.copy (self.__primaries [section])
-      self.__aliases [alias] ['_alias_of'] = section
-
-    # Create the dictionary with both primaries and aliases
-    self.__definitions.update (self.__aliases)
-    self.__definitions.update (self.__primaries)
-
-
   # ---------------------------------------------------------------------------
   # Set the login handler for opening connections
   # ---------------------------------------------------------------------------
@@ -185,110 +120,52 @@
 
 
   # ---------------------------------------------------------------------------
-  # Check if a parameter is given for a connection
+  # Returns a list of connection names
   # ---------------------------------------------------------------------------
 
-  def hasConnectionParameters (self, connection_name):
+  def getConnectionNames (self):
     """
-    Check if the given connection name exists in the connections.conf file.
+    DEPRECATED: use backends.BACKENDS.sections() instead.
     """
 
-    return self.__definitions.has_key (connection_name)
+    return backends.BACKENDS.sections()
 
+  getConnectionNames = log.deprecated_f(getConnectionNames)
 
-  # ---------------------------------------------------------------------------
-  # Get a parameter for a connection
-  # ---------------------------------------------------------------------------
 
-  def getConnectionParameter (self, connection_name, attribute, default = 
None):
-    """
-    Read a parameter from the connections.conf file.
-    """
-
-    try:
-      definition = self.__definitions [connection_name]
-      try:
-        return definition [attribute]
-      except:
-        return default
-    except KeyError:
-      raise NotFoundError, (connection_name, self._location)
-
-
   # ---------------------------------------------------------------------------
-  # Returns a list of connection names
-  # ---------------------------------------------------------------------------
-
-  def getConnectionNames (self, includeAliases = True):
-    """
-    Return a list of all connections from the connections.conf file.
-
-    @param includeAliases: Whether or not to include connection aliases.
-    @return: List with all connection names.
-    """
-
-    if includeAliases:
-      return self.__definitions.keys ()
-    else:
-      return self.__primaries.keys ()
-
-
-  # ---------------------------------------------------------------------------
   # Returns an dictionary of dictionaries describing all connections
   # ---------------------------------------------------------------------------
 
-  def getAllConnectionParameters (self, includeAliases = 1):
+  def getAllConnectionParameters (self):
     """
-    Return a dictionary of all connections from the connections.conf file.
-
-    @param includeAliases: Whether or not to include connection aliases.
-    @return: Dictionary where the keys are connection names and the values are
-      dictionaries with all connection parameters.
+    DEPRECATED: use backends.BACKENDS instead.
     """
 
-    if includeAliases:
-      return copy.deepcopy (self.__definitions)
-    else:
-      return copy.deepcopy (self.__primaries)
+    result = {}
+    for section in backends.BACKENDS.sections():
+        result[section] = dict(backends.BACKENDS.items(section))
 
+  getAllConnectionParameters = log.deprecated_f(getAllConnectionParameters)
 
+
   # ---------------------------------------------------------------------------
   # Returns a dictionary describing a connection
   # ---------------------------------------------------------------------------
 
   def getConnectionParameters (self, connection_name):
     """
-    Return the parameter dictionary for a given connection.
-
-    @return: Dictionary with parameter name and parameter value.
+    DEPRECATED: use backends.BACKENDS.items(connection_name) instead.
     """
 
-    try:
-      return copy.deepcopy (self.__definitions [connection_name])
-    except KeyError:
-      raise NotFoundError, (connection_name, self._location)
+    if not backends.BACKENDS.has_section(connection_name):
+      raise NotFoundError(connection_name)
 
+    return dict(backends.BACKENDS.items(connection_name))
 
-  # ---------------------------------------------------------------------------
-  # Add a connection entry (session specific; i.e., doesn't add
-  # to the connections.conf file, but to the current instance's
-  # list of available connections.
-  # ---------------------------------------------------------------------------
+  getConnectionParameters = log.deprecated_f(getConnectionParameters)
 
-  def addConnectionSpecification (self, name, parameters):
-    """
-    Add a session specific connection entry.
 
-    With this function, a temporary connection definition can be inserted
-    without having to change the connections.conf file.
-
-    @param name: Connection name.
-    @param parameters: Connection parameters as a dictionary.
-    """
-
-    self.__definitions [name.lower ()] = copy.copy (parameters)
-
-
   # ---------------------------------------------------------------------------
   # get a connection instance and optionally log into it
   # ---------------------------------------------------------------------------
@@ -320,8 +197,11 @@
       # This will throw a GConnections.NotFoundError if an unknown connection
       # name is specified. The calling method should catch this exception and
       # handle it properly (exit w/message)
-      parameters = self.getConnectionParameters (connection_base)
+      if not backends.BACKENDS.has_section(connection_base):
+        raise NotFoundError(connection_base)
 
+      parameters = dict(backends.BACKENDS.items(connection_base))
+
       driver   = parameters ['provider'].lower ().replace ('/', '.')
       dbdriver = plugin.find (driver, 'gnue.common.datasources.drivers',
                               'Connection')
@@ -457,10 +337,13 @@
           checkFields = fields
           needFieldConversion = False
 
-        descr = self.getConnectionParameter (connection_base, 'comment', '')
+        if backends.BACKENDS.has_option(connection_base, 'comment'):
+            descr = backends.BACKENDS.get(connection_basename, 'comment')
+        else:
+            descr = connection_base
         text  = u_('Login required for %(newline)s"%(description)s"') \
                  % {'newline': len (descr) and '\n' or '',
-                    'description': descr or connection_base}
+                    'description': descr}
 
         title  = u_("GNU Enterprise: Login to %s") % connection_base
         header = [(text, None, 'label', None, None, []),
@@ -511,10 +394,6 @@
       # of open connections
       self.__openConnections [connection_name] = connection
 
-      if self._eventHandler:
-        self._eventHandler.dispatchEvent ('Connections:Connect',
-              name = connection_name, base = connection_base)
-
     # Done
     connection.__connected = True
 

Modified: trunk/gnue-common/src/datasources/GDataSource.py
===================================================================
--- trunk/gnue-common/src/datasources/GDataSource.py    2009-10-18 17:51:05 UTC 
(rev 9985)
+++ trunk/gnue-common/src/datasources/GDataSource.py    2009-10-18 17:59:43 UTC 
(rev 9986)
@@ -31,7 +31,7 @@
 from gnue.common.definitions import GObjects, GParser, GParserHelpers
 from gnue.common import events
 from gnue.common.formatting import GTypecast
-from gnue.common.datasources import Exceptions, GConditions, GConnections
+from gnue.common.datasources import backends, Exceptions, GConditions, 
GConnections
 
 
 # =============================================================================
@@ -1069,12 +1069,10 @@
 
     # Add our database connection information to the connections
     # manager, then let it handle everything from there.
-    root = self.findParentOfType (None)
-    root._instance.connections.addConnectionSpecification (self.name, {
-           'name': self.name,
-           'provider': self.provider,
-           'dbname': self.dbname,
-           'host': self.host })
+    backends.BACKENDS.add_section(self.name)
+    backends.BACKENDS.set(self.name, 'provider', self.provider)
+    backends.BACKENDS.set(self.name, 'dbname', self.dbname)
+    backends.BACKENDS.set(self.name, 'host', self.host)
 
 
 # =============================================================================

Added: trunk/gnue-common/src/datasources/backends.py
===================================================================
--- trunk/gnue-common/src/datasources/backends.py                               
(rev 0)
+++ trunk/gnue-common/src/datasources/backends.py       2009-10-18 17:59:43 UTC 
(rev 9986)
@@ -0,0 +1,76 @@
+# GNU Enterprise Common Library - Database Backends Management
+#
+# Copyright 2009-2009 Free Software Foundation
+#
+# This file is part of GNU Enterprise.
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 3, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+
+"""
+Management of available database backends.
+"""
+
+from gnue.common.base import config, log
+
+__all__ = ['BACKENDS']
+
+
+# =============================================================================
+# Configuration object mirroring backends.conf
+# =============================================================================
+
+class __BackendsConfig(config.Config):
+
+    def __init__(self, additional_url=None):
+
+        config.Config.__init__(self, 'backends', additional_url)
+
+        # For all aliases, clone the whole section.
+        for section in self.sections():
+            if self.has_option(section, 'aliases'):
+                log.deprecated(
+                    "Backend definition for %(section)s uses 'aliases'" % {
+                        'section': section})
+                for alias in self.get(section, 'aliases').split():
+                    self.add_section(alias)
+                    for (option, value) in self.items(section):
+                        if option != 'aliases':
+                            self.set(alias, option, value)
+
+# -----------------------------------------------------------------------------
+
+BACKENDS = None
+
+# =============================================================================
+# Module initialization
+# =============================================================================
+
+def initialize_backends(additional_url=None):
+    """
+    Initialize the module by loading the configuration files.
+    """
+    
+    global BACKENDS
+    BACKENDS = __BackendsConfig(additional_url)
+
+
+if __name__ == '__main__':
+
+    #initialize_backends()      # TODO: Can initialize here when additional_url
+                                # has been removed
+    pass


Property changes on: trunk/gnue-common/src/datasources/backends.py
___________________________________________________________________
Name: svn:keywords
   + Id





reply via email to

[Prev in Thread] Current Thread [Next in Thread]