diff options
| author | Mike Bayer <mike_mp@zzzcomputing.com> | 2012-07-28 17:05:50 -0400 |
|---|---|---|
| committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2012-07-28 17:05:50 -0400 |
| commit | 22ba1c43b792953ae6f791512d276739c8c09eae (patch) | |
| tree | bdf9f639b01426a8a2e1c8c61d35533026dd4265 /lib/sqlalchemy/dialects | |
| parent | 27913554a85c308d81e6c018669d0246ceecc639 (diff) | |
| download | sqlalchemy-22ba1c43b792953ae6f791512d276739c8c09eae.tar.gz | |
-whitespace bonanza, contd
Diffstat (limited to 'lib/sqlalchemy/dialects')
20 files changed, 240 insertions, 240 deletions
diff --git a/lib/sqlalchemy/dialects/__init__.py b/lib/sqlalchemy/dialects/__init__.py index 4b34da82e..69212cd6e 100644 --- a/lib/sqlalchemy/dialects/__init__.py +++ b/lib/sqlalchemy/dialects/__init__.py @@ -22,10 +22,10 @@ from .. import util def _auto_fn(name): """default dialect importer. - + plugs into the :class:`.PluginLoader` as a first-hit system. - + """ if "." in name: dialect, driver = name.split(".") diff --git a/lib/sqlalchemy/dialects/access/base.py b/lib/sqlalchemy/dialects/access/base.py index 29f10c560..f107c9c8c 100644 --- a/lib/sqlalchemy/dialects/access/base.py +++ b/lib/sqlalchemy/dialects/access/base.py @@ -11,7 +11,7 @@ Support for the Microsoft Access database. .. note:: - The Access dialect is **non-functional as of SQLAlchemy 0.6**, + The Access dialect is **non-functional as of SQLAlchemy 0.6**, pending development efforts to bring it up-to-date. @@ -125,7 +125,7 @@ class AccessExecutionContext(default.DefaultExecutionContext): # self._last_inserted_ids[0] is None: self.cursor.execute("SELECT @@identity AS lastrowid") row = self.cursor.fetchone() - self._last_inserted_ids = [int(row[0])] + self._last_inserted_ids = [int(row[0])] #+ self._last_inserted_ids[1:] # print "LAST ROW ID", self._last_inserted_ids @@ -260,7 +260,7 @@ class AccessDialect(default.DefaultDialect): colargs = \ { - 'nullable': not(col.Required or + 'nullable': not(col.Required or col.Attributes & const.dbAutoIncrField), } default = col.DefaultValue @@ -287,7 +287,7 @@ class AccessDialect(default.DefaultDialect): if isinstance(thecol.type, AcInteger) and \ not (thecol.default and isinstance( - thecol.default.arg, + thecol.default.arg, schema.Sequence )): thecol.autoincrement = False @@ -322,7 +322,7 @@ class AccessDialect(default.DefaultDialect): # This is necessary, so we get the latest updates dtbs = daoEngine.OpenDatabase(connection.engine.url.database) - names = [t.Name for t in dtbs.TableDefs + names = [t.Name for t in dtbs.TableDefs if t.Name[:4] != "MSys" and t.Name[:4] != "~TMP"] dtbs.Close() return names @@ -373,7 +373,7 @@ class AccessCompiler(compiler.SQLCompiler): 'length': 'len', } def visit_function(self, func): - """Access function names differ from the ANSI SQL names; + """Access function names differ from the ANSI SQL names; rewrite common ones""" func.name = self.function_rewrites.get(func.name, func.name) return super(AccessCompiler, self).visit_function(func) diff --git a/lib/sqlalchemy/dialects/firebird/__init__.py b/lib/sqlalchemy/dialects/firebird/__init__.py index 665e32267..f79588d24 100644 --- a/lib/sqlalchemy/dialects/firebird/__init__.py +++ b/lib/sqlalchemy/dialects/firebird/__init__.py @@ -14,7 +14,7 @@ from sqlalchemy.dialects.firebird.base import \ dialect __all__ = ( - 'SMALLINT', 'BIGINT', 'FLOAT', 'FLOAT', 'DATE', 'TIME', + 'SMALLINT', 'BIGINT', 'FLOAT', 'FLOAT', 'DATE', 'TIME', 'TEXT', 'NUMERIC', 'FLOAT', 'TIMESTAMP', 'VARCHAR', 'CHAR', 'BLOB', 'dialect' ) diff --git a/lib/sqlalchemy/dialects/informix/base.py b/lib/sqlalchemy/dialects/informix/base.py index ff096acc6..d1c5933f4 100644 --- a/lib/sqlalchemy/dialects/informix/base.py +++ b/lib/sqlalchemy/dialects/informix/base.py @@ -10,7 +10,7 @@ .. note:: The Informix dialect functions on current SQLAlchemy versions - but is not regularly tested, and may have many issues and + but is not regularly tested, and may have many issues and caveats not currently handled. """ @@ -467,7 +467,7 @@ class InformixDialect(default.DefaultDialect): c = connection.execute( """select t1.constrname as cons_name, t4.colname as local_column, t7.tabname as remote_table, - t6.colname as remote_column, t7.owner as remote_owner + t6.colname as remote_column, t7.owner as remote_owner from sysconstraints as t1 , systables as t2 , sysindexes as t3 , syscolumns as t4 , sysreferences as t5 , syscolumns as t6 , systables as t7 , @@ -476,7 +476,7 @@ class InformixDialect(default.DefaultDialect): and t3.tabid = t2.tabid and t3.idxname = t1.idxname and t4.tabid = t2.tabid and t4.colno in (t3.part1, t3.part2, t3.part3, t3.part4, t3.part5, t3.part6, t3.part7, t3.part8, t3.part9, t3.part10, - t3.part11, t3.part11, t3.part12, t3.part13, t3.part4, t3.part15, t3.part16) + t3.part11, t3.part11, t3.part12, t3.part13, t3.part4, t3.part15, t3.part16) and t5.constrid = t1.constrid and t8.constrid = t5.primary and t6.tabid = t5.ptabid and t6.colno in (t9.part1, t9.part2, t9.part3, t9.part4, t9.part5, t9.part6, t9.part7, t9.part8, t9.part9, t9.part10, @@ -523,7 +523,7 @@ class InformixDialect(default.DefaultDialect): # Select the column positions from sysindexes for sysconstraints data = connection.execute( - """select t2.* + """select t2.* from systables as t1, sysindexes as t2, sysconstraints as t3 where t1.tabid=t2.tabid and t1.tabname=? and t1.owner=? and t2.idxname=t3.idxname and t3.constrtype='P'""", @@ -545,7 +545,7 @@ class InformixDialect(default.DefaultDialect): c = connection.execute( """select t1.colname from syscolumns as t1, systables as t2 - where t2.tabname=? and t1.tabid = t2.tabid and + where t2.tabname=? and t1.tabid = t2.tabid and t1.colno in (%s)""" % place_holder, table_name, *colpositions ).fetchall() @@ -570,7 +570,7 @@ class InformixDialect(default.DefaultDialect): c = connection.execute( """select t1.colname from syscolumns as t1, systables as t2 - where t2.tabname=? and t1.tabid = t2.tabid and + where t2.tabname=? and t1.tabid = t2.tabid and t1.colno in (%s)""" % place_holder, table_name, *colnames ).fetchall() diff --git a/lib/sqlalchemy/dialects/maxdb/base.py b/lib/sqlalchemy/dialects/maxdb/base.py index 76adf97ff..f52fc4fa6 100644 --- a/lib/sqlalchemy/dialects/maxdb/base.py +++ b/lib/sqlalchemy/dialects/maxdb/base.py @@ -8,7 +8,7 @@ .. note:: - The MaxDB dialect is **non-functional as of SQLAlchemy 0.6**, + The MaxDB dialect is **non-functional as of SQLAlchemy 0.6**, pending development efforts to bring it up-to-date. Overview @@ -255,7 +255,7 @@ class MaxTimestamp(sqltypes.DateTime): value[20:])]) else: raise exc.InvalidRequestError( - "datetimeformat '%s' is not supported." % + "datetimeformat '%s' is not supported." % dialect.datetimeformat) return process @@ -283,18 +283,18 @@ class MaxDate(sqltypes.Date): if value is None: return None else: - return datetime.date(int(value[0:4]), int(value[4:6]), + return datetime.date(int(value[0:4]), int(value[4:6]), int(value[6:8])) elif dialect.datetimeformat == 'iso': def process(value): if value is None: return None else: - return datetime.date(int(value[0:4]), int(value[5:7]), + return datetime.date(int(value[0:4]), int(value[5:7]), int(value[8:10])) else: raise exc.InvalidRequestError( - "datetimeformat '%s' is not supported." % + "datetimeformat '%s' is not supported." % dialect.datetimeformat) return process @@ -322,7 +322,7 @@ class MaxTime(sqltypes.Time): if value is None: return None else: - return datetime.time(int(value[0:4]), int(value[4:6]), + return datetime.time(int(value[0:4]), int(value[4:6]), int(value[6:8])) elif dialect.datetimeformat == 'iso': def process(value): @@ -333,7 +333,7 @@ class MaxTime(sqltypes.Time): int(value[8:10])) else: raise exc.InvalidRequestError( - "datetimeformat '%s' is not supported." % + "datetimeformat '%s' is not supported." % dialect.datetimeformat) return process diff --git a/lib/sqlalchemy/dialects/mssql/__init__.py b/lib/sqlalchemy/dialects/mssql/__init__.py index 8a2101c51..e262d208b 100644 --- a/lib/sqlalchemy/dialects/mssql/__init__.py +++ b/lib/sqlalchemy/dialects/mssql/__init__.py @@ -18,9 +18,9 @@ from sqlalchemy.dialects.mssql.base import \ __all__ = ( - 'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT', 'VARCHAR', 'NVARCHAR', 'CHAR', + 'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT', 'VARCHAR', 'NVARCHAR', 'CHAR', 'NCHAR', 'TEXT', 'NTEXT', 'DECIMAL', 'NUMERIC', 'FLOAT', 'DATETIME', - 'DATETIME2', 'DATETIMEOFFSET', 'DATE', 'TIME', 'SMALLDATETIME', + 'DATETIME2', 'DATETIMEOFFSET', 'DATE', 'TIME', 'SMALLDATETIME', 'BINARY', 'VARBINARY', 'BIT', 'REAL', 'IMAGE', 'TIMESTAMP', 'MONEY', 'SMALLMONEY', 'UNIQUEIDENTIFIER', 'SQL_VARIANT', 'dialect' )
\ No newline at end of file diff --git a/lib/sqlalchemy/dialects/mssql/adodbapi.py b/lib/sqlalchemy/dialects/mssql/adodbapi.py index 21e632880..5b2328269 100644 --- a/lib/sqlalchemy/dialects/mssql/adodbapi.py +++ b/lib/sqlalchemy/dialects/mssql/adodbapi.py @@ -16,7 +16,7 @@ import sys class MSDateTime_adodbapi(MSDateTime): def result_processor(self, dialect, coltype): def process(value): - # adodbapi will return datetimes with empty time + # adodbapi will return datetimes with empty time # values as datetime.date() objects. # Promote them back to full datetime.datetime() if type(value) is datetime.date: @@ -49,7 +49,7 @@ class MSDialect_adodbapi(MSDialect): connectors = ["Provider=SQLOLEDB"] if 'port' in keys: - connectors.append ("Data Source=%s, %s" % + connectors.append ("Data Source=%s, %s" % (keys.get("host"), keys.get("port"))) else: connectors.append ("Data Source=%s" % keys.get("host")) diff --git a/lib/sqlalchemy/dialects/mssql/pymssql.py b/lib/sqlalchemy/dialects/mssql/pymssql.py index 9cc42c093..f9f2e7a48 100644 --- a/lib/sqlalchemy/dialects/mssql/pymssql.py +++ b/lib/sqlalchemy/dialects/mssql/pymssql.py @@ -21,8 +21,8 @@ Sample connect string:: mssql+pymssql://<username>:<password>@<freetds_name> Adding "?charset=utf8" or similar will cause pymssql to return -strings as Python unicode objects. This can potentially improve -performance in some scenarios as decoding of strings is +strings as Python unicode objects. This can potentially improve +performance in some scenarios as decoding of strings is handled natively. Limitations diff --git a/lib/sqlalchemy/dialects/mssql/pyodbc.py b/lib/sqlalchemy/dialects/mssql/pyodbc.py index 17dcbfecd..b3b1641e0 100644 --- a/lib/sqlalchemy/dialects/mssql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mssql/pyodbc.py @@ -35,14 +35,14 @@ Examples of pyodbc connection string URLs: dsn=mydsn;UID=user;PWD=pass;LANGUAGE=us_english -* ``mssql+pyodbc://user:pass@host/db`` - connects using a connection +* ``mssql+pyodbc://user:pass@host/db`` - connects using a connection that would appear like:: DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass * ``mssql+pyodbc://user:pass@host:123/db`` - connects using a connection string which includes the port - information using the comma syntax. This will create the following + information using the comma syntax. This will create the following connection string:: DRIVER={SQL Server};Server=host,123;Database=db;UID=user;PWD=pass @@ -83,9 +83,9 @@ the python shell. For example:: Unicode Binds ^^^^^^^^^^^^^ -The current state of PyODBC on a unix backend with FreeTDS and/or +The current state of PyODBC on a unix backend with FreeTDS and/or EasySoft is poor regarding unicode; different OS platforms and versions of UnixODBC -versus IODBC versus FreeTDS/EasySoft versus PyODBC itself dramatically +versus IODBC versus FreeTDS/EasySoft versus PyODBC itself dramatically alter how strings are received. The PyODBC dialect attempts to use all the information it knows to determine whether or not a Python unicode literal can be passed directly to the PyODBC driver or not; while SQLAlchemy can encode @@ -93,13 +93,13 @@ these to bytestrings first, some users have reported that PyODBC mis-handles bytestrings for certain encodings and requires a Python unicode object, while the author has observed widespread cases where a Python unicode is completely misinterpreted by PyODBC, particularly when dealing with -the information schema tables used in table reflection, and the value +the information schema tables used in table reflection, and the value must first be encoded to a bytestring. It is for this reason that whether or not unicode literals for bound -parameters be sent to PyODBC can be controlled using the -``supports_unicode_binds`` parameter to ``create_engine()``. When -left at its default of ``None``, the PyODBC dialect will use its +parameters be sent to PyODBC can be controlled using the +``supports_unicode_binds`` parameter to ``create_engine()``. When +left at its default of ``None``, the PyODBC dialect will use its best guess as to whether or not the driver deals with unicode literals well. When ``False``, unicode literals will be encoded first, and when ``True`` unicode literals will be passed straight through. This is an interim @@ -199,7 +199,7 @@ class MSExecutionContext_pyodbc(MSExecutionContext): super(MSExecutionContext_pyodbc, self).pre_exec() - # don't embed the scope_identity select into an + # don't embed the scope_identity select into an # "INSERT .. DEFAULT VALUES" if self._select_lastrowid and \ self.dialect.use_scope_identity and \ @@ -211,11 +211,11 @@ class MSExecutionContext_pyodbc(MSExecutionContext): def post_exec(self): if self._embedded_scope_identity: # Fetch the last inserted id from the manipulated statement - # We may have to skip over a number of result sets with + # We may have to skip over a number of result sets with # no data (due to triggers, etc.) while True: try: - # fetchall() ensures the cursor is consumed + # fetchall() ensures the cursor is consumed # without closing it (FreeTDS particularly) row = self.cursor.fetchall()[0] break diff --git a/lib/sqlalchemy/dialects/mssql/zxjdbc.py b/lib/sqlalchemy/dialects/mssql/zxjdbc.py index bfa358c0c..4bbd82c07 100644 --- a/lib/sqlalchemy/dialects/mssql/zxjdbc.py +++ b/lib/sqlalchemy/dialects/mssql/zxjdbc.py @@ -68,7 +68,7 @@ class MSDialect_zxjdbc(ZxJDBCConnector, MSDialect): def _get_server_version_info(self, connection): return tuple( - int(x) + int(x) for x in connection.connection.dbversion.split('.') ) diff --git a/lib/sqlalchemy/dialects/mysql/base.py b/lib/sqlalchemy/dialects/mysql/base.py index 5a020f416..ff1cf625c 100644 --- a/lib/sqlalchemy/dialects/mysql/base.py +++ b/lib/sqlalchemy/dialects/mysql/base.py @@ -44,7 +44,7 @@ Connection Timeouts ------------------- MySQL features an automatic connection close behavior, for connections that have -been idle for eight hours or more. To circumvent having this issue, use the +been idle for eight hours or more. To circumvent having this issue, use the ``pool_recycle`` option which controls the maximum age of any connection:: engine = create_engine('mysql+mysqldb://...', pool_recycle=3600) @@ -87,15 +87,15 @@ to be used. Transaction Isolation Level --------------------------- -:func:`.create_engine` accepts an ``isolation_level`` -parameter which results in the command ``SET SESSION -TRANSACTION ISOLATION LEVEL <level>`` being invoked for +:func:`.create_engine` accepts an ``isolation_level`` +parameter which results in the command ``SET SESSION +TRANSACTION ISOLATION LEVEL <level>`` being invoked for every new connection. Valid values for this parameter are -``READ COMMITTED``, ``READ UNCOMMITTED``, +``READ COMMITTED``, ``READ UNCOMMITTED``, ``REPEATABLE READ``, and ``SERIALIZABLE``:: engine = create_engine( - "mysql://scott:tiger@localhost/test", + "mysql://scott:tiger@localhost/test", isolation_level="READ UNCOMMITTED" ) @@ -193,7 +193,7 @@ usual definition of "number of rows matched by an UPDATE or DELETE" statement. This is in contradiction to the default setting on most MySQL DBAPI drivers, which is "number of rows actually modified/deleted". For this reason, the SQLAlchemy MySQL dialects always set the ``constants.CLIENT.FOUND_ROWS`` flag, -or whatever is equivalent for the DBAPI in use, on connect, unless the flag value +or whatever is equivalent for the DBAPI in use, on connect, unless the flag value is overridden using DBAPI-specific options (such as ``client_flag`` for the MySQL-Python driver, ``found_rows`` for the OurSQL driver). @@ -260,7 +260,7 @@ Index Types ~~~~~~~~~~~~~ Some MySQL storage engines permit you to specify an index type when creating -an index or primary key constraint. SQLAlchemy provides this feature via the +an index or primary key constraint. SQLAlchemy provides this feature via the ``mysql_using`` parameter on :class:`.Index`:: Index('my_index', my_table.c.data, mysql_using='hash') @@ -270,7 +270,7 @@ As well as the ``mysql_using`` parameter on :class:`.PrimaryKeyConstraint`:: PrimaryKeyConstraint("data", mysql_using='hash') The value passed to the keyword argument will be simply passed through to the -underlying CREATE INDEX or PRIMARY KEY clause, so it *must* be a valid index +underlying CREATE INDEX or PRIMARY KEY clause, so it *must* be a valid index type for your MySQL storage engine. More information can be found at: @@ -1307,13 +1307,13 @@ class MySQLCompiler(compiler.SQLCompiler): def get_select_precolumns(self, select): """Add special MySQL keywords in place of DISTINCT. - - .. note:: - + + .. note:: + this usage is deprecated. :meth:`.Select.prefix_with` should be used for special keywords at the start of a SELECT. - + """ if isinstance(select._distinct, basestring): return select._distinct.upper() + " " @@ -1361,16 +1361,16 @@ class MySQLCompiler(compiler.SQLCompiler): if limit is None: # hardwire the upper limit. Currently # needed by OurSQL with Python 3 - # (https://bugs.launchpad.net/oursql/+bug/686232), + # (https://bugs.launchpad.net/oursql/+bug/686232), # but also is consistent with the usage of the upper # bound as part of MySQL's "syntax" for OFFSET with # no LIMIT return ' \n LIMIT %s, %s' % ( - self.process(sql.literal(offset)), + self.process(sql.literal(offset)), "18446744073709551615") else: return ' \n LIMIT %s, %s' % ( - self.process(sql.literal(offset)), + self.process(sql.literal(offset)), self.process(sql.literal(limit))) else: # No offset provided, so just use the limit @@ -1384,10 +1384,10 @@ class MySQLCompiler(compiler.SQLCompiler): return None def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw): - return ', '.join(t._compiler_dispatch(self, asfrom=True, **kw) + return ', '.join(t._compiler_dispatch(self, asfrom=True, **kw) for t in [from_table] + list(extra_froms)) - def update_from_clause(self, update_stmt, from_table, + def update_from_clause(self, update_stmt, from_table, extra_froms, from_hints, **kw): return None @@ -1416,7 +1416,7 @@ class MySQLDDLCompiler(compiler.DDLCompiler): constraint_string += "KEY %s (%s)" % ( self.preparer.quote( "idx_autoinc_%s" % auto_inc_column.name, None - ), + ), self.preparer.format_column(auto_inc_column) ) @@ -1453,7 +1453,7 @@ class MySQLDDLCompiler(compiler.DDLCompiler): opts = dict( ( - k[len(self.dialect.name)+1:].upper(), + k[len(self.dialect.name)+1:].upper(), v ) for k, v in table.kwargs.items() @@ -1469,7 +1469,7 @@ class MySQLDDLCompiler(compiler.DDLCompiler): arg = "'%s'" % arg.replace("\\", "\\\\").replace("'", "''") if opt in ('DATA_DIRECTORY', 'INDEX_DIRECTORY', - 'DEFAULT_CHARACTER_SET', 'CHARACTER_SET', + 'DEFAULT_CHARACTER_SET', 'CHARACTER_SET', 'DEFAULT_CHARSET', 'DEFAULT_COLLATE'): opt = opt.replace('_', ' ') @@ -1489,7 +1489,7 @@ class MySQLDDLCompiler(compiler.DDLCompiler): table = preparer.format_table(index.table) columns = [preparer.quote(c.name, c.quote) for c in index.columns] name = preparer.quote( - self._index_identifier(index.name), + self._index_identifier(index.name), index.quote) text = "CREATE " @@ -1598,24 +1598,24 @@ class MySQLTypeCompiler(compiler.GenericTypeCompiler): if type_.precision is None: return self._extend_numeric(type_, "NUMERIC") elif type_.scale is None: - return self._extend_numeric(type_, - "NUMERIC(%(precision)s)" % + return self._extend_numeric(type_, + "NUMERIC(%(precision)s)" % {'precision': type_.precision}) else: - return self._extend_numeric(type_, - "NUMERIC(%(precision)s, %(scale)s)" % + return self._extend_numeric(type_, + "NUMERIC(%(precision)s, %(scale)s)" % {'precision': type_.precision, 'scale' : type_.scale}) def visit_DECIMAL(self, type_): if type_.precision is None: return self._extend_numeric(type_, "DECIMAL") elif type_.scale is None: - return self._extend_numeric(type_, - "DECIMAL(%(precision)s)" % + return self._extend_numeric(type_, + "DECIMAL(%(precision)s)" % {'precision': type_.precision}) else: - return self._extend_numeric(type_, - "DECIMAL(%(precision)s, %(scale)s)" % + return self._extend_numeric(type_, + "DECIMAL(%(precision)s, %(scale)s)" % {'precision': type_.precision, 'scale' : type_.scale}) def visit_DOUBLE(self, type_): @@ -1638,7 +1638,7 @@ class MySQLTypeCompiler(compiler.GenericTypeCompiler): if self._mysql_type(type_) and \ type_.scale is not None and \ type_.precision is not None: - return self._extend_numeric(type_, + return self._extend_numeric(type_, "FLOAT(%s, %s)" % (type_.precision, type_.scale)) elif type_.precision is not None: return self._extend_numeric(type_, "FLOAT(%s)" % (type_.precision,)) @@ -1647,24 +1647,24 @@ class MySQLTypeCompiler(compiler.GenericTypeCompiler): def visit_INTEGER(self, type_): if self._mysql_type(type_) and type_.display_width is not None: - return self._extend_numeric(type_, - "INTEGER(%(display_width)s)" % + return self._extend_numeric(type_, + "INTEGER(%(display_width)s)" % {'display_width': type_.display_width}) else: return self._extend_numeric(type_, "INTEGER") def visit_BIGINT(self, type_): if self._mysql_type(type_) and type_.display_width is not None: - return self._extend_numeric(type_, - "BIGINT(%(display_width)s)" % + return self._extend_numeric(type_, + "BIGINT(%(display_width)s)" % {'display_width': type_.display_width}) else: return self._extend_numeric(type_, "BIGINT") def visit_MEDIUMINT(self, type_): if self._mysql_type(type_) and type_.display_width is not None: - return self._extend_numeric(type_, - "MEDIUMINT(%(display_width)s)" % + return self._extend_numeric(type_, + "MEDIUMINT(%(display_width)s)" % {'display_width': type_.display_width}) else: return self._extend_numeric(type_, "MEDIUMINT") @@ -1677,8 +1677,8 @@ class MySQLTypeCompiler(compiler.GenericTypeCompiler): def visit_SMALLINT(self, type_): if self._mysql_type(type_) and type_.display_width is not None: - return self._extend_numeric(type_, - "SMALLINT(%(display_width)s)" % + return self._extend_numeric(type_, + "SMALLINT(%(display_width)s)" % {'display_width': type_.display_width} ) else: @@ -1728,7 +1728,7 @@ class MySQLTypeCompiler(compiler.GenericTypeCompiler): return self._extend_string(type_, {}, "VARCHAR(%d)" % type_.length) else: raise exc.CompileError( - "VARCHAR requires a length on dialect %s" % + "VARCHAR requires a length on dialect %s" % self.dialect.name) def visit_CHAR(self, type_): @@ -1744,7 +1744,7 @@ class MySQLTypeCompiler(compiler.GenericTypeCompiler): return self._extend_string(type_, {'national':True}, "VARCHAR(%(length)s)" % {'length': type_.length}) else: raise exc.CompileError( - "NVARCHAR requires a length on dialect %s" % + "NVARCHAR requires a length on dialect %s" % self.dialect.name) def visit_NCHAR(self, type_): @@ -1805,8 +1805,8 @@ class MySQLIdentifierPreparer(compiler.IdentifierPreparer): quote = '"' super(MySQLIdentifierPreparer, self).__init__( - dialect, - initial_quote=quote, + dialect, + initial_quote=quote, escape_quote=quote) def _quote_free_identifiers(self, *ids): @@ -1839,7 +1839,7 @@ class MySQLDialect(default.DefaultDialect): preparer = MySQLIdentifierPreparer # default SQL compilation settings - - # these are modified upon initialize(), + # these are modified upon initialize(), # i.e. first connect _backslash_escapes = True _server_ansiquotes = False @@ -1856,7 +1856,7 @@ class MySQLDialect(default.DefaultDialect): else: return None - _isolation_lookup = set(['SERIALIZABLE', + _isolation_lookup = set(['SERIALIZABLE', 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ']) def set_isolation_level(self, connection, level): @@ -1864,7 +1864,7 @@ class MySQLDialect(default.DefaultDialect): if level not in self._isolation_lookup: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " - "Valid isolation levels for %s are %s" % + "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) cursor = connection.cursor() @@ -1936,7 +1936,7 @@ class MySQLDialect(default.DefaultDialect): return self._extract_error_code(e) in \ (2006, 2013, 2014, 2045, 2055) elif isinstance(e, self.dbapi.InterfaceError): - # if underlying connection is closed, + # if underlying connection is closed, # this is the error you get return "(0, '')" in str(e) else: @@ -2148,9 +2148,9 @@ class MySQLDialect(default.DefaultDialect): def _parsed_state_or_create(self, connection, table_name, schema=None, **kw): return self._setup_parser( - connection, - table_name, - schema, + connection, + table_name, + schema, info_cache=kw.get('info_cache', None) ) @@ -2158,7 +2158,7 @@ class MySQLDialect(default.DefaultDialect): def _tabledef_parser(self): """return the MySQLTableDefinitionParser, generate if needed. - The deferred creation ensures that the dialect has + The deferred creation ensures that the dialect has retrieved server version information first. """ diff --git a/lib/sqlalchemy/dialects/mysql/mysqldb.py b/lib/sqlalchemy/dialects/mysql/mysqldb.py index 656e105a7..240f30251 100644 --- a/lib/sqlalchemy/dialects/mysql/mysqldb.py +++ b/lib/sqlalchemy/dialects/mysql/mysqldb.py @@ -26,20 +26,20 @@ MySQLdb will accommodate Python ``unicode`` objects if the ``use_unicode=1`` parameter, or the ``charset`` parameter, is passed as a connection argument. -Without this setting, many MySQL server installations default to +Without this setting, many MySQL server installations default to a ``latin1`` encoding for client connections, which has the effect -of all data being converted into ``latin1``, even if you have ``utf8`` +of all data being converted into ``latin1``, even if you have ``utf8`` or another character set configured on your tables and columns. With versions 4.1 and higher, you can change the connection character set either through server configuration or by including the ``charset`` parameter. The ``charset`` -parameter as received by MySQL-Python also has the side-effect of +parameter as received by MySQL-Python also has the side-effect of enabling ``use_unicode=1``:: # set client encoding to utf8; all strings come back as unicode create_engine('mysql+mysqldb:///mydb?charset=utf8') -Manually configuring ``use_unicode=0`` will cause MySQL-python to +Manually configuring ``use_unicode=0`` will cause MySQL-python to return encoded strings:: # set client encoding to utf8; all strings come back as utf8 str @@ -57,9 +57,9 @@ It is strongly advised to use the latest version of MySQL-Python. from sqlalchemy.dialects.mysql.base import (MySQLDialect, MySQLExecutionContext, MySQLCompiler, MySQLIdentifierPreparer) from sqlalchemy.connectors.mysqldb import ( - MySQLDBExecutionContext, - MySQLDBCompiler, - MySQLDBIdentifierPreparer, + MySQLDBExecutionContext, + MySQLDBCompiler, + MySQLDBIdentifierPreparer, MySQLDBConnector ) diff --git a/lib/sqlalchemy/dialects/mysql/oursql.py b/lib/sqlalchemy/dialects/mysql/oursql.py index 2a3c6b09c..8f7bebe9c 100644 --- a/lib/sqlalchemy/dialects/mysql/oursql.py +++ b/lib/sqlalchemy/dialects/mysql/oursql.py @@ -108,9 +108,9 @@ class MySQLDialect_oursql(MySQLDialect): arg = "'%s'" % arg connection.execution_options(_oursql_plain_query=True).execute(query % arg) - # Because mysql is bad, these methods have to be + # Because mysql is bad, these methods have to be # reimplemented to use _PlainQuery. Basically, some queries - # refuse to return any data if they're run through + # refuse to return any data if they're run through # the parameterized query API, or refuse to be parameterized # in the first place. def do_begin_twophase(self, connection, xid): @@ -135,7 +135,7 @@ class MySQLDialect_oursql(MySQLDialect): # Q: why didn't we need all these "plain_query" overrides earlier ? # am i on a newer/older version of OurSQL ? def has_table(self, connection, table_name, schema=None): - return MySQLDialect.has_table(self, + return MySQLDialect.has_table(self, connection.connect().\ execution_options(_oursql_plain_query=True), table_name, schema) @@ -183,7 +183,7 @@ class MySQLDialect_oursql(MySQLDialect): def initialize(self, connection): return MySQLDialect.initialize( - self, + self, connection.execution_options(_oursql_plain_query=True) ) @@ -222,7 +222,7 @@ class MySQLDialect_oursql(MySQLDialect): opts.setdefault('found_rows', True) ssl = {} - for key in ['ssl_ca', 'ssl_key', 'ssl_cert', + for key in ['ssl_ca', 'ssl_key', 'ssl_cert', 'ssl_capath', 'ssl_cipher']: if key in opts: ssl[key[4:]] = opts[key] diff --git a/lib/sqlalchemy/dialects/mysql/pyodbc.py b/lib/sqlalchemy/dialects/mysql/pyodbc.py index 20a16988a..6271286f9 100644 --- a/lib/sqlalchemy/dialects/mysql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mysql/pyodbc.py @@ -20,7 +20,7 @@ Connect string:: Limitations ----------- -The mysql-pyodbc dialect is subject to unresolved character encoding issues +The mysql-pyodbc dialect is subject to unresolved character encoding issues which exist within the current ODBC drivers available. (see http://code.google.com/p/pyodbc/issues/detail?id=25). Consider usage of OurSQL, MySQLdb, or MySQL-connector/Python. diff --git a/lib/sqlalchemy/dialects/oracle/cx_oracle.py b/lib/sqlalchemy/dialects/oracle/cx_oracle.py index 6e2bc2760..6f0569c30 100644 --- a/lib/sqlalchemy/dialects/oracle/cx_oracle.py +++ b/lib/sqlalchemy/dialects/oracle/cx_oracle.py @@ -9,19 +9,19 @@ Driver ------ -The Oracle dialect uses the cx_oracle driver, available at -http://cx-oracle.sourceforge.net/ . The dialect has several behaviors +The Oracle dialect uses the cx_oracle driver, available at +http://cx-oracle.sourceforge.net/ . The dialect has several behaviors which are specifically tailored towards compatibility with this module. Version 5.0 or greater is **strongly** recommended, as SQLAlchemy makes -extensive use of the cx_oracle output converters for numeric and +extensive use of the cx_oracle output converters for numeric and string conversions. Connecting ---------- -Connecting with create_engine() uses the standard URL approach of -``oracle://user:pass@host:port/dbname[?key=value&key=value...]``. If dbname is present, the -host, port, and dbname tokens are converted to a TNS name using the cx_oracle +Connecting with create_engine() uses the standard URL approach of +``oracle://user:pass@host:port/dbname[?key=value&key=value...]``. If dbname is present, the +host, port, and dbname tokens are converted to a TNS name using the cx_oracle :func:`makedsn()` function. Otherwise, the host token is taken directly as a TNS name. Additional arguments which may be specified either as query string arguments on the @@ -53,7 +53,7 @@ handler so that all string based result values are returned as unicode as well. Generally, the ``NLS_LANG`` environment variable determines the nature of the encoding to be used. -Note that this behavior is disabled when Oracle 8 is detected, as it has been +Note that this behavior is disabled when Oracle 8 is detected, as it has been observed that issues remain when passing Python unicodes to cx_oracle with Oracle 8. LOB Objects @@ -71,7 +71,7 @@ To disable this processing, pass ``auto_convert_lobs=False`` to :func:`create_en Two Phase Transaction Support ----------------------------- -Two Phase transactions are implemented using XA transactions. Success has been reported +Two Phase transactions are implemented using XA transactions. Success has been reported with this feature but it should be regarded as experimental. Precision Numerics @@ -95,14 +95,14 @@ If precision numerics aren't required, the decimal handling can be disabled by passing the flag ``coerce_to_decimal=False`` to :func:`.create_engine`:: - engine = create_engine("oracle+cx_oracle://dsn", + engine = create_engine("oracle+cx_oracle://dsn", coerce_to_decimal=False) .. versionadded:: 0.7.6 Add the ``coerce_to_decimal`` flag. -Another alternative to performance is to use the -`cdecimal <http://pypi.python.org/pypi/cdecimal/>`_ library; +Another alternative to performance is to use the +`cdecimal <http://pypi.python.org/pypi/cdecimal/>`_ library; see :class:`.Numeric` for additional notes. The handler attempts to use the "precision" and "scale" @@ -160,7 +160,7 @@ class _OracleNumeric(sqltypes.Numeric): def result_processor(self, dialect, coltype): # we apply a cx_oracle type handler to all connections # that converts floating point strings to Decimal(). - # However, in some subquery situations, Oracle doesn't + # However, in some subquery situations, Oracle doesn't # give us enough information to determine int or Decimal. # It could even be int/Decimal differently on each row, # regardless of the scale given for the originating type. @@ -190,7 +190,7 @@ class _OracleNumeric(sqltypes.Numeric): else: return None else: - # cx_oracle 4 behavior, will assume + # cx_oracle 4 behavior, will assume # floats return super(_OracleNumeric, self).\ result_processor(dialect, coltype) @@ -237,7 +237,7 @@ class _NativeUnicodeMixin(object): # end Py2K # we apply a connection output handler that returns - # unicode in all cases, so the "native_unicode" flag + # unicode in all cases, so the "native_unicode" flag # will be set for the default String.result_processor. class _OracleChar(_NativeUnicodeMixin, sqltypes.CHAR): @@ -317,15 +317,15 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): getattr(self.compiled, '_quoted_bind_names', None) if quoted_bind_names: if not self.dialect.supports_unicode_statements: - # if DBAPI doesn't accept unicode statements, + # if DBAPI doesn't accept unicode statements, # keys in self.parameters would have been encoded # here. so convert names in quoted_bind_names # to encoded as well. quoted_bind_names = \ dict( - (fromname.encode(self.dialect.encoding), - toname.encode(self.dialect.encoding)) - for fromname, toname in + (fromname.encode(self.dialect.encoding), + toname.encode(self.dialect.encoding)) + for fromname, toname in quoted_bind_names.items() ) for param in self.parameters: @@ -334,10 +334,10 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): del param[fromname] if self.dialect.auto_setinputsizes: - # cx_oracle really has issues when you setinputsizes + # cx_oracle really has issues when you setinputsizes # on String, including that outparams/RETURNING # breaks for varchars - self.set_input_sizes(quoted_bind_names, + self.set_input_sizes(quoted_bind_names, exclude_types=self.dialect._cx_oracle_string_types ) @@ -370,7 +370,7 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): def get_result_proxy(self): if hasattr(self, 'out_parameters') and self.compiled.returning: returning_params = dict( - (k, v.getvalue()) + (k, v.getvalue()) for k, v in self.out_parameters.items() ) return ReturningResultProxy(self, returning_params) @@ -396,7 +396,7 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): impl_type = type.dialect_impl(self.dialect) dbapi_type = impl_type.get_dbapi_type(self.dialect.dbapi) result_processor = impl_type.\ - result_processor(self.dialect, + result_processor(self.dialect, dbapi_type) if result_processor is not None: out_parameters[name] = \ @@ -405,7 +405,7 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): out_parameters[name] = self.out_parameters[name].getvalue() else: result.out_parameters = dict( - (k, v.getvalue()) + (k, v.getvalue()) for k, v in self.out_parameters.items() ) @@ -414,13 +414,13 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): class OracleExecutionContext_cx_oracle_with_unicode(OracleExecutionContext_cx_oracle): """Support WITH_UNICODE in Python 2.xx. - WITH_UNICODE allows cx_Oracle's Python 3 unicode handling - behavior under Python 2.x. This mode in some cases disallows - and in other cases silently passes corrupted data when - non-Python-unicode strings (a.k.a. plain old Python strings) - are passed as arguments to connect(), the statement sent to execute(), + WITH_UNICODE allows cx_Oracle's Python 3 unicode handling + behavior under Python 2.x. This mode in some cases disallows + and in other cases silently passes corrupted data when + non-Python-unicode strings (a.k.a. plain old Python strings) + are passed as arguments to connect(), the statement sent to execute(), or any of the bind parameter keys or values sent to execute(). - This optional context therefore ensures that all statements are + This optional context therefore ensures that all statements are passed as Python unicode objects. """ @@ -451,7 +451,7 @@ class ReturningResultProxy(base.FullyBufferedResultProxy): return ret def _buffer_rows(self): - return collections.deque([tuple(self._returning_params["ret_%d" % i] + return collections.deque([tuple(self._returning_params["ret_%d" % i] for i, c in enumerate(self._returning_params))]) class OracleDialect_cx_oracle(OracleDialect): @@ -483,11 +483,11 @@ class OracleDialect_cx_oracle(OracleDialect): execute_sequence_format = list - def __init__(self, - auto_setinputsizes=True, - auto_convert_lobs=True, - threaded=True, - allow_twophase=True, + def __init__(self, + auto_setinputsizes=True, + auto_convert_lobs=True, + threaded=True, + allow_twophase=True, coerce_to_decimal=True, arraysize=50, **kwargs): OracleDialect.__init__(self, **kwargs) @@ -510,11 +510,11 @@ class OracleDialect_cx_oracle(OracleDialect): self._cx_oracle_string_types = types("STRING", "UNICODE", "NCLOB", "CLOB") self._cx_oracle_unicode_types = types("UNICODE", "NCLOB") - self._cx_oracle_binary_types = types("BFILE", "CLOB", "NCLOB", "BLOB") + self._cx_oracle_binary_types = types("BFILE", "CLOB", "NCLOB", "BLOB") self.supports_unicode_binds = self.cx_oracle_ver >= (5, 0) self.supports_native_decimal = ( - self.cx_oracle_ver >= (5, 0) and + self.cx_oracle_ver >= (5, 0) and coerce_to_decimal ) @@ -572,12 +572,12 @@ class OracleDialect_cx_oracle(OracleDialect): self._detect_decimal_char(connection) def _detect_decimal_char(self, connection): - """detect if the decimal separator character is not '.', as + """detect if the decimal separator character is not '.', as is the case with european locale settings for NLS_LANG. cx_oracle itself uses similar logic when it formats Python - Decimal objects to strings on the bind side (as of 5.0.3), - as Oracle sends/receives string numerics only in the + Decimal objects to strings on the bind side (as of 5.0.3), + as Oracle sends/receives string numerics only in the current locale. """ @@ -588,14 +588,14 @@ class OracleDialect_cx_oracle(OracleDialect): cx_Oracle = self.dbapi conn = connection.connection - # override the output_type_handler that's - # on the cx_oracle connection with a plain + # override the output_type_handler that's + # on the cx_oracle connection with a plain # one on the cursor - def output_type_handler(cursor, name, defaultType, + def output_type_handler(cursor, name, defaultType, size, precision, scale): return cursor.var( - cx_Oracle.STRING, + cx_Oracle.STRING, 255, arraysize=cursor.arraysize) cursor = conn.cursor() @@ -625,7 +625,7 @@ class OracleDialect_cx_oracle(OracleDialect): return cx_Oracle = self.dbapi - def output_type_handler(cursor, name, defaultType, + def output_type_handler(cursor, name, defaultType, size, precision, scale): # convert all NUMBER with precision + positive scale to Decimal # this almost allows "native decimal" mode. @@ -633,22 +633,22 @@ class OracleDialect_cx_oracle(OracleDialect): defaultType == cx_Oracle.NUMBER and \ precision and scale > 0: return cursor.var( - cx_Oracle.STRING, - 255, - outconverter=self._to_decimal, + cx_Oracle.STRING, + 255, + outconverter=self._to_decimal, arraysize=cursor.arraysize) # if NUMBER with zero precision and 0 or neg scale, this appears - # to indicate "ambiguous". Use a slower converter that will - # make a decision based on each value received - the type + # to indicate "ambiguous". Use a slower converter that will + # make a decision based on each value received - the type # may change from row to row (!). This kills # off "native decimal" mode, handlers still needed. elif self.supports_native_decimal and \ defaultType == cx_Oracle.NUMBER \ and not precision and scale <= 0: return cursor.var( - cx_Oracle.STRING, - 255, - outconverter=self._detect_decimal, + cx_Oracle.STRING, + 255, + outconverter=self._detect_decimal, arraysize=cursor.arraysize) # allow all strings to come back natively as Unicode elif defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR): @@ -712,7 +712,7 @@ class OracleDialect_cx_oracle(OracleDialect): def _get_server_version_info(self, connection): return tuple( - int(x) + int(x) for x in connection.connection.version.split('.') ) diff --git a/lib/sqlalchemy/dialects/postgresql/__init__.py b/lib/sqlalchemy/dialects/postgresql/__init__.py index bc0c31275..339634020 100644 --- a/lib/sqlalchemy/dialects/postgresql/__init__.py +++ b/lib/sqlalchemy/dialects/postgresql/__init__.py @@ -14,7 +14,7 @@ from sqlalchemy.dialects.postgresql.base import \ DATE, BYTEA, BOOLEAN, INTERVAL, ARRAY, ENUM, dialect __all__ = ( -'INTEGER', 'BIGINT', 'SMALLINT', 'VARCHAR', 'CHAR', 'TEXT', 'NUMERIC', 'FLOAT', 'REAL', 'INET', +'INTEGER', 'BIGINT', 'SMALLINT', 'VARCHAR', 'CHAR', 'TEXT', 'NUMERIC', 'FLOAT', 'REAL', 'INET', 'CIDR', 'UUID', 'BIT', 'MACADDR', 'DOUBLE_PRECISION', 'TIMESTAMP', 'TIME', 'DATE', 'BYTEA', 'BOOLEAN', 'INTERVAL', 'ARRAY', 'ENUM', 'dialect' ) diff --git a/lib/sqlalchemy/dialects/sqlite/base.py b/lib/sqlalchemy/dialects/sqlite/base.py index b5cb3b782..717d6b49a 100644 --- a/lib/sqlalchemy/dialects/sqlite/base.py +++ b/lib/sqlalchemy/dialects/sqlite/base.py @@ -12,7 +12,7 @@ section regarding that driver. Date and Time Types ------------------- -SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does not provide +SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does not provide out of the box functionality for translating values between Python `datetime` objects and a SQLite-supported format. SQLAlchemy's own :class:`~sqlalchemy.types.DateTime` and related types provide date formatting and parsing functionality when SQlite is used. @@ -36,19 +36,19 @@ Two things to note: This is regardless of the AUTOINCREMENT keyword being present or not. To specifically render the AUTOINCREMENT keyword on the primary key -column when rendering DDL, add the flag ``sqlite_autoincrement=True`` +column when rendering DDL, add the flag ``sqlite_autoincrement=True`` to the Table construct:: Table('sometable', metadata, - Column('id', Integer, primary_key=True), + Column('id', Integer, primary_key=True), sqlite_autoincrement=True) Transaction Isolation Level --------------------------- -:func:`.create_engine` accepts an ``isolation_level`` parameter which results in -the command ``PRAGMA read_uncommitted <level>`` being invoked for every new -connection. Valid values for this parameter are ``SERIALIZABLE`` and +:func:`.create_engine` accepts an ``isolation_level`` parameter which results in +the command ``PRAGMA read_uncommitted <level>`` being invoked for every new +connection. Valid values for this parameter are ``SERIALIZABLE`` and ``READ UNCOMMITTED`` corresponding to a value of 0 and 1, respectively. See the section :ref:`pysqlite_serializable` for an important workaround when using serializable isolation with Pysqlite. @@ -57,31 +57,31 @@ Database Locking Behavior / Concurrency --------------------------------------- Note that SQLite is not designed for a high level of concurrency. The database -itself, being a file, is locked completely during write operations and within +itself, being a file, is locked completely during write operations and within transactions, meaning exactly one connection has exclusive access to the database during this period - all other connections will be blocked during this time. The Python DBAPI specification also calls for a connection model that is always in a transaction; there is no BEGIN method, only commit and rollback. This implies -that a SQLite DBAPI driver would technically allow only serialized access to a +that a SQLite DBAPI driver would technically allow only serialized access to a particular database file at all times. The pysqlite driver attempts to ameliorate this by deferring the actual BEGIN statement until the first DML (INSERT, UPDATE, or DELETE) is received within a transaction. While this breaks serializable isolation, it at least delays the exclusive locking inherent in SQLite's design. -SQLAlchemy's default mode of usage with the ORM is known -as "autocommit=False", which means the moment the :class:`.Session` begins to be +SQLAlchemy's default mode of usage with the ORM is known +as "autocommit=False", which means the moment the :class:`.Session` begins to be used, a transaction is begun. As the :class:`.Session` is used, the autoflush -feature, also on by default, will flush out pending changes to the database +feature, also on by default, will flush out pending changes to the database before each query. The effect of this is that a :class:`.Session` used in its default mode will often emit DML early on, long before the transaction is actually -committed. This again will have the effect of serializing access to the SQLite +committed. This again will have the effect of serializing access to the SQLite database. If highly concurrent reads are desired against the SQLite database, it is advised that the autoflush feature be disabled, and potentially even that autocommit be re-enabled, which has the effect of each SQL statement and flush committing changes immediately. -For more information on SQLite's lack of concurrency by design, please +For more information on SQLite's lack of concurrency by design, please see `Situations Where Another RDBMS May Work Better - High Concurrency <http://www.sqlite.org/whentouse.html>`_ near the bottom of the page. @@ -112,30 +112,30 @@ class _DateTimeMixin(object): class DATETIME(_DateTimeMixin, sqltypes.DateTime): """Represent a Python datetime object in SQLite using a string. - + The default string storage format is:: - + "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(min)02d:%(second)02d.%(microsecond)06d" - + e.g.:: - + 2011-03-15 12:05:57.10558 - - The storage format can be customized to some degree using the + + The storage format can be customized to some degree using the ``storage_format`` and ``regexp`` parameters, such as:: - + import re from sqlalchemy.dialects.sqlite import DATETIME - + dt = DATETIME( storage_format="%(year)04d/%(month)02d/%(day)02d %(hour)02d:%(min)02d:%(second)02d", regexp=re.compile("(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)") ) - - :param storage_format: format string which will be applied to the + + :param storage_format: format string which will be applied to the dict with keys year, month, day, hour, minute, second, and microsecond. - - :param regexp: regular expression which will be applied to + + :param regexp: regular expression which will be applied to incoming result rows. If the regexp contains named groups, the resulting match dict is applied to the Python datetime() constructor as keyword arguments. Otherwise, if positional groups are used, the @@ -204,16 +204,16 @@ class DATE(_DateTimeMixin, sqltypes.Date): """Represent a Python date object in SQLite using a string. The default string storage format is:: - + "%(year)04d-%(month)02d-%(day)02d" - + e.g.:: - + 2011-03-15 - - The storage format can be customized to some degree using the + + The storage format can be customized to some degree using the ``storage_format`` and ``regexp`` parameters, such as:: - + import re from sqlalchemy.dialects.sqlite import DATE @@ -221,11 +221,11 @@ class DATE(_DateTimeMixin, sqltypes.Date): storage_format="%(month)02d/%(day)02d/%(year)04d", regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)") ) - - :param storage_format: format string which will be applied to the + + :param storage_format: format string which will be applied to the dict with keys year, month, and day. - - :param regexp: regular expression which will be applied to + + :param regexp: regular expression which will be applied to incoming result rows. If the regexp contains named groups, the resulting match dict is applied to the Python date() constructor as keyword arguments. Otherwise, if positional groups are used, the @@ -261,18 +261,18 @@ class DATE(_DateTimeMixin, sqltypes.Date): class TIME(_DateTimeMixin, sqltypes.Time): """Represent a Python time object in SQLite using a string. - + The default string storage format is:: - + "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d" - + e.g.:: - + 12:05:57.10558 - - The storage format can be customized to some degree using the + + The storage format can be customized to some degree using the ``storage_format`` and ``regexp`` parameters, such as:: - + import re from sqlalchemy.dialects.sqlite import TIME @@ -280,11 +280,11 @@ class TIME(_DateTimeMixin, sqltypes.Time): storage_format="%(hour)02d-%(minute)02d-%(second)02d-%(microsecond)06d", regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?") ) - - :param storage_format: format string which will be applied to the + + :param storage_format: format string which will be applied to the dict with keys hour, minute, second, and microsecond. - - :param regexp: regular expression which will be applied to + + :param regexp: regular expression which will be applied to incoming result rows. If the regexp contains named groups, the resulting match dict is applied to the Python time() constructor as keyword arguments. Otherwise, if positional groups are used, the @@ -447,7 +447,7 @@ class SQLiteDDLCompiler(compiler.DDLCompiler): issubclass(c.type._type_affinity, sqltypes.Integer) and \ not c.foreign_keys: return None - + return super(SQLiteDDLCompiler, self).\ visit_primary_key_constraint(constraint) @@ -522,7 +522,7 @@ class SQLiteExecutionContext(default.DefaultExecutionContext): def _translate_colname(self, colname): # adjust for dotted column names. SQLite - # in the case of UNION may store col names as + # in the case of UNION may store col names as # "tablename.colname" # in cursor.description if not self._preserve_raw_colnames and "." in colname: @@ -559,7 +559,7 @@ class SQLiteDialect(default.DefaultDialect): # this flag used by pysqlite dialect, and perhaps others in the # future, to indicate the driver is handling date/timestamp - # conversions (and perhaps datetime/time as well on some + # conversions (and perhaps datetime/time as well on some # hypothetical driver ?) self.native_datetime = native_datetime @@ -579,9 +579,9 @@ class SQLiteDialect(default.DefaultDialect): except KeyError: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " - "Valid isolation levels for %s are %s" % + "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) - ) + ) cursor = connection.cursor() cursor.execute("PRAGMA read_uncommitted = %d" % isolation_level) cursor.close() @@ -592,11 +592,11 @@ class SQLiteDialect(default.DefaultDialect): res = cursor.fetchone() if res: value = res[0] - else: + else: # http://www.sqlite.org/changes.html#version_3_3_3 - # "Optional READ UNCOMMITTED isolation (instead of the - # default isolation level of SERIALIZABLE) and - # table level locking when database connections + # "Optional READ UNCOMMITTED isolation (instead of the + # default isolation level of SERIALIZABLE) and + # table level locking when database connections # share a common cache."" # pre-SQLite 3.3.0 default to 0 value = 0 @@ -712,7 +712,7 @@ class SQLiteDialect(default.DefaultDialect): pragma = "PRAGMA " qtable = quote(table_name) c = _pragma_cursor( - connection.execute("%stable_info(%s)" % + connection.execute("%stable_info(%s)" % (pragma, qtable))) found_table = False columns = [] @@ -721,7 +721,7 @@ class SQLiteDialect(default.DefaultDialect): if row is None: break (name, type_, nullable, default, has_default, primary_key) = \ - (row[1], row[2].upper(), not row[3], + (row[1], row[2].upper(), not row[3], row[4], row[4] is not None, row[5]) name = re.sub(r'^\"|\"$', '', name) match = re.match(r'(\w+)(\(.*?\))?', type_) @@ -838,7 +838,7 @@ class SQLiteDialect(default.DefaultDialect): def _pragma_cursor(cursor): - """work around SQLite issue whereby cursor.description + """work around SQLite issue whereby cursor.description is blank when PRAGMA returns no rows.""" if cursor.closed: diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlite.py b/lib/sqlalchemy/dialects/sqlite/pysqlite.py index 71f91aa36..c18fd302f 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -12,15 +12,15 @@ module included with the Python distribution. Driver ------ -When using Python 2.5 and above, the built in ``sqlite3`` driver is +When using Python 2.5 and above, the built in ``sqlite3`` driver is already installed and no additional installation is needed. Otherwise, the ``pysqlite2`` driver needs to be present. This is the same driver as ``sqlite3``, just with a different name. The ``pysqlite2`` driver will be loaded first, and if not found, ``sqlite3`` is loaded. This allows an explicitly installed pysqlite driver to take -precedence over the built in one. As with all dialects, a specific -DBAPI module may be provided to :func:`~sqlalchemy.create_engine()` to control +precedence over the built in one. As with all dialects, a specific +DBAPI module may be provided to :func:`~sqlalchemy.create_engine()` to control this explicitly:: from sqlite3 import dbapi2 as sqlite @@ -64,25 +64,25 @@ The sqlite ``:memory:`` identifier is the default if no filepath is present. Sp Compatibility with sqlite3 "native" date and datetime types ----------------------------------------------------------- -The pysqlite driver includes the sqlite3.PARSE_DECLTYPES and +The pysqlite driver includes the sqlite3.PARSE_DECLTYPES and sqlite3.PARSE_COLNAMES options, which have the effect of any column or expression explicitly cast as "date" or "timestamp" will be converted -to a Python date or datetime object. The date and datetime types provided -with the pysqlite dialect are not currently compatible with these options, -since they render the ISO date/datetime including microseconds, which +to a Python date or datetime object. The date and datetime types provided +with the pysqlite dialect are not currently compatible with these options, +since they render the ISO date/datetime including microseconds, which pysqlite's driver does not. Additionally, SQLAlchemy does not at -this time automatically render the "cast" syntax required for the +this time automatically render the "cast" syntax required for the freestanding functions "current_timestamp" and "current_date" to return -datetime/date types natively. Unfortunately, pysqlite +datetime/date types natively. Unfortunately, pysqlite does not provide the standard DBAPI types in ``cursor.description``, -leaving SQLAlchemy with no way to detect these types on the fly +leaving SQLAlchemy with no way to detect these types on the fly without expensive per-row type checks. Keeping in mind that pysqlite's parsing option is not recommended, -nor should be necessary, for use with SQLAlchemy, usage of PARSE_DECLTYPES +nor should be necessary, for use with SQLAlchemy, usage of PARSE_DECLTYPES can be forced if one configures "native_datetime=True" on create_engine():: - engine = create_engine('sqlite://', + engine = create_engine('sqlite://', connect_args={'detect_types': sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES}, native_datetime=True ) @@ -99,7 +99,7 @@ Threading/Pooling Behavior Pysqlite's default behavior is to prohibit the usage of a single connection in more than one thread. This is controlled by the ``check_same_thread`` Pysqlite flag. This default is intended to work with older versions -of SQLite that did not support multithreaded operation under +of SQLite that did not support multithreaded operation under various circumstances. In particular, older SQLite versions did not allow a ``:memory:`` database to be used in multiple threads under any circumstances. @@ -109,9 +109,9 @@ SQLAlchemy sets up pooling to work with Pysqlite's default behavior: * When a ``:memory:`` SQLite database is specified, the dialect by default will use :class:`.SingletonThreadPool`. This pool maintains a single connection per thread, so that all access to the engine within the current thread use the - same ``:memory:`` database - other threads would access a different + same ``:memory:`` database - other threads would access a different ``:memory:`` database. -* When a file-based database is specified, the dialect will use :class:`.NullPool` +* When a file-based database is specified, the dialect will use :class:`.NullPool` as the source of connections. This pool closes and discards connections which are returned to the pool immediately. SQLite file-based connections have extremely low overhead, so pooling is not necessary. The scheme also @@ -141,7 +141,7 @@ can be passed to Pysqlite as ``False``:: connect_args={'check_same_thread':False}, poolclass=StaticPool) -Note that using a ``:memory:`` database in multiple threads requires a recent +Note that using a ``:memory:`` database in multiple threads requires a recent version of SQLite. Using Temporary Tables with SQLite @@ -175,8 +175,8 @@ Unicode The pysqlite driver only returns Python ``unicode`` objects in result sets, never plain strings, and accommodates ``unicode`` objects within bound parameter -values in all cases. Regardless of the SQLAlchemy string type in use, -string-based result values will by Python ``unicode`` in Python 2. +values in all cases. Regardless of the SQLAlchemy string type in use, +string-based result values will by Python ``unicode`` in Python 2. The :class:`.Unicode` type should still be used to indicate those columns that require unicode, however, so that non-``unicode`` values passed inadvertently will emit a warning. Pysqlite will emit an error if a non-``unicode`` string @@ -191,7 +191,7 @@ The pysqlite DBAPI driver has a long-standing bug in which transactional state is not begun until the first DML statement, that is INSERT, UPDATE or DELETE, is emitted. A SELECT statement will not cause transactional state to begin. While this mode of usage is fine for typical situations -and has the advantage that the SQLite database file is not prematurely +and has the advantage that the SQLite database file is not prematurely locked, it breaks serializable transaction isolation, which requires that the database file be locked upon any SQL being emitted. diff --git a/lib/sqlalchemy/dialects/sybase/pyodbc.py b/lib/sqlalchemy/dialects/sybase/pyodbc.py index 35d8d1542..70bdd71a2 100644 --- a/lib/sqlalchemy/dialects/sybase/pyodbc.py +++ b/lib/sqlalchemy/dialects/sybase/pyodbc.py @@ -17,7 +17,7 @@ Connect strings are of the form:: Unicode Support --------------- -The pyodbc driver currently supports usage of these Sybase types with +The pyodbc driver currently supports usage of these Sybase types with Unicode or multibyte strings:: CHAR @@ -43,7 +43,7 @@ from sqlalchemy.util.compat import decimal class _SybNumeric_pyodbc(sqltypes.Numeric): """Turns Decimals with adjusted() < -6 into floats. - It's not yet known how to get decimals with many + It's not yet known how to get decimals with many significant digits or very large adjusted() into Sybase via pyodbc. diff --git a/lib/sqlalchemy/dialects/sybase/pysybase.py b/lib/sqlalchemy/dialects/sybase/pysybase.py index e3bfae06c..bf8c2096b 100644 --- a/lib/sqlalchemy/dialects/sybase/pysybase.py +++ b/lib/sqlalchemy/dialects/sybase/pysybase.py @@ -38,7 +38,7 @@ class SybaseExecutionContext_pysybase(SybaseExecutionContext): def set_ddl_autocommit(self, dbapi_connection, value): if value: # call commit() on the Sybase connection directly, - # to avoid any side effects of calling a Connection + # to avoid any side effects of calling a Connection # transactional method inside of pre_exec() dbapi_connection.commit() @@ -83,7 +83,7 @@ class SybaseDialect_pysybase(SybaseDialect): def _get_server_version_info(self, connection): vers = connection.scalar("select @@version_number") - # i.e. 15500, 15000, 12500 == (15, 5, 0, 0), (15, 0, 0, 0), + # i.e. 15500, 15000, 12500 == (15, 5, 0, 0), (15, 0, 0, 0), # (12, 5, 0, 0) return (vers / 1000, vers % 1000 / 100, vers % 100 / 10, vers % 10) |
