<commit_before>"""Provides convenient access to SQLObject-managed and/or SQLAlchemy-managed
databases.

This module enables easy use of an SQLObject database by providing an 
auto-connect hub that will utilize the db uri string given in the Paste conf
file called ``sqlobject.dburi``.

A SQLAlchemy ``SessionContext`` is also available: it provides both thread and
process safe ``Session`` objects via the ``session_context.current`` property.
"""
import thread
from paste.deploy.converters import asbool

import pylons
import pylons.util

__all__ = ["PackageHub", "AutoConnectHub"]

# Provide support for sqlalchemy
engines = {}
try:
    import sqlalchemy
    from sqlalchemy.ext import sessioncontext

    def app_scope():
        """Return the id keying the current database session's scope.

        The session is particular to the current Pylons application -- this
        returns an id generated from the current thread and the current Pylons
        application's Globals object at pylons.g (if one is registered).
        """
        try:
            app_scope_id = str(id(pylons.g._current_obj()))
        except TypeError:
            app_scope_id = ''
        return '%s|%i' % (app_scope_id, thread.get_ident())

    def create_engine(uri=None, echo=None):
        """Create a SQLAlchemy db engine. Uses the configuration values from
        ``get_engine_conf`` if none are specified."""
        uri, echo = get_engine_conf(uri, echo)
        engine = sqlalchemy.create_engine(uri, echo=echo)
        return engine

    def get_engine_conf(uri=None, echo=None):
        """Returns a tuple of SQLAlchemy engine configuration values (uri,
        echo) from the Pylons config file values ``sqlalchemy.dburi`` and
        ``sqlalchemy.echo`` when none are specified."""
        if uri is None:
            uri = pylons.util.config_get('sqlalchemy.dburi')
        if not uri:
            raise KeyError('No SQLAlchemy database config found!')
        if echo is None:
            echo = pylons.util.config_get('sqlalchemy.echo', False)
        return uri, echo

    def get_engines():
        """Return a dict of cached SQLAlchemy engines.

        Engines are cached to an application's ``Globals`` (``g``) object. If
        for whatever reason the ``g`` object has not been registered (outside
        of a web request), engines are cached to the global ``engines`` dict
        instead."""
        try:
            if not hasattr(pylons.g, '_db_engines'):
                db_engines = pylons.g._db_engines = {}
            else:
                db_engines = pylons.g._db_engines
        except TypeError:
            db_engines = engines
        return db_engines

    def make_session(uri=None, echo=None):
        """Returns a SQLAlchemy session for the specified database uri from
        the the engine cache (returned from ``get_engines``)``. Uses the
        configuration values from ``get_engine_conf`` when None is specified.
        
        If the uri's engine does not exist, it will be created and added to
        the engine cache.
        """<commit_msg>[svn] rename engines to _db_engines<commit_after>"""Provides convenient access to SQLObject-managed and/or SQLAlchemy-managed
databases.

This module enables easy use of an SQLObject database by providing an 
auto-connect hub that will utilize the db uri string given in the Paste conf
file called ``sqlobject.dburi``.

A SQLAlchemy ``SessionContext`` is also available: it provides both thread and
process safe ``Session`` objects via the ``session_context.current`` property.
"""
import thread
from paste.deploy.converters import asbool

import pylons
import pylons.util

__all__ = ["PackageHub", "AutoConnectHub"]

# Provide support for sqlalchemy
_db_engines = {}
try:
    import sqlalchemy
    from sqlalchemy.ext import sessioncontext

    def app_scope():
        """Return the id keying the current database session's scope.

        The session is particular to the current Pylons application -- this
        returns an id generated from the current thread and the current Pylons
        application's Globals object at pylons.g (if one is registered).
        """
        try:
            app_scope_id = str(id(pylons.g._current_obj()))
        except TypeError:
            app_scope_id = ''
        return '%s|%i' % (app_scope_id, thread.get_ident())

    def create_engine(uri=None, echo=None):
        """Create a SQLAlchemy db engine. Uses the configuration values from
        ``get_engine_conf`` if none are specified."""
        uri, echo = get_engine_conf(uri, echo)
        engine = sqlalchemy.create_engine(uri, echo=echo)
        return engine

    def get_engine_conf(uri=None, echo=None):
        """Returns a tuple of SQLAlchemy engine configuration values (uri,
        echo) from the Pylons config file values ``sqlalchemy.dburi`` and
        ``sqlalchemy.echo`` when none are specified."""
        if uri is None:
            uri = pylons.util.config_get('sqlalchemy.dburi')
        if not uri:
            raise KeyError('No SQLAlchemy database config found!')
        if echo is None:
            echo = pylons.util.config_get('sqlalchemy.echo', False)
        return uri, echo

    def get_engines():
        """Return a dict of cached SQLAlchemy engines.

        Engines are cached to an application's ``Globals`` (``g``) object. If
        for whatever reason the ``g`` object has not been registered (outside
        of a web request), engines are cached to the global ``engines`` dict
        instead."""
        try:
            if not hasattr(pylons.g, '_db_engines'):
                db_engines = pylons.g._db_engines = {}
            else:
                db_engines = pylons.g._db_engines
            return db_engines
        except TypeError:
            return _db_engines

    def make_session(uri=None, echo=None):
        """Returns a SQLAlchemy session for the specified database uri from
        the the engine cache (returned from ``get_engines``)``. Uses the
        configuration values from ``get_engine_conf`` when None is specified.
        
        If the uri's engine does not exist, it will be created and added to
        the engine cache.
        """
{'fraction_non_alphanumeric': 0.08414082687338502, 'fraction_numerical': 0.0, 'mean_word_length': 2.7083832335329343, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1412394', 'n_tokens_mistral': 1740, 'n_tokens_neox': 1663, 'n_words': 638}