root/galaxy-central/eggs/SQLAlchemy-0.5.6_dev_r6498-py2.6.egg/sqlalchemy/engine/__init__.py

リビジョン 3, 10.5 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

行番号 
1# engine/__init__.py
2# Copyright (C) 2005, 2006, 2007, 2008, 2009 Michael Bayer mike_mp@zzzcomputing.com
3#
4# This module is part of SQLAlchemy and is released under
5# the MIT License: http://www.opensource.org/licenses/mit-license.php
6
7"""SQL connections, SQL execution and high-level DB-API interface.
8
9The engine package defines the basic components used to interface
10DB-API modules with higher-level statement construction,
11connection-management, execution and result contexts.  The primary
12"entry point" class into this package is the Engine and it's public
13constructor ``create_engine()``.
14
15This package includes:
16
17base.py
18    Defines interface classes and some implementation classes which
19    comprise the basic components used to interface between a DB-API,
20    constructed and plain-text statements, connections, transactions,
21    and results.
22
23default.py
24    Contains default implementations of some of the components defined
25    in base.py.  All current database dialects use the classes in
26    default.py as base classes for their own database-specific
27    implementations.
28
29strategies.py
30    The mechanics of constructing ``Engine`` objects are represented
31    here.  Defines the ``EngineStrategy`` class which represents how
32    to go from arguments specified to the ``create_engine()``
33    function, to a fully constructed ``Engine``, including
34    initialization of connection pooling, dialects, and specific
35    subclasses of ``Engine``.
36
37threadlocal.py
38    The ``TLEngine`` class is defined here, which is a subclass of
39    the generic ``Engine`` and tracks ``Connection`` and
40    ``Transaction`` objects against the identity of the current
41    thread.  This allows certain programming patterns based around
42    the concept of a "thread-local connection" to be possible.
43    The ``TLEngine`` is created by using the "threadlocal" engine
44    strategy in conjunction with the ``create_engine()`` function.
45
46url.py
47    Defines the ``URL`` class which represents the individual
48    components of a string URL passed to ``create_engine()``.  Also
49    defines a basic module-loading strategy for the dialect specifier
50    within a URL.
51"""
52
53import sqlalchemy.databases
54from sqlalchemy.engine.base import (
55    BufferedColumnResultProxy,
56    BufferedColumnRow,
57    BufferedRowResultProxy,
58    Compiled,
59    Connectable,
60    Connection,
61    DefaultRunner,
62    Dialect,
63    Engine,
64    ExecutionContext,
65    NestedTransaction,
66    ResultProxy,
67    RootTransaction,
68    RowProxy,
69    SchemaIterator,
70    Transaction,
71    TwoPhaseTransaction
72    )
73from sqlalchemy.engine import strategies
74from sqlalchemy import util
75
76
77__all__ = (
78    'BufferedColumnResultProxy',
79    'BufferedColumnRow',
80    'BufferedRowResultProxy',
81    'Compiled',
82    'Connectable',
83    'Connection',
84    'DefaultRunner',
85    'Dialect',
86    'Engine',
87    'ExecutionContext',
88    'NestedTransaction',
89    'ResultProxy',
90    'RootTransaction',
91    'RowProxy',
92    'SchemaIterator',
93    'Transaction',
94    'TwoPhaseTransaction',
95    'create_engine',
96    'engine_from_config',
97    )
98
99
100default_strategy = 'plain'
101def create_engine(*args, **kwargs):
102    """Create a new Engine instance.
103
104    The standard method of specifying the engine is via URL as the
105    first positional argument, to indicate the appropriate database
106    dialect and connection arguments, with additional keyword
107    arguments sent as options to the dialect and resulting Engine.
108
109    The URL is a string in the form
110    ``dialect://user:password@host/dbname[?key=value..]``, where
111    ``dialect`` is a name such as ``mysql``, ``oracle``, ``postgres``,
112    etc.  Alternatively, the URL can be an instance of
113    :class:`~sqlalchemy.engine.url.URL`.
114
115    `**kwargs` takes a wide variety of options which are routed
116    towards their appropriate components.  Arguments may be
117    specific to the Engine, the underlying Dialect, as well as the
118    Pool.  Specific dialects also accept keyword arguments that
119    are unique to that dialect.   Here, we describe the parameters
120    that are common to most ``create_engine()`` usage.
121   
122    :param assert_unicode=False: When set to ``True`` alongside
123        convert_unicode=``True``, asserts that incoming string bind
124        parameters are instances of ``unicode``, otherwise raises an
125        error. Only takes effect when ``convert_unicode==True``. This
126        flag is also available on the ``String`` type and its
127        descendants. New in 0.4.2.
128
129    :param connect_args: a dictionary of options which will be
130        passed directly to the DBAPI's ``connect()`` method as
131        additional keyword arguments.
132
133    :param convert_unicode=False: if set to True, all
134        String/character based types will convert Unicode values to raw
135        byte values going into the database, and all raw byte values to
136        Python Unicode coming out in result sets. This is an
137        engine-wide method to provide unicode conversion across the
138        board. For unicode conversion on a column-by-column level, use
139        the ``Unicode`` column type instead, described in `types`.
140
141    :param creator: a callable which returns a DBAPI connection.
142        This creation function will be passed to the underlying
143        connection pool and will be used to create all new database
144        connections. Usage of this function causes connection
145        parameters specified in the URL argument to be bypassed.
146
147    :param echo=False: if True, the Engine will log all statements
148        as well as a repr() of their parameter lists to the engines
149        logger, which defaults to sys.stdout. The ``echo`` attribute of
150        ``Engine`` can be modified at any time to turn logging on and
151        off. If set to the string ``"debug"``, result rows will be
152        printed to the standard output as well. This flag ultimately
153        controls a Python logger; see `dbengine_logging` at the end of
154        this chapter for information on how to configure logging
155        directly.
156
157    :param echo_pool=False: if True, the connection pool will log
158        all checkouts/checkins to the logging stream, which defaults to
159        sys.stdout. This flag ultimately controls a Python logger; see
160        `dbengine_logging` for information on how to configure logging
161        directly.
162
163    :param encoding='utf-8': the encoding to use for all Unicode
164        translations, both by engine-wide unicode conversion as well as
165        the ``Unicode`` type object.
166
167    :param label_length=None: optional integer value which limits
168        the size of dynamically generated column labels to that many
169        characters. If less than 6, labels are generated as
170        "_(counter)". If ``None``, the value of
171        ``dialect.max_identifier_length`` is used instead.
172
173    :param module=None: used by database implementations which
174        support multiple DBAPI modules, this is a reference to a DBAPI2
175        module to be used instead of the engine's default module. For
176        PostgreSQL, the default is psycopg2. For Oracle, it's cx_Oracle.
177
178    :param pool=None: an already-constructed instance of
179        :class:`~sqlalchemy.pool.Pool`, such as a
180        :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this
181        pool will be used directly as the underlying connection pool
182        for the engine, bypassing whatever connection parameters are
183        present in the URL argument. For information on constructing
184        connection pools manually, see `pooling`.
185
186    :param poolclass=None: a :class:`~sqlalchemy.pool.Pool`
187        subclass, which will be used to create a connection pool
188        instance using the connection parameters given in the URL. Note
189        this differs from ``pool`` in that you don't actually
190        instantiate the pool in this case, you just indicate what type
191        of pool to be used.
192
193    :param max_overflow=10: the number of connections to allow in
194        connection pool "overflow", that is connections that can be
195        opened above and beyond the pool_size setting, which defaults
196        to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`.
197
198    :param pool_size=5: the number of connections to keep open
199        inside the connection pool. This used with :class:`~sqlalchemy.pool.QueuePool` as
200        well as :class:`~sqlalchemy.pool.SingletonThreadPool`.
201
202    :param pool_recycle=-1: this setting causes the pool to recycle
203        connections after the given number of seconds has passed. It
204        defaults to -1, or no timeout. For example, setting to 3600
205        means connections will be recycled after one hour. Note that
206        MySQL in particular will ``disconnect automatically`` if no
207        activity is detected on a connection for eight hours (although
208        this is configurable with the MySQLDB connection itself and the
209        server configuration as well).
210
211    :param pool_timeout=30: number of seconds to wait before giving
212        up on getting a connection from the pool. This is only used
213        with :class:`~sqlalchemy.pool.QueuePool`.
214
215    :param strategy='plain': used to invoke alternate :class:`~sqlalchemy.engine.base.Engine.`
216        implementations. Currently available is the ``threadlocal``
217        strategy, which is described in :ref:`threadlocal_strategy`.
218   
219    """
220
221    strategy = kwargs.pop('strategy', default_strategy)
222    strategy = strategies.strategies[strategy]
223    return strategy.create(*args, **kwargs)
224
225def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
226    """Create a new Engine instance using a configuration dictionary.
227
228    The dictionary is typically produced from a config file where keys
229    are prefixed, such as sqlalchemy.url, sqlalchemy.echo, etc.  The
230    'prefix' argument indicates the prefix to be searched for.
231
232    A select set of keyword arguments will be "coerced" to their
233    expected type based on string values.  In a future release, this
234    functionality will be expanded and include dialect-specific
235    arguments.
236    """
237
238    opts = _coerce_config(configuration, prefix)
239    opts.update(kwargs)
240    url = opts.pop('url')
241    return create_engine(url, **opts)
242
243def _coerce_config(configuration, prefix):
244    """Convert configuration values to expected types."""
245
246    options = dict((key[len(prefix):], configuration[key])
247                   for key in configuration
248                   if key.startswith(prefix))
249    for option, type_ in (
250        ('convert_unicode', bool),
251        ('pool_timeout', int),
252        ('echo', bool),
253        ('echo_pool', bool),
254        ('pool_recycle', int),
255        ('pool_size', int),
256        ('max_overflow', int),
257        ('pool_threadlocal', bool),
258    ):
259        util.coerce_kw_type(options, option, type_)
260    return options
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。