📄 base.py
字号:
# engine/base.py# Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com## This module is part of SQLAlchemy and is released under# the MIT License: http://www.opensource.org/licenses/mit-license.php"""Basic components for SQL execution and interfacing with DB-API.Defines the basic components used to interface DB-API modules withhigher-level statement-construction, connection-management, executionand result contexts."""import StringIO, sysfrom sqlalchemy import exceptions, schema, util, types, loggingfrom sqlalchemy.sql import expressionclass Dialect(object): """Define the behavior of a specific database and DB-API combination. Any aspect of metadata definition, SQL query generation, execution, result-set handling, or anything else which varies between databases is defined under the general category of the Dialect. The Dialect acts as a factory for other database-specific object implementations including ExecutionContext, Compiled, DefaultGenerator, and TypeEngine. All Dialects implement the following attributes: positional True if the paramstyle for this Dialect is positional. paramstyle the paramstyle to be used (some DB-APIs support multiple paramstyles). convert_unicode True if Unicode conversion should be applied to all ``str`` types. encoding type of encoding to use for unicode, usually defaults to 'utf-8'. schemagenerator a [sqlalchemy.schema#SchemaVisitor] class which generates schemas. schemadropper a [sqlalchemy.schema#SchemaVisitor] class which drops schemas. defaultrunner a [sqlalchemy.schema#SchemaVisitor] class which executes defaults. statement_compiler a [sqlalchemy.engine.base#Compiled] class used to compile SQL statements preparer a [sqlalchemy.sql.compiler#IdentifierPreparer] class used to quote identifiers. supports_alter ``True`` if the database supports ``ALTER TABLE``. max_identifier_length The maximum length of identifier names. supports_unicode_statements Indicate whether the DB-API can receive SQL statements as Python unicode strings supports_sane_rowcount Indicate whether the dialect properly implements rowcount for ``UPDATE`` and ``DELETE`` statements. supports_sane_multi_rowcount Indicate whether the dialect properly implements rowcount for ``UPDATE`` and ``DELETE`` statements when executed via executemany. preexecute_pk_sequences Indicate if the dialect should pre-execute sequences on primary key columns during an INSERT, if it's desired that the new row's primary key be available after execution. supports_pk_autoincrement Indicates if the dialect should allow the database to passively assign a primary key column value. dbapi_type_map A mapping of DB-API type objects present in this Dialect's DB-API implmentation mapped to TypeEngine implementations used by the dialect. This is used to apply types to result sets based on the DB-API types present in cursor.description; it only takes effect for result sets against textual statements where no explicit typemap was present. """ def create_connect_args(self, url): """Build DB-API compatible connection arguments. Given a [sqlalchemy.engine.url#URL] object, returns a tuple consisting of a `*args`/`**kwargs` suitable to send directly to the dbapi's connect function. """ raise NotImplementedError() def type_descriptor(self, typeobj): """Transform a generic type to a database-specific type. Transforms the given [sqlalchemy.types#TypeEngine] instance from generic to database-specific. Subclasses will usually use the [sqlalchemy.types#adapt_type()] method in the types module to make this job easy. """ raise NotImplementedError() def oid_column_name(self, column): """Return the oid column name for this Dialect May return ``None`` if the dialect can't o won't support OID/ROWID features. The [sqlalchemy.schema#Column] instance which represents OID for the query being compiled is passed, so that the dialect can inspect the column and its parent selectable to determine if OID/ROWID is not selected for a particular selectable (i.e. Oracle doesnt support ROWID for UNION, GROUP BY, DISTINCT, etc.) """ raise NotImplementedError() def server_version_info(self, connection): """Return a tuple of the database's version number.""" raise NotImplementedError() def reflecttable(self, connection, table, include_columns=None): """Load table description from the database. Given a [sqlalchemy.engine#Connection] and a [sqlalchemy.schema#Table] object, reflect its columns and properties from the database. If include_columns (a list or set) is specified, limit the autoload to the given column names. """ raise NotImplementedError() def has_table(self, connection, table_name, schema=None): """Check the existence of a particular table in the database. Given a [sqlalchemy.engine#Connection] object and a string `table_name`, return True if the given table (possibly within the specified `schema`) exists in the database, False otherwise. """ raise NotImplementedError() def has_sequence(self, connection, sequence_name): """Check the existence of a particular sequence in the database. Given a [sqlalchemy.engine#Connection] object and a string `sequence_name`, return True if the given sequence exists in the database, False otherwise. """ raise NotImplementedError() def get_default_schema_name(self, connection): """Return the string name of the currently selected schema given a [sqlalchemy.engine#Connection].""" raise NotImplementedError() def create_execution_context(self, connection, compiled=None, compiled_parameters=None, statement=None, parameters=None): """Return a new [sqlalchemy.engine#ExecutionContext] object.""" raise NotImplementedError() def do_begin(self, connection): """Provide an implementation of *connection.begin()*, given a DB-API connection.""" raise NotImplementedError() def do_rollback(self, connection): """Provide an implementation of *connection.rollback()*, given a DB-API connection.""" raise NotImplementedError() def create_xid(self): """Create a two-phase transaction ID. This id will be passed to do_begin_twophase(), do_rollback_twophase(), do_commit_twophase(). Its format is unspecified. """ raise NotImplementedError() def do_commit(self, connection): """Provide an implementation of *connection.commit()*, given a DB-API connection.""" raise NotImplementedError() def do_savepoint(self, connection, name): """Create a savepoint with the given name on a SQLAlchemy connection.""" raise NotImplementedError() def do_rollback_to_savepoint(self, connection, name): """Rollback a SQL Alchemy connection to the named savepoint.""" raise NotImplementedError() def do_release_savepoint(self, connection, name): """Release the named savepoint on a SQL Alchemy connection.""" raise NotImplementedError() def do_begin_twophase(self, connection, xid): """Begin a two phase transaction on the given connection.""" raise NotImplementedError() def do_prepare_twophase(self, connection, xid): """Prepare a two phase transaction on the given connection.""" raise NotImplementedError() def do_rollback_twophase(self, connection, xid, is_prepared=True, recover=False): """Rollback a two phase transaction on the given connection.""" raise NotImplementedError() def do_commit_twophase(self, connection, xid, is_prepared=True, recover=False): """Commit a two phase transaction on the given connection.""" raise NotImplementedError() def do_recover_twophase(self, connection): """Recover list of uncommited prepared two phase transaction identifiers on the given connection.""" raise NotImplementedError() def do_executemany(self, cursor, statement, parameters, context=None): """Provide an implementation of *cursor.executemany(statement, parameters)*.""" raise NotImplementedError() def do_execute(self, cursor, statement, parameters, context=None): """Provide an implementation of *cursor.execute(statement, parameters)*.""" raise NotImplementedError() def is_disconnect(self, e): """Return True if the given DB-API error indicates an invalid connection""" raise NotImplementedError()class ExecutionContext(object): """A messenger object for a Dialect that corresponds to a single execution. ExecutionContext should have these datamembers: connection Connection object which can be freely used by default value generators to execute SQL. This Connection should reference the same underlying connection/transactional resources of root_connection. root_connection Connection object which is the source of this ExecutionContext. This Connection may have close_with_result=True set, in which case it can only be used once. dialect dialect which created this ExecutionContext. cursor DB-API cursor procured from the connection, compiled if passed to constructor, sqlalchemy.engine.base.Compiled object being executed, statement string version of the statement to be executed. Is either passed to the constructor, or must be created from the sql.Compiled object by the time pre_exec() has completed. parameters bind parameters passed to the execute() method. For compiled statements, this is a dictionary or list of dictionaries. For textual statements, it should be in a format suitable for the dialect's paramstyle (i.e. dict or list of dicts for non positional, list or list of lists/tuples for positional). isinsert True if the statement is an INSERT. isupdate True if the statement is an UPDATE. should_autocommit True if the statement is a "committable" statement returns_rows True if the statement should return result rows postfetch_cols a list of Column objects for which a server-side default or inline SQL expression value was fired off. applies to inserts and updates. The Dialect should provide an ExecutionContext via the create_execution_context() method. The `pre_exec` and `post_exec` methods will be called for compiled statements. """ def create_cursor(self): """Return a new cursor generated from this ExecutionContext's connection. Some dialects may wish to change the behavior of connection.cursor(), such as postgres which may return a PG "server side" cursor. """ raise NotImplementedError() def pre_execution(self): """Called before an execution of a compiled statement. If a compiled statement was passed to this ExecutionContext, the `statement` and `parameters` datamembers must be initialized after this statement is complete. """ raise NotImplementedError() def post_execution(self): """Called after the execution of a compiled statement. If a compiled statement was passed to this ExecutionContext, the `last_insert_ids`, `last_inserted_params`, etc. datamembers should be available after this method completes. """ raise NotImplementedError() def result(self): """Return a result object corresponding to this ExecutionContext. Returns a ResultProxy. """ raise NotImplementedError()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -