0.6 Changelog

0.6.9

Released: Sat May 05 2012

general

  • [general]

Adjusted the “importlater” mechanism, which isused internally to resolve import cycles,such that the usage of import is completedwhen the import of sqlalchemy or sqlalchemy.ormis done, thereby avoiding any usage of importafter the application starts new threads,fixes.References: #2279

orm

  • [orm] [bug]

fixed inappropriate evaluation of user-mappedobject in a boolean context within query.get().References: #2310

  • [orm] [bug]

Fixed the error formatting raised whena tuple is inadvertently passed to session.query().References: #2297

  • [orm]

Fixed bug whereby the source clauseused by query.join() would be inconsistentif against a column expression that combinedmultiple entities together.References: #2197

  • [orm]

Fixed bug apparent only in Python 3 wherebysorting of persistent + pending objects duringflush would produce an illegal comparison,if the persistent object primary keyis not a single integer.References: #2228

  • [orm]

Fixed bug where query.join() + aliased=Truefrom a joined-inh structure to itself onrelationship() with join condition on the childtable would convert the lead entity into thejoined one inappropriately.References: #2234

  • [orm]

Fixed bug whereby mapper.order_by attribute wouldbe ignored in the “inner” query within asubquery eager load. .References: #2287

  • [orm]

Fixed bug whereby if a mapped classredefined hash() or eq() to somethingnon-standard, which is a supported use caseas SQLA should never consult these,the methods would be consulted if the classwas part of a “composite” (i.e. non-single-entity)result set.References: #2215

  • [orm]

Fixed subtle bug that caused SQL to blowup if: column_property() against subquery +joinedload + LIMIT + order by the columnproperty() occurred. .References: #2188

  • [orm]

The join condition produced by with_parentas well as when using a “dynamic” relationshipagainst a parent will generate uniquebindparams, rather than incorrectly repeatingthe same bindparam. .References: #2207

  • [orm]

Repaired the “no statement condition”assertion in Query which would attemptto raise if a generative method were calledafter from_statement() were called..References: #2199

  • [orm]

Cls.column.collate(“some collation”) nowworks.References: #1776

engine

  • [engine]

Backported the fix for introducedin 0.7.4, which ensures that the connectionis in a valid state before attempting to callrollback()/prepare()/release() on savepointand two-phase transactions.References: #2317

sql

  • [sql]

Fixed two subtle bugs involving columncorrespondence in a selectable,one with the same labeled subquery repeated, the otherwhen the label has been “grouped” andloses itself. Affects.References: #2188

  • [sql]

Fixed bug whereby “warn on unicode” flagwould get set for the String typewhen used with certain dialects. Thisbug is not in 0.7.

  • [sql]

Fixed bug whereby with_only_columns() method ofSelect would fail if a selectable were passed.. However, the FROM behavior isstill incorrect here, so you need 0.7 inany case for this use case to be usable.References: #2270

schema

  • [schema]

Added an informative error message whenForeignKeyConstraint refers to a column name inthe parent that is not found.

postgresql

  • [postgresql]

Fixed bug related to whereby thesame modified index behavior in PG 9 affectedprimary key reflection on a renamed column..References: #2141, #2291

mysql

  • [mysql]

Fixed OurSQL dialect to use ansi-neutralquote symbol “’” for XA commands insteadof ‘”’. .References: #2186

  • [mysql]

a CREATE TABLE will put the COLLATE optionafter CHARSET, which appears to be part ofMySQL’s arbitrary rules regarding if it will actuallywork or not.References: #2225

mssql

  • [mssql] [bug]

Decode incoming values when retrievinglist of index names and the names of columnswithin those indexes.References: #2269

oracle

  • [oracle]

Added ORA-00028 to disconnect codes, usecx_oracle _Error.code to get at the code,.References: #2200

  • [oracle]

repaired the oracle.RAW type which did notgenerate the correct DDL.References: #2220

  • [oracle]

added CURRENT to reserved word list.References: #2212

misc

  • [examples]

Adjusted dictlike-polymorphic.py exampleto apply the CAST such that it works onPG, other databases.References: #2266

0.6.8

Released: Sun Jun 05 2011

orm

  • [orm]

Calling query.get() against a column-based entity isinvalid, this condition now raises a deprecation warning.References: #2144

  • [orm]

a non_primary mapper will inherit the _identity_classof the primary mapper. This so that a non_primaryestablished against a class that’s normally in aninheritance mapping will produce results that areidentity-map compatible with that of the primarymapperReferences: #2151

  • [orm]

Backported 0.7’s identity map implementation, whichdoes not use a mutex around removal. This as some userswere still getting deadlocks despite the adjustmentsin 0.6.7; the 0.7 approach that doesn’t use a mutexdoes not appear to produce “dictionary changed size”issues, the original rationale for the mutex.References: #2148

  • [orm]

Fixed the error message emitted for “can’texecute syncrule for destination column ‘q’;mapper ‘X’ does not map this column” toreference the correct mapper. .References: #2163

  • [orm]

Fixed bug where determination of “self referential”relationship would fail with no workaroundfor joined-inh subclass related to itself,or joined-inh subclass related to a subclassof that with no cols in the sub-sub classin the join condition.References: #2149

  • [orm]

mapper() will ignore non-configured foreign keysto unrelated tables when determining inheritcondition between parent and child class.This is equivalent to behavior alreadyapplied to declarative. Note that 0.7 has amore comprehensive solution to this, alteringhow join() itself determines an FK error.References: #2153

  • [orm]

Fixed bug whereby mapper mapped to an anonymousalias would fail if logging were used, due tounescaped % sign in the alias name.References: #2171

  • [orm]

Modify the text of the message which occurswhen the “identity” key isn’t detected onflush, to include the common cause thatthe Column isn’t set up to detectauto-increment correctly;.References: #2170

  • [orm]

Fixed bug where transaction-level “deleted”collection wouldn’t be cleared of expungedstates, raising an error if they laterbecame transient.References: #2182

engine

  • [engine]

Adjusted the contains() method ofa RowProxy result row such that no exceptionthrow is generated internally;NoSuchColumnError() also will generate itsmessage regardless of whether or not the columnconstruct can be coerced to a string..References: #2178

sql

  • [sql]

Fixed bug whereby if FetchedValue was passedto column server_onupdate, it would nothave its parent “column” assigned, addedtest coverage for all column default assignmentpatterns.References: #2147

  • [sql]

Fixed bug whereby nesting a label of a select()with another label in it would produce incorrectexported columns. Among other things this wouldbreak an ORM column_property() mapping againstanother column_property(). .References: #2167

postgresql

  • [postgresql]

Fixed bug affecting PG 9 whereby index reflectionwould fail if against a column whose namehad changed. .References: #2141

  • [postgresql]

Some unit test fixes regarding numeric arrays,MATCH operator. A potential floating-pointinaccuracy issue was fixed, and certain testsof the MATCH operator only execute within anEN-oriented locale for now. .References: #2175

mssql

  • [mssql]

Fixed bug in MSSQL dialect whereby the aliasingapplied to a schema-qualified table would leakinto enclosing select statements.References: #2169

  • [mssql]

Fixed bug whereby DATETIME2 type would fail onthe “adapt” step when used in result sets orbound parameters. This issue is not in 0.7.References: #2159

0.6.7

Released: Wed Apr 13 2011

orm

  • [orm]

Tightened the iterate vs. remove mutex around theidentity map iteration, attempting to reduce thechance of an (extremely rare) reentrant gc operationcausing a deadlock. Might remove the mutex in0.7.References: #2087

  • [orm]

Added a name argument to Query.subquery(), to allowa fixed name to be assigned to the alias object.References: #2030

  • [orm]

A warning is emitted when a joined-table inheriting mapperhas no primary keys on the locally mapped table(but has pks on the superclass table).References: #2019

  • [orm]

Fixed bug where “middle” class in a polymorphic hierarchywould have no ‘polymorphic_on’ column if it didn’t alsospecify a ‘polymorphic_identity’, leading to strangeerrors upon refresh, wrong class loaded when queryingfrom that target. Also emits the correct WHERE criterionwhen using single table inheritance.References: #2038

  • [orm]

Fixed bug where a column with a SQL or server side defaultthat was excluded from a mapping with include_propertiesor exclude_properties would result in UnmappedColumnError.References: #1995

  • [orm]

A warning is emitted in the unusual case that anappend or similar event on a collection occurs afterthe parent object has been dereferenced, whichprevents the parent from being marked as “dirty”in the session. This will be an exception in 0.7.References: #2046

  • [orm]

Fixed bug in query.options() whereby a pathapplied to a lazyload using string keys couldoverlap a same named attribute on the wrongentity. Note 0.7 has an updated version of thisfix.References: #2098

  • [orm]

Reworded the exception raised when a flushis attempted of a subclass that is not polymorphicagainst the supertype.References: #2063

  • [orm]

Some fixes to the state handling regardingbackrefs, typically when autoflush=False, wherethe back-referenced collection wouldn’tproperly handle add/removes with no netchange. Thanks to Richard Murri for thetest case + patch.References: #2123

  • [orm]

a “having” clause would be copied from theinside to the outside query if from_self()were used..References: #2130

engine

  • [engine]

Fixed bug in QueuePool, SingletonThreadPool wherebyconnections that were discarded via overflow or periodiccleanup() were not explicitly closed, leaving garbagecollection to the task instead. This generally onlyaffects non-reference-counting backends like Jythonand PyPy. Thanks to Jaimy Azle for spottingthis.References: #2102

sql

  • [sql]

Column.copy(), as used in table.tometadata(), copies the‘doc’ attribute.References: #2028

  • [sql]

Added some defs to the resultproxy.c extension so thatthe extension compiles and runs on Python 2.4.References: #2023

  • [sql]

The compiler extension now supports overriding the defaultcompilation of expression._BindParamClause including thatthe auto-generated binds within the VALUES/SET clauseof an insert()/update() statement will also use the newcompilation rules.References: #2042

  • [sql]

Added accessors to ResultProxy “returns_rows”, “is_insert”References: #2089

  • [sql]

The limit/offset keywords to select() as wellas the value passed to select.limit()/offset()will be coerced to integer.References: #2116

postgresql

  • [postgresql]

When explicit sequence execution derives the nameof the auto-generated sequence of a SERIAL column,which currently only occurs if implicit_returning=False,now accommodates if the table + column name is greaterthan 63 characters using the same logic PostgreSQL uses.References: #1083

  • [postgresql]

Added an additional libpq message to the list of “disconnect”exceptions, “could not receive data from server”References: #2044

  • [postgresql]

Added RESERVED_WORDS for postgresql dialect.References: #2092

  • [postgresql]

Fixed the BIT type to allow a “length” parameter, “varying”parameter. Reflection also fixed.References: #2073

mysql

  • [mysql]

oursql dialect accepts the same “ssl” arguments increate_engine() as that of MySQLdb.References: #2047

sqlite

  • [sqlite]

Fixed bug where reflection of foreign keycreated as “REFERENCES ” withoutcol name would fail.References: #2115

mssql

  • [mssql]

Rewrote the query used to get the definition of a view,typically when using the Inspector interface, touse sys.sql_modules instead of the information schema,thereby allowing views definitions longer than 4000characters to be fully returned.References: #2071

oracle

  • [oracle]

Using column names that would require quotesfor the column itself or for a name-generatedbind parameter, such as names with specialcharacters, underscores, non-ascii characters,now properly translate bind parameter keys whentalking to cx_oracle.References: #2100

  • [oracle]

Oracle dialect adds use_binds_for_limits=Falsecreate_engine() flag, will render the LIMIT/OFFSETvalues inline instead of as binds, reported tomodify the execution plan used by Oracle.References: #2116

firebird

  • [firebird]

The “implicit_returning” flag on create_engine() ishonored if set to False.References: #2083

misc

  • [informix]

Added RESERVED_WORDS informix dialect.References: #2092

  • [ext]

The horizontal_shard ShardedSession class accepts the commonSession argument “query_cls” as a constructor argument,to enable further subclassing of ShardedQuery.References: #2090

  • [declarative]

Added an explicit check for the case that the name‘metadata’ is used for a column attribute on adeclarative class.References: #2050

  • [declarative]

Fix error message referencing old @classpropertyname to reference @declared_attrReferences: #2061

  • [declarative]

Arguments in mapper_args that aren’t “hashable”aren’t mistaken for always-hashable, possibly-columnarguments.References: #2091

  • [documentation]

Documented SQLite DATE/TIME/DATETIME types.References: #2029

  • [examples]

The Beaker caching example allows a “query_cls” argumentto the query_callable() function.References: #2090

0.6.6

Released: Sat Jan 08 2011

orm

  • [orm]

Fixed bug whereby a non-“mutable” attribute modified eventwhich occurred on an object that was clean except forpreceding mutable attribute changes would fail to stronglyreference itself in the identity map. This would cause theobject to be garbage collected, losing track of any changesthat weren’t previously saved in the “mutable changes”dictionary.

  • [orm]

Fixed bug whereby “passive_deletes=’all’” wasn’t passingthe correct symbols to lazy loaders during flush, therebycausing an unwarranted load.References: #2013

  • [orm]

Fixed bug which prevented composite mappedattributes from being used on a mapped select statement.. Note the workings of composite are slated tochange significantly in 0.7.References: #1997

  • [orm]

active_history flag also added to composite().The flag has no effect in 0.6, but is insteada placeholder flag for forwards compatibility,as it applies in 0.7 for composites.References: #1976

  • [orm]

Fixed uow bug whereby expired objects passed toSession.delete() would not have unloaded referencesor collections taken into account when deletingobjects, despite passive_deletes remaining atits default of False.References: #2002

  • [orm]

A warning is emitted when version_id_col is specifiedon an inheriting mapper when the inherited mapperalready has one, if those column expressions are notthe same.References: #1987

  • [orm]

“innerjoin” flag doesn’t take effect along the chainof joinedload() joins if a previous join in that chainis an outer join, thus allowing primary rows withouta referenced child row to be correctly returnedin results.References: #1954

  • [orm]

Fixed bug regarding “subqueryload” strategy wherebystrategy would fail if the entity was an aliased()construct.References: #1964

  • [orm]

Fixed bug regarding “subqueryload” strategy wherebythe join would fail if using a multi-level loadof the form from A->joined-subclass->CReferences: #2014

  • [orm]

Fixed indexing of Query objects by -1. It was erroneouslytransformed to the empty slice -1:0 that resulted inIndexError.References: #1968

  • [orm]

The mapper argument “primary_key” can be passed as asingle column as well as a list or tuple.The documentation examples that illustrated it as ascalar value have been changed to lists.References: #1971

  • [orm]

Added active_history flag to relationship()and column_property(), forces attribute events toalways load the “old” value, so that it’s available toattributes.get_history().References: #1961

  • [orm]

Query.get() will raise if the number of paramsin a composite key is too large, as well as toosmall.References: #1977

  • [orm]

Backport of “optimized get” fix from 0.7,improves the generation of joined-inheritance“load expired row” behavior.References: #1992

  • [orm]

A little more verbiage to the “primaryjoin” error,in an unusual condition that the join condition“works” for viewonly but doesn’t work for non-viewonly,and foreign_keys wasn’t used - adds “foreign_keys” tothe suggestion. Also add “foreign_keys” to thesuggestion for the generic “direction” error.

engine

  • [engine]

The “unicode warning” against non-unicode bind datais now raised only when theUnicode type is used explicitly; not whenconvert_unicode=True is used on the engineor String type.

  • [engine]

Fixed memory leak in C version of Decimal resultprocessor.References: #1978

  • [engine]

Implemented sequence check capability for the Cversion of RowProxy, as well as 2.7 style“collections.Sequence” registration for RowProxy.References: #1871

  • [engine]

Threadlocal engine methods rollback(), commit(),prepare() won’t raise if no transaction is in progress;this was a regression introduced in 0.6.References: #1998

  • [engine]

Threadlocal engine returns itself upon begin(),begin_nested(); engine then implements contextmanagermethods to allow the “with” statement.References: #2004

sql

  • [sql]

Fixed operator precedence rules for multiplechains of a single non-associative operator.I.e. “x - (y - z)” will compile as “x - (y - z)”and not “x - y - z”. Also works with labels,i.e. “x - (y - z).label(‘foo’)”References: #1984

  • [sql]

The ‘info’ attribute of Column is copied duringColumn.copy(), i.e. as occurs when using columnsin declarative mixins.References: #1967

  • [sql]

Added a bind processor for booleans which coercesto int, for DBAPIs such as pymssql that naively callstr() on values.

  • [sql]

CheckConstraint will copy its ‘initially’, ‘deferrable’,and ‘_create_rule’ attributes within a copy()/tometadata()References: #2000

postgresql

  • [postgresql]

Single element tuple expressions inside an IN clauseparenthesize correctly, also fromReferences: #1984

  • [postgresql]

Ensured every numeric, float, int code, scalar + array,are recognized by psycopg2 and pg8000’s “numeric”base type.References: #1955

  • [postgresql]

Added as_uuid=True flag to the UUID type, will receiveand return values as Python UUID() objects rather thanstrings. Currently, the UUID type is only known towork with psycopg2.References: #1956

  • [postgresql]

Fixed bug whereby KeyError would occur with non-ENUMsupported PG versions after a pool dispose+recreatewould occur.References: #1989

mysql

  • [mysql]

Fixed error handling for Jython + zxjdbc, such thathas_table() property works again. Regression from0.6.3 (we don’t have a Jython buildbot, sorry)References: #1960

sqlite

  • [sqlite]

The REFERENCES clause in a CREATE TABLE that includesa remote schema to another table with the same schemaname now renders the remote name withoutthe schema clause, as required by SQLite.References: #1851

  • [sqlite]

On the same theme, the REFERENCES clause in a CREATE TABLEthat includes a remote schema to a different schemathan that of the parent table doesn’t render at all,as cross-schema references do not appear to be supported.

mssql

  • [mssql]

The rewrite of index reflection in wasunfortunately not tested correctly, and returned incorrectresults. This regression is now fixed.References: #1770

oracle

  • [oracle]

The cx_oracle “decimal detection” logic, which takes placefor result set columns with ambiguous numeric characteristics,now uses the decimal point character determined by the locale/NLS_LANG setting, using an on-first-connect detection ofthis character. cx_oracle 5.0.3 or greater is also requiredwhen using a non-period-decimal-point NLS_LANG setting..References: #1953

firebird

  • [firebird]

Firebird numeric type now checks for Decimal explicitly,lets float() pass right through, thereby allowingspecial values such as float(‘inf’).References: #2012

misc

  • [declarative]

An error is raised if table_args is not in tupleor dict format, and is not None.References: #1972

  • [sqlsoup]

Added “map_to()” method to SqlSoup, which is a “master”method which accepts explicit arguments for each aspect ofthe selectable and mapping, including a base class permapping.References: #1975

  • [sqlsoup]

Mapped selectables used with the map(), with_labels(),join() methods no longer put the given argument into theinternal “cache” dictionary. Particularly since thejoin() and select() objects are created in the methoditself this was pretty much a pure memory leaking behavior.

  • [examples]

The versioning example now supports detection of changesin an associated relationship().

0.6.5

Released: Sun Oct 24 2010

orm

  • [orm]

Added a new “lazyload” option “immediateload”.Issues the usual “lazy” load operation automaticallyas the object is populated. The use casehere is when loading objects to be placed inan offline cache, or otherwise used afterthe session isn’t available, and straight ‘select’loading, not ‘joined’ or ‘subquery’, is desired.References: #1914

  • [orm]

New Query methods: query.label(name), query.as_scalar(),return the query’s statement as a scalar subquerywith /without label;query.with_entities(*ent), replaces the SELECT list ofthe query with new entities.Roughly equivalent to a generative form of query.values()which accepts mapped entities as well as columnexpressions.References: #1920

  • [orm]

Fixed recursion bug which could occur when movingan object from one reference to another, withbackrefs involved, where the initiating parentwas a subclass (with its own mapper) of theprevious parent.

  • [orm]

Fixed a regression in 0.6.4 which occurred if youpassed an empty list to “include_properties” onmapper()References: #1918

  • [orm]

Fixed labeling bug in Query whereby the NamedTuplewould mis-apply labels if any of the columnexpressions were un-labeled.

  • [orm]

Patched a case where query.join() would adapt theright side to the right side of the left’s joininappropriatelyReferences: #1925

  • [orm]

Query.select_from() has been beefed up to helpensure that a subsequent call to query.join()will use the select_from() entity, assuming it’sa mapped entity and not a plain selectable,as the default “left” side, not the first entityin the Query object’s list of entities.

  • [orm]

The exception raised by Session when it is usedsubsequent to a subtransaction rollback (which is whathappens when a flush fails in autocommit=False mode) hasnow been reworded (this is the “inactive due to arollback in a subtransaction” message). In particular,if the rollback was due to an exception during flush(),the message states this is the case, and reiterates thestring form of the original exception that occurredduring flush. If the session is closed due to explicitusage of subtransactions (not very common), the messagejust states this is the case.

  • [orm]

The exception raised by Mapper when repeated requests toits initialization are made after initialization alreadyfailed no longer assumes the “hasattr” case, sincethere’s other scenarios in which this message getsemitted, and the message also does not compound ontoitself multiple times - you get the same message foreach attempt at usage. The misnomer “compiles” is beingtraded out for “initialize”.

  • [orm]

Fixed bug in query.update() where ‘evaluate’ or ‘fetch’expiration would fail if the column expression key wasa class attribute with a different keyname as theactual column name.References: #1935

  • [orm]

Added an assertion during flush which ensuresthat no NULL-holding identity keys were generatedon “newly persistent” objects.This can occur when user defined code inadvertentlytriggers flushes on not-fully-loaded objects.

  • [orm]

lazy loads for relationship attributes now usethe current state, not the “committed” state,of foreign and primary key attributeswhen issuing SQL, if a flush is not in process.Previously, only the database-committed state wouldbe used. In particular, this would cause a many-to-oneget()-on-lazyload operation to fail, as autoflushis not triggered on these loads when the attributes aredetermined and the “committed” state may not beavailable.References: #1910

  • [orm]

A new flag on relationship(), load_on_pending, allowsthe lazy loader to fire off on pending objects without aflush taking place, as well as a transient object that’sbeen manually “attached” to the session. Note that thisflag blocks attribute events from taking place when anobject is loaded, so backrefs aren’t available untilafter a flush. The flag is only intended for veryspecific use cases.

  • [orm]

Another new flag on relationship(), cascadebackrefs,disables the “save-update” cascade when the event wasinitiated on the “reverse” side of a bidirectionalrelationship. This is a cleaner behavior so thatmany-to-ones can be set on a transient object withoutit getting sucked into the child object’s session,while still allowing the forward collection tocascade. We _might default this to False in 0.7.

  • [orm]

Slight improvement to the behavior of“passive_updates=False” when placed only on themany-to-one side of a relationship; documentation hasbeen clarified that passive_updates=False should reallybe on the one-to-many side.

  • [orm]

Placing passive_deletes=True on a many-to-one emitsa warning, since you probably intended to put it onthe one-to-many side.

  • [orm]

Fixed bug that would prevent “subqueryload” fromworking correctly with single table inheritancefor a relationship from a subclass - the “wheretype in (x, y, z)” only gets placed on the inside,instead of repeatedly.

  • [orm]

When using from_self() with single table inheritance,the “where type in (x, y, z)” is placed on the outsideof the query only, instead of repeatedly. May makesome more adjustments to this.

  • [orm]

scoped_session emits a warning when configure() iscalled if a Session is already present (checks only thecurrent thread)References: #1924

  • [orm]

reworked the internals of mapper.cascade_iterator() tocut down method calls by about 9% in some circumstances.References: #1932

engine

  • [engine]

Fixed a regression in 0.6.4 whereby the change thatallowed cursor errors to be raised consistently brokethe result.lastrowid accessor. Test coverage hasbeen added for result.lastrowid. Note that lastrowidis only supported by Pysqlite and some MySQL drivers,so isn’t super-useful in the general case.

  • [engine]

the logging message emitted by the engine whena connection is first used is now “BEGIN (implicit)”to emphasize that DBAPI has no explicit begin().

  • [engine]

added “views=True” option to metadata.reflect(),will add the list of available views to thosebeing reflected.References: #1936

  • [engine]

engine_from_config() now accepts ‘debug’ for‘echo’, ‘echo_pool’, ‘force’ for ‘convert_unicode’,boolean values for ‘use_native_unicode’.References: #1899

sql

  • [sql]

Fixed bug in TypeDecorator whereby the dialect-specifictype was getting pulled in to generate the DDL for agiven type, which didn’t always return the correct result.

  • [sql]

TypeDecorator can now have a fully constructed typespecified as its “impl”, in addition to a type class.

  • [sql]

TypeDecorator will now place itself as the resultingtype for a binary expression where the type coercionrules would normally return its impl type - previously,a copy of the impl type would be returned which wouldhave the TypeDecorator embedded into it as the “dialect”impl, this was probably an unintentional way of achievingthe desired effect.

  • [sql]

TypeDecorator.load_dialect_impl() returns “self.impl” bydefault, i.e. not the dialect implementation type of“self.impl”. This to support compilation correctly.Behavior can be user-overridden in exactly the same wayas before to the same effect.

  • [sql]

Added typecoerce(expr, type) expression element.Treats the given expression as the given type when evaluatingexpressions and processing result rows, but does notaffect the generation of SQL, other than an anonymouslabel.

  • [sql]

Table.tometadata() now copies Index objects associatedwith the Table as well.

  • [sql]

Table.tometadata() issues a warning if the given Tableis already present in the target MetaData - the existingTable object is returned.

  • [sql]

An informative error message is raised if a Columnwhich has not yet been assigned a name, i.e. as indeclarative, is used in a context where it isexported to the columns collection of an enclosingselect() construct, or if any construct involvingthat column is compiled before its name isassigned.

  • [sql]

as_scalar(), label() can be called on a selectablewhich contains a Column that is not yet named.References: #1862

  • [sql]

Fixed recursion overflow which could occur when operatingwith two expressions both of type “NullType”, butnot the singleton NULLTYPE instance.References: #1907

postgresql

  • [postgresql]

Added “as_tuple” flag to ARRAY type, returns resultsas tuples instead of lists to allow hashing.

  • [postgresql]

Fixed bug which prevented “domain” built from acustom type such as “enum” from being reflected.References: #1933

mysql

  • [mysql]

Fixed bug involving reflection of CURRENT_TIMESTAMPdefault used with ON UPDATE clause, thanks toTaavi BurnsReferences: #1940

mssql

  • [mssql]

Fixed reflection bug which did not properly handlereflection of unknown types.References: #1946

  • [mssql]

Fixed bug where aliasing of tables with “schema” wouldfail to compile properly.References: #1943

  • [mssql]

Rewrote the reflection of indexes to use sys.catalogs, so that column names of any configuration(spaces, embedded commas, etc.) can be reflected.Note that reflection of indexes requires SQLServer 2005 or greater.References: #1770

  • [mssql]

mssql+pymssql dialect now honors the “port” portionof the URL instead of discarding it.References: #1952

oracle

  • [oracle]

The implicit_returning argument to create_engine()is now honored regardless of detected version ofOracle. Previously, the flag would be forcedto False if server version info was < 10.References: #1878

misc

  • [declarative]

@classproperty (soon/now @declaredattr) takes effect formapper_args, table_args, _tablename ona base class that is not a mixin, as well as mixins.References: #1922

  • [declarative]

@classproperty ‘s official name/location for usagewith declarative is sqlalchemy.ext.declarative.declared_attr.Same thing, but moving there since it is more of a“marker” that’s specific to declarative,not just an attribute technique.References: #1915

  • [declarative]

Fixed bug whereby columns on a mixin wouldn’t propagatecorrectly to a single-table, or joined-table,inheritance scheme where the attribute name isdifferent than that of the column.,.References: #1930, #1931

  • [declarative]

A mixin can now specify a column that overridesa column of the same name associated with a superclass.Thanks to Oystein Haaland.

  • [informix]

Major cleanup / modernization of the Informixdialect for 0.6, courtesy Florian Apolloner.References: #1906

  • [tests]

the NoseSQLAlchemyPlugin has been moved to anew package “sqlalchemy_nose” which installsalong with “sqlalchemy”. This so that the “nosetests”script works as always but also allows the–with-coverage option to turn on coverage beforeSQLAlchemy modules are imported, allowing coverageto work correctly.

  • [misc]

CircularDependencyError now has .cycles and .edgesmembers, which are the set of elements involved inone or more cycles, and the set of edges as 2-tuples.References: #1890

0.6.4

Released: Tue Sep 07 2010

orm

  • [orm]

The name ConcurrentModificationError has beenchanged to StaleDataError, and descriptiveerror messages have been revised to reflectexactly what the issue is. Both names willremain available for the foreseeable futurefor schemes that may be specifyingConcurrentModificationError in an “except:”clause.

  • [orm]

Added a mutex to the identity map which mutexesremove operations against iteration methods,which now pre-buffer before returning aniterable. This because asynchronous gccan remove items via the gc thread at any time.References: #1891

  • [orm]

The Session class is now present in sqlalchemy.orm.*.We’re moving away from the usage of create_session(),which has non-standard defaults, for those situationswhere a one-step Session constructor is desired. Mostusers should stick with sessionmaker() for general use,however.

  • [orm]

query.with_parent() now accepts transient objectsand will use the non-persistent values of their pk/fkattributes in order to formulate the criterion.Docs are also clarified as to the purpose of with_parent().

  • [orm]

The include_properties and exclude_properties argumentsto mapper() now accept Column objects as members inaddition to strings. This so that same-named Columnobjects, such as those within a join(), can bedisambiguated.

  • [orm]

A warning is now emitted if a mapper is created against ajoin or other single selectable that includes multiplecolumns with the same name in its .c. collection,and those columns aren’t explicitly named as part ofthe same or separate attributes (or excluded).In 0.7 this warning will be an exception. Note thatthis warning is not emitted when the combination occursas a result of inheritance, so that attributesstill allow being overridden naturally.. In 0.7 this will be improved further.References: #1896

  • [orm]

The primary_key argument to mapper() can now specifya series of columns that are only a subset ofthe calculated “primary key” columns of the mappedselectable, without an error being raised. Thishelps for situations where a selectable’s effectiveprimary key is simpler than the number of columnsin the selectable that are actually marked as“primary_key”, such as a join against twotables on their primary key columns.References: #1896

  • [orm]

An object that’s been deleted now gets a flag‘deleted’, which prohibits the object frombeing re-add()ed to the session, as previouslythe object would live in the identity mapsilently until its attributes were accessed.The make_transient() function now resets thisflag along with the “key” flag.

  • [orm]

make_transient() can be safely called on analready transient instance.

  • [orm]

a warning is emitted in mapper() if the polymorphic_oncolumn is not present either in direct or derivedform in the mapped selectable or in thewith_polymorphic selectable, instead of silentlyignoring it. Look for this to become anexception in 0.7.

  • [orm]

Another pass through the series of error messagesemitted when relationship() is configured withambiguous arguments. The “foreign_keys”setting is no longer mentioned, as it is almostnever needed and it is preferable users set upcorrect ForeignKey metadata, which is now therecommendation. If ‘foreign_keys’is used and is incorrect, the message suggeststhe attribute is probably unnecessary. Docsfor the attribute are beefed up. Thisbecause all confused relationship() users on theML appear to be attempting to use foreign_keysdue to the message, which only confuses themfurther since Table metadata is much clearer.

  • [orm]

If the “secondary” table has no ForeignKey metadataand no foreign_keys is set, even though theuser is passing screwed up information, it is assumedthat primary/secondaryjoin expressions shouldconsider only and all cols in “secondary” to beforeign. It’s not possible with “secondary” forthe foreign keys to be elsewhere in any case.A warning is now emitted instead of an error,and the mapping succeeds.References: #1877

  • [orm]

Moving an o2m object from one collection toanother, or vice versa changing the referencedobject by an m2o, where the foreign key is also amember of the primary key, will now be morecarefully checked during flush if the change invalue of the foreign key on the “many” side is theresult of a change in the primary key of the “one”side, or if the “one” is just a different object.In one case, a cascade-capable DB would havecascaded the value already and we need to look atthe “new” PK value to do an UPDATE, in the other weneed to continue looking at the “old”. We now lookat the “old”, assuming passive_updates=True,unless we know it was a PK switch thattriggered the change.References: #1856

  • [orm]

The value of version_id_col can be changedmanually, and this will result in an UPDATEof the row. Versioned UPDATEs and DELETEsnow use the “committed” value of theversion_id_col in the WHERE clause andnot the pending changed value. Theversion generator is also bypassed ifmanual changes are present on the attribute.References: #1857

  • [orm]

Repaired the usage of merge() when used withconcrete inheriting mappers. Such mappers frequentlyhave so-called “concrete” attributes, which aresubclass attributes that “disable” propagation fromthe parent - these needed to allow a merge()operation to pass through without effect.

  • [orm]

Specifying a non-column based argumentfor column_mapped_collection, including string,text() etc., will raise an error message thatspecifically asks for a column element, no longermisleads with incorrect information abouttext() or literal().References: #1863

  • [orm]

Similarly, for relationship(), foreign_keys,remote_side, order_by - all column-basedexpressions are enforced - lists of stringsare explicitly disallowed since this is avery common error

  • [orm]

Dynamic attributes don’t support collectionpopulation - added an assertion for whenset_committed_value() is called, as well aswhen joinedload() or subqueryload() optionsare applied to a dynamic attribute, insteadof failure / silent failure.References: #1864

  • [orm]

Fixed bug whereby generating a Query derivedfrom one which had the same column repeatedwith different label names, typicallyin some UNION situations, would fail topropagate the inner columns completely tothe outer query.References: #1852

  • [orm]

object_session() raises the properUnmappedInstanceError when presented with anunmapped instance.References: #1881

  • [orm]

Applied further memoizations to calculated Mapperproperties, with significant (~90%) runtime mapper.pycall count reduction in heavily polymorphic mappingconfigurations.

  • [orm]

mapper _get_col_to_prop private method usedby the versioning example is deprecated;now use mapper.get_property_by_column() whichwill remain the public method for this.

  • [orm]

the versioning example works correctly nowif versioning on a col that was formerlyNULL.

engine

  • [engine]

Calling fetchone() or similar on a result thathas already been exhausted, has been closed,or is not a result-returning result nowraises ResourceClosedError, a subclass ofInvalidRequestError, in all cases, regardlessof backend. Previously, some DBAPIs wouldraise ProgrammingError (i.e. pysqlite), otherswould return None leading to downstream breakages(i.e. MySQL-python).

  • [engine]

Fixed bug in Connection whereby if a “disconnect”event occurred in the “initialize” phase of thefirst connection pool connect, an AttributeErrorwould be raised when the Connection would attemptto invalidate the DBAPI connection.References: #1894

  • [engine]

Connection, ResultProxy, as well as Session useResourceClosedError for all “thisconnection/transaction/result is closed” types oferrors.

  • [engine]

Connection.invalidate() can be called more thanonce and subsequent calls do nothing.

sql

  • [sql]

Calling execute() on an alias() construct is pendingdeprecation for 0.7, as it is not itself an“executable” construct. It currently “proxies” itsinner element and is conditionally “executable” butthis is not the kind of ambiguity we like these days.

  • [sql]

The execute() and scalar() methods of ClauseElementare now moved appropriately to the Executablesubclass. ClauseElement.execute()/ scalar() are stillpresent and are pending deprecation in 0.7, but notethese would always raise an error anyway if you werenot an Executable (unless you were an alias(), seeprevious note).

  • [sql]

Added basic math expression coercion forNumeric->Integer,so that resulting type is Numeric regardlessof the direction of the expression.

  • [sql]

Changed the scheme used to generate truncated“auto” index names when using the “index=True”flag on Column. The truncation only takesplace with the auto-generated name, not onethat is user-defined (an error would beraised instead), and the truncation schemeitself is now based on a fragment of an md5hash of the identifier name, so that multipleindexes on columns with similar names stillhave unique names.References: #1855

  • [sql]

The generated index name also is based ona “max index name length” attribute which isseparate from the “max identifier length” -this to appease MySQL who has a max lengthof 64 for index names, separate from theiroverall max length of 255.References: #1412

  • [sql]

the text() construct, if placed in a columnoriented situation, will at least return NULLTYPEfor its type instead of None, allowing it tobe used a little more freely for ad-hoc columnexpressions than before. literal_column()is still the better choice, however.

  • [sql]

Added full description of parent table/column,target table/column in error message raised whenForeignKey can’t resolve target.

  • [sql]

Fixed bug whereby replacing composite foreign keycolumns in a reflected table would cause an attemptto remove the reflected constraint from the tablea second time, raising a KeyError.References: #1865

  • [sql]

the _Label construct, i.e. the one that is producedwhenever you say somecol.label(), now counts itselfin its “proxy_set” unioned with that of itscontained column’s proxy set, instead ofdirectly returning that of the contained column.This allows column correspondenceoperations which depend on the identity of the_Labels themselves to return the correct result

  • [sql]

fixes ORM bug.References: #1852

postgresql

  • [postgresql]

Fixed the psycopg2 dialect to use itsset_isolation_level() method instead of relyingupon the base “SET SESSION ISOLATION” command,as psycopg2 resets the isolation level on each newtransaction otherwise.

mssql

  • [mssql]

Fixed “default schema” query to work withpymssql backend.

oracle

  • [oracle]

Added ROWID type to the Oracle dialect, for thosecases where an explicit CAST might be needed.References: #1879

  • [oracle]

Oracle reflection of indexes has been tuned sothat indexes which include some or all primarykey columns, but not the same set of columnsas that of the primary key, are reflected.Indexes which contain the identical columnsas that of the primary key are skipped withinreflection, as the index in that case is assumedto be the auto-generated primary key index.Previously, any index with PK columns presentwould be skipped. Thanks to Kent Bowerfor the patch.References: #1867

  • [oracle]

Oracle now reflects the names of primary keyconstraints - also thanks to Kent Bower.References: #1868

firebird

  • [firebird]

Fixed bug whereby a column default would fail toreflect if the “default” keyword were lower case.

misc

  • [declarative]

if @classproperty is used with a regular class-boundmapper property attribute, it will be called to get theactual attribute value during initialization. Currently,there’s no advantage to using @classproperty on a columnor relationship attribute of a declarative class thatisn’t a mixin - evaluation is at the same time as if@classproperty weren’t used. But here we at least allowit to function as expected.

  • [declarative]

Fixed bug where “Can’t add additional column” messagewould display the wrong name.

  • [informix]

Applied patches from to getbasic Informix functionality up again. Werely upon end-user testing to ensure thatInformix is working to some degree.References: #1904

  • [documentation]

The docs have been reorganized such that the “APIReference” section is gone - all the docstrings fromthere which were public API are moved into thecontext of the main doc section that talks about it.Main docs divided into “SQLAlchemy Core” and“SQLAlchemy ORM” sections, mapper/relationship docshave been broken out. Lots of sections rewrittenand/or reorganized.

  • [examples]

The beaker_caching example has been reorganizedsuch that the Session, cache manager,declarative_base are part of environment, andcustom cache code is portable and now within“caching_query.py”. This allows the example tobe easier to “drop in” to existing projects.

  • [examples]

the history_meta versioning recipe sets “unique=False”when copying columns, so that the versioningtable handles multiple rows with repeating values.References: #1887

0.6.3

Released: Thu Jul 15 2010

orm

  • [orm]

Removed errant many-to-many load in unitofworkwhich triggered unnecessarily on expired/unloadedcollections. This load now takes place only ifpassive_updates is False and the parent primarykey has changed, or if passive_deletes is Falseand a delete of the parent has occurred.References: #1845

  • [orm]

Column-entities (i.e. query(Foo.id)) copy theirstate more fully when queries are derived fromthemselves + a selectable (i.e. from_self(),union(), etc.), so that join() and such have thecorrect state to work from.References: #1853

  • [orm]

Fixed bug where Query.join() would fail ifquerying a non-ORM column then joining withoutan on clause when a FROM clause is alreadypresent, now raises a checked exception thesame way it does when the clause is notpresent.References: #1853

  • [orm]

Improved the check for an “unmapped class”,including the case where the superclass is mappedbut the subclass is not. Any attempts to accesscls._sa_class_manager.mapper now raiseUnmappedClassError().References: #1142

  • [orm]

Added “column_descriptions” accessor to Query,returns a list of dictionaries containingnaming/typing information about the entitiesthe Query will return. Can be helpful forbuilding GUIs on top of ORM queries.

mysql

  • [mysql]

The _extract_error_code() method now workscorrectly with each MySQL dialect (MySQL-python, OurSQL, MySQL-Connector-Python,PyODBC). Previously,the reconnect logic would fail for OperationalErrorconditions, however since MySQLdb and OurSQLhave their own reconnect feature, there was nosymptom for these drivers here unless onewatched the logs.References: #1848

oracle

  • [oracle]

More tweaks to cx_oracle Decimal handling.“Ambiguous” numerics with no decimal placeare coerced to int at the connection handlerlevel. The advantage here is that intscome back as ints without SQLA typeobjects being involved and without needlessconversion to Decimal first.

Unfortunately, some exotic subquery casescan even see different types betweenindividual result rows, so the Numerichandler, when instructed to return Decimal,can’t take full advantage of “native decimal”mode and must run isinstance() on every valueto check if its Decimal already. Reopen ofReferences: #1840

0.6.2

Released: Tue Jul 06 2010

orm

  • [orm]

Query.join() will check for a call of theform query.join(target, clause_expression),i.e. missing the tuple, and raise an informativeerror message that this is the wrong calling form.

  • [orm]

Fixed bug regarding flushes on self-referentialbi-directional many-to-many relationships, wheretwo objects made to mutually reference each otherin one flush would fail to insert a row for bothsides. Regression from 0.5.References: #1824

  • [orm]

the post_update feature of relationship() has beenreworked architecturally to integrate more closelywith the new 0.6 unit of work. The motivationfor the change is so that multiple “post update”calls, each affecting different foreign keycolumns of the same row, are executed in a singleUPDATE statement, rather than one UPDATEstatement per column per row. Multiple rowupdates are also batched into executemany()s aspossible, while maintaining consistent row ordering.

  • [orm]

Query.statement, Query.subquery(), etc. now transferthe values of bind parameters, i.e. those specifiedby query.params(), into the resulting SQL expression.Previously the values would not be transferredand bind parameters would come out as None.

  • [orm]

Subquery-eager-loading now works with Query objectswhich include params(), as well as get() Queries.

  • [orm]

Can now call make_transient() on an instance thatis referenced by parent objects via many-to-one,without the parent’s foreign key value gettingtemporarily set to None - this was a functionof the “detect primary key switch” flush handler.It now ignores objects that are no longerin the “persistent” state, and the parent’sforeign key identifier is left unaffected.

  • [orm]

query.order_by() now accepts False, which cancelsany existing order_by() state on the Query, allowingsubsequent generative methods to be called which donot support ORDER BY. This is not the same as thealready existing feature of passing None, whichsuppresses any existing order_by() settings, includingthose configured on the mapper. False will make itas though order_by() was never called, whileNone is an active setting.

  • [orm]

An instance which is moved to “transient”, hasan incomplete or missing set of primary keyattributes, and contains expired attributes, willraise an InvalidRequestError if an expired attributeis accessed, instead of getting a recursion overflow.

  • [orm]

The make_transient() function is now in the generateddocumentation.

  • [orm]

make_transient() removes all “loader” callables fromthe state being made transient, removing any“expired” state - all unloaded attributes reset backto undefined, None/empty on access.

sql

  • [sql]

The warning emitted by the Unicode and String typeswith convert_unicode=True no longer embeds the actualvalue passed. This so that the Python warningregistry does not continue to grow in size, the warningis emitted once as per the warning filter settings,and large string values don’t pollute the output.References: #1822

  • [sql]

Fixed bug that would prevent overridden clausecompilation from working for “annotated” expressionelements, which are often generated by the ORM.

  • [sql]

The argument to “ESCAPE” of a LIKE operator or similaris passed through render_literal_value(), which mayimplement escaping of backslashes.References: #1400

  • [sql]

Fixed bug in Enum type which blew away native_enumflag when used with TypeDecorators or other adaptionscenarios.

  • [sql]

Inspector hits bind.connect() when invoked to ensureinitialize has been called. the internal name “.conn”is changed to “.bind”, since that’s what it is.

  • [sql]

Modified the internals of “column annotation” such thata custom Column subclass can safely override_constructor to return Column, for the purposes ofmaking “configurational” column classes that aren’tinvolved in proxying, etc.

  • [sql]

Column.copy() takes along the “unique” attributeamong others, fixes regarding declarativemixinsReferences: #1829

postgresql

  • [postgresql]

render_literal_value() is overridden which escapesbackslashes, currently applies to the ESCAPE clauseof LIKE and similar expressions.Ultimately this will have to detect the value of“standard_conforming_strings” for full behavior.References: #1400

  • [postgresql]

Won’t generate “CREATE TYPE” / “DROP TYPE” ifusing types.Enum on a PG version prior to 8.3 -the supports_native_enum flag is fullyhonored.References: #1836

mysql

  • [mysql]

MySQL dialect doesn’t emit CAST() for MySQL versiondetected < 4.0.2. This allows the unicodecheck on connect to proceed.References: #1826

  • [mysql]

MySQL dialect now detects NO_BACKSLASH_ESCAPES sqlmode, in addition to ANSI_QUOTES.

  • [mysql]

render_literal_value() is overridden which escapesbackslashes, currently applies to the ESCAPE clauseof LIKE and similar expressions. This behavioris derived from detecting the value ofNO_BACKSLASH_ESCAPES.References: #1400

mssql

  • [mssql]

If server_version_info is outside the usualrange of (8, ), (9, ), (10, ), a warning is emittedwhich suggests checking that the FreeTDS versionconfiguration is using 7.0 or 8.0, not 4.2.References: #1825

oracle

  • [oracle]

Fixed ora-8 compatibility flags such that theydon’t cache a stale value from before the firstdatabase connection actually occurs.References: #1819

  • [oracle]

Oracle’s “native decimal” metadata begins to returnambiguous typing information about numericswhen columns are embedded in subqueries as wellas when ROWNUM is consulted with subqueries, as wedo for limit/offset. We’ve added these ambiguousconditions to the cx_oracle “convert to Decimal()”handler, so that we receive numerics as Decimalin more cases instead of as floats. These arethen converted, if requested, into Integeror Float, or otherwise kept as the losslessDecimal.References: #1840

firebird

  • [firebird]

Fixed incorrect signature in do_execute(), errorintroduced in 0.6.1.References: #1823

  • [firebird]

Firebird dialect adds CHAR, VARCHAR types whichaccept a “charset” flag, to support Firebird“CHARACTER SET” clause.References: #1813

misc

  • [declarative]

Added support for @classproperty to provideany kind of schema/mapping construct from adeclarative mixin, including columns with foreignkeys, relationships, column_property, deferred.This solves all such issues on declarative mixins.An error is raised if any MapperProperty subclassis specified on a mixin without using @classproperty.References: #1751, #1796, #1805

  • [declarative]

a mixin class can now define a column that matchesone which is present on a table defined on asubclass. It cannot, however, define one that isnot present in the table, and the error messagehere now works.References: #1821

  • [compiler] [extension]

The ‘default’ compiler is automatically copied overwhen overriding the compilation of a built inclause construct, so no KeyError is raised if theuser-defined compiler is specific to certainbackends and compilation for a different backendis invoked.References: #1838

  • [documentation]

Added documentation for the Inspector.References: #1820

  • [documentation]

Fixed @memoized_property and @memoized_instancemethoddecorators so that Sphinx documentation picks upthese attributes and methods, such asResultProxy.inserted_primary_key.References: #1830

0.6.1

Released: Mon May 31 2010

orm

  • [orm]

Fixed regression introduced in 0.6.0 involving improperhistory accounting on mutable attributes.References: #1782

  • [orm]

Fixed regression introduced in 0.6.0 unit of work refactorthat broke updates for bi-directional relationship()with post_update=True.References: #1807

  • [orm]

session.merge() will not expire attributes on the returnedinstance if that instance is “pending”.References: #1789

  • [orm]

fixed setstate method of CollectionAdapter to notfail during deserialize where parent InstanceState notyet unserialized.References: #1802

  • [orm]

Added internal warning in case an instance without afull PK happened to be expired and then was askedto refresh.References: #1797

  • [orm]

Added more aggressive caching to the mapper’s usage ofUPDATE, INSERT, and DELETE expressions. Assuming thestatement has no per-object SQL expressions attached,the expression objects are cached by the mapper afterthe first create, and their compiled form is storedpersistently in a cache dictionary for the duration ofthe related Engine. The cache is an LRUCache for therare case that a mapper receives an extremelyhigh number of different column patterns as UPDATEs.

sql

  • [sql]

expr.in() now accepts a text() construct as the argument.Grouping parenthesis are added automatically, i.e. usageis like _col.in(text(“select id from table”))_.References: #1793

  • [sql]

Columns of _Binary type (i.e. LargeBinary, BLOB, etc.)will coerce a “basestring” on the right side into a_Binary as well so that required DBAPI processingtakes place.

  • [sql]

Added table.add_is_dependent_on(othertable), allows manualplacement of dependency rules between two Table objectsfor use within create_all(), drop_all(), sorted_tables.References: #1801

  • [sql]

Fixed bug that prevented implicit RETURNING from functioningproperly with composite primary key that contained zeroes.References: #1778

  • [sql]

Fixed errant space character when generating ADD CONSTRAINTfor a named UNIQUE constraint.

  • [sql]

Fixed “table” argument on constructor of ForeignKeyConstraintReferences: #1571

  • [sql]

Fixed bug in connection pool cursor wrapper whereby if acursor threw an exception on close(), the logging of themessage would fail.References: #1786

  • [sql]

the makeproxy() method of ColumnClause and Column now useself.__class to determine the class of object to be returnedinstead of hardcoding to ColumnClause/Column, making it slightlyeasier to produce specific subclasses of these which work inalias/subquery situations.

  • [sql]

func.XXX() doesn’t inadvertently resolve to non-Functionclasses (e.g. fixes func.text()).References: #1798

mysql

  • [mysql]

func.sysdate() emits “SYSDATE()”, i.e. with the endingparenthesis, on MySQL.References: #1794

sqlite

  • [sqlite]

Fixed concatenation of constraints when “PRIMARY KEY”constraint gets moved to column level due to SQLiteAUTOINCREMENT keyword being rendered.References: #1812

oracle

  • [oracle]

Added a check for cx_oracle versions lower than version 5,in which case the incompatible “output type handler” won’tbe used. This will impact decimal accuracy and someunicode handling issues.References: #1775

  • [oracle]

Fixed use_ansi=False mode, which was producing brokenWHERE clauses in pretty much all cases.References: #1790

  • [oracle]

Re-established support for Oracle 8 with cx_oracle,including that use_ansi is set to False automatically,NVARCHAR2 and NCLOB are not rendered for Unicode,“native unicode” check doesn’t fail, cx_oracle“native unicode” mode is disabled, VARCHAR() is emittedwith bytes count instead of char count.References: #1808

  • [oracle]

oracle_xe 5 doesn’t accept a Python unicode object inits connect string in normal Python 2.x mode - so we coerceto str() directly. non-ascii characters aren’t supportedin connect strings here since we don’t know what encodingwe could use.References: #1670

  • [oracle]

FOR UPDATE is emitted in the syntactically correct positionwhen limit/offset is used, i.e. the ROWNUM subquery.However, Oracle can’t really handle FOR UPDATE with ORDER BYor with subqueries, so its still not very usable, but atleast SQLA gets the SQL past the Oracle parser.References: #1815

firebird

  • [firebird]

Added a label to the query used within has_table() andhas_sequence() to work with older versions of Firebirdthat don’t provide labels for result columns.References: #1521

  • [firebird]

Added integer coercion to the “type_conv” attribute whenpassed via query string, so that it is properly interpretedby Kinterbasdb.References: #1779

  • [firebird]

Added ‘connection shutdown’ to the list of exception stringswhich indicate a dropped connection.References: #1646

misc

  • [engines]

Fixed building the C extensions on Python 2.4.References: #1781

  • [engines]

Pool classes will reuse the same “pool_logging_name” settingafter a dispose() occurs.

  • [engines]

Engine gains an “execution_options” argument andupdate_execution_options() method, which will apply toall connections generated by this engine.

  • [sqlsoup]

the SqlSoup constructor accepts a base argument which specifiesthe base class to use for mapped classes, the default beingobject.References: #1783

0.6.0

Released: Sun Apr 18 2010

orm

  • [orm]

Unit of work internals have been rewritten. Units of workwith large numbers of objects interdependent objectscan now be flushed without recursion overflowsas there is no longer reliance upon recursive calls. The number of internal structures now staysconstant for a particular session state, regardless ofhow many relationships are present on mappings. The flowof events now corresponds to a linear list of steps,generated by the mappers and relationships based on actualwork to be done, filtered through a single topological sortfor correct ordering. Flush actions are assembled usingfar fewer steps and less memory.References: #1081, #1742

  • [orm]

Along with the UOW rewrite, this also removes an issueintroduced in 0.6beta3 regarding topological cycle detectionfor units of work with long dependency cycles. We now usean algorithm written by Guido (thanks Guido!).

  • [orm]

one-to-many relationships now maintain a list of positiveparent-child associations within the flush, preventingprevious parents marked as deleted from cascading adelete or NULL foreign key set on those child objects,despite the end-user not removing the child from the oldassociation.References: #1764

  • [orm]

A collection lazy load will switch off defaulteagerloading on the reverse many-to-one side, sincethat loading is by definition unnecessary.References: #1495

  • [orm]

Session.refresh() now does an equivalent expire()on the given instance first, so that the “refresh-expire”cascade is propagated. Previously, refresh() wasnot affected in any way by the presence of “refresh-expire”cascade. This is a change in behavior versus thatof 0.6beta2, where the “lockmode” flag passed to refresh()would cause a version check to occur. Since the instanceis first expired, refresh() always upgrades the objectto the most recent version.

  • [orm]

The ‘refresh-expire’ cascade, when reaching a pending object,will expunge the object if the cascade also includes“delete-orphan”, or will simply detach it otherwise.References: #1754

  • [orm]

id(obj) is no longer used internally within topological.py,as the sorting functions now require hashable objectsonly.References: #1756

  • [orm]

The ORM will set the docstring of all generated descriptorsto None by default. This can be overridden using ‘doc’(or if using Sphinx, attribute docstrings work too).

  • [orm]

Added kw argument ‘doc’ to all mapper property callablesas well as Column(). Will assemble the string ‘doc’ asthe ‘doc’ attribute on the descriptor.

  • [orm]

Usage of version_id_col on a backend that supportscursor.rowcount for execute() but not executemany() now workswhen a delete is issued (already worked for saves, since thosedon’t use executemany()). For a backend that doesn’t supportcursor.rowcount at all, a warning is emitted the sameas with saves.References: #1761

  • [orm]

The ORM now short-term caches the “compiled” form ofinsert() and update() constructs when flushing lists ofobjects of all the same class, thereby avoiding redundantcompilation per individual INSERT/UPDATE within anindividual flush() call.

  • [orm]

internal getattr(), setattr(), getcommitted() methodson ColumnProperty, CompositeProperty, RelationshipPropertyhave been underscored (i.e. are private), signature haschanged.

sql

  • [sql]

Restored some bind-labeling logic from 0.5 which ensuresthat tables with column names that overlap another columnof the form “_” won’t produceerrors if column._label is used as a bind name duringan UPDATE. Test coverage which wasn’t present in 0.5has been added.References: #1755

  • [sql]

somejoin.select(fold_equivalents=True) is no longerdeprecated, and will eventually be rolled into a morecomprehensive version of the feature for.References: #1729

  • [sql]

the Numeric type raises an enormous warning when expectedto convert floats to Decimal from a DBAPI that returns floats.This includes SQLite, Sybase, MS-SQL.References: #1759

  • [sql]

Fixed an error in expression typing which caused an endlessloop for expressions with two NULL types.

  • [sql]

Fixed bug in execution_options() feature whereby the existingTransaction and other state information from the parentconnection would not be propagated to the sub-connection.

  • [sql]

Added new ‘compiled_cache’ execution option. A dictionarywhere Compiled objects will be cached when the Connectioncompiles a clause expression into a dialect- and parameter-specific Compiled object. It is the user’s responsibility tomanage the size of this dictionary, which will have keyscorresponding to the dialect, clause element, the columnnames within the VALUES or SET clause of an INSERT or UPDATE,as well as the “batch” mode for an INSERT or UPDATE statement.

  • [sql]

Added get_pk_constraint() to reflection.Inspector, similarto get_primary_keys() except returns a dict that includes thename of the constraint, for supported backends (PG so far).References: #1769

  • [sql]

Table.create() and Table.drop() no longer apply metadata-level create/drop events.References: #1771

postgresql

  • [postgresql]

PostgreSQL now reflects sequence names associated withSERIAL columns correctly, after the name of the sequencehas been changed. Thanks to Kumar McMillan for the patch.References: #1071

  • [postgresql]

Repaired missing import in psycopg2._PGNumeric type whenunknown numeric is received.

  • [postgresql]

psycopg2/pg8000 dialects now aware of REAL[], FLOAT[],DOUBLE_PRECISION[], NUMERIC[] return types withoutraising an exception.

  • [postgresql]

PostgreSQL reflects the name of primary key constraints,if one exists.References: #1769

oracle

  • [oracle]

Now using cx_oracle output converters so that theDBAPI returns natively the kinds of values we prefer:

  • [oracle]

NUMBER values with positive precision + scale convertto cx_oracle.STRING and then to Decimal. Thisallows perfect precision for the Numeric type whenusing cx_oracle.References: #1759

  • [oracle]

STRING/FIXED_CHAR now convert to unicode natively.SQLAlchemy’s String types then don’t need toapply any kind of conversions.

firebird

  • [firebird]

The functionality of result.rowcount can be disabled on aper-engine basis by setting ‘enable_rowcount=False’on create_engine(). Normally, cursor.rowcount is calledafter any UPDATE or DELETE statement unconditionally,because the cursor is then closed and Firebird requiresan open cursor in order to get a rowcount. Thiscall is slightly expensive however so it can be disabled.To re-enable on a per-execution basis, the‘enable_rowcount=True’ execution option may be used.

misc

  • [engines]

The C extension now also works with DBAPIs which use customsequences as row (and not only tuples).References: #1757

  • [ext]

the compiler extension now allows @compiles decoratorson base classes that extend to child classes, @compilesdecorators on child classes that aren’t broken by a@compiles decorator on the base class.

  • [ext]

Declarative will raise an informative error messageif a non-mapped class attribute is referenced in thestring-based relationship() arguments.

  • [ext]

Further reworked the “mixin” logic in declarative toadditionally allow mapper_args as a @classpropertyon a mixin, such as to dynamically assign polymorphic_identity.

  • [examples]

Updated attribute_shard.py example to use a more robustmethod of searching a Query for binary expressions whichcompare columns against literal values.

0.6beta3

Released: Sun Mar 28 2010

orm

  • [orm]

Major feature: Added new “subquery” loading capability torelationship(). This is an eager loading option whichgenerates a second SELECT for each collection representedin a query, across all parents at once. The queryre-issues the original end-user query wrapped in a subquery,applies joins out to the target collection, and loadsall those collections fully in one result, similar to“joined” eager loading but using all inner joins and notre-fetching full parent rows repeatedly (as most DBAPIs seemto do, even if columns are skipped). Subquery loading isavailable at mapper config level using “lazy=’subquery’” andat the query options level using “subqueryload(props..)”,“subqueryload_all(props…)”.References: #1675

  • [orm]

To accommodate the fact that there are now two kinds of eagerloading available, the new names for eagerload() andeagerload_all() are joinedload() and joinedload_all(). Theold names will remain as synonyms for the foreseeable future.

  • [orm]

The “lazy” flag on the relationship() function now acceptsa string argument for all kinds of loading: “select”, “joined”,“subquery”, “noload” and “dynamic”, where the default is now“select”. The old values of True/False/None still retain their usual meanings and will remainas synonyms for the foreseeable future.

  • [orm]

Added with_hint() method to Query() construct. This callsdirectly down to select().with_hint() and also acceptsentities as well as tables and aliases. See with_hint() in theSQL section below.References: #921

  • [orm]

Fixed bug in Query whereby calling q.join(prop).from_self(…).join(prop) would fail to render the second join outside thesubquery, when joining on the same criterion as was on theinside.

  • [orm]

Fixed bug in Query whereby the usage of aliased() constructswould fail if the underlying table (but not the actual alias)were referenced inside the subquery generated byq.from_self() or q.select_from().

  • [orm]

Fixed bug which affected all eagerload() and similar optionssuch that “remote” eager loads, i.e. eagerloads off of a lazyload such as query(A).options(eagerload(A.b, B.c))wouldn’t eagerload anything, but using eagerload(“b.c”) wouldwork fine.

  • [orm]

Query gains an add_columns(*columns) method which is a multi-version of add_column(col). add_column(col) is futuredeprecated.

  • [orm]

Query.join() will detect if the end result will be“FROM A JOIN A”, and will raise an error if so.

  • [orm]

Query.join(Cls.propname, from_joinpoint=True) will check morecarefully that “Cls” is compatible with the current joinpoint,and act the same way as Query.join(“propname”, from_joinpoint=True)in that regard.

sql

  • [sql]

Added with_hint() method to select() construct. Specifya table/alias, hint text, and optional dialect name, and“hints” will be rendered in the appropriate place in thestatement. Works for Oracle, Sybase, MySQL.References: #921

  • [sql]

Fixed bug introduced in 0.6beta2 where column labels wouldrender inside of column expressions already assigned a label.References: #1747

postgresql

  • [postgresql]

The psycopg2 dialect will log NOTICE messages via the“sqlalchemy.dialects.postgresql” logger name.References: #877

  • [postgresql]

the TIME and TIMESTAMP types are now available from thepostgresql dialect directly, which add the PG-specificargument ‘precision’ to both. ‘precision’ and‘timezone’ are correctly reflected for both TIME andTIMEZONE types.References: #997

mysql

  • [mysql]

No longer guessing that TINYINT(1) should be BOOLEANwhen reflecting - TINYINT(1) is returned. Use Boolean/BOOLEAN in table definition to get boolean conversionbehavior.References: #1752

oracle

  • [oracle]

The Oracle dialect will issue VARCHAR type definitionsusing character counts, i.e. VARCHAR2(50 CHAR), so thatthe column is sized in terms of characters and not bytes.Column reflection of character types will also useALL_TAB_COLUMNS.CHAR_LENGTH instead ofALL_TAB_COLUMNS.DATA_LENGTH. Both of these behaviors takeeffect when the server version is 9 or higher - forversion 8, the old behaviors are used.References: #1744

misc

  • [declarative]

Using a mixin won’t break if the mixin implements anunpredictable getattribute(), i.e. Zope interfaces.References: #1746

  • [declarative]

Using @classdecorator and similar on mixins to definetablename, table_args, etc. now works ifthe method references attributes on the ultimatesubclass.References: #1749

  • [declarative]

relationships and columns with foreign keys aren’tallowed on declarative mixins, sorry.References: #1751

  • [ext]

The sqlalchemy.orm.shard module now becomes an extension,sqlalchemy.ext.horizontal_shard. The old importworks with a deprecation warning.

0.6beta2

Released: Sat Mar 20 2010

orm

  • [orm]

The official name for the relation() function is nowrelationship(), to eliminate confusion over the relationalalgebra term. relation() however will remain availablein equal capacity for the foreseeable future.References: #1740

  • [orm]

Added “version_id_generator” argument to Mapper, this is acallable that, given the current value of the “version_id_col”,returns the next version number. Can be used for alternateversioning schemes such as uuid, timestamps.References: #1692

  • [orm]

added “lockmode” kw argument to Session.refresh(), willpass through the string value to Query the same asin with_lockmode(), will also do version check for aversion_id_col-enabled mapping.

  • [orm]

Fixed bug whereby calling query(A).join(A.bs).add_entity(B)in a joined inheritance scenario would double-add B as atarget and produce an invalid query.References: #1188

  • [orm]

Fixed bug in session.rollback() which involved not removingformerly “pending” objects from the session beforere-integrating “deleted” objects, typically occurred withnatural primary keys. If there was a primary key conflictbetween them, the attach of the deleted would failinternally. The formerly “pending” objects are now expungedfirst.References: #1674

  • [orm]

Removed a lot of logging that nobody really cares about,logging that remains will respond to live changes in thelog level. No significant overhead is added.References: #1719

  • [orm]

Fixed bug in session.merge() which prevented dict-likecollections from merging.

  • [orm]

session.merge() works with relations that specificallydon’t include “merge” in their cascade options - the targetis ignored completely.

  • [orm]

session.merge() will not expire existing scalar attributeson an existing target if the target has a value for thatattribute, even if the incoming merged doesn’t havea value for the attribute. This prevents unnecessary loadson existing items. Will still mark the attr as expiredif the destination doesn’t have the attr, though, whichfulfills some contracts of deferred cols.References: #1681

  • [orm]

The “allow_null_pks” flag is now called “allow_partial_pks”,defaults to True, acts like it did in 0.5 again. Except,it also is implemented within merge() such that a SELECTwon’t be issued for an incoming instance with partiallyNULL primary key if the flag is False.References: #1680

  • [orm]

Fixed bug in 0.6-reworked “many-to-one” optimizationssuch that a many-to-one that is against a non-primary keycolumn on the remote table (i.e. foreign key against aUNIQUE column) will pull the “old” value in from thedatabase during a change, since if it’s in the sessionwe will need it for proper history/backref accounting,and we can’t pull from the local identity map on anon-primary key column.References: #1737

  • [orm]

fixed internal error which would occur if calling has()or similar complex expression on a single-table inheritancerelation().References: #1731

  • [orm]

query.one() no longer applies LIMIT to the query, this toensure that it fully counts all object identities presentin the result, even in the case where joins may concealmultiple identities for two or more rows. As a bonus,one() can now also be called with a query that issuedfrom_statement() to start with since it no longer modifiesthe query.References: #1688

  • [orm]

query.get() now returns None if queried for an identifierthat is present in the identity map with a different classthan the one requested, i.e. when using polymorphic loading.References: #1727

  • [orm]

A major fix in query.join(), when the “on” clause is anattribute of an aliased() construct, but there is alreadyan existing join made out to a compatible target, query properlyjoins to the right aliased() construct instead of stickingonto the right side of the existing join.References: #1706

  • [orm]

Slight improvement to the fix for to not issueneedless updates of the primary key column during a so-called“row switch” operation, i.e. add + delete of two objectswith the same PK.References: #1362

  • [orm]

Now uses sqlalchemy.orm.exc.DetachedInstanceError when anattribute load or refresh action fails due to objectbeing detached from any Session. UnboundExecutionErroris specific to engines bound to sessions and statements.

  • [orm]

Query called in the context of an expression will renderdisambiguating labels in all cases. Note that this doesnot apply to the existing .statement and .subquery()accessor/method, which still honors the .with_labels()setting that defaults to False.

  • [orm]

Query.union() retains disambiguating labels within thereturned statement, thus avoiding various SQL compositionerrors which can result from column name conflicts.References: #1676

  • [orm]

Fixed bug in attribute history that inadvertently invokedeq on mapped instances.

  • [orm]

Some internal streamlining of object loading grants asmall speedup for large results, estimates are around10-15%. Gave the “state” internals a good solidcleanup with less complexity, datamembers,method calls, blank dictionary creates.

  • [orm]

Documentation clarification for query.delete()References: #1689

  • [orm]

Fixed cascade bug in many-to-one relation() when attributewas set to None, introduced in r6711 (cascade deleteditems into session during add()).

  • [orm]

Calling query.order_by() or query.distinct() before callingquery.select_from(), query.with_polymorphic(), orquery.from_statement() raises an exception now instead ofsilently dropping those criterion.References: #1736

  • [orm]

query.scalar() now raises an exception if more than onerow is returned. All other behavior remains the same.References: #1735

  • [orm]

Fixed bug which caused “row switch” logic, that is anINSERT and DELETE replaced by an UPDATE, to fail whenversion_id_col was in use.References: #1692

sql

  • [sql]

join() will now simulate a NATURAL JOIN by default. Meaning,if the left side is a join, it will attempt to join the rightside to the rightmost side of the left first, and not raiseany exceptions about ambiguous join conditions if successfuleven if there are further join targets across the rest ofthe left.References: #1714

  • [sql]

The most common result processors conversion function weremoved to the new “processors” module. Dialect authors areencouraged to use those functions whenever they correspondto their needs instead of implementing custom ones.

  • [sql]

SchemaType and subclasses Boolean, Enum are now serializable,including their ddl listener and other event callables.References: #1694, #1698

  • [sql]

Some platforms will now interpret certain literal valuesas non-bind parameters, rendered literally into the SQLstatement. This to support strict SQL-92 rules that areenforced by some platforms including MS-SQL and Sybase.In this model, bind parameters aren’t allowed in thecolumns clause of a SELECT, nor are certain ambiguousexpressions like “?=?”. When this mode is enabled, the basecompiler will render the binds as inline literals, but only acrossstrings and numeric values. Other types such as dateswill raise an error, unless the dialect subclass definesa literal rendering function for those. The bind parametermust have an embedded literal value already or an erroris raised (i.e. won’t work with straight bindparam(‘x’)).Dialects can also expand upon the areas where binds are notaccepted, such as within argument lists of functions(which don’t work on MS-SQL when native SQL binding is used).

  • [sql]

Added “unicodeerrors” parameter to String, Unicode, etc.Behaves like the ‘errors’ keyword argument tothe standard library’s string.decode() functions. This flagrequires that _convert_unicode is set to “force” - otherwise,SQLAlchemy is not guaranteed to handle the task of unicodeconversion. Note that this flag adds significant performanceoverhead to row-fetching operations for backends that alreadyreturn unicode objects natively (which most DBAPIs do). Thisflag should only be used as an absolute last resort for readingstrings from a column with varied or corrupted encodings,which only applies to databases that accept invalid encodingsin the first place (i.e. MySQL. not PG, Sqlite, etc.)

  • [sql]

Added math negation operator support, -x.

  • [sql]

FunctionElement subclasses are now directly executable thesame way any func.foo() construct is, with automaticSELECT being applied when passed to execute().

  • [sql]

The “type” and “bind” keyword arguments of a func.foo()construct are now local to “func.” constructs and arenot part of the FunctionElement base class, allowinga “type” to be handled in a custom constructor orclass-level variable.

  • [sql]

Restored the keys() method to ResultProxy.

  • [sql]

The type/expression system now does a more complete jobof determining the return type from an expressionas well as the adaptation of the Python operator intoa SQL operator, based on the full left/right/operatorof the given expression. In particularthe date/time/interval system created for PostgreSQLEXTRACT in has now been generalized intothe type system. The previous behavior which oftenoccurred of an expression “column + literal” forcingthe type of “literal” to be the same as that of “column”will now usually not occur - the type of“literal” is first derived from the Python type of theliteral, assuming standard native Python types + datetypes, before falling back to that of the known typeon the other side of the expression. If the“fallback” type is compatible (i.e. CHAR from String),the literal side will use that. TypeDecoratortypes override this by default to coerce the “literal”side unconditionally, which can be changed by implementingthe coerce_compared_value() method. Also part of.References: #1647, #1683

  • [sql]

Made sqlalchemy.sql.expressions.Executable part of publicAPI, used for any expression construct that can be sent toexecute(). FunctionElement now inherits Executable so thatit gains execution_options(), which are also propagatedto the select() that’s generated within execute().Executable in turn subclasses _Generative which marksany ClauseElement that supports the @_generativedecorator - these may also become “public” for the benefitof the compiler extension at some point.

  • [sql]

A change to the solution for - an end-userdefined bind parameter name that directly conflicts witha column-named bind generated directly from the SET orVALUES clause of an update/insert generates a compile error.This reduces call counts and eliminates some cases whereundesirable name conflicts could still occur.References: #1579

  • [sql]

Column() requires a type if it has no foreign keys (this isnot new). An error is now raised if a Column() has no typeand no foreign keys.References: #1705

  • [sql]

the “scale” argument of the Numeric() type is honored whencoercing a returned floating point value into a stringon its way to Decimal - this allows accuracy to functionon SQLite, MySQL.References: #1717

  • [sql]

the copy() method of Column now copies over uninitialized“on table attach” events. Helps with the new declarative“mixin” capability.

mysql

  • [mysql]

Fixed reflection bug whereby when COLLATE was present,nullable flag and server defaults would not be reflected.References: #1655

  • [mysql]

Fixed reflection of TINYINT(1) “boolean” columns defined withinteger flags like UNSIGNED.

  • [mysql]

Further fixes for the mysql-connector dialect.References: #1668

  • [mysql]

Composite PK table on InnoDB where the “autoincrement” columnisn’t first will emit an explicit “KEY” phrase withinCREATE TABLE thereby avoiding errors.References: #1496

  • [mysql]

Added reflection/create table support for a wide rangeof MySQL keywords.References: #1634

  • [mysql]

Fixed import error which could occur reflecting tables ona Windows hostReferences: #1580

sqlite

  • [sqlite]

Added “native_datetime=True” flag to create_engine().This will cause the DATE and TIMESTAMP types to skipall bind parameter and result row processing, underthe assumption that PARSE_DECLTYPES has been enabledon the connection. Note that this is not entirelycompatible with the “func.current_date()”, whichwill be returned as a string.References: #1685

mssql

  • [mssql]

Re-established support for the pymssql dialect.

  • [mssql]

Various fixes for implicit returning, reflection,etc. - the MS-SQL dialects aren’t quite completein 0.6 yet (but are close)

  • [mssql]

Added basic support for mxODBC.References: #1710

  • [mssql]

Removed the text_as_varchar option.

oracle

  • [oracle]

“out” parameters require a type that is supported bycx_oracle. An error will be raised if no cx_oracletype can be found.

  • [oracle]

Oracle ‘DATE’ now does not perform any result processing,as the DATE type in Oracle stores full date+time objects,that’s what you’ll get. Note that the generic types.Datetype will still call value.date() on incoming values,however. When reflecting a table, the reflected typewill be ‘DATE’.

  • [oracle]

Added preliminary support for Oracle’s WITH_UNICODEmode. At the very least this establishes initialsupport for cx_Oracle with Python 3. When WITH_UNICODEmode is used in Python 2.xx, a large and scary warningis emitted asking that the user seriously considerthe usage of this difficult mode of operation.References: #1670

  • [oracle]

The except_() method now renders as MINUS on Oracle,which is more or less equivalent on that platform.References: #1712

  • [oracle]

Added support for rendering and reflectingTIMESTAMP WITH TIME ZONE, i.e. TIMESTAMP(timezone=True).References: #651

  • [oracle]

Oracle INTERVAL type can now be reflected.

misc

  • [py3k]

Improved the installation/test setup regarding Python 3,now that Distribute runs on Py3k. distribute_setup.pyis now included. See README.py3k for Python 3 installation/testing instructions.

  • [engines]

Added an optional C extension to speed up the sql layer byreimplementing RowProxy and the most common result processors.The actual speedups will depend heavily on your DBAPI andthe mix of datatypes used in your tables, and can vary froma 30% improvement to more than 200%. It also provides a modest(~15-20%) indirect improvement to ORM speed for large queries.Note that it is not built/installed by default.See README for installation instructions.

  • [engines]

the execution sequence pulls all rowcount/last inserted IDinfo from the cursor before commit() is called on theDBAPI connection in an “autocommit” scenario. This helpsmxodbc with rowcount and is probably a good idea overall.

  • [engines]

Opened up logging a bit such that isEnabledFor() is calledmore often, so that changes to the log level for engine/poolwill be reflected on next connect. This adds a smallamount of method call overhead. It’s negligible and will makelife a lot easier for all those situations when loggingjust happens to be configured after create_engine() is called.References: #1719

  • [engines]

The assert_unicode flag is deprecated. SQLAlchemy will raisea warning in all cases where it is asked to encode a non-unicodePython string, as well as when a Unicode or UnicodeType typeis explicitly passed a bytestring. The String type will do nothingfor DBAPIs that already accept Python unicode objects.

  • [engines]

Bind parameters are sent as a tuple instead of a list. Somebackend drivers will not accept bind parameters as a list.

  • [engines]

threadlocal engine wasn’t properly closing the connectionupon close() - fixed that.

  • [engines]

Transaction object doesn’t rollback or commit if it isn’t“active”, allows more accurate nesting of begin/rollback/commit.

  • [engines]

Python unicode objects as binds result in the Unicode type,not string, thus eliminating a certain class of unicode errorson drivers that don’t support unicode binds.

  • [engines]

Added “logging_name” argument to create_engine(), Pool() constructoras well as “pool_logging_name” argument to create_engine() whichfilters down to that of Pool. Issues the given string namewithin the “name” field of logging messages instead of the defaulthex identifier string.References: #1555

  • [engines]

The visit_pool() method of Dialect is removed, and replaced withon_connect(). This method returns a callable which receivesthe raw DBAPI connection after each one is created. The callableis assembled into a first_connect/connect pool listener by theconnection strategy if non-None. Provides a simpler interfacefor dialects.

  • [engines]

StaticPool now initializes, disposes and recreates withoutopening a new connection - the connection is only opened whenfirst requested. dispose() also works on AssertionPool now.References: #1728

  • [metadata] [ticket: 1673]

Added the ability to strip schema information when using“tometadata” by passing “schema=None” as an argument. If schemais not specified then the table’s schema is retained.

  • [declarative]

DeclarativeMeta exclusively uses cls.dict (not dict)as the source of class information; _as_declarative exclusivelyuses the dict passed to it as the source of class information(which when using DeclarativeMeta is cls.dict). This shouldin theory make it easier for custom metaclasses to modifythe state passed into _as_declarative.

  • [declarative]

declarative now accepts mixin classes directly, as a meansto provide common functional and column-based elements onall subclasses, as well as a means to propagate a fixedset of table_args or mapper_args to subclasses.For custom combinations of table_args/mapper_args froman inherited mixin to local, descriptors can now be used.New details are all up in the Declarative documentation.Thanks to Chris Withers for putting up with my strifeon this.References: #1707

  • [declarative]

the mapper_args dict is copied when propagating to a subclass,and is taken straight off the class dict to avoid anypropagation from the parent. mapper inheritance alreadypropagates the things you want from the parent mapper.References: #1393

  • [declarative]

An exception is raised when a single-table subclass specifiesa column that is already present on the base class.References: #1732

  • [sybase]

Implemented a preliminary working dialect for Sybase,with sub-implementations for Python-Sybase as wellas Pyodbc. Handles tablecreates/drops and basic round trip functionality.Does not yet include reflection or comprehensivesupport of unicode/special expressions/etc.

  • [examples]

Changed the beaker cache example a bit to have a separateRelationCache option for lazyload caching. This objectdoes a lookup among any number of potential attributesmore efficiently by grouping several into a common structure.Both FromCache and RelationCache are simpler individually.

  • [documentation]

Major cleanup work in the docs to link class, function, andmethod names into the API docs.References: #1700

0.6beta1

Released: Wed Feb 03 2010

orm

  • [orm]

    • Changes to query.update() and query.delete():
      • the ‘expire’ option on query.update() has been renamed to‘fetch’, thus matching that of query.delete().‘expire’ is deprecated and issues a warning.

      • query.update() and query.delete() both default to‘evaluate’ for the synchronize strategy.

      • the ‘synchronize’ strategy for update() and delete()raises an error on failure. There is no implicit fallbackonto “fetch”. Failure of evaluation is based on thestructure of criteria, so success/failure is deterministicbased on code structure.

  • [orm]

    • Enhancements on many-to-one relations:
      • many-to-one relations now fire off a lazyload in fewercases, including in most cases will not fetch the “old”value when a new one is replaced.

      • many-to-one relation to a joined-table subclass now usesget() for a simple load (known as the “use_get”condition), i.e. Related->Sub(Base), without the need toredefine the primaryjoin condition in terms of the basetable.

      • specifying a foreign key with a declarative column, i.e.ForeignKey(MyRelatedClass.id) doesn’t break the “use_get”condition from taking place

      • relation(), eagerload(), and eagerloadall() now featurean option called “innerjoin”. Specify _True or False tocontrol whether an eager join is constructed as an INNERor OUTER join. Default is False as always. The mapperoptions will override whichever setting is specified onrelation(). Should generally be set for many-to-one, notnullable foreign key relations to allow improved joinperformance.

      • the behavior of eagerloading such that the main query iswrapped in a subquery when LIMIT/OFFSET are present nowmakes an exception for the case when all eager loads aremany-to-one joins. In those cases, the eager joins areagainst the parent table directly along with thelimit/offset without the extra overhead of a subquery,since a many-to-one join does not add rows to the result.References: #1186, #1492, #1544

  • [orm]

Enhancements / Changes on Session.merge():

  • [orm]

the “dont_load=True” flag on Session.merge() is deprecatedand is now “load=False”.

  • [orm]

Session.merge() is performance optimized, using half thecall counts for “load=False” mode compared to 0.5 andsignificantly fewer SQL queries in the case of collectionsfor “load=True” mode.

  • [orm]

merge() will not issue a needless merge of attributes if thegiven instance is the same instance which is already present.

  • [orm]

merge() now also merges the “options” associated with a givenstate, i.e. those passed through query.options() which followalong with an instance, such as options to eagerly- orlazyily- load various attributes. This is essential forthe construction of highly integrated caching schemes. Thisis a subtle behavioral change vs. 0.5.

  • [orm]

A bug was fixed regarding the serialization of the “loaderpath” present on an instance’s state, which is also necessarywhen combining the usage of merge() with serialized stateand associated options that should be preserved.

  • [orm]

The all new merge() is showcased in a new comprehensiveexample of how to integrate Beaker with SQLAlchemy. Seethe notes in the “examples” note below.

  • [orm]

Primary key values can now be changed on a joined-table inheritanceobject, and ON UPDATE CASCADE will be taken into account whenthe flush happens. Set the new “passive_updates” flag to Falseon mapper() when using SQLite or MySQL/MyISAM.References: #1362

  • [orm]

flush() now detects when a primary key column was updated byan ON UPDATE CASCADE operation from another primary key, andcan then locate the row for a subsequent UPDATE on the new PKvalue. This occurs when a relation() is there to establishthe relationship as well as passive_updates=True.References: #1671

  • [orm]

the “save-update” cascade will now cascade the pending _removed_values from a scalar or collection attribute into the new sessionduring an add() operation. This so that the flush() operationwill also delete or modify rows of those disconnected items.

  • [orm]

Using a “dynamic” loader with a “secondary” table now producesa query where the “secondary” table is not aliased. Thisallows the secondary Table object to be used in the “order_by”attribute of the relation(), and also allows it to be usedin filter criterion against the dynamic relation.References: #1531

  • [orm]

relation() with uselist=False will emit a warning whenan eager or lazy load locates more than one valid value forthe row. This may be due to primaryjoin/secondaryjoinconditions which aren’t appropriate for an eager LEFT OUTERJOIN or for other conditions.References: #1643

  • [orm]

an explicit check occurs when a synonym() is used withmap_column=True, when a ColumnProperty (deferred or otherwise)exists separately in the properties dictionary sent to mapperwith the same keyname. Instead of silently replacingthe existing property (and possible options on that property),an error is raised.References: #1633

  • [orm]

a “dynamic” loader sets up its query criterion at constructiontime so that the actual query is returned from non-cloningaccessors like “statement”.

  • [orm]

the “named tuple” objects returned when iterating aQuery() are now pickleable.

  • [orm]

mapping to a select() construct now requires that youmake an alias() out of it distinctly. This to eliminateconfusion over such issues asReferences: #1542

  • [orm]

query.join() has been reworked to provide more consistentbehavior and more flexibility (includes)References: #1537

  • [orm]

query.select_from() accepts multiple clauses to producemultiple comma separated entries within the FROM clause.Useful when selecting from multiple-homed join() clauses.

  • [orm]

query.select_from() also accepts mapped classes, aliased()constructs, and mappers as arguments. In particular thishelps when querying from multiple joined-table classes to ensurethe full join gets rendered.

  • [orm]

query.get() can be used with a mapping to an outer joinwhere one or more of the primary key values are None.References: #1135

  • [orm]

query.from_self(), query.union(), others which do a“SELECT * from (SELECT…)” type of nesting will doa better job translating column expressions within the subqueryto the columns clause of the outer query. This ispotentially backwards incompatible with 0.5, in that thismay break queries with literal expressions that do not have labelsapplied (i.e. literal(‘foo’), etc.)References: #1568

  • [orm]

relation primaryjoin and secondaryjoin now check that theyare column-expressions, not just clause elements. this prohibitsthings like FROM expressions being placed there directly.References: #1622

  • [orm]

expression.null() is fully understood the same wayNone is when comparing an object/collection-referencingattribute within query.filter(), filter_by(), etc.References: #1415

  • [orm]

added “make_transient()” helper function which transforms apersistent/ detached instance into a transient one (i.e.deletes the instance_key and removes from any session.)References: #1052

  • [orm]

the allow_null_pks flag on mapper() is deprecated, andthe feature is turned “on” by default. This means thata row which has a non-null value for any of its primary keycolumns will be considered an identity. The need for thisscenario typically only occurs when mapping to an outer join.References: #1339

  • [orm]

the mechanics of “backref” have been fully merged into thefiner grained “back_populates” system, and take place entirelywithin the _generate_backref() method of RelationProperty. Thismakes the initialization procedure of RelationPropertysimpler and allows easier propagation of settings (such as fromsubclasses of RelationProperty) into the reverse reference.The internal BackRef() is gone and backref() returns a plaintuple that is understood by RelationProperty.

  • [orm]

The version_id_col feature on mapper() will raise a warning whenused with dialects that don’t support “rowcount” adequately.References: #1569

  • [orm]

added “execution_options()” to Query, to so options can bepassed to the resulting statement. Currently onlySelect-statements have these options, and the only optionused is “stream_results”, and the only dialect which knows“stream_results” is psycopg2.

  • [orm]

Query.yield_per() will set the “stream_results” statementoption automatically.

  • [orm]

    • Deprecated or removed:
      • ’allow_null_pks’ flag on mapper() is deprecated. It doesnothing now and the setting is “on” in all cases.

      • ’transactional’ flag on sessionmaker() and others isremoved. Use ‘autocommit=True’ to indicate ‘transactional=False’.

      • ’polymorphic_fetch’ argument on mapper() is removed.Loading can be controlled using the ‘with_polymorphic’option.

      • ’select_table’ argument on mapper() is removed. Use‘with_polymorphic=(“*”, )’ for thisfunctionality.

      • ’proxy’ argument on synonym() is removed. This flagdid nothing throughout 0.5, as the “proxy generation”behavior is now automatic.

      • Passing a single list of elements to eagerload(),eagerload_all(), contains_eager(), lazyload(),defer(), and undefer() instead of multiple positional*args is deprecated.

      • Passing a single list of elements to query.order_by(),query.group_by(), query.join(), or query.outerjoin()instead of multiple positional *args is deprecated.

      • query.iterate_instances() is removed. Use query.instances().

      • Query.query_from_parent() is removed. Use thesqlalchemy.orm.with_parent() function to produce a“parent” clause, or alternatively query.with_parent().

      • query._from_self() is removed, use query.from_self()instead.

      • the “comparator” argument to composite() is removed.Use “comparator_factory”.

      • RelationProperty._get_join() is removed.

      • the ‘echo_uow’ flag on Session is removed. Uselogging on the “sqlalchemy.orm.unitofwork” name.

      • session.clear() is removed. use session.expunge_all().

      • session.save(), session.update(), session.save_or_update()are removed. Use session.add() and session.add_all().

      • the “objects” flag on session.flush() remains deprecated.

      • the “dont_load=True” flag on session.merge() is deprecatedin favor of “load=False”.

      • ScopedSession.mapper remains deprecated. See theusage recipe athttp://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionAwareMapper

      • passing an InstanceState (internal SQLAlchemy state object) toattributes.init_collection() or attributes.get_history() isdeprecated. These functions are public API and normallyexpect a regular mapped object instance.

      • the ‘engine’ parameter to declarative_base() is removed.Use the ‘bind’ keyword argument.

sql

  • [sql]

the “autocommit” flag on select() and text() as wellas select().autocommit() are deprecated - now call.execution_options(autocommit=True) on either of thoseconstructs, also available directly on Connection and orm.Query.

  • [sql]

the autoincrement flag on column now indicates the columnwhich should be linked to cursor.lastrowid, if that methodis used. See the API docs for details.

  • [sql]

an executemany() now requires that all bound parametersets require that all keys are present which arepresent in the first bound parameter set. The structureand behavior of an insert/update statement is very muchdetermined by the first parameter set, including whichdefaults are going to fire off, and a minimum ofguesswork is performed with all the rest so that performanceis not impacted. For this reason defaults would otherwisesilently “fail” for missing parameters, so this is now guardedagainst.References: #1566

  • [sql]

returning() support is native to insert(), update(),delete(). Implementations of varying levels offunctionality exist for PostgreSQL, Firebird, MSSQL andOracle. returning() can be called explicitly with columnexpressions which are then returned in the resultset,usually via fetchone() or first().

insert() constructs will also use RETURNING implicitly toget newly generated primary key values, if the databaseversion in use supports it (a version number check isperformed). This occurs if no end-user returning() wasspecified.

  • [sql]

union(), intersect(), except() and other “compound” typesof statements have more consistent behavior w.r.t.parenthesizing. Each compound element embedded withinanother will now be grouped with parenthesis - previously,the first compound element in the list would not be grouped,as SQLite doesn’t like a statement to start withparenthesis. However, PostgreSQL in particular hasprecedence rules regarding INTERSECT, and it ismore consistent for parenthesis to be applied equallyto all sub-elements. So now, the workaround for SQLiteis also what the workaround for PG was previously -when nesting compound elements, the first one usually needs“.alias().select()” called on it to wrap it insideof a subquery.References: #1665

  • [sql]

insert() and update() constructs can now embed bindparam()objects using names that match the keys of columns. Thesebind parameters will circumvent the usual route to thosekeys showing up in the VALUES or SET clause of the generatedSQL.References: #1579

  • [sql]

the Binary type now returns data as a Python string(or a “bytes” type in Python 3), instead of the built-in “buffer” type. This allows symmetric round tripsof binary data.References: #1524

  • [sql]

Added a tuple_() construct, allows sets of expressionsto be compared to another set, typically with IN againstcomposite primary keys or similar. Also accepts anIN with multiple columns. The “scalar select canhave only one column” error message is removed - willrely upon the database to report problems withcol mismatch.

  • [sql]

User-defined “default” and “onupdate” callables whichaccept a context should now call upon“context.current_parameters” to get at the dictionaryof bind parameters currently being processed. Thisdict is available in the same way regardless ofsingle-execute or executemany-style statement execution.

  • [sql]

multi-part schema names, i.e. with dots such as“dbo.master”, are now rendered in select() labelswith underscores for dots, i.e. “dbo_master_table_column”.This is a “friendly” label that behaves betterin result sets.References: #1428

  • [sql]

removed needless “counter” behavior with select()labelnames that match a column name in the table,i.e. generates “tablename_id” for “id”, instead of“tablename_id_1” in an attempt to avoid namingconflicts, when the table has a column actuallynamed “tablename_id” - this is becausethe labeling logic is always applied to all columnsso a naming conflict will never occur.

  • [sql]

calling expr.in([]), i.e. with an empty list, emits a warningbefore issuing the usual “expr != expr” clause. The“expr != expr” can be very expensive, and it’s preferredthat the user not issue in() if the list is empty,instead simply not querying, or modifying the criterionas appropriate for more complex situations.References: #1628

  • [sql]

Added “execution_options()” to select()/text(), which set thedefault options for the Connection. See the note in “engines”.

  • [sql]

    • Deprecated or removed:
      • ”scalar” flag on select() is removed, useselect.as_scalar().

      • ”shortname” attribute on bindparam() is removed.

      • postgres_returning, firebird_returning flags oninsert(), update(), delete() are deprecated, usethe new returning() method.

      • fold_equivalents flag on join is deprecated (will remainuntil is implemented)References: #1131

schema

  • [schema]

the _contains() method of _MetaData now acceptsstrings or Table objects as arguments. If givena Table, the argument is converted to table.key first,i.e. “[schemaname.]References: #1541

  • [schema]

deprecated MetaData.connect() andThreadLocalMetaData.connect() have been removed - sendthe “bind” attribute to bind a metadata.

  • [schema]

deprecated metadata.table_iterator() method removed (usesorted_tables)

  • [schema]

deprecated PassiveDefault - use DefaultClause.

  • [schema]

the “metadata” argument is removed from DefaultGeneratorand subclasses, but remains locally present on Sequence,which is a standalone construct in DDL.

  • [schema]

Removed public mutability from Index and Constraintobjects:

  • ForeignKeyConstraint.append_element()

  • Index.append_column()

  • UniqueConstraint.append_column()

  • PrimaryKeyConstraint.add()

  • PrimaryKeyConstraint.remove()

These should be constructed declaratively (i.e. in oneconstruction).

  • [schema]

The “start” and “increment” attributes on Sequence nowgenerate “START WITH” and “INCREMENT BY” by default,on Oracle and PostgreSQL. Firebird doesn’t supportthese keywords right now.References: #1545

  • [schema]

UniqueConstraint, Index, PrimaryKeyConstraint all acceptlists of column names or column objects as arguments.

  • [schema]

    • Other removed things:
      • Table.key (no idea what this was for)

      • Table.primary_key is not assignable - usetable.append_constraint(PrimaryKeyConstraint(…))

      • Column.bind (get via column.table.bind)

      • Column.metadata (get via column.table.metadata)

      • Column.sequence (use column.default)

      • ForeignKey(constraint=some_parent) (is now private _constraint)

  • [schema]

The usealter flag on ForeignKey is now a shortcut optionfor operations that can be hand-constructed using theDDL() event system. A side effect of this refactor isthat ForeignKeyConstraint objects with use_alter=Truewill _not be emitted on SQLite, which does not supportALTER for foreign keys.

  • [schema]

ForeignKey and ForeignKeyConstraint objects now correctlycopy() all their public keyword arguments.References: #1605

postgresql

  • [postgresql]

New dialects: pg8000, zxjdbc, and pypostgresqlon py3k.

  • [postgresql]

The “postgres” dialect is now named “postgresql” !Connection strings look like:

postgresql://scott:tiger@localhost/testpostgresql+pg8000://scott:tiger@localhost/test

The “postgres” name remains for backwards compatibilityin the following ways:

  • There is a “postgres.py” dummy dialect whichallows old URLs to work, i.e.postgres://scott:tiger@localhost/test

  • The “postgres” name can be imported from the old“databases” module, i.e. “fromsqlalchemy.databases import postgres” as well as“dialects”, “from sqlalchemy.dialects.postgresimport base as pg”, will send a deprecationwarning.

  • Special expression arguments are now named“postgresql_returning” and “postgresql_where”, butthe older “postgres_returning” and“postgres_where” names still work with adeprecation warning.

  • [postgresql]

“postgresql_where” now accepts SQL expressions whichcan also include literals, which will be quoted as needed.

  • [postgresql]

The psycopg2 dialect now uses psycopg2’s “unicode extension”on all new connections, which allows all String/Text/etc.types to skip the need to post-process bytestrings intounicode (an expensive step due to its volume). Otherdialects which return unicode natively (pg8000, zxjdbc)also skip unicode post-processing.

  • [postgresql]

Added new ENUM type, which exists as a schema-levelconstruct and extends the generic Enum type. Automaticallyassociates itself with tables and their parent metadatato issue the appropriate CREATE TYPE/DROP TYPEcommands as needed, supports unicode labels, supportsreflection.References: #1511

  • [postgresql]

INTERVAL supports an optional “precision” argumentcorresponding to the argument that PG accepts.

  • [postgresql]

using new dialect.initialize() feature to set upversion-dependent behavior.

  • [postgresql]

somewhat better support for % signs in table/column names;psycopg2 can’t handle a bind parameter name of%(foobar)s however and SQLA doesn’t want to add overheadjust to treat that one non-existent use case.References: #1279

  • [postgresql]

Inserting NULL into a primary key + foreign key columnwill allow the “not null constraint” error to raise,not an attempt to execute a nonexistent “col_id_seq”sequence.References: #1516

  • [postgresql]

autoincrement SELECT statements, i.e. those whichselect from a procedure that modifies rows, now workwith server-side cursor mode (the named cursor isn’tused for such statements.)

  • [postgresql]

postgresql dialect can properly detect pg “devel” versionstrings, i.e. “8.5devel”References: #1636

  • [postgresql]

The psycopg2 now respects the statement option“stream_results”. This option overrides the connection setting“server_side_cursors”. If true, server side cursors will beused for the statement. If false, they will not be used, evenif “server_side_cursors” is true on theconnection.References: #1619

mysql

  • [mysql]

New dialects: oursql, a new native dialect,MySQL Connector/Python, a native Python port of MySQLdb,and of course zxjdbc on Jython.

  • [mysql]

VARCHAR/NVARCHAR will not render without a length, raisesan error before passing to MySQL. Doesn’t impactCAST since VARCHAR is not allowed in MySQL CAST anyway,the dialect renders CHAR/NCHAR in those cases.

  • [mysql]

all the _detect_XXX() functions now run once underneathdialect.initialize()

  • [mysql]

somewhat better support for % signs in table/column names;MySQLdb can’t handle % signs in SQL when executemany() is used,and SQLA doesn’t want to add overhead just to treat that onenon-existent use case.References: #1279

  • [mysql]

the BINARY and MSBinary types now generate “BINARY” in allcases. Omitting the “length” parameter will generate“BINARY” with no length. Use BLOB to generate an unlengthedbinary column.

  • [mysql]

the “quoting=’quoted’” argument to MSEnum/ENUM is deprecated.It’s best to rely upon the automatic quoting.

  • [mysql]

ENUM now subclasses the new generic Enum type, and also handlesunicode values implicitly, if the given labelnames are unicodeobjects.

  • [mysql]

a column of type TIMESTAMP now defaults to NULL if“nullable=False” is not passed to Column(), and no defaultis present. This is now consistent with all other types,and in the case of TIMESTAMP explicitly renders “NULL”due to MySQL’s “switching” of default nullabilityfor TIMESTAMP columns.References: #1539

sqlite

  • [sqlite]

DATE, TIME and DATETIME types can now take optional storage_formatand regexp argument. storage_format can be used to store those typesusing a custom string format. regexp allows to use a custom regularexpression to match string values from the database.

  • [sqlite]

Time and DateTime types now use by a default a stricter regularexpression to match strings from the database. Use the regexpargument if you are using data stored in a legacy format.

  • [sqlite]

legacy_microseconds on SQLite Time and DateTime types is notsupported anymore. You should use the storage_format argumentinstead.

  • [sqlite]

Date, Time and DateTime types are now stricter in what they accept asbind parameters: Date type only accepts date objects (and datetimeones, because they inherit from date), Time only accepts timeobjects, and DateTime only accepts date and datetime objects.

  • [sqlite]

Table() supports a keyword argument “sqlite_autoincrement”, whichapplies the SQLite keyword “AUTOINCREMENT” to the single integerprimary key column when generating DDL. Will prevent generation ofa separate PRIMARY KEY constraint.References: #1016

mssql

  • [mssql]

MSSQL + Pyodbc + FreeTDS now works for the most part,with possible exceptions regarding binary data as well asunicode schema identifiers.

  • [mssql]

the “has_window_funcs” flag is removed. LIMIT/OFFSETusage will use ROW NUMBER as always, and if on an olderversion of SQL Server, the operation fails. The behavioris exactly the same except the error is raised by SQLserver instead of the dialect, and no flag setting isrequired to enable it.

  • [mssql]

the “auto_identity_insert” flag is removed. This featurealways takes effect when an INSERT statement overrides acolumn that is known to have a sequence on it. As with“has_window_funcs”, if the underlying driver doesn’tsupport this, then you can’t do this operation in anycase, so there’s no point in having a flag.

  • [mssql]

using new dialect.initialize() feature to set upversion-dependent behavior.

  • [mssql]

removed references to sequence which is no longer used.implicit identities in mssql work the same as implicitsequences on any other dialects. Explicit sequences areenabled through the use of “default=Sequence()”. Seethe MSSQL dialect documentation for more information.

oracle

  • [oracle]

unit tests pass 100% with cx_oracle !

  • [oracle]

support for cx_Oracle’s “native unicode” mode which doesnot require NLS_LANG to be set. Use the latest 5.0.2 orlater of cx_oracle.

  • [oracle]

an NCLOB type is added to the base types.

  • [oracle]

use_ansi=False won’t leak into the FROM/WHERE clause ofa statement that’s selecting from a subquery that alsouses JOIN/OUTERJOIN.

  • [oracle]

added native INTERVAL type to the dialect. This supportsonly the DAY TO SECOND interval type so far due to lackof support in cx_oracle for YEAR TO MONTH.References: #1467

  • [oracle]

usage of the CHAR type results in cx_oracle’sFIXED_CHAR dbapi type being bound to statements.

  • [oracle]

the Oracle dialect now features NUMBER which intendsto act justlike Oracle’s NUMBER type. It is the primarynumeric type returned by table reflection and attemptsto return Decimal()/float/int based on the precision/scaleparameters.References: #885

  • [oracle]

func.char_length is a generic function for LENGTH

  • [oracle]

ForeignKey() which includes onupdate= will emit awarning, not emit ON UPDATE CASCADE which is unsupportedby oracle

  • [oracle]

the keys() method of RowProxy() now returns the resultcolumn names normalized to be SQLAlchemy caseinsensitive names. This means they will be lower case forcase insensitive names, whereas the DBAPI would normallyreturn them as UPPERCASE names. This allows row keys() tobe compatible with further SQLAlchemy operations.

  • [oracle]

using new dialect.initialize() feature to set upversion-dependent behavior.

  • [oracle]

using types.BigInteger with Oracle will generateNUMBER(19)References: #1125

  • [oracle]

“case sensitivity” feature will detect an all-lowercasecase-sensitive column name during reflect and add“quote=True” to the generated Column, so that properquoting is maintained.

firebird

  • [firebird]

the keys() method of RowProxy() now returns the resultcolumn names normalized to be SQLAlchemy caseinsensitive names. This means they will be lower case forcase insensitive names, whereas the DBAPI would normallyreturn them as UPPERCASE names. This allows row keys() tobe compatible with further SQLAlchemy operations.

  • [firebird]

using new dialect.initialize() feature to set upversion-dependent behavior.

  • [firebird]

“case sensitivity” feature will detect an all-lowercasecase-sensitive column name during reflect and add“quote=True” to the generated Column, so that properquoting is maintained.

misc

  • [major] [release]

For the full set of feature descriptions, seehttp://docs.sqlalchemy.org/en/latest/changelog/migration_06.html .This document is a work in progress.

  • [major] [release]

All bug fixes and feature enhancements from the mostrecent 0.5 version and below are also included within 0.6.

  • [major] [release]

Platforms targeted now include Python 2.4/2.5/2.6, Python3.1, Jython2.5.

  • [engines]

transaction isolation level may be specified withcreate_engine(… isolation_level=”…”); available onpostgresql and sqlite.References: #443

  • [engines]

Connection has execution_options(), generative methodwhich accepts keywords that affect how the statementis executed w.r.t. the DBAPI. Currently supports“stream_results”, causes psycopg2 to use a serverside cursor for that statement, as well as“autocommit”, which is the new location for the “autocommit”option from select() and text(). select() andtext() also have .execution_options() as well asORM Query().

  • [engines]

fixed the import for entrypoint-driven dialects tonot rely upon silly tb_info trick to determine importerror status.References: #1630

  • [engines]

added first() method to ResultProxy, returns first row andcloses result set immediately.

  • [engines]

RowProxy objects are now pickleable, i.e. the object returnedby result.fetchone(), result.fetchall() etc.

  • [engines]

RowProxy no longer has a close() method, as the row no longermaintains a reference to the parent. Call close() onthe parent ResultProxy instead, or use autoclose.

  • [engines]

ResultProxy internals have been overhauled to greatly reducemethod call counts when fetching columns. Can provide a largespeed improvement (up to more than 100%) when fetching largeresult sets. The improvement is larger when fetching columnsthat have no type-level processing applied and when usingresults as tuples (instead of as dictionaries). Manythanks to Elixir’s Gaëtan de Menten for this dramaticimprovement !References: #1586

  • [engines]

Databases which rely upon postfetch of “last inserted id”to get at a generated sequence value (i.e. MySQL, MS-SQL)now work correctly when there is a composite primary keywhere the “autoincrement” column is not the first primarykey column in the table.

  • [engines]

the last_inserted_ids() method has been renamed to thedescriptor “inserted_primary_key”.

  • [engines]

setting echo=False on createengine() now sets the loglevelto WARN instead of NOTSET. This so that logging can bedisabled for a particular engine even if loggingfor “sqlalchemy.engine” is enabled overall. Note that thedefault setting of “echo” is _None.References: #1554

  • [engines]

ConnectionProxy now has wrapper methods for all transactionlifecycle events, including begin(), rollback(), commit()begin_nested(), begin_prepared(), prepare(), release_savepoint(),etc.

  • [engines]

Connection pool logging now uses both INFO and DEBUGlog levels for logging. INFO is for major events suchas invalidated connections, DEBUG for all the acquire/returnlogging. echo_pool can be False, None, True or “debug”the same way as echo works.

  • [engines]

All pyodbc-dialects now support extra pyodbc-specifickw arguments ‘ansi’, ‘unicode_results’, ‘autocommit’.References: #1621

  • [engines]

the “threadlocal” engine has been rewritten and simplifiedand now supports SAVEPOINT operations.

  • [engines]

    • deprecated or removed
      • result.last_inserted_ids() is deprecated. Useresult.inserted_primary_key

      • dialect.get_default_schema_name(connection) is nowpublic via dialect.default_schema_name.

      • the “connection” argument from engine.transaction() andengine.run_callable() is removed - Connection itselfnow has those methods. All four methods acceptargs and *kwargs which are passed to the given callable,as well as the operating connection.

  • [reflection/inspection]

Table reflection has been expanded and generalized intoa new API called “sqlalchemy.engine.reflection.Inspector”.The Inspector object provides fine-grained information abouta wide variety of schema information, with room for expansion,including table names, column names, view definitions, sequences,indexes, etc.

  • [reflection/inspection]

Views are now reflectable as ordinary Table objects. The sameTable constructor is used, with the caveat that “effective”primary and foreign key constraints aren’t part of the reflectionresults; these have to be specified explicitly if desired.

  • [reflection/inspection]

The existing autoload=True system now uses Inspector underneathso that each dialect need only return “raw” data about tablesand other objects - Inspector is the single place that informationis compiled into Table objects so that consistency is at a maximum.

  • [ddl]

the DDL system has been greatly expanded. the DDL() classnow extends the more generic DDLElement(), which forms the basisof many new constructs:

  • CreateTable()

  • DropTable()

  • AddConstraint()

  • DropConstraint()

  • CreateIndex()

  • DropIndex()

  • CreateSequence()

  • DropSequence()

These support “on” and “execute-at()” just like plain DDL()does. User-defined DDLElement subclasses can be created andlinked to a compiler using the sqlalchemy.ext.compiler extension.

  • [ddl]

The signature of the “on” callable passed to DDL() andDDLElement() is revised as follows:

ddl

the DDLElement object itself

event

the string event name.

target

previously “schema_item”, the Table or MetaData object triggering the event.

connection

the Connection object in use for the operation.

**kw

keyword arguments. In the case of MetaData before/aftercreate/drop, the list of Table objects for whichCREATE/DROP DDL is to be issued is passed as the kwargument “tables”. This is necessary for metadata-levelDDL that is dependent on the presence of specific tables.

  • The “schema_item” attribute of DDL has been renamed to
  • ”target”.
  • [dialect] [refactor]

Dialect modules are now broken into database dialectsplus DBAPI implementations. Connect URLs are nowpreferred to be specified using dialect+driver://…,i.e. “mysql+mysqldb://scott:tiger@localhost/test”. Seethe 0.6 documentation for examples.

  • [dialect] [refactor]

the setuptools entrypoint for external dialects is nowcalled “sqlalchemy.dialects”.

  • [dialect] [refactor]

the “owner” keyword argument is removed from Table. Use“schema” to represent any namespaces to be prepended tothe table name.

  • [dialect] [refactor]

server_version_info becomes a static attribute.

  • [dialect] [refactor]

dialects receive an initialize() event on initialconnection to determine connection properties.

  • [dialect] [refactor]

dialects receive a visit_pool event have an opportunityto establish pool listeners.

  • [dialect] [refactor]

cached TypeEngine classes are cached per-dialect classinstead of per-dialect.

  • [dialect] [refactor]

new UserDefinedType should be used as a base class fornew types, which preserves the 0.5 behavior ofget_col_spec().

  • [dialect] [refactor]

The result_processor() method of all type classes nowaccepts a second argument “coltype”, which is the DBAPItype argument from cursor.description. This argumentcan help some types decide on the most efficient processingof result values.

  • [dialect] [refactor]

Deprecated Dialect.get_params() removed.

  • [dialect] [refactor]

Dialect.get_rowcount() has been renamed to a descriptor“rowcount”, and calls cursor.rowcount directly. Dialectswhich need to hardwire a rowcount in for certain callsshould override the method to provide different behavior.

  • [dialect] [refactor]

DefaultRunner and subclasses have been removed. The jobof this object has been simplified and moved intoExecutionContext. Dialects which support sequences shouldadd a fire_sequence() method to their execution contextimplementation.References: #1566

  • [dialect] [refactor]

Functions and operators generated by the compiler now use(almost) regular dispatch functions of the form“visit” and “visit_fn” to providecustomed processing. This replaces the need to copy the“functions” and “operators” dictionaries in compilersubclasses with straightforward visitor methods, and alsoallows compiler subclasses complete control overrendering, as the full _Function or _BinaryExpressionobject is passed in.

  • [types]

The construction of types within dialects has been totallyoverhauled. Dialects now define publicly available typesas UPPERCASE names exclusively, and internal implementationtypes using underscore identifiers (i.e. are private).The system by which types are expressed in SQL and DDLhas been moved to the compiler system. This has theeffect that there are much fewer type objects withinmost dialects. A detailed document on this architecturefor dialect authors is inlib/sqlalchemy/dialects/type_migration_guidelines.txt .

  • [types]

Types no longer make any guesses as to defaultparameters. In particular, Numeric, Float, NUMERIC,FLOAT, DECIMAL don’t generate any length or scale unlessspecified.

  • [types]

types.Binary is renamed to types.LargeBinary, it onlyproduces BLOB, BYTEA, or a similar “long binary” type.New base BINARY and VARBINARYtypes have been added to access these MySQL/MS-SQL specifictypes in an agnostic way.References: #1664

  • [types]

String/Text/Unicode types now skip the unicode() checkon each result column value if the dialect hasdetected the DBAPI as returning Python unicode objectsnatively. This check is issued on first connectusing “SELECT CAST ‘some text’ AS VARCHAR(10)” orequivalent, then checking if the returned objectis a Python unicode. This allows vast performanceincreases for native-unicode DBAPIs, includingpysqlite/sqlite3, psycopg2, and pg8000.

  • [types]

Most types result processors have been checked for possible speedimprovements. Specifically, the following generic types have beenoptimized, resulting in varying speed improvements:Unicode, PickleType, Interval, TypeDecorator, Binary.Also the following dbapi-specific implementations have been improved:Time, Date and DateTime on Sqlite, ARRAY on PostgreSQL,Time on MySQL, Numeric(as_decimal=False) on MySQL, oursql andpypostgresql, DateTime on cx_oracle and LOB-based types on cx_oracle.

  • [types]

Reflection of types now returns the exact UPPERCASEtype within types.py, or the UPPERCASE type withinthe dialect itself if the type is not a standard SQLtype. This means reflection now returns more accurateinformation about reflected types.

  • [types]

Added a new Enum generic type. Enum is a schema-aware objectto support databases which require specific DDL in order touse enum or equivalent; in the case of PG it handles thedetails of CREATE TYPE, and on other databases withoutnative enum support will by generate VARCHAR + an inline CHECKconstraint to enforce the enum.References: #1109, #1511

  • [types]

The Interval type includes a “native” flag which controlsif native INTERVAL types (postgresql + oracle) are selectedif available, or not. “day_precision” and “second_precision”arguments are also added which propagate as appropriatelyto these native types. Related to.References: #1467

  • [types]

The Boolean type, when used on a backend that doesn’thave native boolean support, will generate a CHECKconstraint “col IN (0, 1)” along with the int/smallint-based column type. This can be switched off ifdesired with createconstraint=False.Note that MySQL has no native boolean _or CHECK constraintsupport so this feature isn’t available on that platform.References: #1589

  • [types]

PickleType now uses == for comparison of values whenmutable=True, unless the “comparator” argument with acomparison function is specified to the type. Objectsbeing pickled will be compared based on identity (whichdefeats the purpose of mutable=True) if eq() is notoverridden or a comparison function is not provided.

  • [types]

The default “precision” and “scale” arguments of Numericand Float have been removed and now default to None.NUMERIC and FLOAT will be rendered with no numericarguments by default unless these values are provided.

  • [types]

AbstractType.get_search_list() is removed - the gamesthat was used for are no longer necessary.

  • [types]

Added a generic BigInteger type, compiles toBIGINT or NUMBER(19).References: #1125

  • [types]

sqlsoup has been overhauled to explicitly support an 0.5 stylesession, using autocommit=False, autoflush=True. Defaultbehavior of SQLSoup now requires the usual usage of commit()and rollback(), which have been added to its interface. Anexplicit Session or scoped_session can be passed to theconstructor, allowing these arguments to be overridden.

  • [types]

sqlsoup db..update() and delete() now callquery(cls).update() and delete(), respectively.

  • [types]

sqlsoup now has execute() and connection(), which call uponthe Session methods of those names, ensuring that the bind isin terms of the SqlSoup object’s bind.

  • [types]

sqlsoup objects no longer have the ‘query’ attribute - it’snot needed for sqlsoup’s usage paradigm and it gets in theway of a column that is actually named ‘query’.

  • [types]

The signature of the proxy_factory callable passed toassociation_proxy is now (lazy_collection, creator,value_attr, association_proxy), adding a fourth argumentthat is the parent AssociationProxy argument. Allowsserializability and subclassing of the built in collections.References: #1259

  • [types]

association_proxy now has basic comparator methods .any(),.has(), .contains(), ==, !=, thanks to Scott Torborg.References: #1372