-from sqlalchemy import Column, ForeignKey, Integer, String, create_engine
-from sqlalchemy.orm import Session, relationship, backref, joinedload_all
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.orm.collections import attribute_mapped_collection
from datetime import datetime
-from sqlalchemy import (
- create_engine,
- Column,
- Integer,
- String,
- DateTime,
- Float,
- ForeignKey,
- and_,
-)
-from sqlalchemy.orm import relationship, Session
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import DateTime
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
Base = declarative_base()
"""
-from sqlalchemy import String, Integer, Column, create_engine, ForeignKey
-from sqlalchemy.orm import relationship, Session
-from sqlalchemy.orm.collections import MappedCollection
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.ext.associationproxy import association_proxy
import operator
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.associationproxy import association_proxy
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm.collections import MappedCollection
+
class Base(object):
id = Column(Integer, primary_key=True)
from datetime import datetime
-from sqlalchemy import (
- create_engine,
- Column,
- Integer,
- String,
- DateTime,
- Float,
- ForeignKey,
-)
-from sqlalchemy.orm import relationship, Session
-from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import DateTime
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.associationproxy import association_proxy
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
Base = declarative_base()
"""
-from sqlalchemy import (
- create_engine,
- MetaData,
- Table,
- Column,
- Integer,
- Text,
- ForeignKey,
-)
-from sqlalchemy.orm import mapper, relationship, Session
-
-from sqlalchemy.orm.attributes import (
- set_attribute,
- get_attribute,
- del_attribute,
-)
-from sqlalchemy.orm.instrumentation import is_instrumented
-
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Table
+from sqlalchemy import Text
from sqlalchemy.ext.instrumentation import InstrumentationManager
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm.attributes import del_attribute
+from sqlalchemy.orm.attributes import get_attribute
+from sqlalchemy.orm.attributes import set_attribute
+from sqlalchemy.orm.instrumentation import is_instrumented
class MyClassState(InstrumentationManager):
"""
-Illustrates how to embed `dogpile.cache <https://dogpilecache.readthedocs.io/>`_
-functionality within
-the :class:`.Query` object, allowing full cache control as well as the
-ability to pull "lazy loaded" attributes from long term cache
-as well.
-
-.. versionchanged:: 0.8 The example was modernized to use
- dogpile.cache, replacing Beaker as the caching library in
- use.
+Illustrates how to embed
+`dogpile.cache <https://dogpilecache.readthedocs.io/>`_
+functionality within the :class:`.Query` object, allowing full cache control
+as well as the ability to pull "lazy loaded" attributes from long term cache.
In this demo, the following techniques are illustrated:
"""
+from .caching_query import FromCache
+from .caching_query import RelationshipCache
from .environment import Session
-from .model import Person, cache_address_bits
-from .caching_query import FromCache, RelationshipCache
+from .model import cache_address_bits
+from .model import Person
def load_name_range(start, end, invalidate=False):
# illustrate the address loading from either cache/already
# on the Person
print(
- "\n\nPeople plus addresses, two through twelve, addresses possibly from cache"
+ "\n\nPeople plus addresses, two through twelve, addresses "
+ "possibly from cache"
)
for p in load_name_range(2, 12):
print(p.format_full())
dogpile.cache constructs.
"""
+from dogpile.cache.api import NO_VALUE
+
from sqlalchemy.orm.interfaces import MapperOption
from sqlalchemy.orm.query import Query
-from dogpile.cache.api import NO_VALUE
class CachingQuery(Query):
"""Construct a new FromCache.
:param region: the cache region. Should be a
- region configured in the dictionary of dogpile
- regions.
+ region configured in the dictionary of dogpile
+ regions.
:param cache_key: optional. A string cache key
- that will serve as the key to the query. Use this
- if your query has a huge amount of parameters (such
- as when using in_()) which correspond more simply to
- some other identifier.
+ that will serve as the key to the query. Use this
+ if your query has a huge amount of parameters (such
+ as when using in_()) which correspond more simply to
+ some other identifier.
"""
self.region = region
"""Construct a new RelationshipCache.
:param attribute: A Class.attribute which
- indicates a particular class relationship() whose
- lazy loader should be pulled from the cache.
+ indicates a particular class relationship() whose
+ lazy loader should be pulled from the cache.
:param region: name of the cache region.
:param cache_key: optional. A string cache key
- that will serve as the key to the query, bypassing
- the usual means of forming a key from the Query itself.
+ that will serve as the key to the query, bypassing
+ the usual means of forming a key from the Query itself.
"""
self.region = region
bootstrap fixture data if necessary.
"""
-from . import caching_query
-from sqlalchemy import create_engine
-from sqlalchemy.orm import scoped_session, sessionmaker
-from sqlalchemy.ext.declarative import declarative_base
-from dogpile.cache.region import make_region
-import os
from hashlib import md5
+import os
import sys
+from dogpile.cache.region import make_region
+
+from sqlalchemy import create_engine
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import scoped_session
+from sqlalchemy.orm import sessionmaker
+from . import caching_query
+
+
py2k = sys.version_info < (3, 0)
if py2k:
- input = raw_input
+ input = raw_input # noqa
# dogpile cache regions. A home base for cache configurations.
regions = {}
-"""Installs some sample data. Here we have a handful of postal codes for a few US/
-Canadian cities. Then, 100 Person records are installed, each with a
-randomly selected postal code.
+"""Installs some sample data. Here we have a handful of postal codes for
+a few US/Canadian cities. Then, 100 Person records are installed, each
+with a randomly selected postal code.
"""
-from .environment import Session, Base
-from .model import City, Country, PostalCode, Person, Address
import random
+from .environment import Base
+from .environment import Session
+from .model import Address
+from .model import City
+from .model import Country
+from .model import Person
+from .model import PostalCode
+
def install():
Base.metadata.create_all(Session().bind)
"""
+from .caching_query import FromCache
from .environment import Session
from .model import Person
-from .caching_query import FromCache
+
# load Person objects. cache the result in the "default" cache region
print("loading people....")
"""
-from dogpile.cache.api import CacheBackend, NO_VALUE
+from dogpile.cache.api import CacheBackend
+from dogpile.cache.api import NO_VALUE
from dogpile.cache.region import register_backend
City --(has a)--> Country
"""
-from sqlalchemy import Column, Integer, String, ForeignKey
+from sqlalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.orm import relationship
from .caching_query import RelationshipCache
-from .environment import Base, bootstrap
+from .environment import Base
+from .environment import bootstrap
class Country(Base):
term cache.
"""
-from .environment import Session, root
-from .model import Person, cache_address_bits
-from sqlalchemy.orm import joinedload
import os
+from sqlalchemy.orm import joinedload
+from .environment import root
+from .environment import Session
+from .model import cache_address_bits
+from .model import Person
+
+
for p in Session.query(Person).options(
joinedload(Person.addresses), cache_address_bits
):
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import sessionmaker
+
+
class ProxyDict(object):
def __init__(self, parent, collection_name, childclass, keyname):
self.parent = parent
self.collection.append(value)
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
-from sqlalchemy.orm import sessionmaker, relationship
-
engine = create_engine("sqlite://", echo=True)
Base = declarative_base(engine)
-"""Illustrates an explicit way to persist an XML document expressed using ElementTree.
+"""
+Illustrates an explicit way to persist an XML document expressed using
+ElementTree.
Each DOM node is stored in an individual
table row, with attributes represented in a separate table. The
(very narrow) subset of xpath.
This example explicitly marshals/unmarshals the ElementTree document into
-mapped entities which have their own tables. Compare to pickle.py which
-uses pickle to accomplish the same task. Note that the usage of both
-styles of persistence are identical, as is the structure of the main Document class.
+mapped entities which have their own tables. Compare to pickle.py which uses
+pickle to accomplish the same task. Note that the usage of both styles of
+persistence are identical, as is the structure of the main Document class.
"""
-################################# PART I - Imports/Coniguration ####################################
-from sqlalchemy import (
- MetaData,
- Table,
- Column,
- Integer,
- String,
- ForeignKey,
- Unicode,
- and_,
- create_engine,
-)
-from sqlalchemy.orm import mapper, relationship, Session, lazyload
+# PART I - Imports/Configuration
+import io
+import os
+import re
+from xml.etree import ElementTree
-import sys, os, io, re
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import Unicode
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
-from xml.etree import ElementTree
e = create_engine("sqlite://")
meta = MetaData()
-################################# PART II - Table Metadata #########################################
+# PART II - Table Metadata
# stores a top level record of an XML document.
documents = Table(
meta.create_all(e)
-#################################### PART III - Model #############################################
+# PART III - Model
# our document class. contains a string name,
# and the ElementTree root element.
+
+
class Document(object):
def __init__(self, name, element):
self.filename = name
return buf.getvalue()
-#################################### PART IV - Persistence Mapping #################################
+# PART IV - Persistence Mapping
+
+# Node class. a non-public class which will represent the DB-persisted
+# Element/SubElement object. We cannot create mappers for ElementTree elements
+# directly because they are at the very least not new-style classes, and also
+# may be backed by native implementations. so here we construct an adapter.
+
-# Node class. a non-public class which will represent
-# the DB-persisted Element/SubElement object. We cannot create mappers for
-# ElementTree elements directly because they are at the very least not new-style
-# classes, and also may be backed by native implementations.
-# so here we construct an adapter.
class _Node(object):
pass
-# Attribute class. also internal, this will represent the key/value attributes stored for
-# a particular Node.
+# Attribute class. also internal, this will represent the key/value attributes
+# stored for a particular Node.
+
+
class _Attribute(object):
def __init__(self, name, value):
self.name = name
mapper(_Attribute, attributes)
-# define marshalling functions that convert from _Node/_Attribute to/from ElementTree objects.
-# this will set the ElementTree element as "document._element", and append the root _Node
-# object to the "_root" mapped collection.
+# define marshalling functions that convert from _Node/_Attribute to/from
+# ElementTree objects. this will set the ElementTree element as
+# "document._element", and append the root _Node object to the "_root" mapped
+# collection.
+
+
class ElementTreeMarshal(object):
def __get__(self, document, owner):
if document is None:
# override Document's "element" attribute with the marshaller.
Document.element = ElementTreeMarshal()
-########################################### PART V - Basic Persistence Example #####################
+# PART V - Basic Persistence Example
line = "\n--------------------------------------------------------"
print(document)
-############################################ PART VI - Searching for Paths #########################
+# PART VI - Searching for Paths
# manually search for a document which contains "/somefile/header/field1:hi"
d = (
print(d)
# generalize the above approach into an extremely impoverished xpath function:
+
+
def find_document(path, compareto):
j = documents
prev_elements = None
"""
-##################### PART I - Imports/Configuration #########################
-from sqlalchemy import (
- MetaData,
- Table,
- Column,
- Integer,
- String,
- ForeignKey,
- Unicode,
- and_,
- create_engine,
-)
-from sqlalchemy.orm import mapper, relationship, Session, lazyload
-
-import sys, os, io, re
+# PART I - Imports/Configuration
+import io
+import os
+import re
from xml.etree import ElementTree
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import Unicode
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
+
e = create_engine("sqlite://", echo=True)
meta = MetaData()
-####################### PART II - Table Metadata #############################
+# PART II - Table Metadata
# stores a top level record of an XML document.
documents = Table(
meta.create_all(e)
-########################### PART III - Model #################################
+# PART III - Model
# our document class. contains a string name,
# and the ElementTree root element.
+
+
class Document(object):
def __init__(self, name, element):
self.filename = name
return buf.getvalue()
-########################## PART IV - Persistence Mapping #####################
+# PART IV - Persistence Mapping
+
+# Node class. a non-public class which will represent the DB-persisted
+# Element/SubElement object. We cannot create mappers for ElementTree elements
+# directly because they are at the very least not new-style classes, and also
+# may be backed by native implementations. so here we construct an adapter.
+
-# Node class. a non-public class which will represent
-# the DB-persisted Element/SubElement object. We cannot create mappers for
-# ElementTree elements directly because they are at the very least not new-style
-# classes, and also may be backed by native implementations.
-# so here we construct an adapter.
class _Node(object):
pass
-# Attribute class. also internal, this will represent the key/value attributes stored for
-# a particular Node.
+# Attribute class. also internal, this will represent the key/value attributes
+# stored for a particular Node.
+
+
class _Attribute(object):
def __init__(self, name, value):
self.name = name
},
)
-# the _Node objects change the way they load so that a list of _Nodes will organize
-# themselves hierarchically using the ElementTreeMarshal. this depends on the ordering of
-# nodes being hierarchical as well; relationship() always applies at least ROWID/primary key
-# ordering to rows which will suffice.
+# the _Node objects change the way they load so that a list of _Nodes will
+# organize themselves hierarchically using the ElementTreeMarshal. this
+# depends on the ordering of nodes being hierarchical as well; relationship()
+# always applies at least ROWID/primary key ordering to rows which will
+# suffice.
mapper(
_Node,
elements,
mapper(_Attribute, attributes)
-# define marshalling functions that convert from _Node/_Attribute to/from ElementTree objects.
-# this will set the ElementTree element as "document._element", and append the root _Node
-# object to the "_nodes" mapped collection.
+# define marshalling functions that convert from _Node/_Attribute to/from
+# ElementTree objects. this will set the ElementTree element as
+# "document._element", and append the root _Node object to the "_nodes" mapped
+# collection.
+
+
class ElementTreeMarshal(object):
def __get__(self, document, owner):
if document is None:
# override Document's "element" attribute with the marshaller.
Document.element = ElementTreeMarshal()
-###################### PART V - Basic Persistence Example ####################
+# PART V - Basic Persistence Example
line = "\n--------------------------------------------------------"
print(document)
-######################## PART VI - Searching for Paths #######################
+# PART VI - Searching for Paths
# manually search for a document which contains "/somefile/header/field1:hi"
print("\nManual search for /somefile/header/field1=='hi':", line)
print(d)
# generalize the above approach into an extremely impoverished xpath function:
+
+
def find_document(path, compareto):
j = documents
prev_elements = None
-"""illustrates a quick and dirty way to persist an XML document expressed using ElementTree and pickle.
+"""
+illustrates a quick and dirty way to persist an XML document expressed using
+ElementTree and pickle.
This is a trivial example using PickleType to marshal/unmarshal the ElementTree
-document into a binary column. Compare to explicit.py which stores the individual components of the ElementTree
-structure in distinct rows using two additional mapped entities. Note that the usage of both
-styles of persistence are identical, as is the structure of the main Document class.
+document into a binary column. Compare to explicit.py which stores the
+individual components of the ElementTree structure in distinct rows using two
+additional mapped entities. Note that the usage of both styles of persistence
+are identical, as is the structure of the main Document class.
+
"""
-from sqlalchemy import (
- create_engine,
- MetaData,
- Table,
- Column,
- Integer,
- String,
- PickleType,
-)
-from sqlalchemy.orm import mapper, Session
+import os
+import sys
+from xml.etree import ElementTree
-import sys, os
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import PickleType
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
-from xml.etree import ElementTree
e = create_engine("sqlite://")
meta = MetaData()
# setup a comparator for the PickleType since it's a mutable
# element.
+
+
def are_elements_equal(x, y):
return x == y
# our document class. contains a string name,
# and the ElementTree root element.
+
+
class Document(object):
def __init__(self, name, element):
self.filename = name
# setup mapper.
mapper(Document, documents)
-###### time to test ! #########
+# time to test !
# get ElementTree document
filename = os.path.join(os.path.dirname(__file__), "test.xml")
.. autosource::
-"""
+""" # noqa
objects, but is also slightly more complex.
"""
-from sqlalchemy.ext.declarative import as_declarative, declared_attr
-from sqlalchemy import create_engine, Integer, Column, String, ForeignKey
-from sqlalchemy.orm import Session, relationship, backref
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.associationproxy import association_proxy
+from sqlalchemy.ext.declarative import as_declarative
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
@as_declarative()
.. versionadded:: 0.8.3
"""
-from sqlalchemy.ext.declarative import as_declarative, declared_attr
-from sqlalchemy import create_engine, Integer, Column, String, and_
-from sqlalchemy.orm import Session, relationship, foreign, remote, backref
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import create_engine
from sqlalchemy import event
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import as_declarative
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import foreign
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import remote
+from sqlalchemy.orm import Session
@as_declarative()
"""
-from sqlalchemy.ext.declarative import as_declarative, declared_attr
-from sqlalchemy import (
- create_engine,
- Integer,
- Column,
- String,
- ForeignKey,
- Table,
-)
-from sqlalchemy.orm import Session, relationship
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy.ext.declarative import as_declarative
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
@as_declarative()
is completely automated.
"""
-from sqlalchemy.ext.declarative import as_declarative, declared_attr
-from sqlalchemy import create_engine, Integer, Column, String, ForeignKey
-from sqlalchemy.orm import Session, relationship
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import as_declarative
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
@as_declarative()
"""a directed graph example."""
-from sqlalchemy import Column, Integer, ForeignKey, create_engine
-from sqlalchemy.orm import relationship, sessionmaker
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import sessionmaker
+
Base = declarative_base()
"""Concrete-table (table-per-class) inheritance example."""
-from sqlalchemy import (
- Column,
- Integer,
- String,
- ForeignKey,
- create_engine,
- inspect,
- or_,
-)
-from sqlalchemy.orm import relationship, Session, with_polymorphic
-from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import or_
+from sqlalchemy import String
from sqlalchemy.ext.declarative import ConcreteBase
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import with_polymorphic
Base = declarative_base()
"""Joined-table (table-per-subclass) inheritance example."""
-from sqlalchemy import (
- Column,
- Integer,
- String,
- ForeignKey,
- create_engine,
- inspect,
- or_,
-)
-from sqlalchemy.orm import relationship, Session, with_polymorphic
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import or_
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import with_polymorphic
+
Base = declarative_base()
"""Single-table (table-per-hierarchy) inheritance example."""
-from sqlalchemy import (
- Column,
- Integer,
- String,
- ForeignKey,
- create_engine,
- inspect,
- or_,
-)
-from sqlalchemy.orm import relationship, Session, with_polymorphic
-from sqlalchemy.ext.declarative import declarative_base, declared_attr
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import or_
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import with_polymorphic
+
Base = declarative_base()
"foreign key" column.
"""
-from sqlalchemy import *
-from sqlalchemy.orm import *
+
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import TypeDecorator
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
Base = declarative_base()
"""
-from sqlalchemy import *
-from sqlalchemy.orm import *
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import join
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import foreign
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
Base = declarative_base()
-from sqlalchemy import (
- MetaData,
- Table,
- Column,
- Integer,
- String,
- ForeignKey,
- create_engine,
-)
-from sqlalchemy.orm import mapper, relationship, sessionmaker
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import sessionmaker
meta = MetaData()
# Member objects "belong" to their parent, are deleted when
# removed from the collection
cascade="all, delete-orphan",
- # "delete, delete-orphan" cascade does not load in objects on delete,
- # allows ON DELETE CASCADE to handle it.
+ # "delete, delete-orphan" cascade does not load in objects on
+ # delete, allows ON DELETE CASCADE to handle it.
# this only works with a database that supports ON DELETE CASCADE -
# *not* sqlite or MySQL with MyISAM
passive_deletes=True,
# disappear automatically without the need for additional SQL.
sess.delete(org)
print(
- "-------------------------\nflush three - delete org, delete members in one statement\n"
+ "-------------------------\nflush three - delete org, "
+ "delete members in one statement\n"
)
sess.commit()
descendants and changing the prefix.
"""
-from sqlalchemy import Column, Integer, String, func, select, create_engine
-from sqlalchemy.orm import remote, foreign, relationship, Session
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import foreign
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import remote
+from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import cast
-from sqlalchemy.dialects.postgresql import ARRAY
+
Base = declarative_base()
"""
-from sqlalchemy import (
- create_engine,
- Column,
- Integer,
- String,
- select,
- case,
- func,
-)
-from sqlalchemy.orm import Session, aliased
-from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy import case
+from sqlalchemy import Column
+from sqlalchemy import create_engine
from sqlalchemy import event
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import Session
+
Base = declarative_base()
-h, --help show this help message and exit
--test TEST run specific test name
--dburl DBURL database URL, default sqlite:///profile.db
- --num NUM Number of iterations/items/etc for tests; default is 0
- module-specific
+ --num NUM Number of iterations/items/etc for tests;
+ default is module-specific
--profile run profiling and dump call counts
--dump dump full call profile (implies --profile)
--runsnake invoke runsnakerun (implies --profile)
$ python test_loads.py --num 100 --runsnake --test test_joinedload
-"""
+""" # noqa
import argparse
import cProfile
-import pstats
import os
-import time
+import pstats
import re
import sys
+import time
class Profiler(object):
from . import Profiler
+
if __name__ == "__main__":
Profiler.main()
"""
-from . import Profiler
-
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import Column, Integer, String, create_engine, bindparam
from sqlalchemy.orm import Session
+from . import Profiler
+
Base = declarative_base()
engine = None
"""
-from . import Profiler
-
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import Column, Integer, String, create_engine, bindparam
from sqlalchemy.orm import Session
+from . import Profiler
+
Base = declarative_base()
engine = None
provide a huge amount of functionality.
"""
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import Bundle
+from sqlalchemy.orm import Session
from . import Profiler
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import Column, Integer, String, create_engine
-from sqlalchemy.orm import Session, Bundle
Base = declarative_base()
engine = None
# going to do this, so see how this pushes you right back into
# ORM land anyway :)
class SimpleCustomer(object):
- def __init__(self, id, name, description):
- self.id = id
+ def __init__(self, id_, name, description):
+ self.id = id_
self.name = name
self.description = description
"""
-from . import Profiler
+import random
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import (
- Column,
- Integer,
- String,
- create_engine,
- bindparam,
- select,
-)
-from sqlalchemy.orm import Session, deferred
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy.ext import baked
-import random
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import Session
+from . import Profiler
+
Base = declarative_base()
engine = None
a database connection, inserts the row, commits and closes.
"""
-from . import Profiler
-
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import pool
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import Column, Integer, String, create_engine, bindparam, pool
from sqlalchemy.orm import Session
+from . import Profiler
+
Base = declarative_base()
engine = None
E.g.::
- print session.query(Road).filter(Road.road_geom.intersects(r1.road_geom)).all()
+ print session.query(Road).filter(
+ Road.road_geom.intersects(r1.road_geom)).all()
.. autosource::
-from sqlalchemy.types import UserDefinedType, _Binary, TypeDecorator
-from sqlalchemy.sql import expression, type_coerce
-from sqlalchemy import event, Table
import binascii
+from sqlalchemy import event
+from sqlalchemy import Table
+from sqlalchemy.sql import expression
+from sqlalchemy.sql import type_coerce
+from sqlalchemy.types import UserDefinedType
+
+
# Python datatypes
]
)
- # or use an explicit TextualGisElement (similar to saying func.GeomFromText())
+ # or use an explicit TextualGisElement
+ # (similar to saying func.GeomFromText())
r = Road(
road_name="Dave Cres",
road_geom=TextualGisElement(
session.commit()
- # after flush and/or commit, all the TextualGisElements become PersistentGisElements.
+ # after flush and/or commit, all the TextualGisElements
+ # become PersistentGisElements.
assert str(r.road_geom) == "LINESTRING(198231 263418,198213 268322)"
r1 = session.query(Road).filter(Road.road_name == "Graeme Ave").one()
)
print(session.execute(stmt).fetchall())
- # TODO: for some reason the auto-generated labels have the internal replacement
- # strings exposed, even though PG doesn't complain
+ # TODO: for some reason the auto-generated labels have the internal
+ # replacement strings exposed, even though PG doesn't complain
# look up the hex binary version, using SQLAlchemy casts
as_binary = session.scalar(
select([type_coerce(r.road_geom, Geometry(coerce_="binary"))])
)
- assert (
- as_binary.as_hex
- == "01020000000200000000000000b832084100000000e813104100000000283208410000000088601041"
+ assert as_binary.as_hex == (
+ "01020000000200000000000000b832084100000000"
+ "e813104100000000283208410000000088601041"
)
# back again, same method !
* a function which can return a single shard id, given an instance
to be saved; this is called "shard_chooser"
* a function which can return a list of shard ids which apply to a particular
- instance identifier; this is called "id_chooser". If it returns all shard ids,
+ instance identifier; this is called "id_chooser".If it returns all shard ids,
all shards will be searched.
* a function which can return a list of shard ids to try, given a particular
Query ("query_chooser"). If it returns all shard ids, all shards will be
-from sqlalchemy import (
- create_engine,
- Table,
- Column,
- Integer,
- String,
- ForeignKey,
- Float,
- DateTime,
-)
-from sqlalchemy.orm import sessionmaker, relationship
-from sqlalchemy.ext.horizontal_shard import ShardedSession
-from sqlalchemy.sql import operators, visitors
-from sqlalchemy.ext.declarative import declarative_base
+import datetime
+
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import DateTime
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.ext.horizontal_shard import ShardedSession
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.sql import operators
+from sqlalchemy.sql import visitors
-import datetime
# db1 is used for id generation. The "pool_threadlocal"
# causes the id_generator() to use the same connection as that
-import sys
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import create_engine, Integer, Column, ForeignKey, String, func
-from sqlalchemy.orm import relationship, Session, joinedload
-from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
import curses
-import time
-import textwrap
-import re
-import random
import logging
+import random
+import re
+import sys
+import textwrap
+import time
+
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.ext.hybrid import hybrid_method
+from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
_PY3 = sys.version_info > (3, 0)
if _PY3:
COLOR_MAP = {
"K": curses.COLOR_BLACK,
- "R": curses.COLOR_RED,
"B": curses.COLOR_BLUE,
"C": curses.COLOR_CYAN,
"G": curses.COLOR_GREEN,
"""
Illustrates an extension which creates version tables for entities and stores
-records for each change. The given extensions generate an anonymous "history" class which
-represents historical versions of the target object.
+records for each change. The given extensions generate an anonymous "history"
+class which represents historical versions of the target object.
Compare to the :ref:`examples_versioned_rows` examples which write updates
as new rows in the same table, without using a separate history table.
"""Versioned mixin class and other utilities."""
+import datetime
+
+from sqlalchemy import Column
+from sqlalchemy import DateTime
+from sqlalchemy import event
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import Integer
+from sqlalchemy import Table
+from sqlalchemy import util
from sqlalchemy.ext.declarative import declared_attr
-from sqlalchemy.orm import mapper, attributes, object_mapper
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import object_mapper
from sqlalchemy.orm.exc import UnmappedColumnError
-from sqlalchemy import Table, Column, ForeignKeyConstraint, Integer, DateTime
-from sqlalchemy import event, util
-import datetime
from sqlalchemy.orm.properties import RelationshipProperty
class Versioned(object):
@declared_attr
def __mapper_cls__(cls):
- def map(cls, *arg, **kw):
+ def map_(cls, *arg, **kw):
mp = mapper(cls, *arg, **kw)
_history_mapper(mp)
return mp
- return map
+ return map_
__table_args__ = {"sqlite_autoincrement": True}
"""Use sqlite_autoincrement, to ensure unique integer values
are used for new rows even for rows taht have been deleted."""
-def versioned_objects(iter):
- for obj in iter:
+def versioned_objects(iter_):
+ for obj in iter_:
if hasattr(obj, "__history_mapper__"):
yield obj
module functions."""
from unittest import TestCase
+import warnings
+
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
-from .history_meta import Versioned, versioned_session
-from sqlalchemy import (
- create_engine,
- Column,
- Integer,
- String,
- ForeignKey,
- Boolean,
- select,
-)
-from sqlalchemy.orm import (
- clear_mappers,
- Session,
- deferred,
- relationship,
- column_property,
-)
-from sqlalchemy.testing import AssertsCompiledSQL, eq_, assert_raises, ne_
-from sqlalchemy.testing.entities import ComparableEntity
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import deferred
from sqlalchemy.orm import exc as orm_exc
-import warnings
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.entities import ComparableEntity
+from .history_meta import Versioned
+from .history_meta import versioned_session
+
warnings.simplefilter("error")
"""
-from sqlalchemy import Column, String, Integer, ForeignKey, create_engine
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.orm import (
- attributes,
- relationship,
- backref,
- sessionmaker,
- make_transient,
- validates,
- Session,
-)
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.associationproxy import association_proxy
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import make_transient
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import validates
from sqlalchemy.orm.collections import attribute_mapped_collection
-from sqlalchemy import event
@event.listens_for(Session, "before_flush")
row is inserted with the new data, keeping the old row intact.
"""
-from sqlalchemy.orm import (
- sessionmaker,
- relationship,
- make_transient,
- backref,
- Session,
-)
-from sqlalchemy import Column, ForeignKey, create_engine, Integer, String
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import attributes
-from sqlalchemy import event
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import make_transient
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
class Versioned(object):
as the ability to see which row is the most "current" vesion.
"""
-from sqlalchemy.orm import (
- sessionmaker,
- relationship,
- make_transient,
- backref,
- Session,
- column_property,
-)
-from sqlalchemy import (
- Column,
- ForeignKeyConstraint,
- create_engine,
- Integer,
- String,
- Boolean,
- select,
- func,
-)
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import event
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import attributes
-from sqlalchemy import event
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import make_transient
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
class Versioned(object):
"""
-from sqlalchemy import (
- create_engine,
- Integer,
- String,
- event,
- Column,
- DateTime,
- inspect,
- literal,
-)
-from sqlalchemy.orm import (
- make_transient,
- Session,
- relationship,
- attributes,
- backref,
- make_transient_to_detached,
- Query,
-)
-from sqlalchemy.ext.declarative import declarative_base
import datetime
import time
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import DateTime
+from sqlalchemy import event
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import make_transient
+from sqlalchemy.orm import make_transient_to_detached
+from sqlalchemy.orm import Query
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
+
Base = declarative_base()
# this will be the current time as the test runs
"""
-from sqlalchemy.orm.interfaces import PropComparator
-from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import event
from sqlalchemy import literal_column
+from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.orm.interfaces import PropComparator
from .dictlike import ProxiedDictMixin
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
+from . import util as _util # noqa
+from .inspection import inspect # noqa
+from .schema import BLANK_SCHEMA # noqa
+from .schema import CheckConstraint # noqa
+from .schema import Column # noqa
+from .schema import ColumnDefault # noqa
+from .schema import Constraint # noqa
+from .schema import DDL # noqa
+from .schema import DefaultClause # noqa
+from .schema import FetchedValue # noqa
+from .schema import ForeignKey # noqa
+from .schema import ForeignKeyConstraint # noqa
+from .schema import Index # noqa
+from .schema import MetaData # noqa
+from .schema import PassiveDefault # noqa
+from .schema import PrimaryKeyConstraint # noqa
+from .schema import Sequence # noqa
+from .schema import Table # noqa
+from .schema import ThreadLocalMetaData # noqa
+from .schema import UniqueConstraint # noqa
+from .sql import alias # noqa
+from .sql import all_ # noqa
+from .sql import and_ # noqa
+from .sql import any_ # noqa
+from .sql import asc # noqa
+from .sql import between # noqa
+from .sql import bindparam # noqa
+from .sql import case # noqa
+from .sql import cast # noqa
+from .sql import collate # noqa
+from .sql import column # noqa
+from .sql import delete # noqa
+from .sql import desc # noqa
+from .sql import distinct # noqa
+from .sql import except_ # noqa
+from .sql import except_all # noqa
+from .sql import exists # noqa
+from .sql import extract # noqa
+from .sql import false # noqa
+from .sql import func # noqa
+from .sql import funcfilter # noqa
+from .sql import insert # noqa
+from .sql import intersect # noqa
+from .sql import intersect_all # noqa
+from .sql import join # noqa
+from .sql import lateral # noqa
+from .sql import literal # noqa
+from .sql import literal_column # noqa
+from .sql import modifier # noqa
+from .sql import not_ # noqa
+from .sql import null # noqa
+from .sql import nullsfirst # noqa
+from .sql import nullslast # noqa
+from .sql import or_ # noqa
+from .sql import outerjoin # noqa
+from .sql import outparam # noqa
+from .sql import over # noqa
+from .sql import select # noqa
+from .sql import subquery # noqa
+from .sql import table # noqa
+from .sql import tablesample # noqa
+from .sql import text # noqa
+from .sql import true # noqa
+from .sql import tuple_ # noqa
+from .sql import type_coerce # noqa
+from .sql import union # noqa
+from .sql import union_all # noqa
+from .sql import update # noqa
+from .sql import within_group # noqa
+from .types import ARRAY # noqa
+from .types import BIGINT # noqa
+from .types import BigInteger # noqa
+from .types import BINARY # noqa
+from .types import Binary # noqa
+from .types import BLOB # noqa
+from .types import BOOLEAN # noqa
+from .types import Boolean # noqa
+from .types import CHAR # noqa
+from .types import CLOB # noqa
+from .types import DATE # noqa
+from .types import Date # noqa
+from .types import DATETIME # noqa
+from .types import DateTime # noqa
+from .types import DECIMAL # noqa
+from .types import Enum # noqa
+from .types import FLOAT # noqa
+from .types import Float # noqa
+from .types import INT # noqa
+from .types import INTEGER # noqa
+from .types import Integer # noqa
+from .types import Interval # noqa
+from .types import JSON # noqa
+from .types import LargeBinary # noqa
+from .types import NCHAR # noqa
+from .types import NUMERIC # noqa
+from .types import Numeric # noqa
+from .types import NVARCHAR # noqa
+from .types import PickleType # noqa
+from .types import REAL # noqa
+from .types import SMALLINT # noqa
+from .types import SmallInteger # noqa
+from .types import String # noqa
+from .types import TEXT # noqa
+from .types import Text # noqa
+from .types import TIME # noqa
+from .types import Time # noqa
+from .types import TIMESTAMP # noqa
+from .types import TypeDecorator # noqa
+from .types import Unicode # noqa
+from .types import UnicodeText # noqa
+from .types import VARBINARY # noqa
+from .types import VARCHAR # noqa
+
+from .engine import create_engine # noqa nosort
+from .engine import engine_from_config # noqa nosort
-from .sql import (
- alias,
- all_,
- and_,
- any_,
- asc,
- between,
- bindparam,
- case,
- cast,
- collate,
- column,
- delete,
- desc,
- distinct,
- except_,
- except_all,
- exists,
- extract,
- false,
- func,
- funcfilter,
- insert,
- intersect,
- intersect_all,
- join,
- lateral,
- literal,
- literal_column,
- modifier,
- not_,
- null,
- nullsfirst,
- nullslast,
- or_,
- outerjoin,
- outparam,
- over,
- select,
- subquery,
- table,
- tablesample,
- text,
- true,
- tuple_,
- type_coerce,
- union,
- union_all,
- update,
- within_group,
-)
-
-from .types import (
- ARRAY,
- BIGINT,
- BINARY,
- BLOB,
- BOOLEAN,
- BigInteger,
- Binary,
- Boolean,
- CHAR,
- CLOB,
- DATE,
- DATETIME,
- DECIMAL,
- Date,
- DateTime,
- Enum,
- FLOAT,
- Float,
- INT,
- INTEGER,
- Integer,
- Interval,
- JSON,
- LargeBinary,
- NCHAR,
- NVARCHAR,
- NUMERIC,
- Numeric,
- PickleType,
- REAL,
- SMALLINT,
- SmallInteger,
- String,
- TEXT,
- TIME,
- TIMESTAMP,
- Text,
- Time,
- TypeDecorator,
- Unicode,
- UnicodeText,
- VARBINARY,
- VARCHAR,
-)
-
-
-from .schema import (
- CheckConstraint,
- Column,
- ColumnDefault,
- Constraint,
- DefaultClause,
- FetchedValue,
- ForeignKey,
- ForeignKeyConstraint,
- Index,
- MetaData,
- PassiveDefault,
- PrimaryKeyConstraint,
- Sequence,
- Table,
- ThreadLocalMetaData,
- UniqueConstraint,
- DDL,
- BLANK_SCHEMA,
-)
-
-
-from .inspection import inspect
-from .engine import create_engine, engine_from_config
__version__ = "1.3.0b2"
def __go(lcls):
global __all__
- from . import events
+ from . import events # noqa
from . import util as _sa_util
import inspect as _inspect
"""
-import sys
import re
+import sys
import warnings
from . import Connector
return error_handler
def create_connect_args(self, url):
- """ Return a tuple of *args,**kwargs for creating a connection.
+ r"""Return a tuple of \*args, \**kwargs for creating a connection.
The mxODBC 3.x connection constructor looks like this:
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
+import re
+
from . import Connector
from .. import util
-import re
-
-
class PyODBCConnector(Connector):
driver = "pyodbc"
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import sys
+
from . import Connector
compatibility with pre 0.6 versions.
"""
-from ..dialects.sqlite import base as sqlite
-from ..dialects.postgresql import base as postgresql
-
-postgres = postgresql
-from ..dialects.mysql import base as mysql
-from ..dialects.oracle import base as oracle
from ..dialects.firebird import base as firebird
from ..dialects.mssql import base as mssql
+from ..dialects.mysql import base as mysql
+from ..dialects.oracle import base as oracle
+from ..dialects.postgresql import base as postgresql
+from ..dialects.sqlite import base as sqlite
from ..dialects.sybase import base as sybase
+postgres = postgresql
+
+
__all__ = (
"firebird",
"mssql",
from .. import util
+
_translates = {"postgres": "postgresql"}
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import base, kinterbasdb, fdb # noqa
+from sqlalchemy.dialects.firebird.base import BIGINT
+from sqlalchemy.dialects.firebird.base import BLOB
+from sqlalchemy.dialects.firebird.base import CHAR
+from sqlalchemy.dialects.firebird.base import DATE
+from sqlalchemy.dialects.firebird.base import FLOAT
+from sqlalchemy.dialects.firebird.base import NUMERIC
+from sqlalchemy.dialects.firebird.base import SMALLINT
+from sqlalchemy.dialects.firebird.base import TEXT
+from sqlalchemy.dialects.firebird.base import TIME
+from sqlalchemy.dialects.firebird.base import TIMESTAMP
+from sqlalchemy.dialects.firebird.base import VARCHAR
+from . import base # noqa
+from . import fdb # noqa
+from . import kinterbasdb # noqa
-from sqlalchemy.dialects.firebird.base import (
- SMALLINT,
- BIGINT,
- FLOAT,
- DATE,
- TIME,
- TEXT,
- NUMERIC,
- TIMESTAMP,
- VARCHAR,
- CHAR,
- BLOB,
-)
base.dialect = dialect = fdb.dialect
import datetime
-from sqlalchemy import schema as sa_schema
-from sqlalchemy import exc, types as sqltypes, sql, util
-from sqlalchemy.sql import expression
-from sqlalchemy.engine import base, default, reflection
+from sqlalchemy import exc
+from sqlalchemy import sql
+from sqlalchemy import types as sqltypes
+from sqlalchemy import util
+from sqlalchemy.engine import default
+from sqlalchemy.engine import reflection
from sqlalchemy.sql import compiler
+from sqlalchemy.sql import expression
from sqlalchemy.sql.elements import quoted_name
-
-from sqlalchemy.types import (
- BIGINT,
- BLOB,
- DATE,
- FLOAT,
- INTEGER,
- NUMERIC,
- SMALLINT,
- TEXT,
- TIME,
- TIMESTAMP,
- Integer,
-)
+from sqlalchemy.types import BIGINT
+from sqlalchemy.types import BLOB
+from sqlalchemy.types import DATE
+from sqlalchemy.types import FLOAT
+from sqlalchemy.types import INTEGER
+from sqlalchemy.types import Integer
+from sqlalchemy.types import NUMERIC
+from sqlalchemy.types import SMALLINT
+from sqlalchemy.types import TEXT
+from sqlalchemy.types import TIME
+from sqlalchemy.types import TIMESTAMP
RESERVED_WORDS = set(
# no syntax for these
# http://www.firebirdsql.org/manual/generatorguide-sqlsyntax.html
if create.element.start is not None:
- raise NotImplemented(
+ raise NotImplementedError(
"Firebird SEQUENCE doesn't support START WITH"
)
if create.element.increment is not None:
- raise NotImplemented(
+ raise NotImplementedError(
"Firebird SEQUENCE doesn't support INCREMENT BY"
)
name = name and name.rstrip()
if name is None:
return None
- elif name.upper() == name and not self.identifier_preparer._requires_quotes(
- name.lower()
- ):
+ elif name.upper() == name and not (
+ self.identifier_preparer._requires_quotes
+ )(name.lower()):
return name.lower()
elif name.lower() == name:
return quoted_name(name, quote=True)
def denormalize_name(self, name):
if name is None:
return None
- elif name.lower() == name and not self.identifier_preparer._requires_quotes(
- name.lower()
- ):
+ elif name.lower() == name and not (
+ self.identifier_preparer._requires_quotes
+ )(name.lower()):
return name.upper()
else:
return name
.. dialect:: firebird+fdb
:name: fdb
:dbapi: pyodbc
- :connectstring: firebird+fdb://user:password@host:port/path/to/db\
-[?key=value&key=value...]
+ :connectstring: firebird+fdb://user:password@host:port/path/to/db[?key=value&key=value...]
:url: http://pypi.python.org/pypi/fdb/
fdb is a kinterbasdb compatible DBAPI for Firebird.
http://pythonhosted.org/fdb/usage-guide.html#retaining-transactions
- information on the "retaining" flag.
-"""
+""" # noqa
from .kinterbasdb import FBDialect_kinterbasdb
from ... import util
.. dialect:: firebird+kinterbasdb
:name: kinterbasdb
:dbapi: kinterbasdb
- :connectstring: firebird+kinterbasdb://user:password@host:port/path/to/db\
-[?key=value&key=value...]
+ :connectstring: firebird+kinterbasdb://user:password@host:port/path/to/db[?key=value&key=value...]
:url: http://firebirdsql.org/index.php?op=devel&sub=python
Arguments
http://kinterbasdb.sourceforge.net/dist_docs/usage.html#special_issue_concurrency
-"""
+""" # noqa
-from .base import FBDialect, FBExecutionContext
-from ... import util, types as sqltypes
-from re import match
import decimal
+from re import match
+
+from .base import FBDialect
+from .base import FBExecutionContext
+from ... import types as sqltypes
+from ... import util
class _kinterbasdb_numeric(object):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import base, pyodbc, adodbapi, pymssql, zxjdbc, mxodbc # noqa
+from . import adodbapi # noqa
+from . import base # noqa
+from . import mxodbc # noqa
+from . import pymssql # noqa
+from . import pyodbc # noqa
+from . import zxjdbc # noqa
+from .base import BIGINT
+from .base import BINARY
+from .base import BIT
+from .base import CHAR
+from .base import DATE
+from .base import DATETIME
+from .base import DATETIME2
+from .base import DATETIMEOFFSET
+from .base import DECIMAL
+from .base import FLOAT
+from .base import IMAGE
+from .base import INTEGER
+from .base import MONEY
+from .base import NCHAR
+from .base import NTEXT
+from .base import NUMERIC
+from .base import NVARCHAR
+from .base import REAL
+from .base import ROWVERSION
+from .base import SMALLDATETIME
+from .base import SMALLINT
+from .base import SMALLMONEY
+from .base import SQL_VARIANT
+from .base import TEXT
+from .base import TIME
+from .base import TIMESTAMP
+from .base import TINYINT
+from .base import UNIQUEIDENTIFIER
+from .base import VARBINARY
+from .base import VARCHAR
+from .base import XML
-from .base import (
- INTEGER,
- BIGINT,
- SMALLINT,
- TINYINT,
- VARCHAR,
- NVARCHAR,
- CHAR,
- NCHAR,
- TEXT,
- NTEXT,
- DECIMAL,
- NUMERIC,
- FLOAT,
- DATETIME,
- DATETIME2,
- DATETIMEOFFSET,
- DATE,
- TIME,
- SMALLDATETIME,
- BINARY,
- VARBINARY,
- BIT,
- REAL,
- IMAGE,
- TIMESTAMP,
- ROWVERSION,
- MONEY,
- SMALLMONEY,
- UNIQUEIDENTIFIER,
- SQL_VARIANT,
- XML,
-)
base.dialect = dialect = pyodbc.dialect
"""
import datetime
-from sqlalchemy import types as sqltypes, util
-from sqlalchemy.dialects.mssql.base import MSDateTime, MSDialect
import sys
+from sqlalchemy import types as sqltypes
+from sqlalchemy import util
+from sqlalchemy.dialects.mssql.base import MSDateTime
+from sqlalchemy.dialects.mssql.base import MSDialect
+
class MSDateTime_adodbapi(MSDateTime):
def result_processor(self, dialect, coltype):
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
"""
.. dialect:: mssql
:name: Microsoft SQL Server
Large Text/Binary Type Deprecation
----------------------------------
-Per `SQL Server 2012/2014 Documentation <http://technet.microsoft.com/en-us/library/ms187993.aspx>`_,
-the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL Server
-in a future release. SQLAlchemy normally relates these types to the
+Per
+`SQL Server 2012/2014 Documentation <http://technet.microsoft.com/en-us/library/ms187993.aspx>`_,
+the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL
+Server in a future release. SQLAlchemy normally relates these types to the
:class:`.UnicodeText`, :class:`.Text` and :class:`.LargeBinary` datatypes.
In order to accommodate this change, a new flag ``deprecate_large_types``
established. If the dialect is used to render DDL without the flag being
set, it is interpreted the same as ``False``.
-* On first connection, the dialect detects if SQL Server version 2012 or greater
- is in use; if the flag is still at ``None``, it sets it to ``True`` or
- ``False`` based on whether 2012 or greater is detected.
+* On first connection, the dialect detects if SQL Server version 2012 or
+ greater is in use; if the flag is still at ``None``, it sets it to ``True``
+ or ``False`` based on whether 2012 or greater is detected.
* The flag can be set to either ``True`` or ``False`` when the dialect
is created, typically via :func:`.create_engine`::
* Complete control over whether the "old" or "new" types are rendered is
available in all SQLAlchemy versions by using the UPPERCASE type objects
instead: :class:`.NVARCHAR`, :class:`.VARCHAR`, :class:`.types.VARBINARY`,
- :class:`.TEXT`, :class:`.mssql.NTEXT`, :class:`.mssql.IMAGE` will always remain
- fixed and always output exactly that type.
+ :class:`.TEXT`, :class:`.mssql.NTEXT`, :class:`.mssql.IMAGE` will always
+ remain fixed and always output exactly that type.
.. versionadded:: 1.0.0
Background on SQL Server snapshot isolation is available at
http://msdn.microsoft.com/en-us/library/ms175095.aspx.
+""" # noqa
-"""
import codecs
import datetime
import operator
import re
-from ... import sql, schema as sa_schema, exc, util
-from ...sql import compiler, expression, util as sql_util, quoted_name
+from . import information_schema as ischema
from ... import engine
-from ...engine import reflection, default
+from ... import exc
+from ... import schema as sa_schema
+from ... import sql
from ... import types as sqltypes
-from ...types import (
- INTEGER,
- BIGINT,
- SMALLINT,
- DECIMAL,
- NUMERIC,
- FLOAT,
- DATETIME,
- DATE,
- BINARY,
- TEXT,
- VARCHAR,
- NVARCHAR,
- CHAR,
- NCHAR,
-)
-
-
+from ... import util
+from ...engine import default
+from ...engine import reflection
+from ...sql import compiler
+from ...sql import expression
+from ...sql import quoted_name
+from ...sql import util as sql_util
+from ...types import BIGINT
+from ...types import BINARY
+from ...types import CHAR
+from ...types import DATE
+from ...types import DATETIME
+from ...types import DECIMAL
+from ...types import FLOAT
+from ...types import INTEGER
+from ...types import NCHAR
+from ...types import NUMERIC
+from ...types import NVARCHAR
+from ...types import SMALLINT
+from ...types import TEXT
+from ...types import VARCHAR
from ...util import update_wrapper
-from . import information_schema as ischema
+
# http://sqlserverbuilds.blogspot.com/
MS_2016_VERSION = (13,)
insert_has_sequence = seq_column is not None
if insert_has_sequence:
- self._enable_identity_insert = seq_column.key in self.compiled_parameters[
- 0
- ] or (
+ self._enable_identity_insert = (
+ seq_column.key in self.compiled_parameters[0]
+ ) or (
self.compiled.statement.parameters
and (
(
break
(
name,
- type,
+ type_,
nullable,
charlen,
numericprec,
row[columns.c.column_default],
row[columns.c.collation_name],
)
- coltype = self.ischema_names.get(type, None)
+ coltype = self.ischema_names.get(type_, None)
kwargs = {}
if coltype in (
if coltype is None:
util.warn(
- "Did not recognize type '%s' of column '%s'" % (type, name)
+ "Did not recognize type '%s' of column '%s'"
+ % (type_, name)
)
coltype = sqltypes.NULLTYPE
else:
# TODO: should be using the sys. catalog with SQL Server, not information
# schema
-from ... import Table, MetaData, Column
-from ...types import String, Unicode, UnicodeText, Integer, TypeDecorator
from ... import cast
+from ... import Column
+from ... import MetaData
+from ... import Table
from ... import util
-from ...sql import expression
from ...ext.compiler import compiles
+from ...sql import expression
+from ...types import Integer
+from ...types import String
+from ...types import TypeDecorator
+from ...types import Unicode
+
ischema = MetaData()
"""
+from .base import _MSDate
+from .base import _MSDateTime
+from .base import _MSTime
+from .base import MSDialect
+from .base import VARBINARY
+from .pyodbc import _MSNumeric_pyodbc
+from .pyodbc import MSExecutionContext_pyodbc
from ... import types as sqltypes
from ...connectors.mxodbc import MxODBCConnector
-from .pyodbc import MSExecutionContext_pyodbc, _MSNumeric_pyodbc
-from .base import (
- MSDialect,
- MSSQLStrictCompiler,
- VARBINARY,
- _MSDateTime,
- _MSDate,
- _MSTime,
-)
class _MSNumeric_mxodbc(_MSNumeric_pyodbc):
.. dialect:: mssql+pymssql
:name: pymssql
:dbapi: pymssql
- :connectstring: mssql+pymssql://<username>:<password>@<freetds_name>/?\
-charset=utf8
+ :connectstring: mssql+pymssql://<username>:<password>@<freetds_name>/?charset=utf8
:url: http://pymssql.org/
pymssql is a Python module that provides a Python DBAPI interface around
Modern versions of this driver work very well with SQL Server and
FreeTDS from Linux and is highly recommended.
-"""
-from .base import MSDialect, MSIdentifierPreparer
-from ... import types as sqltypes, util, processors
+""" # noqa
import re
+from .base import MSDialect
+from .base import MSIdentifierPreparer
+from ... import processors
+from ... import types as sqltypes
+from ... import util
+
class _MSNumeric_pymssql(sqltypes.Numeric):
def result_processor(self, dialect, type_):
A PyODBC connection string can also be sent exactly as specified in
`ConnectionStrings <https://code.google.com/p/pyodbc/wiki/ConnectionStrings>`_
-into the driver using the parameter ``odbc_connect``. The delimeters must be URL escaped, however,
-as illustrated below using ``urllib.quote_plus``::
+into the driver using the parameter ``odbc_connect``. The delimeters must be
+URL escaped, however, as illustrated below using ``urllib.quote_plus``::
import urllib
params = urllib.quote_plus("DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password")
.. seealso::
- `fast executemany
- <https://github.com/mkleehammer/pyodbc/wiki/Features-beyond-the-DB-API#fast_executemany>`_
+ `fast executemany <https://github.com/mkleehammer/pyodbc/wiki/Features-beyond-the-DB-API#fast_executemany>`_
- on github
-"""
+""" # noqa
-from .base import MSExecutionContext, MSDialect, BINARY, VARBINARY
-from ...connectors.pyodbc import PyODBCConnector
-from ... import types as sqltypes, util, exc
import decimal
import re
+from .base import BINARY
+from .base import MSDialect
+from .base import MSExecutionContext
+from .base import VARBINARY
+from ... import exc
+from ... import types as sqltypes
+from ... import util
+from ...connectors.pyodbc import PyODBCConnector
+
class _ms_numeric_pyodbc(object):
.. dialect:: mssql+zxjdbc
:name: zxJDBC for Jython
:dbapi: zxjdbc
- :connectstring: mssql+zxjdbc://user:pass@host:port/dbname\
-[?key=value&key=value...]
+ :connectstring: mssql+zxjdbc://user:pass@host:port/dbname[?key=value&key=value...]
:driverurl: http://jtds.sourceforge.net/
.. note:: Jython is not supported by current versions of SQLAlchemy. The
zxjdbc dialect should be considered as experimental.
-"""
-from ...connectors.zxJDBC import ZxJDBCConnector
-from .base import MSDialect, MSExecutionContext
+""" # noqa
+from .base import MSDialect
+from .base import MSExecutionContext
from ... import engine
+from ...connectors.zxJDBC import ZxJDBCConnector
class MSExecutionContext_zxjdbc(MSExecutionContext):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import (
- base,
- mysqldb,
- oursql,
- pyodbc,
- zxjdbc,
- mysqlconnector,
- pymysql,
- gaerdbms,
- cymysql,
-)
-
-from .base import (
- BIGINT,
- BINARY,
- BIT,
- BLOB,
- BOOLEAN,
- CHAR,
- DATE,
- DATETIME,
- DECIMAL,
- DOUBLE,
- ENUM,
- DECIMAL,
- FLOAT,
- INTEGER,
- INTEGER,
- JSON,
- LONGBLOB,
- LONGTEXT,
- MEDIUMBLOB,
- MEDIUMINT,
- MEDIUMTEXT,
- NCHAR,
- NVARCHAR,
- NUMERIC,
- SET,
- SMALLINT,
- REAL,
- TEXT,
- TIME,
- TIMESTAMP,
- TINYBLOB,
- TINYINT,
- TINYTEXT,
- VARBINARY,
- VARCHAR,
- YEAR,
-)
+from . import base # noqa
+from . import cymysql # noqa
+from . import gaerdbms # noqa
+from . import mysqlconnector # noqa
+from . import mysqldb # noqa
+from . import oursql # noqa
+from . import pymysql # noqa
+from . import pyodbc # noqa
+from . import zxjdbc # noqa
+from .base import BIGINT
+from .base import BINARY
+from .base import BIT
+from .base import BLOB
+from .base import BOOLEAN
+from .base import CHAR
+from .base import DATE
+from .base import DATETIME
+from .base import DECIMAL
+from .base import DOUBLE
+from .base import ENUM
+from .base import FLOAT
+from .base import INTEGER
+from .base import JSON
+from .base import LONGBLOB
+from .base import LONGTEXT
+from .base import MEDIUMBLOB
+from .base import MEDIUMINT
+from .base import MEDIUMTEXT
+from .base import NCHAR
+from .base import NUMERIC
+from .base import NVARCHAR
+from .base import REAL
+from .base import SET
+from .base import SMALLINT
+from .base import TEXT
+from .base import TIME
+from .base import TIMESTAMP
+from .base import TINYBLOB
+from .base import TINYINT
+from .base import TINYTEXT
+from .base import VARBINARY
+from .base import VARCHAR
+from .base import YEAR
+from .dml import Insert
+from .dml import insert
-from .dml import insert, Insert
# default dialect
base.dialect = dialect = mysqldb.dialect
"VARCHAR",
"YEAR",
"dialect",
+ "insert",
+ "Insert",
)
Transaction Isolation Level
---------------------------
-All MySQL dialects support setting of transaction isolation level
-both via a dialect-specific parameter :paramref:`.create_engine.isolation_level`
-accepted by :func:`.create_engine`,
-as well as the :paramref:`.Connection.execution_options.isolation_level`
-argument as passed to :meth:`.Connection.execution_options`.
-This feature works by issuing the command
-``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for
-each new connection. For the special AUTOCOMMIT isolation level, DBAPI-specific
+All MySQL dialects support setting of transaction isolation level both via a
+dialect-specific parameter :paramref:`.create_engine.isolation_level` accepted
+by :func:`.create_engine`, as well as the
+:paramref:`.Connection.execution_options.isolation_level` argument as passed to
+:meth:`.Connection.execution_options`. This feature works by issuing the
+command ``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for each new
+connection. For the special AUTOCOMMIT isolation level, DBAPI-specific
techniques are used.
To set isolation level using :func:`.create_engine`::
character set encoding is also in place, when the binary data itself is not
valid for that encoding::
- default.py:509: Warning: (1300, "Invalid utf8mb4 character string: 'F9876A'")
+ default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
+ 'F9876A'")
cursor.execute(statement, parameters)
This warning is due to the fact that the MySQL client library is attempting to
-interpret the binary string as a unicode object even if a datatype such as
-:class:`.LargeBinary` is in use. To resolve this, the SQL statement requires
+interpret the binary string as a unicode object even if a datatype such
+as :class:`.LargeBinary` is in use. To resolve this, the SQL statement requires
a binary "character set introducer" be present before any non-NULL value
that renders like this::
INSERT INTO table (data) VALUES (_binary %s)
-These character set introducers are provided by the DBAPI driver, assuming
-the use of mysqlclient or PyMySQL (both of which are recommended). Add the
-query string parameter ``binary_prefix=true`` to the URL to repair this warning::
+These character set introducers are provided by the DBAPI driver, assuming the
+use of mysqlclient or PyMySQL (both of which are recommended). Add the query
+string parameter ``binary_prefix=true`` to the URL to repair this warning::
# mysqlclient
- engine = create_engine("mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
+ engine = create_engine(
+ "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
# PyMySQL
- engine = create_engine("mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
+ engine = create_engine(
+ "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
+
The ``binary_prefix`` flag may or may not be supported by other MySQL drivers.
-SQLAlchemy itself cannot render this ``_binary`` prefix reliably, as it does not
-work with the NULL value, which is valid to be sent as a bound parameter.
+SQLAlchemy itself cannot render this ``_binary`` prefix reliably, as it does
+not work with the NULL value, which is valid to be sent as a bound parameter.
As the MySQL driver renders parameters directly into the SQL string, it's the
most efficient place for this additional keyword to be passed.
Some limited direct support for MySQL extensions to SQL is currently
available.
-* INSERT..ON DUPLICATE KEY UPDATE: See :ref:`mysql_insert_on_duplicate_key_update`
+* INSERT..ON DUPLICATE KEY UPDATE: See
+ :ref:`mysql_insert_on_duplicate_key_update`
* SELECT pragma::
.. seealso::
- `CREATE INDEX <http://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - \
- MySQL documentation
+ `CREATE INDEX <http://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - MySQL documentation
Index Types
~~~~~~~~~~~~~
However, to accommodate the vast majority of MySQL databases that do not
specify this new flag, SQLAlchemy emits the "NULL" specifier explicitly with
-any TIMESTAMP column that does not specify ``nullable=False``. In order
-to accommodate newer databases that specify ``explicit_defaults_for_timestamp``,
+any TIMESTAMP column that does not specify ``nullable=False``. In order to
+accommodate newer databases that specify ``explicit_defaults_for_timestamp``,
SQLAlchemy also emits NOT NULL for TIMESTAMP columns that do specify
``nullable=False``. The following example illustrates::
``explicit_defaults_for_timestamp``. Prior to this version, it will
not render "NOT NULL" for a TIMESTAMP column that is ``nullable=False``.
-"""
+""" # noqa
+from array import array as _array
from collections import defaultdict
import re
import sys
+from . import reflection as _reflection
+from .enumerated import ENUM
+from .enumerated import SET
+from .json import JSON
+from .json import JSONIndexType
+from .json import JSONPathType
+from .types import _FloatType
+from .types import _IntegerType
+from .types import _MatchType
+from .types import _NumericType
+from .types import _StringType
+from .types import BIGINT
+from .types import BIT
+from .types import CHAR
+from .types import DATETIME
+from .types import DECIMAL
+from .types import DOUBLE
+from .types import FLOAT
+from .types import INTEGER
+from .types import LONGBLOB
+from .types import LONGTEXT
+from .types import MEDIUMBLOB
+from .types import MEDIUMINT
+from .types import MEDIUMTEXT
+from .types import NCHAR
+from .types import NUMERIC
+from .types import NVARCHAR
+from .types import REAL
+from .types import SMALLINT
+from .types import TEXT
+from .types import TIME
+from .types import TIMESTAMP
+from .types import TINYBLOB
+from .types import TINYINT
+from .types import TINYTEXT
+from .types import VARCHAR
+from .types import YEAR
+from ... import exc
+from ... import log
from ... import schema as sa_schema
-from ... import exc, log, sql, util
-from ...sql import compiler, elements
-from array import array as _array
-
-from ...engine import reflection
-from ...engine import default
+from ... import sql
from ... import types as sqltypes
+from ... import util
+from ...engine import default
+from ...engine import reflection
+from ...sql import compiler
+from ...sql import elements
+from ...types import BINARY
+from ...types import BLOB
+from ...types import BOOLEAN
+from ...types import DATE
+from ...types import VARBINARY
from ...util import topological
-from ...types import DATE, BOOLEAN, BLOB, BINARY, VARBINARY
-
-from . import reflection as _reflection
-from .types import (
- BIGINT,
- BIT,
- CHAR,
- DECIMAL,
- DATETIME,
- DOUBLE,
- FLOAT,
- INTEGER,
- LONGBLOB,
- LONGTEXT,
- MEDIUMBLOB,
- MEDIUMINT,
- MEDIUMTEXT,
- NCHAR,
- NUMERIC,
- NVARCHAR,
- REAL,
- SMALLINT,
- TEXT,
- TIME,
- TIMESTAMP,
- TINYBLOB,
- TINYINT,
- TINYTEXT,
- VARCHAR,
- YEAR,
-)
-from .types import (
- _StringType,
- _IntegerType,
- _NumericType,
- _FloatType,
- _MatchType,
-)
-from .enumerated import ENUM, SET
-from .json import JSON, JSONIndexType, JSONPathType
RESERVED_WORDS = set(
"SET", type_, type_._enumerated_values
)
- def visit_BOOLEAN(self, type, **kw):
+ def visit_BOOLEAN(self, type_, **kw):
return "BOOL"
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""
+r"""
.. dialect:: mysql+cymysql
:name: CyMySQL
:dbapi: cymysql
- :connectstring: mysql+cymysql://<username>:<password>@<host>/<dbname>\
-[?<options>]
+ :connectstring: mysql+cymysql://<username>:<password>@<host>/<dbname>[?<options>]
:url: https://github.com/nakagami/CyMySQL
-"""
-import re
+""" # noqa
+from .base import BIT
+from .base import MySQLDialect
from .mysqldb import MySQLDialect_mysqldb
-from .base import BIT, MySQLDialect
from ... import util
-from ...sql.elements import ClauseElement
+from ... import exc
+from ... import util
+from ...sql.base import _generative
from ...sql.dml import Insert as StandardInsert
+from ...sql.elements import ClauseElement
from ...sql.expression import alias
from ...util.langhelpers import public_factory
-from ...sql.base import _generative
-from ... import exc
-from ... import util
+
__all__ = ("Insert", "insert")
import re
from .types import _StringType
-from ... import exc, sql, util
+from ... import exc
+from ... import sql
+from ... import util
from ...sql import sqltypes
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
+r"""
.. dialect:: mysql+gaerdbms
:name: Google Cloud SQL
:dbapi: rdbms
:connectstring: mysql+gaerdbms:///<dbname>?instance=<instancename>
- :url: https://developers.google.com/appengine/docs/python/cloud-sql/\
-developers-guide
+ :url: https://developers.google.com/appengine/docs/python/cloud-sql/developers-guide
This dialect is based primarily on the :mod:`.mysql.mysqldb` dialect with
minimal changes.
implementation is installed within the :class:`.Engine` by
default.
-"""
+""" # noqa
import os
+import re
+from sqlalchemy.util import warn_deprecated
from .mysqldb import MySQLDialect_mysqldb
from ...pool import NullPool
-import re
-from sqlalchemy.util import warn_deprecated
def _is_dev_environment():
from __future__ import absolute_import
-from ...sql import elements
from ... import types as sqltypes
-from ... import util
class JSON(sqltypes.JSON):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
+r"""
.. dialect:: mysql+mysqlconnector
:name: MySQL Connector/Python
:dbapi: myconnpy
- :connectstring: mysql+mysqlconnector://<user>:<password>@\
-<host>[:<port>]/<dbname>
+ :connectstring: mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
:url: http://dev.mysql.com/downloads/connector/python/
upstream mysql-connector-python driver or if appropriate usage patterns
are contributed to SQLAlchemy.
-"""
+""" # noqa
-from .base import (
- MySQLDialect,
- MySQLExecutionContext,
- MySQLCompiler,
- MySQLIdentifierPreparer,
- BIT,
-)
-
-from ... import util
import re
+
+from .base import BIT
+from .base import MySQLCompiler
+from .base import MySQLDialect
+from .base import MySQLExecutionContext
+from .base import MySQLIdentifierPreparer
from ... import processors
+from ... import util
class MySQLExecutionContext_mysqlconnector(MySQLExecutionContext):
# hack description encoding since mysqlconnector randomly
# returns bytes or not
- self._description_decoder = processors.to_conditional_unicode_processor_factory(
- self.description_encoding
- )
+ self._description_decoder = (
+ processors.to_conditional_unicode_processor_factory
+ )(self.description_encoding)
def _check_unicode_description(self, connection):
# hack description encoding since mysqlconnector randomly
"""
-from .base import (
- MySQLDialect,
- MySQLExecutionContext,
- MySQLCompiler,
- MySQLIdentifierPreparer,
-)
+import re
+
+from .base import MySQLCompiler
+from .base import MySQLDialect
+from .base import MySQLExecutionContext
+from .base import MySQLIdentifierPreparer
from .base import TEXT
from ... import sql
from ... import util
-import re
class MySQLExecutionContext_mysqldb(MySQLExecutionContext):
"""
-import re
-from .base import BIT, MySQLDialect, MySQLExecutionContext
-from ... import types as sqltypes, util
+from .base import BIT
+from .base import MySQLDialect
+from .base import MySQLExecutionContext
+from ... import types as sqltypes
+from ... import util
class _oursqlBIT(BIT):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
+r"""
.. dialect:: mysql+pymysql
:name: PyMySQL
:dbapi: pymysql
- :connectstring: mysql+pymysql://<username>:<password>@<host>/<dbname>\
-[?<options>]
+ :connectstring: mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
:url: https://pymysql.readthedocs.io/
Unicode
and targets 100% compatibility. Most behavioral notes for MySQL-python apply
to the pymysql driver as well.
-"""
+""" # noqa
from .mysqldb import MySQLDialect_mysqldb
-from ...util import langhelpers, py3k
+from ...util import langhelpers
+from ...util import py3k
class MySQLDialect_pymysql(MySQLDialect_mysqldb):
"""
-from .base import MySQLDialect, MySQLExecutionContext
-from ...connectors.pyodbc import PyODBCConnector
-from ... import util
import re
+from .base import MySQLDialect
+from .base import MySQLExecutionContext
+from ... import util
+from ...connectors.pyodbc import PyODBCConnector
+
class MySQLExecutionContext_pyodbc(MySQLExecutionContext):
def get_lastrowid(self):
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re
-from ... import log, util
+
+from .enumerated import _EnumeratedValues
+from .enumerated import SET
+from .types import DATETIME
+from .types import TIME
+from .types import TIMESTAMP
+from ... import log
from ... import types as sqltypes
-from .enumerated import _EnumeratedValues, SET
-from .types import DATETIME, TIME, TIMESTAMP
+from ... import util
class ReflectedState(object):
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import datetime
-from ... import exc, util
+
+from ... import exc
from ... import types as sqltypes
+from ... import util
class _NumericType(object):
self,
charset=None,
collation=None,
- ascii=False,
+ ascii=False, # noqa
binary=False,
unicode=False,
national=False,
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
+r"""
.. dialect:: mysql+zxjdbc
:name: zxjdbc for Jython
:dbapi: zxjdbc
- :connectstring: mysql+zxjdbc://<user>:<password>@<hostname>[:<port>]/\
-<database>
+ :connectstring: mysql+zxjdbc://<user>:<password>@<hostname>[:<port>]/<database>
:driverurl: http://dev.mysql.com/downloads/connector/j/
.. note:: Jython is not supported by current versions of SQLAlchemy. The
``characterEncoding`` connection property to ``UTF-8``. It may be
overridden via a ``create_engine`` URL parameter.
-"""
+""" # noqa
import re
-from ... import types as sqltypes, util
+from .base import BIT
+from .base import MySQLDialect
+from .base import MySQLExecutionContext
+from ... import types as sqltypes
+from ... import util
from ...connectors.zxJDBC import ZxJDBCConnector
-from .base import BIT, MySQLDialect, MySQLExecutionContext
class _ZxJDBCBit(BIT):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import base, cx_oracle, zxjdbc # noqa
+from . import base # noqa
+from . import cx_oracle # noqa
+from . import zxjdbc # noqa
+from .base import BFILE
+from .base import BINARY_DOUBLE
+from .base import BINARY_FLOAT
+from .base import BLOB
+from .base import CHAR
+from .base import CLOB
+from .base import DATE
+from .base import DOUBLE_PRECISION
+from .base import FLOAT
+from .base import INTERVAL
+from .base import LONG
+from .base import NCLOB
+from .base import NUMBER
+from .base import NVARCHAR
+from .base import NVARCHAR2
+from .base import RAW
+from .base import ROWID
+from .base import TIMESTAMP
+from .base import VARCHAR
+from .base import VARCHAR2
-from .base import (
- VARCHAR,
- NVARCHAR,
- CHAR,
- DATE,
- NUMBER,
- BLOB,
- BFILE,
- BINARY_FLOAT,
- BINARY_DOUBLE,
- CLOB,
- NCLOB,
- TIMESTAMP,
- RAW,
- FLOAT,
- DOUBLE_PRECISION,
- LONG,
- INTERVAL,
- VARCHAR2,
- NVARCHAR2,
- ROWID,
-)
base.dialect = dialect = cx_oracle.dialect
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
+r"""
.. dialect:: oracle
:name: Oracle
.. versionadded:: 1.0.0
-"""
+""" # noqa
+from itertools import groupby
import re
-from sqlalchemy import util, sql
-from sqlalchemy.engine import default, reflection
-from sqlalchemy.sql import compiler, visitors, expression, util as sql_util
-from sqlalchemy.sql import operators as sql_operators
-from sqlalchemy.sql.elements import quoted_name
-from sqlalchemy import types as sqltypes, schema as sa_schema
-from sqlalchemy.types import (
- VARCHAR,
- NVARCHAR,
- CHAR,
- BLOB,
- CLOB,
- TIMESTAMP,
- FLOAT,
- INTEGER,
-)
-from itertools import groupby
+from ... import schema as sa_schema
+from ... import sql
+from ... import types as sqltypes
+from ... import util
+from ...engine import default
+from ...engine import reflection
+from ...sql import compiler
+from ...sql import expression
+from ...sql import util as sql_util
+from ...sql import visitors
+from ...sql.elements import quoted_name
+from ...types import BLOB
+from ...types import CHAR
+from ...types import CLOB
+from ...types import FLOAT
+from ...types import INTEGER
+from ...types import NVARCHAR
+from ...types import TIMESTAMP
+from ...types import VARCHAR
+
RESERVED_WORDS = set(
"SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN "
if util.py2k:
if isinstance(name, str):
name = name.decode(self.encoding)
- if name.upper() == name and not self.identifier_preparer._requires_quotes(
- name.lower()
- ):
+ if name.upper() == name and not (
+ self.identifier_preparer._requires_quotes
+ )(name.lower()):
return name.lower()
elif name.lower() == name:
return quoted_name(name, quote=True)
def denormalize_name(self, name):
if name is None:
return None
- elif name.lower() == name and not self.identifier_preparer._requires_quotes(
- name.lower()
- ):
+ elif name.lower() == name and not (
+ self.identifier_preparer._requires_quotes
+ )(name.lower()):
name = name.upper()
if util.py2k:
if not self.supports_unicode_binds:
name = name.encode(self.encoding)
else:
- name = unicode(name)
+ name = unicode(name) # noqa
return name
def _get_default_schema_name(self, connection):
if not rec["referred_table"]:
if resolve_synonyms:
- ref_remote_name, ref_remote_owner, ref_dblink, ref_synonym = self._resolve_synonym(
+ (
+ ref_remote_name,
+ ref_remote_owner,
+ ref_dblink,
+ ref_synonym,
+ ) = self._resolve_synonym(
connection,
desired_owner=self.denormalize_name(remote_owner),
desired_table=self.denormalize_name(remote_table),
unique_keys = filter(lambda x: x[1] == "U", constraint_data)
uniques_group = groupby(unique_keys, lambda x: x[0])
- index_names = set(
- [
- ix["name"]
- for ix in self.get_indexes(
- connection, table_name, schema=schema
- )
- ]
- )
+ index_names = {
+ ix["name"]
+ for ix in self.get_indexes(connection, table_name, schema=schema)
+ }
return [
{
"name": name,
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
-
+r"""
.. dialect:: oracle+cx_oracle
:name: cx-Oracle
:dbapi: cx_oracle
- :connectstring: oracle+cx_oracle://user:pass@host:port/dbname\
-[?key=value&key=value...]
+ :connectstring: oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
:url: http://cx-oracle.sourceforge.net/
Additional Connect Arguments
within the URL, which includes parameters such as ``mode``, ``purity``,
``events``, ``threaded``, and others::
- e = create_engine("oracle+cx_oracle://user:pass@dsn?mode=SYSDBA&events=true")
+ e = create_engine(
+ "oracle+cx_oracle://user:pass@dsn?mode=SYSDBA&events=true")
.. versionchanged:: 1.3 the cx_oracle dialect now accepts all argument names
within the URL string itself, to be passed to the cx_Oracle DBAPI. As
itself. These options are always passed directly to :func:`.create_engine`,
such as::
- e = create_engine("oracle+cx_oracle://user:pass@dsn", coerce_to_unicode=False)
+ e = create_engine(
+ "oracle+cx_oracle://user:pass@dsn", coerce_to_unicode=False)
The parameters accepted by the cx_oracle dialect are as follows:
.. _cx_oracle_setinputsizes:
-Fine grained control over cx_Oracle data binding and performance with setinputsizes
------------------------------------------------------------------------------------
+Fine grained control over cx_Oracle data binding performance with setinputsizes
+-------------------------------------------------------------------------------
The cx_Oracle DBAPI has a deep and fundamental reliance upon the usage of the
DBAPI ``setinputsizes()`` call. The purpose of this call is to establish the
altering the type coercion behavior at the same time.
Users of the cx_Oracle dialect are **strongly encouraged** to read through
-cx_Oracle's list of built-in datatype symbols at http://cx-oracle.readthedocs.io/en/latest/module.html#types.
-Note that in some cases, signficant performance degradation can occur when using
-these types vs. not, in particular when specifying ``cx_Oracle.CLOB``.
-
-On the SQLAlchemy side, the :meth:`.DialectEvents.do_setinputsizes` event
-can be used both for runtime visibliity (e.g. logging) of the setinputsizes
-step as well as to fully control how ``setinputsizes()`` is used on a per-statement
+cx_Oracle's list of built-in datatype symbols at
+http://cx-oracle.readthedocs.io/en/latest/module.html#types.
+Note that in some cases, signficant performance degradation can occur when
+using these types vs. not, in particular when specifying ``cx_Oracle.CLOB``.
+
+On the SQLAlchemy side, the :meth:`.DialectEvents.do_setinputsizes` event can
+be used both for runtime visibliity (e.g. logging) of the setinputsizes step as
+well as to fully control how ``setinputsizes()`` is used on a per-statement
basis.
.. versionadded:: 1.2.9 Added :meth:`.DialectEvents.setinputsizes`
Example 1 - logging all setinputsizes calls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-The following example illustrates how to log the intermediary values from
-a SQLAlchemy perspective before they are converted to the raw ``setinputsizes()``
+The following example illustrates how to log the intermediary values from a
+SQLAlchemy perspective before they are converted to the raw ``setinputsizes()``
parameter dictionary. The keys of the dictionary are :class:`.BindParameter`
objects which have a ``.key`` and a ``.type`` attribute::
reworked to take advantage of newer cx_Oracle features as well
as better integration of outputtypehandlers.
-"""
+""" # noqa
from __future__ import absolute_import
-from .base import OracleCompiler, OracleDialect, OracleExecutionContext
-from . import base as oracle
-from ...engine import result as _result
-from sqlalchemy import types as sqltypes, util, exc, processors
-from ...util import compat
-import random
import collections
import decimal
+import random
import re
+from . import base as oracle
+from .base import OracleCompiler
+from .base import OracleDialect
+from .base import OracleExecutionContext
+from ... import exc
+from ... import processors
+from ... import types as sqltypes
+from ... import util
+from ...engine import result as _result
+from ...util import compat
+
class _OracleInteger(sqltypes.Integer):
def get_dbapi_type(self, dbapi):
- # see https://github.com/oracle/python-cx_Oracle/issues/208#issuecomment-409715955
+ # see https://github.com/oracle/python-cx_Oracle/issues/
+ # 208#issuecomment-409715955
return int
def _cx_oracle_var(self, dialect, cursor):
for bind, name in self.compiled.bind_names.items():
if name in self.out_parameters:
- type = bind.type
- impl_type = type.dialect_impl(self.dialect)
+ type_ = bind.type
+ impl_type = type_.dialect_impl(self.dialect)
dbapi_type = impl_type.get_dbapi_type(
self.dialect.dbapi
)
"""
- id = random.randint(0, 2 ** 128)
- return (0x1234, "%032x" % id, "%032x" % 9)
+ id_ = random.randint(0, 2 ** 128)
+ return (0x1234, "%032x" % id_, "%032x" % 9)
def do_executemany(self, cursor, statement, parameters, context=None):
if isinstance(parameters, tuple):
.. note:: Jython is not supported by current versions of SQLAlchemy. The
zxjdbc dialect should be considered as experimental.
-"""
+""" # noqa
+import collections
import decimal
import re
-from sqlalchemy import sql, types as sqltypes, util
-from sqlalchemy.connectors.zxJDBC import ZxJDBCConnector
-from sqlalchemy.dialects.oracle.base import (
- OracleCompiler,
- OracleDialect,
- OracleExecutionContext,
-)
-from sqlalchemy.engine import result as _result
-from sqlalchemy.sql import expression
-import collections
+from .base import OracleCompiler
+from .base import OracleDialect
+from .base import OracleExecutionContext
+from ... import sql
+from ... import types as sqltypes
+from ... import util
+from ...connectors.zxJDBC import ZxJDBCConnector
+from ...engine import result as _result
+from ...sql import expression
+
SQLException = zxJDBC = None
Specially handled by OracleReturningDataHandler.
"""
- def __init__(self, type):
- self.type = type
+ def __init__(self, type_):
+ self.type = type_
def __eq__(self, other):
if isinstance(other, ReturningParam):
class OracleReturningDataHandler(OracleDataHandler):
"""zxJDBC DataHandler that specially handles ReturningParam."""
- def setJDBCObject(self, statement, index, object, dbtype=None):
- if type(object) is ReturningParam:
- statement.registerReturnParameter(index, object.type)
+ def setJDBCObject(self, statement, index, object_, dbtype=None):
+ if type(object_) is ReturningParam:
+ statement.registerReturnParameter(index, object_.type)
elif dbtype is None:
OracleDataHandler.setJDBCObject(
- self, statement, index, object
+ self, statement, index, object_
)
else:
OracleDataHandler.setJDBCObject(
- self, statement, index, object, dbtype
+ self, statement, index, object_, dbtype
)
self.DataHandler = OracleReturningDataHandler
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import (
- base,
- psycopg2,
- pg8000,
- pypostgresql,
- pygresql,
- zxjdbc,
- psycopg2cffi,
-) # noqa
+from . import base
+from . import pg8000 # noqa
+from . import psycopg2 # noqa
+from . import psycopg2cffi # noqa
+from . import pygresql # noqa
+from . import pypostgresql # noqa
+from . import zxjdbc # noqa
+from .array import All
+from .array import Any
+from .array import ARRAY
+from .array import array
+from .base import BIGINT
+from .base import BIT
+from .base import BOOLEAN
+from .base import BYTEA
+from .base import CHAR
+from .base import CIDR
+from .base import CreateEnumType
+from .base import DATE
+from .base import DOUBLE_PRECISION
+from .base import DropEnumType
+from .base import ENUM
+from .base import FLOAT
+from .base import INET
+from .base import INTEGER
+from .base import INTERVAL
+from .base import MACADDR
+from .base import MONEY
+from .base import NUMERIC
+from .base import OID
+from .base import REAL
+from .base import REGCLASS
+from .base import SMALLINT
+from .base import TEXT
+from .base import TIME
+from .base import TIMESTAMP
+from .base import TSVECTOR
+from .base import UUID
+from .base import VARCHAR
+from .dml import Insert
+from .dml import insert
+from .ext import aggregate_order_by
+from .ext import array_agg
+from .ext import ExcludeConstraint
+from .hstore import HSTORE
+from .hstore import hstore
+from .json import JSON
+from .json import JSONB
+from .ranges import DATERANGE
+from .ranges import INT4RANGE
+from .ranges import INT8RANGE
+from .ranges import NUMRANGE
+from .ranges import TSRANGE
+from .ranges import TSTZRANGE
-from .base import (
- INTEGER,
- BIGINT,
- SMALLINT,
- VARCHAR,
- CHAR,
- TEXT,
- NUMERIC,
- FLOAT,
- REAL,
- INET,
- CIDR,
- UUID,
- BIT,
- MACADDR,
- MONEY,
- OID,
- REGCLASS,
- DOUBLE_PRECISION,
- TIMESTAMP,
- TIME,
- DATE,
- BYTEA,
- BOOLEAN,
- INTERVAL,
- ENUM,
- TSVECTOR,
- DropEnumType,
- CreateEnumType,
-)
-from .hstore import HSTORE, hstore
-from .json import JSON, JSONB
-from .array import array, ARRAY, Any, All
-from .ext import aggregate_order_by, ExcludeConstraint, array_agg
-from .dml import insert, Insert
-
-from .ranges import (
- INT4RANGE,
- INT8RANGE,
- NUMRANGE,
- DATERANGE,
- TSRANGE,
- TSTZRANGE,
-)
base.dialect = dialect = psycopg2.dialect
"INT8RANGE",
"NUMRANGE",
"DATERANGE",
+ "TSVECTOR",
"TSRANGE",
"TSTZRANGE",
"JSON",
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .base import ischema_names, colspecs
-from ...sql import expression, operators
-from ...sql.base import SchemaEventTarget
+from .base import colspecs
+from .base import ischema_names
from ... import types as sqltypes
+from ...sql import expression
+from ...sql import operators
+
try:
- from uuid import UUID as _python_UUID
+ from uuid import UUID as _python_UUID # noqa
except ImportError:
_python_UUID = None
)
The :class:`.postgresql.ARRAY` type provides all operations defined on the
- core :class:`.types.ARRAY` type, including support for "dimensions", indexed
- access, and simple matching such as :meth:`.types.ARRAY.Comparator.any`
- and :meth:`.types.ARRAY.Comparator.all`. :class:`.postgresql.ARRAY` class also
+ core :class:`.types.ARRAY` type, including support for "dimensions",
+ indexed access, and simple matching such as
+ :meth:`.types.ARRAY.Comparator.any` and
+ :meth:`.types.ARRAY.Comparator.all`. :class:`.postgresql.ARRAY` class also
provides PostgreSQL-specific methods for containment operations, including
:meth:`.postgresql.ARRAY.Comparator.contains`
- :meth:`.postgresql.ARRAY.Comparator.contained_by`,
- and :meth:`.postgresql.ARRAY.Comparator.overlap`, e.g.::
+ :meth:`.postgresql.ARRAY.Comparator.contained_by`, and
+ :meth:`.postgresql.ARRAY.Comparator.overlap`, e.g.::
mytable.c.data.contains([1, 2])
INSERT...ON CONFLICT (Upsert)
------------------------------
-Starting with version 9.5, PostgreSQL allows "upserts" (update or insert)
-of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement.
-A candidate row will only be inserted if that row does not violate
-any unique constraints. In the case of a unique constraint violation,
-a secondary action can occur which can be either "DO UPDATE", indicating
-that the data in the target row should be updated, or "DO NOTHING",
-which indicates to silently skip this row.
+Starting with version 9.5, PostgreSQL allows "upserts" (update or insert) of
+rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement. A
+candidate row will only be inserted if that row does not violate any unique
+constraints. In the case of a unique constraint violation, a secondary action
+can occur which can be either "DO UPDATE", indicating that the data in the
+target row should be updated, or "DO NOTHING", which indicates to silently skip
+this row.
Conflicts are determined using existing unique constraints and indexes. These
constraints may be identified either using their name as stated in DDL,
named constraint or by column inference:
* The :paramref:`.Insert.on_conflict_do_update.index_elements` argument
- specifies a sequence containing string column names, :class:`.Column` objects,
- and/or SQL expression elements, which would identify a unique index::
+ specifies a sequence containing string column names, :class:`.Column`
+ objects, and/or SQL expression elements, which would identify a unique
+ index::
do_update_stmt = insert_stmt.on_conflict_do_update(
index_elements=['id'],
"""
from collections import defaultdict
-import re
import datetime as dt
+import re
-
-from sqlalchemy.sql import elements
-from ... import sql, schema, exc, util
-from ...engine import default, reflection
-from ...sql import compiler, expression
+from ... import exc
+from ... import schema
+from ... import sql
+from ... import util
+from ...engine import default
+from ...engine import reflection
+from ...sql import compiler
+from ...sql import elements
+from ...sql import expression
from ...sql import sqltypes
+from ...types import BIGINT
+from ...types import BOOLEAN
+from ...types import CHAR
+from ...types import DATE
+from ...types import FLOAT
+from ...types import INTEGER
+from ...types import NUMERIC
+from ...types import REAL
+from ...types import SMALLINT
+from ...types import TEXT
+from ...types import VARCHAR
+
try:
- from uuid import UUID as _python_UUID
+ from uuid import UUID as _python_UUID # noqa
except ImportError:
_python_UUID = None
-from sqlalchemy.types import (
- INTEGER,
- BIGINT,
- SMALLINT,
- VARCHAR,
- CHAR,
- TEXT,
- FLOAT,
- NUMERIC,
- DATE,
- BOOLEAN,
- REAL,
-)
AUTOCOMMIT_REGEXP = re.compile(
r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|"
class PGTypeCompiler(compiler.GenericTypeCompiler):
- def visit_TSVECTOR(self, type, **kw):
+ def visit_TSVECTOR(self, type_, **kw):
return "TSVECTOR"
def visit_INET(self, type_, **kw):
for conname, condef, conschema in c.fetchall():
m = re.search(FK_REGEX, condef).groups()
- constrained_columns, referred_schema, referred_table, referred_columns, _, match, _, onupdate, _, ondelete, deferrable, _, initially = (
- m
- )
+ (
+ constrained_columns,
+ referred_schema,
+ referred_table,
+ referred_columns,
+ _,
+ match,
+ _,
+ onupdate,
+ _,
+ ondelete,
+ deferrable,
+ _,
+ initially,
+ ) = m
if deferrable is not None:
deferrable = True if deferrable == "DEFERRABLE" else False
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from ...sql.elements import ClauseElement, _literal_as_binds
+from . import ext
+from ... import util
+from ...sql import schema
+from ...sql.base import _generative
from ...sql.dml import Insert as StandardInsert
+from ...sql.elements import ClauseElement
from ...sql.expression import alias
-from ...sql import schema
from ...util.langhelpers import public_factory
-from ...sql.base import _generative
-from ... import util
-from . import ext
+
__all__ = ("Insert", "insert")
set_=None,
where=None,
):
- """
+ r"""
Specifies a DO UPDATE SET action for ON CONFLICT clause.
Either the ``constraint`` or ``index_elements`` argument is
Additional WHERE criterion that can be used to infer a
conditional target index.
- :param set_:
+ :param set\_:
Required argument. A dictionary or other mapping object
with column names as keys and expressions or literals as values,
specifying the ``SET`` actions to take.
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from ...sql import expression
+from .array import ARRAY
from ...sql import elements
+from ...sql import expression
from ...sql import functions
from ...sql.schema import ColumnCollectionConstraint
-from .array import ARRAY
class aggregate_order_by(expression.ColumnElement):
Defines an EXCLUDE constraint as described in the `postgres
documentation`__.
- __ http://www.postgresql.org/docs/9.0/\
-static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE
- """
+ __ http://www.postgresql.org/docs/9.0/static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE
+
+ """ # noqa
__visit_name__ = "exclude_constraint"
import re
-from .base import ischema_names
from .array import ARRAY
+from .base import ischema_names
from ... import types as sqltypes
+from ... import util
from ...sql import functions as sqlfunc
from ...sql import operators
-from ... import util
+
__all__ = ("HSTORE", "hstore")
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import absolute_import
-from .base import ischema_names, colspecs
+from .base import colspecs
+from .base import ischema_names
from ... import types as sqltypes
-from ...sql import operators
-from ...sql import elements
from ... import util
+from ...sql import operators
+
__all__ = ("JSON", "JSONB")
* Path index operations returning text (the ``#>>`` operator)::
- data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')].astext == \
-'some value'
+ data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')].astext == 'some value'
.. versionchanged:: 1.1 The :meth:`.ColumnElement.cast` operator on
JSON objects now requires that the :attr:`.JSON.Comparator.astext`
:class:`.JSONB`
- """
+ """ # noqa
astext_type = sqltypes.Text()
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""
+r"""
.. dialect:: postgresql+pg8000
:name: pg8000
:dbapi: pg8000
- :connectstring: \
-postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...]
+ :connectstring: postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...]
:url: https://pythonhosted.org/pg8000/
:ref:`psycopg2_isolation_level`
-"""
-from ... import util, exc
+""" # noqa
import decimal
+import re
+
+from .base import _DECIMAL_TYPES
+from .base import _FLOAT_TYPES
+from .base import _INT_TYPES
+from .base import PGCompiler
+from .base import PGDialect
+from .base import PGExecutionContext
+from .base import PGIdentifierPreparer
+from .base import UUID
+from .json import JSON
+from ... import exc
from ... import processors
from ... import types as sqltypes
-from .base import (
- PGDialect,
- PGCompiler,
- PGIdentifierPreparer,
- PGExecutionContext,
- _DECIMAL_TYPES,
- _FLOAT_TYPES,
- _INT_TYPES,
- UUID,
-)
-import re
-from sqlalchemy.dialects.postgresql.json import JSON
+from ... import util
from ...sql.elements import quoted_name
+
try:
- from uuid import UUID as _python_UUID
+ from uuid import UUID as _python_UUID # noqa
except ImportError:
_python_UUID = None
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
r"""
.. dialect:: postgresql+psycopg2
:name: psycopg2
was built. This value can be overridden by passing a pathname to psycopg2,
using ``host`` as an additional keyword argument::
- create_engine("postgresql+psycopg2://user:password@/dbname?\
-host=/var/lib/postgresql")
+ create_engine("postgresql+psycopg2://user:password@/dbname?host=/var/lib/postgresql")
.. seealso::
- `PQconnectdbParams <http://www.postgresql.org/docs/9.1/static/libpq-connect.html#LIBPQ-PQCONNECTDBPARAMS>`_
+ `PQconnectdbParams \
+ <http://www.postgresql.org/docs/9.1/static/libpq-connect.html#LIBPQ-PQCONNECTDBPARAMS>`_
.. _psycopg2_execution_options:
:meth:`.Connection.execution_options`, :meth:`.Executable.execution_options`,
:meth:`.Query.execution_options`, in addition to those not specific to DBAPIs:
-* ``isolation_level`` - Set the transaction isolation level for the lifespan of a
- :class:`.Connection` (can only be set on a connection, not a statement
+* ``isolation_level`` - Set the transaction isolation level for the lifespan
+ of a :class:`.Connection` (can only be set on a connection, not a statement
or query). See :ref:`psycopg2_isolation_level`.
-* ``stream_results`` - Enable or disable usage of psycopg2 server side cursors -
- this feature makes use of "named" cursors in combination with special
- result handling methods so that result rows are not fully buffered.
+* ``stream_results`` - Enable or disable usage of psycopg2 server side
+ cursors - this feature makes use of "named" cursors in combination with
+ special result handling methods so that result rows are not fully buffered.
If ``None`` or not set, the ``server_side_cursors`` option of the
:class:`.Engine` is used.
------------------------------------
Modern versions of psycopg2 include a feature known as
-`Fast Execution Helpers <http://initd.org/psycopg/docs/extras.html#fast-execution-helpers>`_,
+`Fast Execution Helpers \
+<http://initd.org/psycopg/docs/extras.html#fast-execution-helpers>`_,
which have been shown in benchmarking to improve psycopg2's executemany()
performance with INSERTS by multiple orders of magnitude. SQLAlchemy
allows this extension to be used for all ``executemany()`` style calls
is passed directly to ``psycopg2.connect()``, and from SQLAlchemy is passed
using the :paramref:`.create_engine.connect_args` parameter::
- # libpq direct parameter setting;
- # only works for PostgreSQL **9.1 and above**
- engine = create_engine("postgresql://user:pass@host/dbname",
- connect_args={'client_encoding': 'utf8'})
+ engine = create_engine(
+ "postgresql://user:pass@host/dbname",
+ connect_args={'client_encoding': 'utf8'})
# using the query string is equivalent
engine = create_engine("postgresql://user:pass@host/dbname?client_encoding=utf8")
NOTICE logging
---------------
-The psycopg2 dialect will log PostgreSQL NOTICE messages via the
-``sqlalchemy.dialects.postgresql`` logger::
+The psycopg2 dialect will log PostgreSQL NOTICE messages
+via the ``sqlalchemy.dialects.postgresql`` logger::
import logging
logging.getLogger('sqlalchemy.dialects.postgresql').setLevel(logging.INFO)
place within SQLAlchemy's own marshalling logic, and not that of ``psycopg2``
which may be more performant.
-"""
+""" # noqa
from __future__ import absolute_import
-import re
+import decimal
import logging
+import re
-from ... import util, exc
-import decimal
+from .base import _DECIMAL_TYPES
+from .base import _FLOAT_TYPES
+from .base import _INT_TYPES
+from .base import ENUM
+from .base import PGCompiler
+from .base import PGDialect
+from .base import PGExecutionContext
+from .base import PGIdentifierPreparer
+from .base import UUID
+from .hstore import HSTORE
+from .json import JSON
+from .json import JSONB
+from ... import exc
from ... import processors
-from ...engine import result as _result
-from ...sql import expression
from ... import types as sqltypes
-from .base import (
- PGDialect,
- PGCompiler,
- PGIdentifierPreparer,
- PGExecutionContext,
- ENUM,
- _DECIMAL_TYPES,
- _FLOAT_TYPES,
- _INT_TYPES,
- UUID,
-)
-from .hstore import HSTORE
-from .json import JSON, JSONB
+from ... import util
+from ...engine import result as _result
+
try:
- from uuid import UUID as _python_UUID
+ from uuid import UUID as _python_UUID # noqa
except ImportError:
_python_UUID = None
class _PGUUID(UUID):
def bind_processor(self, dialect):
if not self.as_uuid and dialect.use_native_uuid:
- nonetype = type(None)
def process(value):
if value is not None:
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""
+r"""
.. dialect:: postgresql+psycopg2cffi
:name: psycopg2cffi
:dbapi: psycopg2cffi
- :connectstring: \
-postgresql+psycopg2cffi://user:password@host:port/dbname\
-[?key=value&key=value...]
+ :connectstring: postgresql+psycopg2cffi://user:password@host:port/dbname[?key=value&key=value...]
:url: http://pypi.python.org/pypi/psycopg2cffi/
``psycopg2cffi`` is an adaptation of ``psycopg2``, using CFFI for the C
:mod:`sqlalchemy.dialects.postgresql.psycopg2`
-"""
+""" # noqa
from .psycopg2 import PGDialect_psycopg2
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
"""
.. dialect:: postgresql+pygresql
:name: pygresql
:dbapi: pgdb
- :connectstring: postgresql+pygresql://user:password@host:port/dbname\
-[?key=value&key=value...]
+ :connectstring: postgresql+pygresql://user:password@host:port/dbname[?key=value&key=value...]
:url: http://www.pygresql.org/
-"""
+""" # noqa
import decimal
import re
-from ... import exc, processors, util
-from ...types import Numeric, JSON as Json
-from ...sql.elements import Null
-from .base import (
- PGDialect,
- PGCompiler,
- PGIdentifierPreparer,
- _DECIMAL_TYPES,
- _FLOAT_TYPES,
- _INT_TYPES,
- UUID,
-)
+from .base import _DECIMAL_TYPES
+from .base import _FLOAT_TYPES
+from .base import _INT_TYPES
+from .base import PGCompiler
+from .base import PGDialect
+from .base import PGIdentifierPreparer
+from .base import UUID
from .hstore import HSTORE
-from .json import JSON, JSONB
+from .json import JSON
+from .json import JSONB
+from ... import exc
+from ... import processors
+from ... import util
+from ...sql.elements import Null
+from ...types import JSON as Json
+from ...types import Numeric
class _PGNumeric(Numeric):
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
"""
.. dialect:: postgresql+pypostgresql
:name: py-postgresql
:dbapi: pypostgresql
- :connectstring: postgresql+pypostgresql://user:password@host:port/dbname\
-[?key=value&key=value...]
+ :connectstring: postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...]
:url: http://python.projects.pgfoundry.org/
-"""
-from ... import util
-from ... import types as sqltypes
-from .base import PGDialect, PGExecutionContext
+""" # noqa
+
+from .base import PGDialect
+from .base import PGExecutionContext
from ... import processors
+from ... import types as sqltypes
+from ... import util
class PGNumeric(sqltypes.Numeric):
from .base import ischema_names
from ... import types as sqltypes
+
__all__ = ("INT4RANGE", "INT8RANGE", "NUMRANGE")
"""
+from .base import PGDialect
+from .base import PGExecutionContext
from ...connectors.zxJDBC import ZxJDBCConnector
-from .base import PGDialect, PGExecutionContext
class PGExecutionContext_zxjdbc(PGExecutionContext):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import base, pysqlite, pysqlcipher # noqa
+from . import base # noqa
+from . import pysqlcipher # noqa
+from . import pysqlite # noqa
+from .base import BLOB
+from .base import BOOLEAN
+from .base import CHAR
+from .base import DATE
+from .base import DATETIME
+from .base import DECIMAL
+from .base import FLOAT
+from .base import INTEGER
+from .base import JSON
+from .base import NUMERIC
+from .base import REAL
+from .base import SMALLINT
+from .base import TEXT
+from .base import TIME
+from .base import TIMESTAMP
+from .base import VARCHAR
-from sqlalchemy.dialects.sqlite.base import (
- BLOB,
- BOOLEAN,
- CHAR,
- DATE,
- DATETIME,
- DECIMAL,
- FLOAT,
- INTEGER,
- JSON,
- REAL,
- NUMERIC,
- SMALLINT,
- TEXT,
- TIME,
- TIMESTAMP,
- VARCHAR,
-)
# default dialect
base.dialect = dialect = pysqlite.dialect
.. seealso::
- `Type Affinity <http://www.sqlite.org/datatype3.html#affinity>`_ - in the SQLite documentation
+ `Type Affinity <http://www.sqlite.org/datatype3.html#affinity>`_ -
+ in the SQLite documentation
.. _sqlite_autoincrement:
Allowing autoincrement behavior SQLAlchemy types other than Integer/INTEGER
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-SQLite's typing model is based on naming conventions. Among
-other things, this means that any type name which contains the
-substring ``"INT"`` will be determined to be of "integer affinity". A
-type named ``"BIGINT"``, ``"SPECIAL_INT"`` or even ``"XYZINTQPR"``, will be considered by
-SQLite to be of "integer" affinity. However, **the SQLite
-autoincrement feature, whether implicitly or explicitly enabled,
-requires that the name of the column's type
-is exactly the string "INTEGER"**. Therefore, if an
-application uses a type like :class:`.BigInteger` for a primary key, on
-SQLite this type will need to be rendered as the name ``"INTEGER"`` when
-emitting the initial ``CREATE TABLE`` statement in order for the autoincrement
-behavior to be available.
+SQLite's typing model is based on naming conventions. Among other things, this
+means that any type name which contains the substring ``"INT"`` will be
+determined to be of "integer affinity". A type named ``"BIGINT"``,
+``"SPECIAL_INT"`` or even ``"XYZINTQPR"``, will be considered by SQLite to be
+of "integer" affinity. However, **the SQLite autoincrement feature, whether
+implicitly or explicitly enabled, requires that the name of the column's type
+is exactly the string "INTEGER"**. Therefore, if an application uses a type
+like :class:`.BigInteger` for a primary key, on SQLite this type will need to
+be rendered as the name ``"INTEGER"`` when emitting the initial ``CREATE
+TABLE`` statement in order for the autoincrement behavior to be available.
One approach to achieve this is to use :class:`.Integer` on SQLite
only using :meth:`.TypeEngine.with_variant`::
Column("id", BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
)
-Another is to use a subclass of :class:`.BigInteger` that overrides its DDL name
-to be ``INTEGER`` when compiled against SQLite::
+Another is to use a subclass of :class:`.BigInteger` that overrides its DDL
+name to be ``INTEGER`` when compiled against SQLite::
from sqlalchemy import BigInteger
from sqlalchemy.ext.compiler import compiles
----------------------------
SQLite supports "transaction isolation" in a non-standard way, along two
-axes. One is that of the `PRAGMA read_uncommitted <http://www.sqlite.org/pragma.html#pragma_read_uncommitted>`_
+axes. One is that of the
+`PRAGMA read_uncommitted <http://www.sqlite.org/pragma.html#pragma_read_uncommitted>`_
instruction. This setting can essentially switch SQLite between its
default mode of ``SERIALIZABLE`` isolation, and a "dirty read" isolation
mode normally referred to as ``READ UNCOMMITTED``.
1
Therefore, the workaround applied by SQLAlchemy only impacts
-:meth:`.ResultProxy.keys` and :meth:`.RowProxy.keys()` in the public API.
-In the very specific case where
-an application is forced to use column names that contain dots, and the
-functionality of :meth:`.ResultProxy.keys` and :meth:`.RowProxy.keys()`
-is required to return these dotted names unmodified, the ``sqlite_raw_colnames``
-execution option may be provided, either on a per-:class:`.Connection` basis::
+:meth:`.ResultProxy.keys` and :meth:`.RowProxy.keys()` in the public API. In
+the very specific case where an application is forced to use column names that
+contain dots, and the functionality of :meth:`.ResultProxy.keys` and
+:meth:`.RowProxy.keys()` is required to return these dotted names unmodified,
+the ``sqlite_raw_colnames`` execution option may be provided, either on a
+per-:class:`.Connection` basis::
result = conn.execution_options(sqlite_raw_colnames=True).execute('''
select x.a, x.b from x where a=1
When using the per-:class:`.Engine` execution option, note that
**Core and ORM queries that use UNION may not function properly**.
-"""
+""" # noqa
import datetime
import re
+from .json import JSON
+from .json import JSONIndexType
+from .json import JSONPathType
+from ... import exc
from ... import processors
-from ... import sql, exc
-from ... import types as sqltypes, schema as sa_schema
+from ... import schema as sa_schema
+from ... import sql
+from ... import types as sqltypes
from ... import util
-from ...engine import default, reflection
+from ...engine import default
+from ...engine import reflection
from ...sql import compiler
-
-from ...types import (
- BLOB,
- BOOLEAN,
- CHAR,
- DECIMAL,
- FLOAT,
- INTEGER,
- REAL,
- NUMERIC,
- SMALLINT,
- TEXT,
- TIMESTAMP,
- VARCHAR,
-)
-from .json import JSON, JSONIndexType, JSONPathType
+from ...types import BLOB # noqa
+from ...types import BOOLEAN # noqa
+from ...types import CHAR # noqa
+from ...types import DECIMAL # noqa
+from ...types import FLOAT # noqa
+from ...types import INTEGER # noqa
+from ...types import NUMERIC # noqa
+from ...types import REAL # noqa
+from ...types import SMALLINT # noqa
+from ...types import TEXT # noqa
+from ...types import TIMESTAMP # noqa
+from ...types import VARCHAR # noqa
class _DateTimeMixin(object):
is called with positional arguments via
``*map(int, match_obj.groups(0))``.
- """
+ """ # noqa
_storage_format = (
"%(year)04d-%(month)02d-%(day)02d "
def bind_processor(self, dialect):
datetime_datetime = datetime.datetime
datetime_date = datetime.date
- format = self._storage_format
+ format_ = self._storage_format
def process(value):
if value is None:
return None
elif isinstance(value, datetime_datetime):
- return format % {
+ return format_ % {
"year": value.year,
"month": value.month,
"day": value.day,
"microsecond": value.microsecond,
}
elif isinstance(value, datetime_date):
- return format % {
+ return format_ % {
"year": value.year,
"month": value.month,
"day": value.day,
def bind_processor(self, dialect):
datetime_date = datetime.date
- format = self._storage_format
+ format_ = self._storage_format
def process(value):
if value is None:
return None
elif isinstance(value, datetime_date):
- return format % {
+ return format_ % {
"year": value.year,
"month": value.month,
"day": value.day,
def bind_processor(self, dialect):
datetime_time = datetime.time
- format = self._storage_format
+ format_ = self._storage_format
def process(value):
if value is None:
return None
elif isinstance(value, datetime_time):
- return format % {
+ return format_ % {
"hour": value.hour,
"minute": value.minute,
"second": value.second,
Driver
------
-The driver here is the `pysqlcipher <https://pypi.python.org/pypi/pysqlcipher>`_
+The driver here is the
+`pysqlcipher <https://pypi.python.org/pypi/pysqlcipher>`_
driver, which makes use of the SQLCipher engine. This system essentially
introduces new PRAGMA commands to SQLite which allows the setting of a
passphrase and other encryption parameters, allowing the database
time, at the expense of slower startup time for new connections.
-"""
+""" # noqa
+
from __future__ import absolute_import
+
from .pysqlite import SQLiteDialect_pysqlite
-from ...engine import url as _url
from ... import pool
+from ...engine import url as _url
class SQLiteDialect_pysqlcipher(SQLiteDialect_pysqlite):
scope is to begin, we emit ``"BEGIN"`` ourselves.
When we take control of ``"BEGIN"``, we can also control directly SQLite's
-locking modes, introduced at `BEGIN TRANSACTION <http://sqlite.org/lang_transaction.html>`_,
+locking modes, introduced at
+`BEGIN TRANSACTION <http://sqlite.org/lang_transaction.html>`_,
by adding the desired locking mode to our ``"BEGIN"``::
@event.listens_for(engine, "begin")
.. seealso::
- `BEGIN TRANSACTION <http://sqlite.org/lang_transaction.html>`_ - on the SQLite site
+ `BEGIN TRANSACTION <http://sqlite.org/lang_transaction.html>`_ -
+ on the SQLite site
- `sqlite3 SELECT does not BEGIN a transaction <http://bugs.python.org/issue9924>`_ - on the Python bug tracker
+ `sqlite3 SELECT does not BEGIN a transaction <http://bugs.python.org/issue9924>`_ -
+ on the Python bug tracker
- `sqlite3 module breaks transactions and potentially corrupts data <http://bugs.python.org/issue10740>`_ - on the Python bug tracker
+ `sqlite3 module breaks transactions and potentially corrupts data <http://bugs.python.org/issue10740>`_ -
+ on the Python bug tracker
-"""
-
-from sqlalchemy.dialects.sqlite.base import SQLiteDialect, DATETIME, DATE
-from sqlalchemy import exc, pool
-from sqlalchemy import types as sqltypes
-from sqlalchemy import util
+""" # noqa
import os
+from .base import DATE
+from .base import DATETIME
+from .base import SQLiteDialect
+from ... import exc
+from ... import pool
+from ... import types as sqltypes
+from ... import util
+
class _SQLite_pysqliteTimeStamp(DATETIME):
def bind_processor(self, dialect):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import base, pysybase, pyodbc # noqa
+from . import base # noqa
+from . import pyodbc # noqa
+from . import pysybase # noqa
+from .base import BIGINT
+from .base import BINARY
+from .base import BIT
+from .base import CHAR
+from .base import DATE
+from .base import DATETIME
+from .base import FLOAT
+from .base import IMAGE
+from .base import INT
+from .base import INTEGER
+from .base import MONEY
+from .base import NCHAR
+from .base import NUMERIC
+from .base import NVARCHAR
+from .base import SMALLINT
+from .base import SMALLMONEY
+from .base import TEXT
+from .base import TIME
+from .base import TINYINT
+from .base import UNICHAR
+from .base import UNITEXT
+from .base import UNIVARCHAR
+from .base import VARBINARY
+from .base import VARCHAR
-from .base import (
- CHAR,
- VARCHAR,
- TIME,
- NCHAR,
- NVARCHAR,
- TEXT,
- DATE,
- DATETIME,
- FLOAT,
- NUMERIC,
- BIGINT,
- INT,
- INTEGER,
- SMALLINT,
- BINARY,
- VARBINARY,
- UNITEXT,
- UNICHAR,
- UNIVARCHAR,
- IMAGE,
- BIT,
- MONEY,
- SMALLMONEY,
- TINYINT,
-)
# default dialect
base.dialect = dialect = pyodbc.dialect
caveats not currently handled.
"""
-import operator
+
import re
-from sqlalchemy.sql import compiler, expression, text, bindparam
-from sqlalchemy.engine import default, base, reflection
-from sqlalchemy import types as sqltypes
-from sqlalchemy.sql import operators as sql_operators
+from sqlalchemy import exc
from sqlalchemy import schema as sa_schema
-from sqlalchemy import util, sql, exc
-
-from sqlalchemy.types import (
- CHAR,
- VARCHAR,
- TIME,
- NCHAR,
- NVARCHAR,
- TEXT,
- DATE,
- DATETIME,
- FLOAT,
- NUMERIC,
- BIGINT,
- INT,
- INTEGER,
- SMALLINT,
- BINARY,
- VARBINARY,
- DECIMAL,
- TIMESTAMP,
- Unicode,
- UnicodeText,
- REAL,
-)
+from sqlalchemy import types as sqltypes
+from sqlalchemy import util
+from sqlalchemy.engine import default
+from sqlalchemy.engine import reflection
+from sqlalchemy.sql import compiler
+from sqlalchemy.sql import text
+from sqlalchemy.types import BIGINT
+from sqlalchemy.types import BINARY
+from sqlalchemy.types import CHAR
+from sqlalchemy.types import DATE
+from sqlalchemy.types import DATETIME
+from sqlalchemy.types import DECIMAL
+from sqlalchemy.types import FLOAT
+from sqlalchemy.types import INT # noqa
+from sqlalchemy.types import INTEGER
+from sqlalchemy.types import NCHAR
+from sqlalchemy.types import NUMERIC
+from sqlalchemy.types import NVARCHAR
+from sqlalchemy.types import REAL
+from sqlalchemy.types import SMALLINT
+from sqlalchemy.types import TEXT
+from sqlalchemy.types import TIME
+from sqlalchemy.types import TIMESTAMP
+from sqlalchemy.types import Unicode
+from sqlalchemy.types import VARBINARY
+from sqlalchemy.types import VARCHAR
+
RESERVED_WORDS = set(
[
)
if util.py2k:
- if isinstance(schema, unicode):
+ if isinstance(schema, unicode): # noqa
schema = schema.encode("ascii")
- if isinstance(table_name, unicode):
+ if isinstance(table_name, unicode): # noqa
table_name = table_name.encode("ascii")
result = connection.execute(
TABLEID_SQL, schema_name=schema, table_name=table_name
type_,
nullable,
autoincrement,
- default,
+ default_,
precision,
scale,
length,
type_,
bool(nullable),
bool(autoincrement),
- default,
+ default_,
precision,
scale,
length,
)
if util.py2k:
- if isinstance(schema, unicode):
+ if isinstance(schema, unicode): # noqa
schema = schema.encode("ascii")
tables = connection.execute(TABLE_SQL, schema_name=schema)
)
if util.py2k:
- if isinstance(view_name, unicode):
+ if isinstance(view_name, unicode): # noqa
view_name = view_name.encode("ascii")
view = connection.execute(VIEW_DEF_SQL, view_name=view_name)
)
if util.py2k:
- if isinstance(schema, unicode):
+ if isinstance(schema, unicode): # noqa
schema = schema.encode("ascii")
views = connection.execute(VIEW_SQL, schema_name=schema)
"""
+from sqlalchemy.connectors.mxodbc import MxODBCConnector
from sqlalchemy.dialects.sybase.base import SybaseDialect
from sqlalchemy.dialects.sybase.base import SybaseExecutionContext
-from sqlalchemy.connectors.mxodbc import MxODBCConnector
class SybaseExecutionContext_mxodbc(SybaseExecutionContext):
.. dialect:: sybase+pyodbc
:name: PyODBC
:dbapi: pyodbc
- :connectstring: sybase+pyodbc://<username>:<password>@<dsnname>\
-[/<database>]
+ :connectstring: sybase+pyodbc://<username>:<password>@<dsnname>[/<database>]
:url: http://pypi.python.org/pypi/pyodbc/
UNITEXT
UNIVARCHAR
-"""
+""" # noqa
-from sqlalchemy.dialects.sybase.base import (
- SybaseDialect,
- SybaseExecutionContext,
-)
-from sqlalchemy.connectors.pyodbc import PyODBCConnector
-from sqlalchemy import types as sqltypes, processors
import decimal
+from sqlalchemy import processors
+from sqlalchemy import types as sqltypes
+from sqlalchemy.connectors.pyodbc import PyODBCConnector
+from sqlalchemy.dialects.sybase.base import SybaseDialect
+from sqlalchemy.dialects.sybase.base import SybaseExecutionContext
+
class _SybNumeric_pyodbc(sqltypes.Numeric):
"""Turns Decimals with adjusted() < -6 into floats.
.. dialect:: sybase+pysybase
:name: Python-Sybase
:dbapi: Sybase
- :connectstring: sybase+pysybase://<username>:<password>@<dsn>/\
-[database name]
+ :connectstring: sybase+pysybase://<username>:<password>@<dsn>/[database name]
:url: http://python-sybase.sourceforge.net/
Unicode Support
The python-sybase driver does not appear to support non-ASCII strings of any
kind at this time.
-"""
+""" # noqa
-from sqlalchemy import types as sqltypes, processors
-from sqlalchemy.dialects.sybase.base import (
- SybaseDialect,
- SybaseExecutionContext,
- SybaseSQLCompiler,
-)
+from sqlalchemy import processors
+from sqlalchemy import types as sqltypes
+from sqlalchemy.dialects.sybase.base import SybaseDialect
+from sqlalchemy.dialects.sybase.base import SybaseExecutionContext
+from sqlalchemy.dialects.sybase.base import SybaseSQLCompiler
class _SybNumeric(sqltypes.Numeric):
within a URL.
"""
-from .interfaces import (
- Connectable,
- CreateEnginePlugin,
- Dialect,
- ExecutionContext,
- ExceptionContext,
- # backwards compat
- Compiled,
- TypeCompiler,
-)
-
-from .base import (
- Connection,
- Engine,
- NestedTransaction,
- RootTransaction,
- Transaction,
- TwoPhaseTransaction,
-)
-
-from .result import (
- BaseRowProxy,
- BufferedColumnResultProxy,
- BufferedColumnRow,
- BufferedRowResultProxy,
- FullyBufferedResultProxy,
- ResultProxy,
- RowProxy,
-)
-
-from .util import connection_memoize
-
-
-from . import util, strategies
+from . import strategies
+from . import util # noqa
+from .base import Connection # noqa
+from .base import Engine # noqa
+from .base import NestedTransaction # noqa
+from .base import RootTransaction # noqa
+from .base import Transaction # noqa
+from .base import TwoPhaseTransaction # noqa
+from .interfaces import Compiled # noqa
+from .interfaces import Connectable # noqa
+from .interfaces import CreateEnginePlugin # noqa
+from .interfaces import Dialect # noqa
+from .interfaces import ExceptionContext # noqa
+from .interfaces import ExecutionContext # noqa
+from .interfaces import TypeCompiler # noqa
+from .result import BaseRowProxy # noqa
+from .result import BufferedColumnResultProxy # noqa
+from .result import BufferedColumnRow # noqa
+from .result import BufferedRowResultProxy # noqa
+from .result import FullyBufferedResultProxy # noqa
+from .result import ResultProxy # noqa
+from .result import RowProxy # noqa
+from .util import connection_memoize # noqa
+from ..sql import ddl # noqa
+
# backwards compat
-from ..sql import ddl
default_strategy = "plain"
Behavior here varies per backend, and
individual dialects should be consulted directly.
- Note that the isolation level can also be set on a per-:class:`.Connection`
- basis as well, using the
+ Note that the isolation level can also be set on a
+ per-:class:`.Connection` basis as well, using the
:paramref:`.Connection.execution_options.isolation_level`
feature.
``(sql, *multiparams, **params)``, to which the ``mock`` strategy will
dispatch all statement execution. Used only by ``strategy='mock'``.
- """
+ """ # noqa
strategy = kwargs.pop("strategy", default_strategy)
strategy = strategies.strategies[strategy]
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import with_statement
-"""Defines :class:`.Connection` and :class:`.Engine`.
+import contextlib
+import sys
-"""
+from .interfaces import Connectable
+from .interfaces import ExceptionContext
+from .util import _distill_params
+from .. import exc
+from .. import interfaces
+from .. import log
+from .. import util
+from ..sql import schema
+from ..sql import util as sql_util
-import sys
-from .. import exc, util, log, interfaces
-from ..sql import util as sql_util
-from ..sql import schema
-from .interfaces import Connectable, ExceptionContext
-from .util import _distill_params
-import contextlib
+"""Defines :class:`.Connection` and :class:`.Engine`.
+
+"""
class Connection(Connectable):
def __enter__(self):
return self
- def __exit__(self, type, value, traceback):
+ def __exit__(self, type_, value, traceback):
self.close()
def execution_options(self, **opt):
:ref:`schema_translating`
- """
+ """ # noqa
c = self._clone()
c._execution_options = c._execution_options.union(opt)
if self._has_events or self.engine._has_events:
self.__can_reconnect = False
self.__transaction = None
- def scalar(self, object, *multiparams, **params):
+ def scalar(self, object_, *multiparams, **params):
"""Executes and returns the first column of the first row.
The underlying result/cursor is closed after execution.
"""
- return self.execute(object, *multiparams, **params).scalar()
+ return self.execute(object_, *multiparams, **params).scalar()
- def execute(self, object, *multiparams, **params):
+ def execute(self, object_, *multiparams, **params):
r"""Executes a SQL statement construct and returns a
:class:`.ResultProxy`.
DBAPI-agnostic way, use the :func:`~.expression.text` construct.
"""
- if isinstance(object, util.string_types[0]):
- return self._execute_text(object, multiparams, params)
+ if isinstance(object_, util.string_types[0]):
+ return self._execute_text(object_, multiparams, params)
try:
- meth = object._execute_on_connection
+ meth = object_._execute_on_connection
except AttributeError:
- raise exc.ObjectNotExecutableError(object)
+ raise exc.ObjectNotExecutableError(object_)
else:
return meth(self, multiparams, params)
def __enter__(self):
return self
- def __exit__(self, type, value, traceback):
- if type is None and self.is_active:
+ def __exit__(self, type_, value, traceback):
+ if type_ is None and self.is_active:
try:
self.commit()
except:
def __enter__(self):
return self.conn
- def __exit__(self, type, value, traceback):
- if type is not None:
+ def __exit__(self, type_, value, traceback):
+ if type_ is not None:
self.transaction.rollback()
else:
self.transaction.commit()
"""
-import re
-import random
-from . import reflection, interfaces, result
-from ..sql import compiler, expression, schema
-from .. import types as sqltypes
-from .. import exc, util, pool, processors
import codecs
+import random
+import re
import weakref
+
+from . import interfaces
+from . import reflection
+from . import result
from .. import event
+from .. import exc
+from .. import pool
+from .. import processors
+from .. import types as sqltypes
+from .. import util
+from ..sql import compiler
+from ..sql import expression
+from ..sql import schema
+
AUTOCOMMIT_REGEXP = re.compile(
r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER)", re.I | re.UNICODE
self.label_length = label_length
if self.description_encoding == "use_encoding":
- self._description_decoder = processors.to_unicode_processor_factory(
- encoding
- )
+ self._description_decoder = (
+ processors.to_unicode_processor_factory
+ )(encoding)
elif self.description_encoding is not None:
- self._description_decoder = processors.to_unicode_processor_factory(
- self.description_encoding
- )
+ self._description_decoder = (
+ processors.to_unicode_processor_factory
+ )(self.description_encoding)
self._encoder = codecs.getencoder(self.encoding)
self._decoder = processors.to_unicode_processor_factory(self.encoding)
"""Define core interfaces used by the engine system."""
from .. import util
-
-# backwards compat
-from ..sql.compiler import Compiled, TypeCompiler
+from ..sql.compiler import Compiled # noqa
+from ..sql.compiler import TypeCompiler # noqa
class Dialect(object):
raise NotImplementedError()
- def execute(self, object, *multiparams, **params):
+ def execute(self, object_, *multiparams, **params):
"""Executes the given construct and returns a :class:`.ResultProxy`."""
raise NotImplementedError()
- def scalar(self, object, *multiparams, **params):
+ def scalar(self, object_, *multiparams, **params):
"""Executes and returns the first column of the first row.
The underlying cursor is closed after execution.
'name' attribute..
"""
-from .. import exc, sql
-from ..sql import schema as sa_schema
+from .base import Connectable
+from .. import exc
+from .. import inspection
+from .. import sql
from .. import util
+from ..sql import schema as sa_schema
from ..sql.type_api import TypeEngine
from ..util import deprecated
from ..util import topological
-from .. import inspection
-from .base import Connectable
@util.decorator
and :class:`.RowProxy."""
-from .. import exc, util
-from ..sql import expression, sqltypes, util as sql_util
import collections
import operator
+from .. import exc
+from .. import util
+from ..sql import expression
+from ..sql import sqltypes
+from ..sql import util as sql_util
+
+
# This reconstructor is necessary so that pickles with the C extension or
# without use the same Binary format.
try:
obj,
untranslated,
)
- for idx, colname, mapped_type, coltype, obj, untranslated in raw_iterator
+ for (
+ idx,
+ colname,
+ mapped_type,
+ coltype,
+ obj,
+ untranslated,
+ ) in raw_iterator
]
def _colnames_from_description(self, context, cursor_description):
return d
def _key_fallback(self, key, raiseerr=True):
- map = self._keymap
+ map_ = self._keymap
result = None
if isinstance(key, util.string_types):
- result = map.get(key if self.case_sensitive else key.lower())
+ result = map_.get(key if self.case_sensitive else key.lower())
# fallback for targeting a ColumnElement to a textual expression
# this is a rare use case which only occurs when matching text()
# or colummn('name') constructs to ColumnElements, or after a
if (
key._label
and (key._label if self.case_sensitive else key._label.lower())
- in map
+ in map_
):
- result = map[
+ result = map_[
key._label if self.case_sensitive else key._label.lower()
]
elif (
hasattr(key, "name")
and (key.name if self.case_sensitive else key.name.lower())
- in map
+ in map_
):
# match is only on name.
- result = map[
+ result = map_[
key.name if self.case_sensitive else key.name.lower()
]
# search extra hard to make sure this
else:
return None
else:
- map[key] = result
+ map_[key] = result
return result
def _has_key(self, key):
from operator import attrgetter
-from sqlalchemy.engine import base, threadlocal, url
-from sqlalchemy import util, event
-from sqlalchemy import pool as poollib
-from sqlalchemy.sql import schema
+from . import base
+from . import threadlocal
+from . import url
+from .. import event
+from .. import pool as poollib
+from .. import util
+from ..sql import schema
+
strategies = {}
element
)
- def execute(self, object, *multiparams, **params):
+ def execute(self, object_, *multiparams, **params):
raise NotImplementedError()
engine strategy is used.
"""
-from .. import util
-from . import base
import weakref
+from . import base
+from .. import util
+
class TLConnection(base.Connection):
def __init__(self, *arg, **kw):
def __enter__(self):
return self
- def __exit__(self, type, value, traceback):
- if type is None:
+ def __exit__(self, type_, value, traceback):
+ if type_ is None:
self.commit()
else:
self.rollback()
"""
import re
-from .. import exc, util
-from . import Dialect
-from ..dialects import registry, plugins
+
+from .interfaces import Dialect
+from .. import exc
+from .. import util
+from ..dialects import plugins
+from ..dialects import registry
class URL(object):
def py_fallback():
- def _distill_params(multiparams, params):
- """Given arguments from the calling form *multiparams, **params,
+ def _distill_params(multiparams, params): # noqa
+ r"""Given arguments from the calling form \*multiparams, \**params,
return a list of bind parameter structures, usually a list of
dictionaries.
try:
- from sqlalchemy.cutils import _distill_params
+ from sqlalchemy.cutils import _distill_params # noqa
except ImportError:
globals().update(py_fallback())
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .api import CANCEL, NO_RETVAL, listen, listens_for, remove, contains
-from .base import Events, dispatcher
-from .attr import RefCollection
-from .legacy import _legacy_signature
+from .api import CANCEL # noqa
+from .api import contains # noqa
+from .api import listen # noqa
+from .api import listens_for # noqa
+from .api import NO_RETVAL # noqa
+from .api import remove # noqa
+from .attr import RefCollection # noqa
+from .base import dispatcher # noqa
+from .base import Events # noqa
+from .legacy import _legacy_signature # noqa
"""
from __future__ import absolute_import
-from .. import util, exc
from .base import _registrars
from .registry import _EventKey
+from .. import exc
+from .. import util
+
CANCEL = util.symbol("CANCEL")
NO_RETVAL = util.symbol("NO_RETVAL")
"""
-from __future__ import absolute_import, with_statement
+from __future__ import absolute_import
+from __future__ import with_statement
+
+import collections
+from itertools import chain
+import weakref
+
+from . import legacy
+from . import registry
from .. import exc
from .. import util
from ..util import threading
-from . import registry
-from . import legacy
-from itertools import chain
-import weakref
-import collections
class RefCollection(util.MemoizedSlots):
import weakref
+from .attr import _ClsLevelDispatch
+from .attr import _EmptyListener
+from .attr import _JoinedListener
from .. import util
-from .attr import _ClsLevelDispatch, _EmptyListener, _JoinedListener
+
_registrars = util.defaultdict(list)
from __future__ import absolute_import
-import weakref
import collections
import types
-from .. import exc, util
+import weakref
+
+from .. import exc
+from .. import util
_key_to_collection = collections.defaultdict(dict)
self, propagate=False, insert=False, named=False, retval=None
):
- target, identifier, fn = (
- self.dispatch_target,
- self.identifier,
- self._listen_fn,
- )
+ target, identifier = self.dispatch_target, self.identifier
dispatch_collection = getattr(target.dispatch, identifier)
"""Core event interfaces."""
-from . import event, exc
+from . import event
+from . import exc
+from .engine import Connectable
+from .engine import Dialect
+from .engine import Engine
from .pool import Pool
-from .engine import Connectable, Engine, Dialect
from .sql.base import SchemaEventTarget
:meth:`.ConnectionEvents.handle_error` hook.
.. versionchanged:: 1.1 The :meth:`.handle_error` event will now
- receive all exceptions that inherit from ``BaseException``, including
- ``SystemExit`` and ``KeyboardInterrupt``. The setting for
- :attr:`.ExceptionContext.is_disconnect` is ``True`` in this case
- and the default for :attr:`.ExceptionContext.invalidate_pool_on_disconnect`
- is ``False``.
+ receive all exceptions that inherit from ``BaseException``,
+ including ``SystemExit`` and ``KeyboardInterrupt``. The setting for
+ :attr:`.ExceptionContext.is_disconnect` is ``True`` in this case and
+ the default for
+ :attr:`.ExceptionContext.invalidate_pool_on_disconnect` is
+ ``False``.
.. versionchanged:: 1.0.0 The :meth:`.handle_error` event is now
invoked when an :class:`.Engine` fails during the initial
@classmethod
def _listen(cls, event_key, retval=False):
- target, identifier, fn = (
- event_key.dispatch_target,
- event_key.identifier,
- event_key.fn,
- )
+ target = event_key.dispatch_target
target._has_events = True
event_key.base_listen()
invalidate_pool = True
-class TimeoutError(SQLAlchemyError):
+class TimeoutError(SQLAlchemyError): # noqa
"""Raised when a connection pool times out on getting a connection."""
from .. import util as _sa_util
+
_sa_util.dependencies.resolve_all("sqlalchemy.ext")
"""
import operator
-from .. import exc, orm, util
-from ..orm import collections, interfaces
+
+from .. import exc
+from .. import inspect
+from .. import orm
+from .. import util
+from ..orm import collections
+from ..orm import interfaces
from ..sql import or_
from ..sql.operators import ColumnOperators
-from .. import inspect
def association_proxy(target_collection, attr, **kw):
.. versionadded:: 1.3
- """
+ """ # noqa
def __init__(self, parent, owning_class, target_class, value_attr):
self.parent = parent
def _initialize_scalar_accessors(self):
if self.parent.getset_factory:
- get, set = self.parent.getset_factory(None, self)
+ get, set_ = self.parent.getset_factory(None, self)
else:
- get, set = self.parent._default_getset(None)
- self._scalar_get, self._scalar_set = get, set
+ get, set_ = self.parent._default_getset(None)
+ self._scalar_get, self._scalar_set = get, set_
def _default_getset(self, collection_class):
attr = self.value_attr
def _create(self, value):
return self.creator(value)
- def _get(self, object):
- return self.getter(object)
+ def _get(self, object_):
+ return self.getter(object_)
- def _set(self, object, value):
- return self.setter(object, value)
+ def _set(self, object_, value):
+ return self.setter(object_, value)
def __getitem__(self, index):
if not isinstance(index, slice):
def _create(self, key, value):
return self.creator(key, value)
- def _get(self, object):
- return self.getter(object)
+ def _get(self, object_):
+ return self.getter(object_)
- def _set(self, object, key, value):
- return self.setter(object, key, value)
+ def _set(self, object_, key, value):
+ return self.setter(object_, key, value)
def __getitem__(self, key):
return self._get(self.col[key])
def _create(self, value):
return self.creator(value)
- def _get(self, object):
- return self.getter(object)
+ def _get(self, object_):
+ return self.getter(object_)
def __len__(self):
return len(self.col)
we've declared are in an un-mapped state.
-"""
+""" # noqa
from .declarative import declarative_base as _declarative_base
from .declarative.base import _DeferredMapperConfig
-from ..sql import and_
-from ..schema import ForeignKeyConstraint
-from ..orm import relationship, backref, interfaces
-from ..orm.mapper import _CONFIGURE_MUTEX
from .. import util
+from ..orm import backref
+from ..orm import interfaces
+from ..orm import relationship
+from ..orm.mapper import _CONFIGURE_MUTEX
+from ..schema import ForeignKeyConstraint
+from ..sql import and_
def classname_for_table(base, tablename, table):
"""
-from ..orm.query import Query
-from ..orm import strategy_options
-from ..orm.session import Session
-from ..sql import util as sql_util, func, literal_column
-from ..orm import exc as orm_exc
+import copy
+import logging
+
from .. import exc as sa_exc
from .. import util
+from ..orm import exc as orm_exc
+from ..orm import strategy_options
+from ..orm.query import Query
+from ..orm.session import Session
+from ..sql import func
+from ..sql import literal_column
+from ..sql import util as sql_util
-import copy
-import logging
log = logging.getLogger(__name__)
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .api import (
- declarative_base,
- synonym_for,
- comparable_using,
- instrument_declarative,
- ConcreteBase,
- AbstractConcreteBase,
- DeclarativeMeta,
- DeferredReflection,
- has_inherited_table,
- declared_attr,
- as_declarative,
-)
+from .api import AbstractConcreteBase
+from .api import as_declarative
+from .api import comparable_using
+from .api import ConcreteBase
+from .api import declarative_base
+from .api import DeclarativeMeta
+from .api import declared_attr
+from .api import DeferredReflection
+from .api import has_inherited_table
+from .api import instrument_declarative
+from .api import synonym_for
__all__ = [
"""Public API functions and helpers for declarative."""
-from ...schema import Table, MetaData, Column
-from ...orm import (
- synonym as _orm_synonym,
- comparable_property,
- interfaces,
- properties,
- attributes,
-)
-from ...orm.util import polymorphic_union
-from ...orm.base import _mapper_or_none
-from ...util import OrderedDict, hybridmethod, hybridproperty
-from ... import util
-from ... import exc
-import weakref
import re
+import weakref
-from .base import (
- _as_declarative,
- _declarative_constructor,
- _DeferredMapperConfig,
- _add_attribute,
- _del_attribute,
-)
+from .base import _add_attribute
+from .base import _as_declarative
+from .base import _declarative_constructor
+from .base import _DeferredMapperConfig
+from .base import _del_attribute
from .clsregistry import _class_resolver
+from ... import exc
+from ... import util
+from ...orm import attributes
+from ...orm import comparable_property
+from ...orm import interfaces
+from ...orm import properties
+from ...orm import synonym as _orm_synonym
+from ...orm.base import _mapper_or_none
+from ...orm.util import polymorphic_union
+from ...schema import MetaData
+from ...schema import Table
+from ...util import hybridmethod
+from ...util import hybridproperty
+from ...util import OrderedDict
def instrument_declarative(cls, registry, metadata):
@declared_attr.cascading
def id(cls):
if has_inherited_table(cls):
- return Column(ForeignKey('myclass.id'), primary_key=True)
+ return Column(
+ ForeignKey('myclass.id'), primary_key=True)
else:
return Column(Integer, primary_key=True)
compatible callable to use as the meta type of the generated
declarative base class.
- .. versionchanged:: 1.1 if :paramref:`.declarative_base.cls` is a single class (rather
- than a tuple), the constructed base class will inherit its docstring.
+ .. versionchanged:: 1.1 if :paramref:`.declarative_base.cls` is a
+ single class (rather than a tuple), the constructed base class will
+ inherit its docstring.
.. seealso::
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Internal implementation for declarative."""
-from ...schema import Table, Column
-from ...orm import mapper, class_mapper, synonym
-from ...orm.interfaces import MapperProperty
-from ...orm.properties import ColumnProperty, CompositeProperty
-from ...orm.attributes import QueryableAttribute
-from ...orm.base import _is_mapped_class, InspectionAttr
-from ... import util, exc
-from ...util import topological
-from ...sql import expression
-from ... import event
-from . import clsregistry
import collections
import weakref
+
from sqlalchemy.orm import instrumentation
+from . import clsregistry
+from ... import event
+from ... import exc
+from ... import util
+from ...orm import class_mapper
+from ...orm import mapper
+from ...orm import synonym
+from ...orm.attributes import QueryableAttribute
+from ...orm.base import _is_mapped_class
+from ...orm.base import InspectionAttr
+from ...orm.interfaces import MapperProperty
+from ...orm.properties import ColumnProperty
+from ...orm.properties import CompositeProperty
+from ...schema import Column
+from ...schema import Table
+from ...sql import expression
+from ...util import topological
+
declared_attr = declarative_props = None
# make a copy of it so a class-level dictionary
# is not overwritten when we update column-based
# arguments.
- mapper_args_fn = lambda: dict(
- cls.__mapper_args__
- ) # noqa
+ def mapper_args_fn():
+ return dict(cls.__mapper_args__)
+
elif name == "__tablename__":
check_decl = _check_declared_props_nocascade(
obj, name, cls
# defined attribute here to allow a clean
# override, if there's another
# subclass below then it still tries to use
- # this. not sure if there is enough information
- # here to add this as a feature later on.
+ # this. not sure if there is enough
+ # information here to add this as a feature
+ # later on.
util.warn(
"Attribute '%s' on class %s cannot be "
"processed due to "
:func:`.relationship` using strings.
"""
-from ...orm.properties import (
- ColumnProperty,
- RelationshipProperty,
- SynonymProperty,
-)
-from ...schema import _get_table_key
-from ...orm import class_mapper, interfaces
-from ... import util
-from ... import inspection
-from ... import exc
import weakref
+from ... import exc
+from ... import inspection
+from ... import util
+from ...orm import class_mapper
+from ...orm import interfaces
+from ...orm.properties import ColumnProperty
+from ...orm.properties import RelationshipProperty
+from ...orm.properties import SynonymProperty
+from ...schema import _get_table_key
+
+
# strong references to registries which we place in
# the _decl_class_registry, which is usually weak referencing.
# the internal registries here link to classes with weakrefs and remove
from .. import inspect
from .. import util
-from ..orm.session import Session
from ..orm.query import Query
+from ..orm.session import Session
+
__all__ = ["ShardedSession", "ShardedQuery"]
any descriptor-based expression system.
Consider a mapping ``Interval``, representing integer ``start`` and ``end``
-values. We can define higher level functions on mapped classes that produce
-SQL expressions at the class level, and Python expression evaluation at the
+values. We can define higher level functions on mapped classes that produce SQL
+expressions at the class level, and Python expression evaluation at the
instance level. Below, each function decorated with :class:`.hybrid_method` or
:class:`.hybrid_property` may receive ``self`` as an instance of the class, or
as the class itself::
.. note:: The :meth:`.hybrid_property.comparator` decorator introduced
in this section **replaces** the use of the
- :meth:`.hybrid_property.expression` decorator. They cannot be used together.
+ :meth:`.hybrid_property.expression` decorator.
+ They cannot be used together.
The example class below allows case-insensitive comparisons on the attribute
named ``word_insensitive``::
``FirstNameOnly.name`` to repurpose its getter and setter for the subclass.
When overriding :meth:`.hybrid_property.expression` and
-:meth:`.hybrid_property.comparator` alone as the first reference
-to the superclass, these names conflict
-with the same-named accessors on the class-level :class:`.QueryableAttribute`
-object returned at the class level. To override these methods when
-referring directly to the parent class descriptor, add
-the special qualifier :attr:`.hybrid_property.overrides`, which will
-de-reference the instrumented attribute back to the hybrid object::
+:meth:`.hybrid_property.comparator` alone as the first reference to the
+superclass, these names conflict with the same-named accessors on the class-
+level :class:`.QueryableAttribute` object returned at the class level. To
+override these methods when referring directly to the parent class descriptor,
+add the special qualifier :attr:`.hybrid_property.overrides`, which will de-
+reference the instrumented attribute back to the hybrid object::
class FirstNameLastName(FirstNameOnly):
# ...
Hybrid Value Objects
--------------------
-Note in our previous example, if we were to compare the
-``word_insensitive`` attribute of a ``SearchWord`` instance to a plain
-Python string, the plain Python string would not be coerced to lower
-case - the ``CaseInsensitiveComparator`` we built, being returned by
+Note in our previous example, if we were to compare the ``word_insensitive``
+attribute of a ``SearchWord`` instance to a plain Python string, the plain
+Python string would not be coerced to lower case - the
+``CaseInsensitiveComparator`` we built, being returned by
``@word_insensitive.comparator``, only applies to the SQL side.
-A more comprehensive form of the custom comparator is to construct a
-*Hybrid Value Object*. This technique applies the target value or
-expression to a value object which is then returned by the accessor in
-all cases. The value object allows control of all operations upon
-the value as well as how compared values are treated, both on the SQL
-expression side as well as the Python value side. Replacing the
-previous ``CaseInsensitiveComparator`` class with a new
+A more comprehensive form of the custom comparator is to construct a *Hybrid
+Value Object*. This technique applies the target value or expression to a value
+object which is then returned by the accessor in all cases. The value object
+allows control of all operations upon the value as well as how compared values
+are treated, both on the SQL expression side as well as the Python value side.
+Replacing the previous ``CaseInsensitiveComparator`` class with a new
``CaseInsensitiveWord`` class::
class CaseInsensitiveWord(Comparator):
key = 'word'
"Label to apply to Query tuple results"
-Above, the ``CaseInsensitiveWord`` object represents ``self.word``,
-which may be a SQL function, or may be a Python native. By
-overriding ``operate()`` and ``__clause_element__()`` to work in terms
-of ``self.word``, all comparison operations will work against the
-"converted" form of ``word``, whether it be SQL side or Python side.
-Our ``SearchWord`` class can now deliver the ``CaseInsensitiveWord``
-object unconditionally from a single hybrid call::
+Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may
+be a SQL function, or may be a Python native. By overriding ``operate()`` and
+``__clause_element__()`` to work in terms of ``self.word``, all comparison
+operations will work against the "converted" form of ``word``, whether it be
+SQL side or Python side. Our ``SearchWord`` class can now deliver the
+``CaseInsensitiveWord`` object unconditionally from a single hybrid call::
class SearchWord(Base):
__tablename__ = 'searchword'
def word_insensitive(self):
return CaseInsensitiveWord(self.word)
-The ``word_insensitive`` attribute now has case-insensitive comparison
-behavior universally, including SQL expression vs. Python expression
-(note the Python value is converted to lower case on the Python side
-here)::
+The ``word_insensitive`` attribute now has case-insensitive comparison behavior
+universally, including SQL expression vs. Python expression (note the Python
+value is converted to lower case on the Python side here)::
>>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks")
SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
>>> print ws1.word_insensitive
someword
-The Hybrid Value pattern is very useful for any kind of value that may
-have multiple representations, such as timestamps, time deltas, units
-of measurement, currencies and encrypted passwords.
+The Hybrid Value pattern is very useful for any kind of value that may have
+multiple representations, such as timestamps, time deltas, units of
+measurement, currencies and encrypted passwords.
.. seealso::
Building Transformers
----------------------
-A *transformer* is an object which can receive a :class:`.Query`
-object and return a new one. The :class:`.Query` object includes a
-method :meth:`.with_transformation` that returns a new :class:`.Query`
-transformed by the given function.
+A *transformer* is an object which can receive a :class:`.Query` object and
+return a new one. The :class:`.Query` object includes a method
+:meth:`.with_transformation` that returns a new :class:`.Query` transformed by
+the given function.
We can combine this with the :class:`.Comparator` class to produce one type
of recipe which can both set up the FROM clause of a query as well as assign
filtering criterion.
-Consider a mapped class ``Node``, which assembles using adjacency list
-into a hierarchical tree pattern::
+Consider a mapped class ``Node``, which assembles using adjacency list into a
+hierarchical tree pattern::
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
parent_id = Column(Integer, ForeignKey('node.id'))
parent = relationship("Node", remote_side=id)
-Suppose we wanted to add an accessor ``grandparent``. This would
-return the ``parent`` of ``Node.parent``. When we have an instance of
-``Node``, this is simple::
+Suppose we wanted to add an accessor ``grandparent``. This would return the
+``parent`` of ``Node.parent``. When we have an instance of ``Node``, this is
+simple::
from sqlalchemy.ext.hybrid import hybrid_property
def grandparent(self):
return self.parent.parent
-For the expression, things are not so clear. We'd need to construct
-a :class:`.Query` where we :meth:`~.Query.join` twice along
-``Node.parent`` to get to the ``grandparent``. We can instead return
-a transforming callable that we'll combine with the
-:class:`.Comparator` class to receive any :class:`.Query` object, and
-return a new one that's joined to the ``Node.parent`` attribute and
-filtered based on the given criterion::
+For the expression, things are not so clear. We'd need to construct a
+:class:`.Query` where we :meth:`~.Query.join` twice along ``Node.parent`` to
+get to the ``grandparent``. We can instead return a transforming callable
+that we'll combine with the :class:`.Comparator` class to receive any
+:class:`.Query` object, and return a new one that's joined to the
+``Node.parent`` attribute and filtered based on the given criterion::
from sqlalchemy.ext.hybrid import Comparator
def grandparent(cls):
return GrandparentTransformer(cls)
-The ``GrandparentTransformer`` overrides the core
-:meth:`.Operators.operate` method at the base of the
-:class:`.Comparator` hierarchy to return a query-transforming
-callable, which then runs the given comparison operation in a
-particular context. Such as, in the example above, the ``operate``
-method is called, given the :attr:`.Operators.eq` callable as well as
-the right side of the comparison ``Node(id=5)``. A function
-``transform`` is then returned which will transform a :class:`.Query`
-first to join to ``Node.parent``, then to compare ``parent_alias``
-using :attr:`.Operators.eq` against the left and right sides, passing
-into :class:`.Query.filter`:
+The ``GrandparentTransformer`` overrides the core :meth:`.Operators.operate`
+method at the base of the :class:`.Comparator` hierarchy to return a query-
+transforming callable, which then runs the given comparison operation in a
+particular context. Such as, in the example above, the ``operate`` method is
+called, given the :attr:`.Operators.eq` callable as well as the right side of
+the comparison ``Node(id=5)``. A function ``transform`` is then returned which
+will transform a :class:`.Query` first to join to ``Node.parent``, then to
+compare ``parent_alias`` using :attr:`.Operators.eq` against the left and right
+sides, passing into :class:`.Query.filter`:
.. sourcecode:: pycon+sql
WHERE :param_1 = node_1.parent_id
{stop}
-We can modify the pattern to be more verbose but flexible by separating
-the "join" step from the "filter" step. The tricky part here is ensuring
-that successive instances of ``GrandparentTransformer`` use the same
+We can modify the pattern to be more verbose but flexible by separating the
+"join" step from the "filter" step. The tricky part here is ensuring that
+successive instances of ``GrandparentTransformer`` use the same
:class:`.AliasedClass` object against ``Node``. Below we use a simple
-memoizing approach that associates a ``GrandparentTransformer``
-with each class::
+memoizing approach that associates a ``GrandparentTransformer`` with each
+class::
class Node(Base):
WHERE :param_1 = node_1.parent_id
{stop}
-The "transformer" pattern is an experimental pattern that starts
-to make usage of some functional programming paradigms.
-While it's only recommended for advanced and/or patient developers,
-there's probably a whole lot of amazing things it can be used for.
+The "transformer" pattern is an experimental pattern that starts to make usage
+of some functional programming paradigms. While it's only recommended for
+advanced and/or patient developers, there's probably a whole lot of amazing
+things it can be used for.
-"""
+""" # noqa
from .. import util
-from ..orm import attributes, interfaces
+from ..orm import attributes
+from ..orm import interfaces
+
HYBRID_METHOD = util.symbol("HYBRID_METHOD")
"""Symbol indicating an :class:`InspectionAttr` that's
rules.
-
-
-
-
Subclassing
===========
FROM person
WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s
-"""
+""" # noqa
from __future__ import absolute_import
from sqlalchemy import inspect
-from ..orm.attributes import flag_modified
from ..ext.hybrid import hybrid_property
+from ..orm.attributes import flag_modified
__all__ = ["index_property"]
being used to determine class instrumentation resolution.
"""
-from ..orm import instrumentation as orm_instrumentation
-from ..orm.instrumentation import (
- ClassManager,
- InstrumentationFactory,
- _default_state_getter,
- _default_dict_getter,
- _default_manager_getter,
-)
-from ..orm import attributes, collections, base as orm_base
+import weakref
+
from .. import util
+from ..orm import attributes
+from ..orm import base as orm_base
+from ..orm import collections
from ..orm import exc as orm_exc
-import weakref
+from ..orm import instrumentation as orm_instrumentation
+from ..orm.instrumentation import _default_dict_getter
+from ..orm.instrumentation import _default_manager_getter
+from ..orm.instrumentation import _default_state_getter
+from ..orm.instrumentation import ClassManager
+from ..orm.instrumentation import InstrumentationFactory
+
INSTRUMENTATION_MANAGER = "__sa_instrumentation_manager__"
"""Attribute, elects custom instrumentation when present on a mapped class.
:meth:`MutableBase._parents` collection is restored to all ``Point`` objects.
"""
+import weakref
+
+from .. import event
+from .. import types
+from ..orm import Mapper
+from ..orm import mapper
+from ..orm import object_mapper
from ..orm.attributes import flag_modified
-from .. import event, types
-from ..orm import mapper, object_mapper, Mapper
-from ..util import memoized_property
from ..sql.base import SchemaEventTarget
-import weakref
+from ..util import memoized_property
class MutableBase(object):
if not attrs or listen_keys.intersection(attrs):
load(state)
- def set(target, value, oldvalue, initiator):
+ def set_(target, value, oldvalue, initiator):
"""Listen for set/replace events on the target
data member.
parent_cls, "refresh_flush", load_attrs, raw=True, propagate=True
)
event.listen(
- attribute, "set", set, raw=True, retval=True, propagate=True
+ attribute, "set", set_, raw=True, retval=True, propagate=True
)
event.listen(parent_cls, "pickle", pickle, raw=True, propagate=True)
event.listen(
"""
-from ..orm.collections import collection, collection_adapter
from .. import util
+from ..orm.collections import collection
+from ..orm.collections import collection_adapter
+
__all__ = ["ordering_list"]
"""
+import re
+
+from .. import Column
+from .. import Table
+from ..engine import Engine
from ..orm import class_mapper
-from ..orm.session import Session
-from ..orm.mapper import Mapper
-from ..orm.interfaces import MapperProperty
from ..orm.attributes import QueryableAttribute
-from .. import Table, Column
-from ..engine import Engine
-from ..util import pickle, byte_buffer, b64encode, b64decode, text_type
-import re
+from ..orm.interfaces import MapperProperty
+from ..orm.mapper import Mapper
+from ..orm.session import Session
+from ..util import b64decode
+from ..util import b64encode
+from ..util import byte_buffer
+from ..util import pickle
+from ..util import text_type
__all__ = ["Serializer", "Deserializer", "dumps", "loads"]
if isinstance(obj, QueryableAttribute):
cls = obj.impl.class_
key = obj.impl.key
- id = "attribute:" + key + ":" + b64encode(pickle.dumps(cls))
+ id_ = "attribute:" + key + ":" + b64encode(pickle.dumps(cls))
elif isinstance(obj, Mapper) and not obj.non_primary:
- id = "mapper:" + b64encode(pickle.dumps(obj.class_))
+ id_ = "mapper:" + b64encode(pickle.dumps(obj.class_))
elif isinstance(obj, MapperProperty) and not obj.parent.non_primary:
- id = (
+ id_ = (
"mapperprop:"
+ b64encode(pickle.dumps(obj.parent.class_))
+ ":"
+ obj.key
)
elif isinstance(obj, Table):
- id = "table:" + text_type(obj.key)
+ id_ = "table:" + text_type(obj.key)
elif isinstance(obj, Column) and isinstance(obj.table, Table):
- id = (
+ id_ = (
"column:" + text_type(obj.table.key) + ":" + text_type(obj.key)
)
elif isinstance(obj, Session):
- id = "session:"
+ id_ = "session:"
elif isinstance(obj, Engine):
- id = "engine:"
+ id_ = "engine:"
else:
return None
- return id
+ return id_
pickler.persistent_id = persistent_id
return pickler
else:
return None
- def persistent_load(id):
- m = our_ids.match(text_type(id))
+ def persistent_load(id_):
+ m = our_ids.match(text_type(id_))
if not m:
return None
else:
"""
-from . import util, exc
+from . import exc
+from . import util
+
_registrars = util.defaultdict(list)
"""
-from . import event, util
+from . import event
+from . import util
class PoolListener(object):
import logging
import sys
+
# set initial level to WARN. This so that
# log statements don't occur in the absence of explicit
# logging being enabled for 'sqlalchemy'.
'debug' -> logging.DEBUG
True -> logging.INFO
- False -> Effective level of underlying logger
- (logging.WARNING by default)
+ False -> Effective level of underlying logger (
+ logging.WARNING by default)
None -> same as False
"""
"""
-from . import exc
-from .mapper import (
- Mapper,
- _mapper_registry,
- class_mapper,
- configure_mappers,
- reconstructor,
- validates,
-)
-from .interfaces import EXT_CONTINUE, EXT_STOP, EXT_SKIP, PropComparator
-from .deprecated_interfaces import (
- MapperExtension,
- SessionExtension,
- AttributeExtension,
-)
-from .util import (
- aliased,
- join,
- object_mapper,
- outerjoin,
- polymorphic_union,
- was_deleted,
- with_parent,
- with_polymorphic,
-)
-from .properties import ColumnProperty
-from .relationships import RelationshipProperty
-from .descriptor_props import (
- ComparableProperty,
- CompositeProperty,
- SynonymProperty,
-)
-from .relationships import foreign, remote
-from .session import (
- Session,
- object_session,
- sessionmaker,
- make_transient,
- make_transient_to_detached,
-)
-from .scoping import scoped_session
-from . import mapper as mapperlib
-from .query import AliasOption, Query, Bundle
-from ..util.langhelpers import public_factory
-from .. import util as _sa_util
-from . import strategies as _strategies
+from . import exc # noqa
+from . import mapper as mapperlib # noqa
+from . import strategy_options
+from .deprecated_interfaces import AttributeExtension # noqa
+from .deprecated_interfaces import MapperExtension # noqa
+from .deprecated_interfaces import SessionExtension # noqa
+from .descriptor_props import ComparableProperty # noqa
+from .descriptor_props import CompositeProperty # noqa
+from .descriptor_props import SynonymProperty # noqa
+from .interfaces import EXT_CONTINUE # noqa
+from .interfaces import EXT_SKIP # noqa
+from .interfaces import EXT_STOP # noqa
+from .interfaces import PropComparator # noqa
+from .mapper import _mapper_registry
+from .mapper import class_mapper # noqa
+from .mapper import configure_mappers # noqa
+from .mapper import Mapper # noqa
+from .mapper import reconstructor # noqa
+from .mapper import validates # noqa
+from .properties import ColumnProperty # noqa
+from .query import AliasOption # noqa
+from .query import Bundle # noqa
+from .query import Query # noqa
+from .relationships import foreign # noqa
+from .relationships import RelationshipProperty # noqa
+from .relationships import remote # noqa
+from .scoping import scoped_session # noqa
+from .session import make_transient # noqa
+from .session import make_transient_to_detached # noqa
+from .session import object_session # noqa
+from .session import Session # noqa
+from .session import sessionmaker # noqa
+from .strategy_options import Load # noqa
+from .util import aliased # noqa
+from .util import join # noqa
+from .util import object_mapper # noqa
+from .util import outerjoin # noqa
+from .util import polymorphic_union # noqa
+from .util import was_deleted # noqa
+from .util import with_parent # noqa
+from .util import with_polymorphic # noqa
from .. import sql as _sql
+from .. import util as _sa_util
+from ..util.langhelpers import public_factory
def create_session(bind=None, **kwargs):
mapperlib._CONFIGURE_MUTEX.release()
-from . import strategy_options
-
joinedload = strategy_options.joinedload._unbound_fn
joinedload_all = strategy_options.joinedload._unbound_all_fn
contains_eager = strategy_options.contains_eager._unbound_fn
defaultload = strategy_options.defaultload._unbound_fn
selectin_polymorphic = strategy_options.selectin_polymorphic._unbound_fn
-from .strategy_options import Load
-
def eagerload(*args, **kwargs):
"""A synonym for :func:`joinedload()`."""
def __go(lcls):
global __all__
- from .. import util as sa_util
- from . import dynamic
- from . import events
- from . import loading
+ from .. import util as sa_util # noqa
+ from . import dynamic # noqa
+ from . import events # noqa
+ from . import loading # noqa
import inspect as _inspect
__all__ = sorted(
"""
import operator
-from .. import util, event, inspection
-from . import interfaces, collections, exc as orm_exc
-
-from .base import instance_state, instance_dict, manager_of_class
-
-from .base import (
- PASSIVE_NO_RESULT,
- ATTR_WAS_SET,
- ATTR_EMPTY,
- NO_VALUE,
- NEVER_SET,
- NO_CHANGE,
- CALLABLES_OK,
- SQL_OK,
- RELATED_OBJECT_OK,
- INIT_OK,
- NON_PERSISTENT_OK,
- LOAD_AGAINST_COMMITTED,
- PASSIVE_OFF,
- PASSIVE_RETURN_NEVER_SET,
- PASSIVE_NO_INITIALIZE,
- PASSIVE_NO_FETCH,
- PASSIVE_NO_FETCH_RELATED,
- PASSIVE_ONLY_PERSISTENT,
- NO_AUTOFLUSH,
- NO_RAISE,
-)
-from .base import state_str, instance_str
+
+from . import collections
+from . import exc as orm_exc
+from . import interfaces
+from .base import ATTR_EMPTY
+from .base import ATTR_WAS_SET
+from .base import CALLABLES_OK
+from .base import INIT_OK
+from .base import instance_dict
+from .base import instance_state
+from .base import instance_str
+from .base import LOAD_AGAINST_COMMITTED
+from .base import manager_of_class
+from .base import NEVER_SET
+from .base import NO_AUTOFLUSH
+from .base import NO_CHANGE # noqa
+from .base import NO_RAISE
+from .base import NO_VALUE
+from .base import NON_PERSISTENT_OK # noqa
+from .base import PASSIVE_NO_FETCH
+from .base import PASSIVE_NO_FETCH_RELATED # noqa
+from .base import PASSIVE_NO_INITIALIZE
+from .base import PASSIVE_NO_RESULT
+from .base import PASSIVE_OFF
+from .base import PASSIVE_ONLY_PERSISTENT
+from .base import PASSIVE_RETURN_NEVER_SET
+from .base import RELATED_OBJECT_OK # noqa
+from .base import SQL_OK # noqa
+from .base import state_str
+from .. import event
+from .. import inspection
+from .. import util
@inspection._self_inspects
"""
-from .. import util, inspection, exc as sa_exc
-from ..sql import expression
-from . import exc
import operator
+from . import exc
+from .. import exc as sa_exc
+from .. import inspection
+from .. import util
+from ..sql import expression
+
+
PASSIVE_NO_RESULT = util.symbol(
"PASSIVE_NO_RESULT",
"""Symbol returned by a loader callable or other attribute/history
"""
-import inspect
import operator
import weakref
-from ..sql import expression
-from .. import util, exc as sa_exc
+from sqlalchemy.util.compat import inspect_getargspec
from . import base
+from .. import exc as sa_exc
+from .. import util
+from ..sql import expression
-from sqlalchemy.util.compat import inspect_getargspec
__all__ = [
"collection",
"""
-from .. import sql, util, exc as sa_exc
-from . import attributes, exc, sync, unitofwork, util as mapperutil
-from .interfaces import ONETOMANY, MANYTOONE, MANYTOMANY
+from . import attributes
+from . import exc
+from . import sync
+from . import unitofwork
+from . import util as mapperutil
+from .interfaces import MANYTOMANY
+from .interfaces import MANYTOONE
+from .interfaces import ONETOMANY
+from .. import exc as sa_exc
+from .. import sql
+from .. import util
class DependencyProcessor(object):
)
result = connection.execute(statement, secondary_delete)
- if result.supports_sane_multi_rowcount() and result.rowcount != len(
- secondary_delete
- ):
+ if (
+ result.supports_sane_multi_rowcount()
+ ) and result.rowcount != len(secondary_delete):
raise exc.StaleDataError(
"DELETE statement on table '%s' expected to delete "
"%d row(s); Only %d were matched."
)
result = connection.execute(statement, secondary_update)
- if result.supports_sane_multi_rowcount() and result.rowcount != len(
- secondary_update
- ):
+ if (
+ result.supports_sane_multi_rowcount()
+ ) and result.rowcount != len(secondary_update):
raise exc.StaleDataError(
"UPDATE statement on table '%s' expected to update "
"%d row(s); Only %d were matched."
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .. import event, util
from .interfaces import EXT_CONTINUE
+from .. import event
+from .. import util
@util.langhelpers.dependency_for("sqlalchemy.orm.interfaces")
"""
-from .interfaces import MapperProperty, PropComparator
-from .util import _none_set
from . import attributes
-from .. import util, sql, exc as sa_exc, event, schema
-from ..sql import expression
from . import properties
from . import query
+from .interfaces import MapperProperty
+from .interfaces import PropComparator
+from .util import _none_set
+from .. import event
+from .. import exc as sa_exc
+from .. import schema
+from .. import sql
+from .. import util
+from ..sql import expression
class DescriptorProperty(MapperProperty):
return self.comparator_factory(self, mapper)
class CompositeBundle(query.Bundle):
- def __init__(self, property, expr):
- self.property = property
+ def __init__(self, property_, expr):
+ self.property = property_
super(CompositeProperty.CompositeBundle, self).__init__(
- property.key, *expr
+ property_.key, *expr
)
def create_row_processor(self, query, procs, labels):
"""
-from .. import log, util, exc
-from ..sql import operators
-from . import (
- attributes,
- object_session,
- util as orm_util,
- strategies,
- object_mapper,
- exc as orm_exc,
- properties,
-)
+from . import attributes
+from . import exc as orm_exc
+from . import object_mapper
+from . import object_session
+from . import properties
+from . import strategies
+from . import util as orm_util
from .query import Query
+from .. import exc
+from .. import log
+from .. import util
@log.class_logger
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import operator
-from ..sql import operators
+
from .. import inspect
from .. import util
+from ..sql import operators
class UnevaluatableError(Exception):
"""ORM event interfaces.
"""
-from .. import event, exc, util
-from .base import _mapper_or_none
-import inspect
import weakref
+
+from . import instrumentation
from . import interfaces
-from . import mapperlib, instrumentation
-from .session import Session, sessionmaker
-from .scoping import scoped_session
+from . import mapperlib
from .attributes import QueryableAttribute
+from .base import _mapper_or_none
from .query import Query
-from sqlalchemy.util.compat import inspect_getargspec
+from .scoping import scoped_session
+from .session import Session
+from .session import sessionmaker
+from .. import event
+from .. import exc
+from .. import util
+from ..util.compat import inspect_getargspec
class InstrumentationEvents(event.Events):
class AttributeEvents(event.Events):
- """Define events for object attributes.
+ r"""Define events for object attributes.
These are typically defined on the class-bound descriptor for the
target class.
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""SQLAlchemy ORM exceptions."""
-from .. import exc as sa_exc, util
+from .. import exc as sa_exc
+from .. import util
+
NO_STATE = (AttributeError, KeyError)
"""Exception types that may be raised by instrumentation implementations."""
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import weakref
+
from . import attributes
-from .. import util
-from .. import exc as sa_exc
from . import util as orm_util
+from .. import exc as sa_exc
+from .. import util
class IdentityMap(object):
in the map"""
self.add(state)
- def update(self, dict):
+ def update(self, dict_):
raise NotImplementedError("IdentityMap uses add() to insert data")
def clear(self):
"""
-from . import exc, collections, interfaces, state
-from .. import util
from . import base
+from . import collections
+from . import exc
+from . import interfaces
+from . import state
+from .. import util
_memoized_key_collection = util.group_expirable_memoized_property()
if mgr is not None
]
- for base in self._bases:
- self.update(base)
+ for base_ in self._bases:
+ self.update(base_)
self.dispatch._events._new_classmanager_instance(class_, self)
# events._InstanceEventsHold.populate(class_, self)
from __future__ import absolute_import
-from .. import util
-from ..sql import operators
-from .base import (
- ONETOMANY,
- MANYTOONE,
- MANYTOMANY,
- EXT_CONTINUE,
- EXT_STOP,
- EXT_SKIP,
- NOT_EXTENSION,
-)
-from .base import InspectionAttr, InspectionAttrInfo, _MappedAttribute
import collections
-from .. import inspect
+
from . import path_registry
+from .base import _MappedAttribute # noqa
+from .base import EXT_CONTINUE
+from .base import EXT_SKIP
+from .base import EXT_STOP
+from .base import InspectionAttr # noqa
+from .base import InspectionAttrInfo # noqa
+from .base import MANYTOMANY
+from .base import MANYTOONE
+from .base import NOT_EXTENSION
+from .base import ONETOMANY
+from .. import inspect
+from .. import util
+from ..sql import operators
+
# imported later
MapperExtension = SessionExtension = AttributeExtension = None
"""
from __future__ import absolute_import
+import collections
+
+from . import attributes
+from . import exc as orm_exc
+from . import path_registry
+from . import strategy_options
+from .base import _DEFER_FOR_STATE
+from .base import _SET_DEFERRED_EXPIRED
+from .util import _none_set
+from .util import state_str
+from .. import exc as sa_exc
from .. import util
-from . import attributes, exc as orm_exc
from ..sql import util as sql_util
-from . import strategy_options
-from . import path_registry
-from .. import sql
-from .util import _none_set, state_str
-from .base import _SET_DEFERRED_EXPIRED, _DEFER_FOR_STATE
-from .. import exc as sa_exc
-import collections
_new_runid = util.counter()
"""
from __future__ import absolute_import
+from collections import deque
+from itertools import chain
+import sys
import types
import weakref
-from itertools import chain
-from collections import deque
-from .. import sql, util, log, exc as sa_exc, event, schema, inspection
-from ..sql import expression, visitors, operators, util as sql_util
-from . import instrumentation, attributes, exc as orm_exc, loading
+from . import attributes
+from . import exc as orm_exc
+from . import instrumentation
+from . import loading
from . import properties
from . import util as orm_util
-from .interfaces import (
- MapperProperty,
- InspectionAttr,
- _MappedAttribute,
- EXT_SKIP,
-)
-
-
-from .base import (
- _class_to_mapper,
- _state_mapper,
- class_mapper,
- state_str,
- _INSTRUMENTOR,
-)
+from .base import _class_to_mapper
+from .base import _INSTRUMENTOR
+from .base import _state_mapper
+from .base import class_mapper
+from .base import state_str
+from .interfaces import _MappedAttribute
+from .interfaces import EXT_SKIP
+from .interfaces import InspectionAttr
+from .interfaces import MapperProperty
from .path_registry import PathRegistry
-
-import sys
+from .. import event
+from .. import exc as sa_exc
+from .. import inspection
+from .. import log
+from .. import schema
+from .. import sql
+from .. import util
+from ..sql import expression
+from ..sql import operators
+from ..sql import util as sql_util
+from ..sql import visitors
_mapper_registry = weakref.WeakKeyDictionary()
self.polymorphic_map[self.polymorphic_identity] = self
if self.polymorphic_load and self.concrete:
- raise exc.ArgumentError(
+ raise sa_exc.ArgumentError(
"polymorphic_load is not currently supported "
"with concrete table inheritance"
)
if self.mapped_table is mapper.mapped_table:
self.polymorphic_on = mapper.polymorphic_on
else:
- self.polymorphic_on = self.mapped_table.corresponding_column(
- mapper.polymorphic_on
- )
+ self.polymorphic_on = (
+ self.mapped_table.corresponding_column
+ )(mapper.polymorphic_on)
# we can use the parent mapper's _set_polymorphic_identity
# directly; it ensures the polymorphic_identity of the
# instance's mapper is used so is portable to subclasses.
@_memoized_configured_property
def _equivalent_columns(self):
- """Create a map of all *equivalent* columns, based on
+ """Create a map of all equivalent columns, based on
the determination of column pairs that are equated to
one another based on inherit condition. This is designed
to work with the queries that util.polymorphic_union
only).
The resulting structure is a dictionary of columns mapped
- to lists of equivalent columns, i.e.
+ to lists of equivalent columns, e.g.::
- {
- tablea.col1:
- {tableb.col1, tablec.col1},
- tablea.col2:
- {tabled.col2}
- }
+ {
+ tablea.col1:
+ {tableb.col1, tablec.col1},
+ tablea.col2:
+ {tabled.col2}
+ }
"""
result = util.column_dict()
if queue:
visitables.append((queue, mpp, None, None))
elif item_type is mpp:
- instance, instance_mapper, corresponding_state, corresponding_dict = (
- iterator.popleft()
+ (
+ instance,
+ instance_mapper,
+ corresponding_state,
+ corresponding_dict,
+ ) = iterator.popleft()
+ yield (
+ instance,
+ instance_mapper,
+ corresponding_state,
+ corresponding_dict,
)
- yield instance, instance_mapper, corresponding_state, corresponding_dict
visitables.append(
(
deque(instance_mapper._props.values()),
"""
-from .. import inspection
-from .. import util
-from .. import exc
from itertools import chain
-from .base import class_mapper
import logging
+from .base import class_mapper
+from .. import exc
+from .. import inspection
+from .. import util
+
+
log = logging.getLogger(__name__)
"""
+from itertools import chain
+from itertools import groupby
import operator
-from itertools import groupby, chain
-from .. import sql, util, exc as sa_exc
-from . import attributes, sync, exc as orm_exc, evaluator
-from .base import state_str, _entity_descriptor
+
+from . import attributes
+from . import evaluator
+from . import exc as orm_exc
+from . import loading
+from . import sync
+from .base import _entity_descriptor
+from .base import state_str
+from .. import exc as sa_exc
+from .. import sql
+from .. import util
from ..sql import expression
from ..sql.base import _from_objects
-from . import loading
def _bulk_insert(
has_all_pks,
has_all_defaults,
)
- for state, state_dict, params, mp, conn, value_params, has_all_pks, has_all_defaults in _collect_insert_commands(
+ for (
+ state,
+ state_dict,
+ params,
+ mp,
+ conn,
+ value_params,
+ has_all_pks,
+ has_all_defaults,
+ ) in _collect_insert_commands(
table,
((None, mapping, mapper, connection) for mapping in mappings),
bulk=True,
chain(
(
(state, state_dict, mapper, connection, False)
- for state, state_dict, mapper, connection in states_to_insert
+ for (state, state_dict, mapper, connection) in states_to_insert
),
(
(state, state_dict, mapper, connection, True)
- for state, state_dict, mapper, connection, update_version_id in states_to_update
+ for (
+ state,
+ state_dict,
+ mapper,
+ connection,
+ update_version_id,
+ ) in states_to_update
),
),
)
params[col.key] = value
if mapper.base_mapper.eager_defaults:
- has_all_defaults = mapper._server_onupdate_default_cols[
- table
- ].issubset(params)
+ has_all_defaults = (
+ mapper._server_onupdate_default_cols[table]
+ ).issubset(params)
else:
has_all_defaults = True
"""
from __future__ import absolute_import
-from .. import util, log
-from ..sql import expression
from . import attributes
+from .interfaces import PropComparator
+from .interfaces import StrategizedProperty
from .util import _orm_full_deannotate
+from .. import log
+from .. import util
+from ..sql import expression
-from .interfaces import PropComparator, StrategizedProperty
__all__ = ["ColumnProperty"]
util.warn(
(
"On mapper %s, primary key column '%s' is being combined "
- "with distinct primary key column '%s' in attribute '%s'. "
- "Use explicit properties to give each column its own mapped "
- "attribute name."
+ "with distinct primary key column '%s' in attribute '%s'. "
+ "Use explicit properties to give each column its own "
+ "mapped attribute name."
)
% (self.parent, self.columns[1], self.columns[0], self.key)
)
from itertools import chain
-from . import (
- attributes,
- interfaces,
- object_mapper,
- persistence,
- exc as orm_exc,
- loading,
-)
-from .base import (
- _entity_descriptor,
- _is_aliased_class,
- _is_mapped_class,
- _orm_columns,
- _generative,
- InspectionAttr,
-)
+from . import attributes
+from . import exc as orm_exc
+from . import interfaces
+from . import loading
+from . import persistence
+from . import properties
+from .base import _entity_descriptor
+from .base import _generative
+from .base import _is_aliased_class
+from .base import _is_mapped_class
+from .base import _orm_columns
+from .base import InspectionAttr
from .path_registry import PathRegistry
-from .util import (
- AliasedClass,
- ORMAdapter,
- join as orm_join,
- with_parent,
- aliased,
- _entity_corresponds_to,
-)
-from .. import sql, util, log, exc as sa_exc, inspect, inspection
-from ..sql.expression import _interpret_as_from
-from ..sql import util as sql_util, expression, visitors
+from .util import _entity_corresponds_to
+from .util import aliased
+from .util import AliasedClass
+from .util import join as orm_join
+from .util import object_mapper
+from .util import ORMAdapter
+from .util import with_parent
+from .. import exc as sa_exc
+from .. import inspect
+from .. import inspection
+from .. import log
+from .. import sql
+from .. import util
+from ..sql import expression
+from ..sql import util as sql_util
+from ..sql import visitors
from ..sql.base import ColumnCollection
-from . import properties
+from ..sql.expression import _interpret_as_from
+from ..sql.selectable import ForUpdateArg
+
__all__ = ["Query", "QueryContext", "aliased"]
"""
self._invoke_all_eagers = value
- def with_parent(self, instance, property=None, from_entity=None):
+ def with_parent(self, instance, property=None, from_entity=None): # noqa
"""Add filtering criterion that relates the given instance
to a child object or collection, using its attribute state
as well as an established :func:`.relationship()`
isinstance(prop, properties.RelationshipProperty)
and prop.mapper is entity_zero.mapper
):
- property = prop
+ property = prop # noqa
break
else:
raise sa_exc.InvalidRequestError(
# figure out the best "left" side based on our existing froms /
# entities
assert prop is None
- left, replace_from_obj_index, use_entity_index = self._join_determine_implicit_left_side(
- left, right, onclause
- )
+ (
+ left,
+ replace_from_obj_index,
+ use_entity_index,
+ ) = self._join_determine_implicit_left_side(left, right, onclause)
else:
# left is given via a relationship/name. Determine where in our
# "froms" list it should be spliced/appended as well as what
# existing entity it corresponds to.
assert prop is not None
- replace_from_obj_index, use_entity_index = self._join_place_explicit_left_side(
- left
- )
+ (
+ replace_from_obj_index,
+ use_entity_index,
+ ) = self._join_place_explicit_left_side(left)
# this should never happen because we would not have found a place
# to join on
(note this may consist of multiple result rows if join-loaded
collections are present).
- Calling :meth:`.Query.first` results in an execution of the underlying query.
+ Calling :meth:`.Query.first` results in an execution of the underlying
+ query.
.. seealso::
values or sql expressions as values. If :ref:`parameter-ordered
mode <updates_order_parameters>` is desired, the values can be
passed as a list of 2-tuples;
- this requires that the :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
+ this requires that the
+ :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
flag is passed to the :paramref:`.Query.update.update_args` dictionary
as well.
context.order_by = None
if self._distinct is True and context.order_by:
- context.primary_columns += sql_util.expand_column_list_from_order_by(
- context.primary_columns, context.order_by
- )
+ context.primary_columns += (
+ sql_util.expand_column_list_from_order_by
+ )(context.primary_columns, context.order_by)
context.froms += tuple(context.eager_joins.values())
statement = sql.select(
)
-from ..sql.selectable import ForUpdateArg
-
-
class LockmodeArg(ForUpdateArg):
@classmethod
def parse_legacy_query(self, mode):
"""
from __future__ import absolute_import
-from .. import sql, util, exc as sa_exc, schema, log
+import collections
import weakref
-from .util import CascadeOptions, _orm_annotate, _orm_deannotate
-from . import dependency
+
from . import attributes
-from ..sql.util import (
- ClauseAdapter,
- join_condition,
- _shallow_annotate,
- visit_binary_product,
- _deep_deannotate,
- selectables_overlap,
- adapt_criterion_to_null,
-)
+from . import dependency
+from . import mapper as mapperlib
from .base import state_str
-
-from ..sql import operators, expression, visitors
-from .interfaces import (
- MANYTOMANY,
- MANYTOONE,
- ONETOMANY,
- StrategizedProperty,
- PropComparator,
-)
+from .interfaces import MANYTOMANY
+from .interfaces import MANYTOONE
+from .interfaces import ONETOMANY
+from .interfaces import PropComparator
+from .interfaces import StrategizedProperty
+from .util import _orm_annotate
+from .util import _orm_deannotate
+from .util import CascadeOptions
+from .. import exc as sa_exc
+from .. import log
+from .. import schema
+from .. import sql
+from .. import util
from ..inspection import inspect
-from . import mapper as mapperlib
-import collections
+from ..sql import expression
+from ..sql import operators
+from ..sql import visitors
+from ..sql.util import _deep_deannotate
+from ..sql.util import _shallow_annotate
+from ..sql.util import adapt_criterion_to_null
+from ..sql.util import ClauseAdapter
+from ..sql.util import join_condition
+from ..sql.util import selectables_overlap
+from ..sql.util import visit_binary_product
def remote(expr):
@log.class_logger
-@util.langhelpers.dependency_for("sqlalchemy.orm.properties")
+@util.langhelpers.dependency_for("sqlalchemy.orm.properties", add_to_all=True)
class RelationshipProperty(StrategizedProperty):
"""Describes an object property that holds a single item or list
of items that correspond to a related database table.
.. seealso::
- :doc:`/orm/loading_relationships` - Full documentation on relationship loader
- configuration.
+ :doc:`/orm/loading_relationships` - Full documentation on
+ relationship loader configuration.
:ref:`dynamic_relationship` - detail on the ``dynamic`` option.
else:
of_type = None
- pj, sj, source, dest, secondary, target_adapter = self.property._create_joins(
+ (
+ pj,
+ sj,
+ source,
+ dest,
+ secondary,
+ target_adapter,
+ ) = self.property._create_joins(
source_selectable=adapt_from,
source_polymorphic=True,
of_type=of_type,
else:
source_selectable = None
- pj, sj, source, dest, secondary, target_adapter = self.property._create_joins(
+ (
+ pj,
+ sj,
+ source,
+ dest,
+ secondary,
+ target_adapter,
+ ) = self.property._create_joins(
dest_polymorphic=True,
dest_selectable=to_selectable,
source_selectable=source_selectable,
Above, the SQL should be "address.user_id = 5". The callable
returned by this method produces the value "5" based on the identity
- of ``u1`.
+ of ``u1``.
"""
if self.uselist is None:
self.uselist = self.direction is not MANYTOONE
if not self.viewonly:
- self._dependency_processor = dependency.DependencyProcessor.from_relationship(
- self
- )
+ self._dependency_processor = (
+ dependency.DependencyProcessor.from_relationship
+ )(self)
@util.memoized_property
def _use_get(self):
single_crit = dest_mapper._single_table_criterion
aliased = aliased or (source_selectable is not None)
- primaryjoin, secondaryjoin, secondary, target_adapter, dest_selectable = self._join_condition.join_targets(
+ (
+ primaryjoin,
+ secondaryjoin,
+ secondary,
+ target_adapter,
+ dest_selectable,
+ ) = self._join_condition.join_targets(
source_selectable, dest_selectable, aliased, single_crit
)
if source_selectable is None:
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .. import exc as sa_exc
-from ..util import ScopedRegistry, ThreadLocalRegistry, warn
-from . import class_mapper, exc as orm_exc
+from . import class_mapper
+from . import exc as orm_exc
from .session import Session
+from .. import exc as sa_exc
+from ..util import ScopedRegistry
+from ..util import ThreadLocalRegistry
+from ..util import warn
__all__ = ["scoped_session"]
def makeprop(name):
- def set(self, attr):
+ def set_(self, attr):
setattr(self.registry(), name, attr)
def get(self):
return getattr(self.registry(), name)
- return property(get, set)
+ return property(get, set_)
for prop in (
"""Provides the Session class and related utilities."""
-import weakref
-from .. import util, sql, engine, exc as sa_exc
-from ..sql import util as sql_util, expression
-from . import SessionExtension, attributes, exc, query, loading, identity
-from ..inspection import inspect
-from .base import (
- object_mapper,
- class_mapper,
- _class_to_mapper,
- _state_mapper,
- object_state,
- _none_set,
- state_str,
- instance_str,
-)
import itertools
+import sys
+import weakref
+
+from . import attributes
+from . import exc
+from . import identity
+from . import loading
from . import persistence
-from .unitofwork import UOWTransaction
+from . import query
from . import state as statelib
-import sys
+from .base import _class_to_mapper
+from .base import _none_set
+from .base import _state_mapper
+from .base import instance_str
+from .base import object_mapper
+from .base import object_state
+from .base import state_str
+from .deprecated_interfaces import SessionExtension
+from .unitofwork import UOWTransaction
+from .. import engine
+from .. import exc as sa_exc
+from .. import sql
+from .. import util
+from ..inspection import inspect
+from ..sql import expression
+from ..sql import util as sql_util
+
__all__ = ["Session", "SessionTransaction", "SessionExtension", "sessionmaker"]
def __enter__(self):
return self
- def __exit__(self, type, value, traceback):
+ def __exit__(self, type_, value, traceback):
self._assert_active(deactive_ok=True, prepared_ok=True)
if self.session.transaction is None:
return
- if type is None:
+ if type_ is None:
try:
self.commit()
except:
:param subtransactions: if True, indicates that this
:meth:`~.Session.begin` can create a "subtransaction".
- :param nested: if True, begins a SAVEPOINT transaction and is equivalent
- to calling :meth:`~.Session.begin_nested`. For documentation on
- SAVEPOINT transactions, please see :ref:`session_begin_nested`.
+ :param nested: if True, begins a SAVEPOINT transaction and is
+ equivalent to calling :meth:`~.Session.begin_nested`. For
+ documentation on SAVEPOINT transactions, please see
+ :ref:`session_begin_nested`.
:return: the :class:`.SessionTransaction` object. Note that
:class:`.SessionTransaction`
"""
import weakref
-from .. import util
-from .. import inspection
-from .. import exc as sa_exc
-from . import exc as orm_exc, interfaces
-from .path_registry import PathRegistry
-from .base import (
- PASSIVE_NO_RESULT,
- SQL_OK,
- NEVER_SET,
- ATTR_WAS_SET,
- NO_VALUE,
- PASSIVE_NO_INITIALIZE,
- INIT_OK,
- PASSIVE_OFF,
-)
+
from . import base
+from . import exc as orm_exc
+from . import interfaces
+from .base import ATTR_WAS_SET
+from .base import INIT_OK
+from .base import NEVER_SET
+from .base import NO_VALUE
+from .base import PASSIVE_NO_INITIALIZE
+from .base import PASSIVE_NO_RESULT
+from .base import PASSIVE_OFF
+from .base import SQL_OK
+from .path_registry import PathRegistry
+from .. import exc as sa_exc
+from .. import inspection
+from .. import util
@inspection._self_inspects
"detached" states; once the object is :term:`detached`, the
:attr:`.InstanceState.deleted` attribute **no longer returns
True**; in order to detect that a state was deleted, regardless
- of whether or not the object is associated with a :class:`.Session`,
- use the :attr:`.InstanceState.was_deleted` accessor.
+ of whether or not the object is associated with a
+ :class:`.Session`, use the :attr:`.InstanceState.was_deleted`
+ accessor.
.. versionadded: 1.1
self._commit_all_states([(self, dict_)], instance_dict)
@classmethod
- def _commit_all_states(self, iter, instance_dict=None):
+ def _commit_all_states(self, iter_, instance_dict=None):
"""Mass / highly inlined version of commit_all()."""
- for state, dict_ in iter:
+ for state, dict_ in iter_:
state_dict = state.__dict__
state.committed_state.clear()
"""sqlalchemy.orm.interfaces.LoaderStrategy
implementations, and related MapperOptions."""
-from .. import exc as sa_exc, inspect
-from .. import util, log, event
-from ..sql import util as sql_util, visitors
-from .. import sql
-from . import (
- attributes,
- interfaces,
- exc as orm_exc,
- loading,
- unitofwork,
- util as orm_util,
- query,
-)
-from .state import InstanceState
-from .util import _none_set, aliased
+import itertools
+
+from . import attributes
+from . import exc as orm_exc
+from . import interfaces
+from . import loading
from . import properties
-from .interfaces import LoaderStrategy, StrategizedProperty
-from .base import _SET_DEFERRED_EXPIRED, _DEFER_FOR_STATE
+from . import query
+from . import unitofwork
+from . import util as orm_util
+from .base import _DEFER_FOR_STATE
+from .base import _SET_DEFERRED_EXPIRED
+from .interfaces import LoaderStrategy
+from .interfaces import StrategizedProperty
from .session import _state_session
-import itertools
+from .state import InstanceState
+from .util import _none_set
+from .util import aliased
+from .. import event
+from .. import exc as sa_exc
+from .. import inspect
+from .. import log
+from .. import sql
+from .. import util
+from ..sql import util as sql_util
+from ..sql import visitors
def _register_attribute(
join_condition.create_lazy_clause()
)
- self._rev_lazywhere, self._rev_bind_to_col, self._rev_equated_columns = join_condition.create_lazy_clause(
- reverse_direction=True
- )
+ (
+ self._rev_lazywhere,
+ self._rev_bind_to_col,
+ self._rev_equated_columns,
+ ) = join_condition.create_lazy_clause(reverse_direction=True)
self.logger.info("%s lazy loading clause %s", self, self._lazywhere)
# "lazyload" option on a "no load"
# attribute - "eager" attributes always have a
# class-level lazyloader installed.
- set_lazy_callable = InstanceState._instance_level_callable_processor(
- mapper.class_manager, LoadLazyAttribute(key, self), key
- )
+ set_lazy_callable = (
+ InstanceState._instance_level_callable_processor
+ )(mapper.class_manager, LoadLazyAttribute(key, self), key)
populators["new"].append((self.key, set_lazy_callable))
elif context.populate_existing or mapper.always_refresh:
elif subq_path.contains_mapper(self.mapper):
return
- leftmost_mapper, leftmost_attr, leftmost_relationship = self._get_leftmost(
- subq_path
- )
+ (
+ leftmost_mapper,
+ leftmost_attr,
+ leftmost_relationship,
+ ) = self._get_leftmost(subq_path)
orig_query = context.attributes.get(
("orig_query", SubqueryLoader), context.query
)
if user_defined_adapter is not False:
- clauses, adapter, add_to_collection = self._setup_query_on_user_defined_adapter(
+ (
+ clauses,
+ adapter,
+ add_to_collection,
+ ) = self._setup_query_on_user_defined_adapter(
context, entity, path, adapter, user_defined_adapter
)
else:
elif path.contains_mapper(self.mapper):
return
- clauses, adapter, add_to_collection, chained_from_outerjoin = self._generate_row_adapter(
+ (
+ clauses,
+ adapter,
+ add_to_collection,
+ chained_from_outerjoin,
+ ) = self._generate_row_adapter(
context,
entity,
path,
context.primary_columns.append(col)
if self.parent_property.order_by:
- context.eager_order_by += eagerjoin._target_adapter.copy_and_process(
- util.to_list(self.parent_property.order_by)
- )
+ context.eager_order_by += (
+ eagerjoin._target_adapter.copy_and_process
+ )(util.to_list(self.parent_property.order_by))
def _splice_nested_inner_join(
self, path, join_obj, clauses, onclause, splicing=False
# imitate the same method that subquery eager loading uses,
# looking for the adapted "secondary" table
eagerjoin = q._from_obj[0]
- eager_order_by = eagerjoin._target_adapter.copy_and_process(
- util.to_list(self.parent_property.order_by)
+
+ return q.order_by(
+ *eagerjoin._target_adapter.copy_and_process(
+ util.to_list(self.parent_property.order_by)
+ )
)
- return q.order_by(*eager_order_by)
q.add_criteria(_setup_outermost_orderby)
"""
-from .interfaces import MapperOption, PropComparator, MapperProperty
+from . import util as orm_util
from .attributes import QueryableAttribute
+from .base import _class_to_mapper
+from .base import _is_aliased_class
+from .base import _is_mapped_class
+from .base import InspectionAttr
+from .interfaces import MapperOption
+from .interfaces import PropComparator
+from .path_registry import _DEFAULT_TOKEN
+from .path_registry import _WILDCARD_TOKEN
+from .path_registry import PathRegistry
+from .path_registry import TokenRegistry
+from .util import _orm_full_deannotate
+from .. import exc as sa_exc
+from .. import inspect
from .. import util
-from ..sql.base import _generative, Generative
-from .. import exc as sa_exc, inspect
-from .base import (
- _is_aliased_class,
- _class_to_mapper,
- _is_mapped_class,
- InspectionAttr,
-)
-from . import util as orm_util
-from .path_registry import (
- PathRegistry,
- TokenRegistry,
- _WILDCARD_TOKEN,
- _DEFAULT_TOKEN,
-)
+from ..sql import expression as sql_expr
+from ..sql.base import _generative
+from ..sql.base import Generative
class Load(Generative, MapperOption):
return _UnboundLoad().undefer_group(name)
-from ..sql import expression as sql_expr
-from .util import _orm_full_deannotate
-
-
@loader_option()
def with_expression(loadopt, key, expression):
r"""Apply an ad-hoc SQL expression to a "deferred expression" attribute.
"""
-from . import exc, util as orm_util, attributes
+from . import attributes
+from . import exc
+from . import util as orm_util
def populate(
"""
-from .. import util, event
-from ..util import topological
-from . import attributes, persistence, util as orm_util
+from . import attributes
from . import exc as orm_exc
-import itertools
+from . import persistence
+from . import util as orm_util
+from .. import event
+from .. import util
+from ..util import topological
def track_cascade_events(descriptor, prop):
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .. import sql, util, event, exc as sa_exc, inspection
-from ..sql import expression, util as sql_util, operators
-from .interfaces import PropComparator, MapperProperty
-from . import attributes
import re
-from .base import (
- instance_str,
- state_str,
- state_class_str,
- attribute_str,
- state_attribute_str,
- object_mapper,
- object_state,
- _none_set,
- _never_set,
-)
-from .base import class_mapper, _class_to_mapper
-from .base import InspectionAttr
-from .path_registry import PathRegistry
+from . import attributes # noqa
+from .base import _class_to_mapper # noqa
+from .base import _never_set # noqa
+from .base import _none_set # noqa
+from .base import attribute_str # noqa
+from .base import class_mapper # noqa
+from .base import InspectionAttr # noqa
+from .base import instance_str # noqa
+from .base import object_mapper # noqa
+from .base import object_state # noqa
+from .base import state_attribute_str # noqa
+from .base import state_class_str # noqa
+from .base import state_str # noqa
+from .interfaces import MapperProperty # noqa
+from .interfaces import PropComparator # noqa
+from .path_registry import PathRegistry # noqa
+from .. import event
+from .. import exc as sa_exc
+from .. import inspection
+from .. import sql
+from .. import util
+from ..sql import expression
+from ..sql import util as sql_util
+
all_cascades = frozenset(
(
return sql.type_coerce(sql.null(), types[name]).label(name)
result = []
- for type, table in table_map.items():
+ for type_, table in table_map.items():
if typecolname is not None:
result.append(
sql.select(
[col(name, table) for name in colnames]
+ [
sql.literal_column(
- sql_util._quote_ddl_expr(type)
+ sql_util._quote_ddl_expr(type_)
).label(typecolname)
],
from_obj=[table],
:param class: mapped class (must be a positional argument)
:param ident: primary key, may be a scalar or tuple argument.
- ;param identity_token: optional identity token
+ :param identity_token: optional identity token
.. versionadded:: 1.2 added identity_token
:param class: mapped class (must be a positional argument)
:param row: :class:`.RowProxy` row returned by a :class:`.ResultProxy`
(must be given as a keyword arg)
- ;param identity_token: optional identity token
+ :param identity_token: optional identity token
.. versionadded:: 1.2 added identity_token
else:
adapt_from = left_info.selectable
- pj, sj, source, dest, secondary, target_adapter = prop._create_joins(
+ (
+ pj,
+ sj,
+ source,
+ dest,
+ secondary,
+ target_adapter,
+ ) = prop._create_joins(
source_selectable=adapt_from,
dest_selectable=adapt_to,
source_polymorphic=True,
return prop._with_parent(instance, from_entity=from_entity)
-def has_identity(object):
+def has_identity(object_):
"""Return True if the given object has a database
identity.
:func:`.was_deleted`
"""
- state = attributes.instance_state(object)
+ state = attributes.instance_state(object_)
return state.has_identity
-def was_deleted(object):
+def was_deleted(object_):
"""Return True if the given object was deleted
within a session flush.
"""
- state = attributes.instance_state(object)
+ state = attributes.instance_state(object_)
return state.was_deleted
SQLAlchemy connection pool.
"""
+from .base import _ConnectionFairy # noqa
+from .base import _ConnectionRecord # noqa
+from .base import _finalize_fairy # noqa
from .base import _refs # noqa
-from .base import Pool # noqa
-from .impl import ( # noqa
- QueuePool,
- StaticPool,
- NullPool,
- AssertionPool,
- SingletonThreadPool,
-)
-from .dbapi_proxy import manage, clear_managers # noqa
-
-from .base import reset_rollback, reset_commit, reset_none # noqa
+from .base import Pool
+from .base import reset_commit
+from .base import reset_none
+from .base import reset_rollback
+from .dbapi_proxy import clear_managers
+from .dbapi_proxy import manage
+from .impl import AssertionPool
+from .impl import NullPool
+from .impl import QueuePool
+from .impl import SingletonThreadPool
+from .impl import StaticPool
+
+
+__all__ = [
+ "Pool",
+ "reset_commit",
+ "reset_none",
+ "reset_rollback",
+ "clear_managers",
+ "manage",
+ "AssertionPool",
+ "NullPool",
+ "QueuePool",
+ "SingletonThreadPool",
+ "StaticPool",
+]
# as these are likely to be used in various test suites, debugging
# setups, keep them in the sqlalchemy.pool namespace
-from .base import _ConnectionFairy, _ConnectionRecord, _finalize_fairy # noqa
import time
import weakref
-from .. import exc, log, event, interfaces, util
+from .. import event
+from .. import exc
+from .. import interfaces
+from .. import log
+from .. import util
from ..util import threading
from .impl import QueuePool
from ..util import threading
+
proxies = {}
import traceback
import weakref
-from .base import Pool, _ConnectionRecord
+from .base import _ConnectionRecord
+from .base import Pool
from .. import exc
from .. import util
-from ..util import queue as sqla_queue
from ..util import chop_traceback
+from ..util import queue as sqla_queue
from ..util import threading
"""
import codecs
-import re
import datetime
+import re
+
from . import util
return process
- def to_float(value):
+ def to_float(value): # noqa
if value is None:
return None
else:
return float(value)
- def to_str(value):
+ def to_str(value): # noqa
if value is None:
return None
else:
return str(value)
- def int_to_boolean(value):
+ def int_to_boolean(value): # noqa
if value is None:
return None
else:
TIME_RE = re.compile(r"(\d+):(\d+):(\d+)(?:\.(\d+))?")
DATE_RE = re.compile(r"(\d+)-(\d+)-(\d+)")
- str_to_datetime = str_to_datetime_processor_factory(
+ str_to_datetime = str_to_datetime_processor_factory( # noqa
DATETIME_RE, datetime.datetime
)
- str_to_time = str_to_datetime_processor_factory(TIME_RE, datetime.time)
- str_to_date = str_to_datetime_processor_factory(DATE_RE, datetime.date)
+ str_to_time = str_to_datetime_processor_factory( # noqa
+ TIME_RE, datetime.time
+ ) # noqa
+ str_to_date = str_to_datetime_processor_factory( # noqa
+ DATE_RE, datetime.date
+ ) # noqa
return locals()
try:
- from sqlalchemy.cprocessors import (
- UnicodeResultProcessor,
- DecimalResultProcessor,
- to_float,
- to_str,
- int_to_boolean,
- str_to_datetime,
- str_to_time,
- str_to_date,
- )
+ from sqlalchemy.cprocessors import DecimalResultProcessor # noqa
+ from sqlalchemy.cprocessors import int_to_boolean # noqa
+ from sqlalchemy.cprocessors import str_to_date # noqa
+ from sqlalchemy.cprocessors import str_to_datetime # noqa
+ from sqlalchemy.cprocessors import str_to_time # noqa
+ from sqlalchemy.cprocessors import to_float # noqa
+ from sqlalchemy.cprocessors import to_str # noqa
+ from sqlalchemy.cprocessors import UnicodeResultProcessor # noqa
def to_unicode_processor_factory(encoding, errors=None):
if errors is not None:
"""
-from .sql.base import SchemaVisitor
-
-
-from .sql.schema import (
- BLANK_SCHEMA,
- CheckConstraint,
- Column,
- ColumnDefault,
- Constraint,
- DefaultClause,
- DefaultGenerator,
- FetchedValue,
- ForeignKey,
- ForeignKeyConstraint,
- Index,
- MetaData,
- PassiveDefault,
- PrimaryKeyConstraint,
- SchemaItem,
- Sequence,
- Table,
- ThreadLocalMetaData,
- UniqueConstraint,
- _get_table_key,
- ColumnCollectionConstraint,
- ColumnCollectionMixin,
-)
-
-
-from .sql.naming import conv
-
-
-from .sql.ddl import (
- DDL,
- CreateTable,
- DropTable,
- CreateSequence,
- DropSequence,
- CreateIndex,
- DropIndex,
- CreateSchema,
- DropSchema,
- _DropView,
- CreateColumn,
- AddConstraint,
- DropConstraint,
- DDLBase,
- DDLElement,
- _CreateDropBase,
- _DDLCompiles,
- sort_tables,
- sort_tables_and_constraints,
- SetTableComment,
- DropTableComment,
- SetColumnComment,
- DropColumnComment,
-)
+from .sql.base import SchemaVisitor # noqa
+from .sql.ddl import _CreateDropBase # noqa
+from .sql.ddl import _DDLCompiles # noqa
+from .sql.ddl import _DropView # noqa
+from .sql.ddl import AddConstraint # noqa
+from .sql.ddl import CreateColumn # noqa
+from .sql.ddl import CreateIndex # noqa
+from .sql.ddl import CreateSchema # noqa
+from .sql.ddl import CreateSequence # noqa
+from .sql.ddl import CreateTable # noqa
+from .sql.ddl import DDL # noqa
+from .sql.ddl import DDLBase # noqa
+from .sql.ddl import DDLElement # noqa
+from .sql.ddl import DropColumnComment # noqa
+from .sql.ddl import DropConstraint # noqa
+from .sql.ddl import DropIndex # noqa
+from .sql.ddl import DropSchema # noqa
+from .sql.ddl import DropSequence # noqa
+from .sql.ddl import DropTable # noqa
+from .sql.ddl import DropTableComment # noqa
+from .sql.ddl import SetColumnComment # noqa
+from .sql.ddl import SetTableComment # noqa
+from .sql.ddl import sort_tables # noqa
+from .sql.ddl import sort_tables_and_constraints # noqa
+from .sql.naming import conv # noqa
+from .sql.schema import _get_table_key # noqa
+from .sql.schema import BLANK_SCHEMA # noqa
+from .sql.schema import CheckConstraint # noqa
+from .sql.schema import Column # noqa
+from .sql.schema import ColumnCollectionConstraint # noqa
+from .sql.schema import ColumnCollectionMixin # noqa
+from .sql.schema import ColumnDefault # noqa
+from .sql.schema import Constraint # noqa
+from .sql.schema import DefaultClause # noqa
+from .sql.schema import DefaultGenerator # noqa
+from .sql.schema import FetchedValue # noqa
+from .sql.schema import ForeignKey # noqa
+from .sql.schema import ForeignKeyConstraint # noqa
+from .sql.schema import Index # noqa
+from .sql.schema import MetaData # noqa
+from .sql.schema import PassiveDefault # noqa
+from .sql.schema import PrimaryKeyConstraint # noqa
+from .sql.schema import SchemaItem # noqa
+from .sql.schema import Sequence # noqa
+from .sql.schema import Table # noqa
+from .sql.schema import ThreadLocalMetaData # noqa
+from .sql.schema import UniqueConstraint # noqa
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .expression import (
- Alias,
- ClauseElement,
- ColumnCollection,
- ColumnElement,
- CompoundSelect,
- Delete,
- FromClause,
- Insert,
- Join,
- Select,
- Selectable,
- TableClause,
- TableSample,
- Update,
- alias,
- and_,
- any_,
- all_,
- asc,
- between,
- bindparam,
- case,
- cast,
- collate,
- column,
- delete,
- desc,
- distinct,
- except_,
- except_all,
- exists,
- extract,
- false,
- False_,
- func,
- funcfilter,
- insert,
- intersect,
- intersect_all,
- join,
- label,
- lateral,
- literal,
- literal_column,
- modifier,
- not_,
- null,
- nullsfirst,
- nullslast,
- or_,
- outerjoin,
- outparam,
- over,
- quoted_name,
- select,
- subquery,
- table,
- tablesample,
- text,
- true,
- True_,
- tuple_,
- type_coerce,
- union,
- union_all,
- update,
- within_group,
-)
-
-from .visitors import ClauseVisitor
+from .expression import Alias # noqa
+from .expression import alias # noqa
+from .expression import all_ # noqa
+from .expression import and_ # noqa
+from .expression import any_ # noqa
+from .expression import asc # noqa
+from .expression import between # noqa
+from .expression import bindparam # noqa
+from .expression import case # noqa
+from .expression import cast # noqa
+from .expression import ClauseElement # noqa
+from .expression import collate # noqa
+from .expression import column # noqa
+from .expression import ColumnCollection # noqa
+from .expression import ColumnElement # noqa
+from .expression import CompoundSelect # noqa
+from .expression import Delete # noqa
+from .expression import delete # noqa
+from .expression import desc # noqa
+from .expression import distinct # noqa
+from .expression import except_ # noqa
+from .expression import except_all # noqa
+from .expression import exists # noqa
+from .expression import extract # noqa
+from .expression import false # noqa
+from .expression import False_ # noqa
+from .expression import FromClause # noqa
+from .expression import func # noqa
+from .expression import funcfilter # noqa
+from .expression import Insert # noqa
+from .expression import insert # noqa
+from .expression import intersect # noqa
+from .expression import intersect_all # noqa
+from .expression import Join # noqa
+from .expression import join # noqa
+from .expression import label # noqa
+from .expression import lateral # noqa
+from .expression import literal # noqa
+from .expression import literal_column # noqa
+from .expression import modifier # noqa
+from .expression import not_ # noqa
+from .expression import null # noqa
+from .expression import nullsfirst # noqa
+from .expression import nullslast # noqa
+from .expression import or_ # noqa
+from .expression import outerjoin # noqa
+from .expression import outparam # noqa
+from .expression import over # noqa
+from .expression import quoted_name # noqa
+from .expression import Select # noqa
+from .expression import select # noqa
+from .expression import Selectable # noqa
+from .expression import subquery # noqa
+from .expression import table # noqa
+from .expression import TableClause # noqa
+from .expression import TableSample # noqa
+from .expression import tablesample # noqa
+from .expression import text # noqa
+from .expression import true # noqa
+from .expression import True_ # noqa
+from .expression import tuple_ # noqa
+from .expression import type_coerce # noqa
+from .expression import union # noqa
+from .expression import union_all # noqa
+from .expression import Update # noqa
+from .expression import update # noqa
+from .expression import within_group # noqa
+from .visitors import ClauseVisitor # noqa
def __go(lcls):
if not (name.startswith("_") or _inspect.ismodule(obj))
)
- from .annotation import _prepare_annotations, Annotated
- from .elements import AnnotatedColumnElement, ClauseList
- from .selectable import AnnotatedFromClause
+ from .annotation import _prepare_annotations
+ from .annotation import Annotated # noqa
+ from .elements import AnnotatedColumnElement
+ from .elements import ClauseList # noqa
+ from .selectable import AnnotatedFromClause # noqa
_prepare_annotations(ColumnElement, AnnotatedColumnElement)
_prepare_annotations(FromClause, AnnotatedFromClause)
_sa_util.dependencies.resolve_all("sqlalchemy.sql")
- from . import naming
+ from . import naming # noqa
__go(locals())
"""
-from .. import util
from . import operators
+from .. import util
class Annotated(object):
"""
-from .. import util, exc
import itertools
-from .visitors import ClauseVisitor
import re
+from .visitors import ClauseVisitor
+from .. import exc
+from .. import util
+
+
PARSE_AUTOCOMMIT = util.symbol("PARSE_AUTOCOMMIT")
NO_ARG = util.symbol("NO_ARG")
def __delitem__(self, key):
raise NotImplementedError()
- def __setattr__(self, key, object):
+ def __setattr__(self, key, obj):
raise NotImplementedError()
def __setitem__(self, key, value):
c for c in self._all_columns if c is not column
]
- def update(self, iter):
- cols = list(iter)
+ def update(self, iter_):
+ cols = list(iter_)
all_col_set = set(self._all_columns)
self._all_columns.extend(
c for label, c in cols if c not in all_col_set
)
self._data.update((label, c) for label, c in cols)
- def extend(self, iter):
- cols = list(iter)
+ def extend(self, iter_):
+ cols = list(iter_)
all_col_set = set(self._all_columns)
self._all_columns.extend(c for c in cols if c not in all_col_set)
self._data.update((c.key, c) for c in cols)
"""
import contextlib
-import re
-from . import (
- schema,
- sqltypes,
- operators,
- functions,
- visitors,
- elements,
- selectable,
- crud,
-)
-from .. import util, exc
import itertools
+import re
+
+from . import crud
+from . import elements
+from . import functions
+from . import operators
+from . import schema
+from . import selectable
+from . import sqltypes
+from . import visitors
+from .. import exc
+from .. import util
+
RESERVED_WORDS = set(
[
table_text = preparer.format_table(insert_stmt.table)
if insert_stmt._hints:
- dialect_hints, table_text = self._setup_crud_hints(
- insert_stmt, table_text
- )
- else:
- dialect_hints = None
+ _, table_text = self._setup_crud_hints(insert_stmt, table_text)
text += table_text
within INSERT and UPDATE statements.
"""
-from .. import util
-from .. import exc
+import operator
+
from . import dml
from . import elements
-import operator
+from .. import exc
+from .. import util
+
REQUIRED = util.symbol(
"REQUIRED",
# getters - these are normally just column.key,
# but in the case of mysql multi-table update, the rules for
# .key must conditionally take tablename into account
- _column_as_key, _getattr_col_key, _col_bind_name = _key_getters_for_crud_column(
- compiler, stmt
- )
+ (
+ _column_as_key,
+ _getattr_col_key,
+ _col_bind_name,
+ ) = _key_getters_for_crud_column(compiler, stmt)
# if we have statement parameters - set defaults in the
# compiled params
kw,
):
- need_pks, implicit_returning, implicit_return_defaults, postfetch_lastrowid = _get_returning_modifiers(
- compiler, stmt
- )
+ (
+ need_pks,
+ implicit_returning,
+ implicit_return_defaults,
+ postfetch_lastrowid,
+ ) = _get_returning_modifiers(compiler, stmt)
cols = [stmt.table.c[_column_as_key(name)] for name in stmt.select_names]
kw,
):
- need_pks, implicit_returning, implicit_return_defaults, postfetch_lastrowid = _get_returning_modifiers(
- compiler, stmt
- )
+ (
+ need_pks,
+ implicit_returning,
+ implicit_return_defaults,
+ postfetch_lastrowid,
+ ) = _get_returning_modifiers(compiler, stmt)
if stmt._parameter_ordering:
parameter_ordering = [
"""
-from .. import util
+from .base import _bind_or_error
+from .base import _generative
+from .base import Executable
+from .base import SchemaVisitor
from .elements import ClauseElement
-from .base import Executable, _generative, SchemaVisitor, _bind_or_error
-from ..util import topological
from .. import event
from .. import exc
+from .. import util
+from ..util import topological
class _DDLCompiles(ClauseElement):
DDL('something').execute_if(dialect=('postgresql', 'mysql'))
- :param callable_: A callable, which will be invoked with
+ :param callable\_: A callable, which will be invoked with
four positional arguments as well as optional keyword
arguments:
include_foreign_key_constraints = None
self.connection.execute(
+ # fmt: off
CreateTable(
table,
- include_foreign_key_constraints=include_foreign_key_constraints,
+ include_foreign_key_constraints= # noqa
+ include_foreign_key_constraints,
)
+ # fmt: on
)
if hasattr(table, "indexes"):
"""Default implementation of SQL comparison operations.
"""
-from .. import exc, util
-from . import type_api
from . import operators
-from .elements import (
- BindParameter,
- True_,
- False_,
- BinaryExpression,
- Null,
- _const_expr,
- _clause_element_as_expr,
- ClauseList,
- ColumnElement,
- TextClause,
- UnaryExpression,
- collate,
- _is_literal,
- _literal_as_text,
- ClauseElement,
- and_,
- or_,
- Slice,
- Visitable,
- _literal_as_binds,
- CollectionAggregate,
- Tuple,
-)
-from .selectable import SelectBase, Alias, Selectable, ScalarSelect
+from . import type_api
+from .elements import _clause_element_as_expr
+from .elements import _const_expr
+from .elements import _is_literal
+from .elements import _literal_as_text
+from .elements import and_
+from .elements import BinaryExpression
+from .elements import BindParameter
+from .elements import ClauseElement
+from .elements import ClauseList
+from .elements import collate
+from .elements import CollectionAggregate
+from .elements import ColumnElement
+from .elements import False_
+from .elements import Null
+from .elements import or_
+from .elements import TextClause
+from .elements import True_
+from .elements import Tuple
+from .elements import UnaryExpression
+from .elements import Visitable
+from .selectable import Alias
+from .selectable import ScalarSelect
+from .selectable import Selectable
+from .selectable import SelectBase
+from .. import exc
+from .. import util
def _boolean_compare(
"""
-from .base import (
- Executable,
- _generative,
- _from_objects,
- DialectKWArgs,
- ColumnCollection,
-)
-from .elements import (
- ClauseElement,
- _literal_as_text,
- Null,
- and_,
- _clone,
- _column_as_key,
-)
-from .selectable import (
- _interpret_as_from,
- _interpret_as_select,
- HasPrefixes,
- HasCTE,
-)
-from .. import util
+from .base import _from_objects
+from .base import _generative
+from .base import DialectKWArgs
+from .base import Executable
+from .elements import _clone
+from .elements import _column_as_key
+from .elements import _literal_as_text
+from .elements import and_
+from .elements import ClauseElement
+from .elements import Null
+from .selectable import _interpret_as_from
+from .selectable import _interpret_as_select
+from .selectable import HasCTE
+from .selectable import HasPrefixes
from .. import exc
+from .. import util
class UpdateBase(
v = {}
if self.parameters is None:
- self.parameters, self._has_multi_parameters = self._process_colparams(
- v
- )
+ (
+ self.parameters,
+ self._has_multi_parameters,
+ ) = self._process_colparams(v)
else:
if self._has_multi_parameters:
self.parameters = list(self.parameters)
:meth:`.ResultProxy.last_updated_params`.
:param preserve_parameter_order: if True, the update statement is
- expected to receive parameters **only** via the :meth:`.Update.values`
- method, and they must be passed as a Python ``list`` of 2-tuples.
- The rendered UPDATE statement will emit the SET clause for each
- referenced column maintaining this order.
+ expected to receive parameters **only** via the
+ :meth:`.Update.values` method, and they must be passed as a Python
+ ``list`` of 2-tuples. The rendered UPDATE statement will emit the SET
+ clause for each referenced column maintaining this order.
.. versionadded:: 1.0.10
.. seealso::
:ref:`updates_order_parameters` - full example of the
- :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order` flag
+ :paramref:`~.update.preserve_parameter_order` flag
If both ``values`` and compile-time bind parameters are present, the
compile-time bind parameters override the information specified
from __future__ import unicode_literals
-from .. import util, exc, inspection
-from . import type_api
-from . import operators
-from .visitors import Visitable, cloned_traverse, traverse
-from .annotation import Annotated
import itertools
-from .base import Executable, PARSE_AUTOCOMMIT, Immutable, NO_ARG
-from .base import _generative
import numbers
-
-import re
import operator
+import re
+
+from . import operators
+from . import type_api
+from .annotation import Annotated
+from .base import _generative
+from .base import Executable
+from .base import Immutable
+from .base import NO_ARG
+from .base import PARSE_AUTOCOMMIT
+from .visitors import cloned_traverse
+from .visitors import traverse
+from .visitors import Visitable
+from .. import exc
+from .. import inspection
+from .. import util
def _clone(element, **kw):
if util.py3k:
return str(self.compile())
else:
- return unicode(self.compile()).encode("ascii", "backslashreplace")
+ return unicode(self.compile()).encode( # noqa
+ "ascii", "backslashreplace"
+ ) # noqa
def __and__(self, other):
"""'and' at the ClauseElement level.
__visit_name__ = "typeclause"
- def __init__(self, type):
- self.type = type
+ def __init__(self, type_):
+ self.type = type_
class TextClause(Executable, ClauseElement):
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
- The positional form of :meth:`.TextClause.columns` also provides
- the unique feature of **positional column targeting**, which is
- particularly useful when using the ORM with complex textual queries.
- If we specify the columns from our model to :meth:`.TextClause.columns`,
+ The positional form of :meth:`.TextClause.columns` also provides the
+ unique feature of **positional column targeting**, which is
+ particularly useful when using the ORM with complex textual queries. If
+ we specify the columns from our model to :meth:`.TextClause.columns`,
the result set will match to those columns positionally, meaning the
name or origin of the column in the textual SQL doesn't matter::
__visit_name__ = "cast"
def __init__(self, expression, type_):
- """Produce a ``CAST`` expression.
+ r"""Produce a ``CAST`` expression.
:func:`.cast` returns an instance of :class:`.Cast`.
expression or a Python string which will be coerced into a bound
literal value.
- :param type_: A :class:`.TypeEngine` class or instance indicating
+ :param type\_: A :class:`.TypeEngine` class or instance indicating
the type to which the ``CAST`` should apply.
.. seealso::
__visit_name__ = "type_coerce"
def __init__(self, expression, type_):
- """Associate a SQL expression with a particular type, without rendering
+ r"""Associate a SQL expression with a particular type, without rendering
``CAST``.
E.g.::
expression or a Python string which will be coerced into a bound
literal value.
- :param type_: A :class:`.TypeEngine` class or instance indicating
+ :param type\_: A :class:`.TypeEngine` class or instance indicating
the type to which the expression is coerced.
.. seealso::
def __init__(
self, element, partition_by=None, order_by=None, range_=None, rows=None
):
- """Produce an :class:`.Over` object against a function.
+ r"""Produce an :class:`.Over` object against a function.
Used against aggregate or so-called "window" functions,
for database backends that support window functions.
mutually-exclusive parameters each accept a 2-tuple, which contains
a combination of integers and None::
- func.row_number().over(order_by=my_table.c.some_column, range_=(None, 0))
+ func.row_number().over(
+ order_by=my_table.c.some_column, range_=(None, 0))
The above would produce::
- ROW_NUMBER() OVER(ORDER BY some_column RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
+ ROW_NUMBER() OVER(ORDER BY some_column
+ RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
A value of None indicates "unbounded", a
value of zero indicates "current row", and negative / positive
:param order_by: a column element or string, or a list
of such, that will be used as the ORDER BY clause
of the OVER construct.
- :param range_: optional range clause for the window. This is a
+ :param range\_: optional range clause for the window. This is a
tuple value which can contain integer values or None, and will
render a RANGE BETWEEN PRECEDING / FOLLOWING clause
]
-from .visitors import Visitable
-from .functions import func, modifier, FunctionElement, Function
-from ..util.langhelpers import public_factory
-from .elements import (
- ClauseElement,
- ColumnElement,
- BindParameter,
- CollectionAggregate,
- UnaryExpression,
- BooleanClauseList,
- Label,
- Cast,
- Case,
- ColumnClause,
- TextClause,
- Over,
- Null,
- True_,
- False_,
- BinaryExpression,
- Tuple,
- TypeClause,
- Extract,
- Grouping,
- WithinGroup,
- not_,
- quoted_name,
- collate,
- literal_column,
- between,
- literal,
- outparam,
- TypeCoerce,
- ClauseList,
- FunctionFilter,
-)
-
-from .elements import (
- SavepointClause,
- RollbackToSavepointClause,
- ReleaseSavepointClause,
-)
-
-from .base import ColumnCollection, Generative, Executable, PARSE_AUTOCOMMIT
-
-from .selectable import (
- Alias,
- Join,
- Select,
- Selectable,
- TableClause,
- CompoundSelect,
- CTE,
- FromClause,
- FromGrouping,
- Lateral,
- SelectBase,
- alias,
- GenerativeSelect,
- subquery,
- HasCTE,
- HasPrefixes,
- HasSuffixes,
- lateral,
- Exists,
- ScalarSelect,
- TextAsFrom,
- TableSample,
- tablesample,
-)
+from .base import _from_objects # noqa
+from .base import ColumnCollection # noqa
+from .base import Executable # noqa
+from .base import Generative # noqa
+from .base import PARSE_AUTOCOMMIT # noqa
+from .dml import Delete # noqa
+from .dml import Insert # noqa
+from .dml import Update # noqa
+from .dml import UpdateBase # noqa
+from .dml import ValuesBase # noqa
+from .elements import _clause_element_as_expr # noqa
+from .elements import _clone # noqa
+from .elements import _cloned_difference # noqa
+from .elements import _cloned_intersection # noqa
+from .elements import _column_as_key # noqa
+from .elements import _corresponding_column_or_error # noqa
+from .elements import _expression_literal_as_text # noqa
+from .elements import _is_column # noqa
+from .elements import _labeled # noqa
+from .elements import _literal_as_binds # noqa
+from .elements import _literal_as_label_reference # noqa
+from .elements import _literal_as_text # noqa
+from .elements import _only_column_elements # noqa
+from .elements import _select_iterables # noqa
+from .elements import _string_or_unprintable # noqa
+from .elements import _truncated_label # noqa
+from .elements import between # noqa
+from .elements import BinaryExpression # noqa
+from .elements import BindParameter # noqa
+from .elements import BooleanClauseList # noqa
+from .elements import Case # noqa
+from .elements import Cast # noqa
+from .elements import ClauseElement # noqa
+from .elements import ClauseList # noqa
+from .elements import collate # noqa
+from .elements import CollectionAggregate # noqa
+from .elements import ColumnClause # noqa
+from .elements import ColumnElement # noqa
+from .elements import Extract # noqa
+from .elements import False_ # noqa
+from .elements import FunctionFilter # noqa
+from .elements import Grouping # noqa
+from .elements import Label # noqa
+from .elements import literal # noqa
+from .elements import literal_column # noqa
+from .elements import not_ # noqa
+from .elements import Null # noqa
+from .elements import outparam # noqa
+from .elements import Over # noqa
+from .elements import quoted_name # noqa
+from .elements import ReleaseSavepointClause # noqa
+from .elements import RollbackToSavepointClause # noqa
+from .elements import SavepointClause # noqa
+from .elements import TextClause # noqa
+from .elements import True_ # noqa
+from .elements import Tuple # noqa
+from .elements import TypeClause # noqa
+from .elements import TypeCoerce # noqa
+from .elements import UnaryExpression # noqa
+from .elements import WithinGroup # noqa
+from .functions import func # noqa
+from .functions import Function # noqa
+from .functions import FunctionElement # noqa
+from .functions import modifier # noqa
+from .selectable import _interpret_as_from # noqa
+from .selectable import Alias # noqa
+from .selectable import alias # noqa
+from .selectable import CompoundSelect # noqa
+from .selectable import CTE # noqa
+from .selectable import Exists # noqa
+from .selectable import FromClause # noqa
+from .selectable import FromGrouping # noqa
+from .selectable import GenerativeSelect # noqa
+from .selectable import HasCTE # noqa
+from .selectable import HasPrefixes # noqa
+from .selectable import HasSuffixes # noqa
+from .selectable import Join # noqa
+from .selectable import Lateral # noqa
+from .selectable import lateral # noqa
+from .selectable import ScalarSelect # noqa
+from .selectable import Select # noqa
+from .selectable import Selectable # noqa
+from .selectable import SelectBase # noqa
+from .selectable import subquery # noqa
+from .selectable import TableClause # noqa
+from .selectable import TableSample # noqa
+from .selectable import tablesample # noqa
+from .selectable import TextAsFrom # noqa
+from .visitors import Visitable # noqa
+from ..util.langhelpers import public_factory # noqa
-from .dml import Insert, Update, Delete, UpdateBase, ValuesBase
-
# factory functions - these pull class-bound constructors and classmethods
# from SQL elements and selectables into public functions. This allows
# the functions to be available in the sqlalchemy.sql.* namespace and
label = public_factory(Label, ".expression.label")
case = public_factory(Case, ".expression.case")
cast = public_factory(Cast, ".expression.cast")
-extract = public_factory(Extract, ".expression.extract")
+extract = public_factory(Extract, ".exp # noqaression.extract")
tuple_ = public_factory(Tuple, ".expression.tuple_")
except_ = public_factory(CompoundSelect._create_except, ".expression.except_")
except_all = public_factory(
# internal functions still being called from tests and the ORM,
# these might be better off in some other namespace
-from .base import _from_objects
-from .elements import (
- _literal_as_text,
- _clause_element_as_expr,
- _is_column,
- _labeled,
- _only_column_elements,
- _string_or_unprintable,
- _truncated_label,
- _clone,
- _cloned_difference,
- _cloned_intersection,
- _column_as_key,
- _literal_as_binds,
- _select_iterables,
- _corresponding_column_or_error,
- _literal_as_label_reference,
- _expression_literal_as_text,
-)
-from .selectable import _interpret_as_from
# old names for compatibility
"""SQL function API, factories, and built-in functions.
"""
-from . import sqltypes, schema
-from .base import Executable, ColumnCollection
-from .elements import (
- ClauseList,
- Cast,
- Extract,
- _literal_as_binds,
- literal_column,
- _type_from_args,
- ColumnElement,
- _clone,
- Over,
- BindParameter,
- FunctionFilter,
- Grouping,
- WithinGroup,
- BinaryExpression,
-)
-from .selectable import FromClause, Select, Alias
-from . import util as sqlutil
+from . import annotation
from . import operators
+from . import schema
+from . import sqltypes
+from . import util as sqlutil
+from .base import ColumnCollection
+from .base import Executable
+from .elements import _clone
+from .elements import _literal_as_binds
+from .elements import _type_from_args
+from .elements import BinaryExpression
+from .elements import BindParameter
+from .elements import Cast
+from .elements import ClauseList
+from .elements import ColumnElement
+from .elements import Extract
+from .elements import FunctionFilter
+from .elements import Grouping
+from .elements import literal_column
+from .elements import Over
+from .elements import WithinGroup
+from .selectable import Alias
+from .selectable import FromClause
+from .selectable import Select
from .visitors import VisitableType
from .. import util
-from . import annotation
+
_registry = util.defaultdict(dict)
_has_args = True
-class max(ReturnTypeFromArgs):
+class max(ReturnTypeFromArgs): # noqa
pass
-class min(ReturnTypeFromArgs):
+class min(ReturnTypeFromArgs): # noqa
pass
-class sum(ReturnTypeFromArgs):
+class sum(ReturnTypeFromArgs): # noqa
pass
-class now(GenericFunction):
+class now(GenericFunction): # noqa
type = sqltypes.DateTime
.. seealso::
:func:`.postgresql.array_agg` - PostgreSQL-specific version that
- returns :class:`.postgresql.ARRAY`, which has PG-specific operators added.
+ returns :class:`.postgresql.ARRAY`, which has PG-specific operators
+ added.
"""
"""
-from .schema import (
- Constraint,
- ForeignKeyConstraint,
- PrimaryKeyConstraint,
- UniqueConstraint,
- CheckConstraint,
- Index,
- Table,
- Column,
-)
-from .. import event, events
-from .. import exc
-from .elements import _truncated_label, _defer_name, _defer_none_name, conv
import re
+from .elements import _defer_name
+from .elements import _defer_none_name
+from .elements import conv
+from .schema import CheckConstraint
+from .schema import Column
+from .schema import Constraint
+from .schema import ForeignKeyConstraint
+from .schema import Index
+from .schema import PrimaryKeyConstraint
+from .schema import Table
+from .schema import UniqueConstraint
+from .. import event
+from .. import events # noqa
+from .. import exc
+
class ConventionDict(object):
def __init__(self, const, table, convention):
"""Defines operators used in SQL expressions."""
+from operator import add
+from operator import and_
+from operator import contains
+from operator import eq
+from operator import ge
+from operator import getitem
+from operator import gt
+from operator import inv
+from operator import le
+from operator import lshift
+from operator import lt
+from operator import mod
+from operator import mul
+from operator import ne
+from operator import neg
+from operator import or_
+from operator import rshift
+from operator import sub
+from operator import truediv
+
from .. import util
-from operator import (
- and_,
- or_,
- inv,
- add,
- mul,
- sub,
- mod,
- truediv,
- lt,
- le,
- ne,
- gt,
- ge,
- eq,
- neg,
- getitem,
- lshift,
- rshift,
- contains,
-)
if util.py2k:
from operator import div
"""
from __future__ import absolute_import
-from .. import exc, util, event, inspection
-from .base import SchemaEventTarget, DialectKWArgs
-import operator
-from . import visitors
-from . import type_api
-from .base import _bind_or_error, ColumnCollection
-from .elements import (
- ClauseElement,
- ColumnClause,
- _as_truncated,
- TextClause,
- _literal_as_text,
- ColumnElement,
- quoted_name,
-)
-from .selectable import TableClause
import collections
+import operator
+
import sqlalchemy
from . import ddl
+from . import type_api
+from . import visitors
+from .base import _bind_or_error
+from .base import ColumnCollection
+from .base import DialectKWArgs
+from .base import SchemaEventTarget
+from .elements import _as_truncated
+from .elements import _literal_as_text
+from .elements import ClauseElement
+from .elements import ColumnClause
+from .elements import ColumnElement
+from .elements import quoted_name
+from .elements import TextClause
+from .selectable import TableClause
+from .. import event
+from .. import exc
+from .. import inspection
+from .. import util
+
RETAIN_SCHEMA = util.symbol("retain_schema")
the table resides in a schema other than the default selected schema
for the engine's database connection. Defaults to ``None``.
- If the owning :class:`.MetaData` of this :class:`.Table` specifies
- its own :paramref:`.MetaData.schema` parameter, then that schema
- name will be applied to this :class:`.Table` if the schema parameter
- here is set to ``None``. To set a blank schema name on a :class:`.Table`
- that would otherwise use the schema set on the owning :class:`.MetaData`,
+ If the owning :class:`.MetaData` of this :class:`.Table` specifies its
+ own :paramref:`.MetaData.schema` parameter, then that schema name will
+ be applied to this :class:`.Table` if the schema parameter here is set
+ to ``None``. To set a blank schema name on a :class:`.Table` that
+ would otherwise use the schema set on the owning :class:`.MetaData`,
specify the special symbol :attr:`.BLANK_SCHEMA`.
.. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to
The quoting rules for the schema name are the same as those for the
``name`` parameter, in that quoting is applied for reserved words or
- case-sensitive names; to enable unconditional quoting for the
- schema name, specify the flag
- ``quote_schema=True`` to the constructor, or use the
- :class:`.quoted_name` construct to specify the name.
+ case-sensitive names; to enable unconditional quoting for the schema
+ name, specify the flag ``quote_schema=True`` to the constructor, or use
+ the :class:`.quoted_name` construct to specify the name.
:param useexisting: Deprecated. Use :paramref:`.Table.extend_existing`.
Column('id', ForeignKey('other.id'),
primary_key=True, autoincrement='ignore_fk')
- It is typically not desirable to have "autoincrement" enabled
- on a column that refers to another via foreign key, as such a column
- is required to refer to a value that originates from elsewhere.
+ It is typically not desirable to have "autoincrement" enabled on a
+ column that refers to another via foreign key, as such a column is
+ required to refer to a value that originates from elsewhere.
The setting has these two effects on columns that meet the
above criteria:
To resolve these cycles, either the
:paramref:`.ForeignKeyConstraint.use_alter` parameter may be appled
to those constraints, or use the
- :func:`.schema.sort_tables_and_constraints` function which will break
- out foreign key constraints involved in cycles separately.
+ :func:`.schema.sort_tables_and_constraints` function which will
+ break out foreign key constraints involved in cycles separately.
.. seealso::
"""
-from .elements import (
- ClauseElement,
- TextClause,
- ClauseList,
- and_,
- Grouping,
- UnaryExpression,
- literal_column,
- BindParameter,
-)
-from .elements import (
- _clone,
- _literal_as_text,
- _interpret_as_column_or_from,
- _expand_cloned,
- _select_iterables,
- _anonymous_label,
- _clause_element_as_expr,
- _cloned_intersection,
- _cloned_difference,
- True_,
- _literal_as_label_reference,
- _literal_and_labels_as_label_reference,
-)
-from .base import (
- Immutable,
- Executable,
- _generative,
- ColumnCollection,
- ColumnSet,
- _from_objects,
- Generative,
-)
-from . import type_api
-from .. import inspection
-from .. import util
-from .. import exc
-from operator import attrgetter
-from . import operators
-import operator
import collections
-from .annotation import Annotated
import itertools
+import operator
+from operator import attrgetter
+
from sqlalchemy.sql.visitors import Visitable
+from . import operators
+from . import type_api
+from .annotation import Annotated
+from .base import _from_objects
+from .base import _generative
+from .base import ColumnCollection
+from .base import ColumnSet
+from .base import Executable
+from .base import Generative
+from .base import Immutable
+from .elements import _anonymous_label
+from .elements import _clause_element_as_expr
+from .elements import _clone
+from .elements import _cloned_difference
+from .elements import _cloned_intersection
+from .elements import _expand_cloned
+from .elements import _interpret_as_column_or_from
+from .elements import _literal_and_labels_as_label_reference
+from .elements import _literal_as_label_reference
+from .elements import _literal_as_text
+from .elements import _select_iterables
+from .elements import and_
+from .elements import BindParameter
+from .elements import ClauseElement
+from .elements import ClauseList
+from .elements import Grouping
+from .elements import literal_column
+from .elements import TextClause
+from .elements import True_
+from .elements import UnaryExpression
+from .. import exc
+from .. import inspection
+from .. import util
def _interpret_as_from(element):
to join, or no way to join, an error is raised.
:param ignore_nonexistent_tables: Deprecated - this
- flag is no longer used. Only resolution errors regarding
- the two given tables are propagated.
+ flag is no longer used. Only resolution errors regarding
+ the two given tables are propagated.
:param a_subset: An optional expression that is a sub-component
- of ``a``. An attempt will be made to join to just this sub-component
- first before looking at the full ``a`` construct, and if found
- will be successful even if there are other ways to join to ``a``.
- This allows the "right side" of a join to be passed thereby
- providing a "natural join".
+ of ``a``. An attempt will be made to join to just this sub-component
+ first before looking at the full ``a`` construct, and if found
+ will be successful even if there are other ways to join to ``a``.
+ This allows the "right side" of a join to be passed thereby
+ providing a "natural join".
"""
constraints = cls._joincond_scan_left_right(
"""Represent a TABLESAMPLE clause.
This object is constructed from the :func:`~.expression.tablesample` module
- level function as well as the :meth:`.FromClause.tablesample` method available
- on all :class:`.FromClause` subclasses.
+ level function as well as the :meth:`.FromClause.tablesample` method
+ available on all :class:`.FromClause` subclasses.
.. versionadded:: 1.1
a numerical value which usually renders as a ``LIMIT``
expression in the resulting select. Backends that don't
support ``LIMIT`` will attempt to provide similar
- functionality. This parameter is typically specified more naturally
- using the :meth:`.Select.limit` method on an existing
+ functionality. This parameter is typically specified more
+ naturally using the :meth:`.Select.limit` method on an existing
:class:`.Select`.
.. seealso::
"""
-import datetime as dt
import codecs
-import collections
+import datetime as dt
+import decimal
import json
from . import elements
-from .type_api import (
- TypeEngine,
- TypeDecorator,
- to_instance,
- Variant,
- Emulated,
- NativeForEmulated,
-)
-from .elements import (
- quoted_name,
- TypeCoerce as type_coerce,
- _defer_name,
- Slice,
- _literal_as_binds,
-)
-from .. import exc, util, processors
-from .base import _bind_or_error, SchemaEventTarget
from . import operators
-from .. import inspection
+from . import type_api
+from .base import _bind_or_error
+from .base import SchemaEventTarget
+from .elements import _defer_name
+from .elements import _literal_as_binds
+from .elements import quoted_name
+from .elements import Slice
+from .elements import TypeCoerce as type_coerce # noqa
+from .type_api import Emulated
+from .type_api import NativeForEmulated # noqa
+from .type_api import to_instance
+from .type_api import TypeDecorator
+from .type_api import TypeEngine
+from .type_api import Variant
from .. import event
-from ..util import pickle
+from .. import exc
+from .. import inspection
+from .. import processors
+from .. import util
from ..util import compat
-import decimal
+from ..util import pickle
+
if util.jython:
import array
raise NotImplementedError()
def __getitem__(self, index):
- adjusted_op, adjusted_right_expr, result_type = self._setup_getitem(
- index
- )
+ (
+ adjusted_op,
+ adjusted_right_expr,
+ result_type,
+ ) = self._setup_getitem(index)
return self.operate(
adjusted_op, adjusted_right_expr, result_type=result_type
)
"""A bool datatype.
- :class:`.Boolean` typically uses BOOLEAN or SMALLINT on the DDL side, and on
- the Python side deals in ``True`` or ``False``.
+ :class:`.Boolean` typically uses BOOLEAN or SMALLINT on the DDL side,
+ and on the Python side deals in ``True`` or ``False``.
The :class:`.Boolean` datatype currently has two levels of assertion
that the values persisted are simple true/false values. For all
just the basic type.
Index operations return an expression object whose type defaults to
- :class:`.JSON` by default, so that further JSON-oriented instructions
- may be called upon the result type. Note that there are backend-specific
- idiosyncracies here, including that the PostgreSQL database does not generally
- compare a "json" to a "json" structure without type casts. These idiosyncracies
- can be accommodated in a backend-neutral way by making explicit use
- of the :func:`.cast` and :func:`.type_coerce` constructs.
- Comparison of specific index elements of a :class:`.JSON` object
- to other objects works best if the **left hand side is CAST to a string**
- and the **right hand side is rendered as a JSON string**; a future SQLAlchemy
- feature such as a generic "astext" modifier may simplify this at some point:
+ :class:`.JSON` by default, so that further JSON-oriented instructions may
+ be called upon the result type. Note that there are backend-specific
+ idiosyncracies here, including that the PostgreSQL database does not
+ generally compare a "json" to a "json" structure without type casts. These
+ idiosyncracies can be accommodated in a backend-neutral way by making
+ explicit use of the :func:`.cast` and :func:`.type_coerce` constructs.
+ Comparison of specific index elements of a :class:`.JSON` object to other
+ objects works best if the **left hand side is CAST to a string** and the
+ **right hand side is rendered as a JSON string**; a future SQLAlchemy
+ feature such as a generic "astext" modifier may simplify this at some
+ point:
* **Compare an element of a JSON structure to a string**::
data_table.c.data['some_key'], String
) == type_coerce(55, JSON)
- * **Compare an element of a JSON structure to some other JSON structure** - note
- that Python dictionaries are typically not ordered so care should be taken
- here to assert that the JSON structures are identical::
+ * **Compare an element of a JSON structure to some other JSON structure**
+ - note that Python dictionaries are typically not ordered so care should
+ be taken here to assert that the JSON structures are identical::
from sqlalchemy import cast, type_coerce
from sqlalchemy import String, JSON
from sqlalchemy import null
from sqlalchemy.dialects.postgresql import JSON
- obj1 = MyObject(json_value=null()) # will *always* insert SQL NULL
- obj2 = MyObject(json_value=JSON.NULL) # will *always* insert JSON string "null"
+ # will *always* insert SQL NULL
+ obj1 = MyObject(json_value=null())
+
+ # will *always* insert JSON string "null"
+ obj2 = MyObject(json_value=JSON.NULL)
session.add_all([obj1, obj2])
session.commit()
:paramref:`.JSON.none_as_null` does **not** apply to the
values passed to :paramref:`.Column.default` and
- :paramref:`.Column.server_default`; a value of ``None`` passed for
- these parameters means "no default present".
+ :paramref:`.Column.server_default`; a value of ``None``
+ passed for these parameters means "no default present".
.. seealso::
with PostgreSQL, as it provides additional operators specific
to that backend.
- :class:`.types.ARRAY` is part of the Core in support of various SQL standard
- functions such as :class:`.array_agg` which explicitly involve arrays;
- however, with the exception of the PostgreSQL backend and possibly
- some third-party dialects, no other SQLAlchemy built-in dialect has
- support for this type.
+ :class:`.types.ARRAY` is part of the Core in support of various SQL
+ standard functions such as :class:`.array_agg` which explicitly involve
+ arrays; however, with the exception of the PostgreSQL backend and possibly
+ some third-party dialects, no other SQLAlchemy built-in dialect has support
+ for this type.
An :class:`.types.ARRAY` type is constructed given the "type"
of element::
serves to define the kind of type that the ``[]`` operator should
return, e.g. for an ARRAY of INTEGER with two dimensions::
- >>> expr = table.c.column[5] # returns ARRAY(Integer, dimensions=1)
- >>> expr = expr[6] # returns Integer
+ >>> expr = table.c.column[5] # returns ARRAY(Integer, dimensions=1)
+ >>> expr = expr[6] # returns Integer
For 1-dimensional arrays, an :class:`.types.ARRAY` instance with no
dimension parameter will generally assume single-dimensional behaviors.
})
The :class:`.types.ARRAY` type also provides for the operators
- :meth:`.types.ARRAY.Comparator.any` and :meth:`.types.ARRAY.Comparator.all`.
- The PostgreSQL-specific version of :class:`.types.ARRAY` also provides additional
- operators.
+ :meth:`.types.ARRAY.Comparator.any` and
+ :meth:`.types.ARRAY.Comparator.all`. The PostgreSQL-specific version of
+ :class:`.types.ARRAY` also provides additional operators.
.. versionadded:: 1.1.0
}
if util.py3k:
- _type_map[bytes] = LargeBinary()
+ _type_map[bytes] = LargeBinary() # noqa
_type_map[str] = Unicode()
else:
- _type_map[unicode] = Unicode()
+ _type_map[unicode] = Unicode() # noqa
_type_map[str] = String()
_type_map_get = _type_map.get
# back-assign to type_api
-from . import type_api
-
type_api.BOOLEANTYPE = BOOLEANTYPE
type_api.STRINGTYPE = STRINGTYPE
type_api.INTEGERTYPE = INTEGERTYPE
"""
-from .. import exc, util
from . import operators
-from .visitors import Visitable, VisitableType
from .base import SchemaEventTarget
+from .visitors import Visitable
+from .visitors import VisitableType
+from .. import exc
+from .. import util
+
# these are back-assigned by sqltypes.
BOOLEANTYPE = None
raise NotImplementedError()
def with_variant(self, type_, dialect_name):
- """Produce a new type object that will utilize the given
+ r"""Produce a new type object that will utilize the given
type when applied to the dialect of the given name.
e.g.::
itself provides a :meth:`.Variant.with_variant`
that can be called repeatedly.
- :param type_: a :class:`.TypeEngine` that will be selected
+ :param type\_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param dialect_name: base name of the dialect which uses
def __str__(self):
if util.py2k:
- return unicode(self.compile()).encode("ascii", "backslashreplace")
+ return unicode(self.compile()).encode( # noqa
+ "ascii", "backslashreplace"
+ ) # noqa
else:
return str(self.compile())
impl._set_parent_with_dispatch(parent)
def with_variant(self, type_, dialect_name):
- """Return a new :class:`.Variant` which adds the given
+ r"""Return a new :class:`.Variant` which adds the given
type + dialect name to the mapping, in addition to the
mapping present in this :class:`.Variant`.
- :param type_: a :class:`.TypeEngine` that will be selected
+ :param type\_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param dialect_name: base name of the dialect which uses
"""
-from .. import exc, util
-from .base import _from_objects, ColumnSet
-from . import operators, visitors
-from itertools import chain
from collections import deque
+from itertools import chain
-from .elements import (
- BindParameter,
- ColumnClause,
- ColumnElement,
- Null,
- UnaryExpression,
- literal_column,
- Label,
- _label_reference,
- _textual_label_reference,
-)
-from .selectable import (
- SelectBase,
- ScalarSelect,
- Join,
- FromClause,
- FromGrouping,
-)
+from . import operators
+from . import visitors
+from .annotation import _deep_annotate # noqa
+from .annotation import _deep_deannotate # noqa
+from .annotation import _shallow_annotate # noqa
+from .base import _from_objects
+from .base import ColumnSet
+from .ddl import sort_tables # noqa
+from .elements import _find_columns # noqa
+from .elements import _label_reference
+from .elements import _textual_label_reference
+from .elements import BindParameter
+from .elements import ColumnClause
+from .elements import ColumnElement
+from .elements import Null
+from .elements import UnaryExpression
from .schema import Column
+from .selectable import FromClause
+from .selectable import FromGrouping
+from .selectable import Join
+from .selectable import ScalarSelect
+from .selectable import SelectBase
+from .. import exc
+from .. import util
+
join_condition = util.langhelpers.public_factory(
Join._join_condition, ".sql.util.join_condition"
)
-# names that are still being imported from the outside
-from .annotation import _shallow_annotate, _deep_annotate, _deep_deannotate
-from .elements import _find_columns
-from .ddl import sort_tables
-
def find_join_source(clauses, join_to):
"""Given a list of FROM clauses and a selectable,
"""
from collections import deque
-from .. import util
import operator
+
from .. import exc
+from .. import util
+
__all__ = [
"VisitableType",
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .warnings import assert_warnings
-
-from . import config
-
-from .exclusions import (
- db_spec,
- _is_excluded,
- fails_if,
- skip_if,
- future,
- fails_on,
- fails_on_everything_except,
- skip,
- only_on,
- exclude,
- against as _against,
- _server_version,
- only_if,
- fails,
-)
+from . import config # noqa
+from . import mock # noqa
+from .assertions import assert_raises # noqa
+from .assertions import assert_raises_message # noqa
+from .assertions import AssertsCompiledSQL # noqa
+from .assertions import AssertsExecutionResults # noqa
+from .assertions import ComparesTables # noqa
+from .assertions import emits_warning # noqa
+from .assertions import emits_warning_on # noqa
+from .assertions import eq_ # noqa
+from .assertions import eq_ignore_whitespace # noqa
+from .assertions import eq_regex # noqa
+from .assertions import expect_deprecated # noqa
+from .assertions import expect_warnings # noqa
+from .assertions import in_ # noqa
+from .assertions import is_ # noqa
+from .assertions import is_false # noqa
+from .assertions import is_not_ # noqa
+from .assertions import is_true # noqa
+from .assertions import le_ # noqa
+from .assertions import ne_ # noqa
+from .assertions import not_in_ # noqa
+from .assertions import startswith_ # noqa
+from .assertions import uses_deprecated # noqa
+from .config import db # noqa
+from .config import requirements as requires # noqa
+from .exclusions import _is_excluded # noqa
+from .exclusions import _server_version # noqa
+from .exclusions import against as _against # noqa
+from .exclusions import db_spec # noqa
+from .exclusions import exclude # noqa
+from .exclusions import fails # noqa
+from .exclusions import fails_if # noqa
+from .exclusions import fails_on # noqa
+from .exclusions import fails_on_everything_except # noqa
+from .exclusions import future # noqa
+from .exclusions import only_if # noqa
+from .exclusions import only_on # noqa
+from .exclusions import skip # noqa
+from .exclusions import skip_if # noqa
+from .util import adict # noqa
+from .util import fail # noqa
+from .util import force_drop_names # noqa
+from .util import provide_metadata # noqa
+from .util import rowset # noqa
+from .util import run_as_contextmanager # noqa
+from .util import teardown_events # noqa
+from .warnings import assert_warnings # noqa
def against(*queries):
return _against(config._current, *queries)
-from .assertions import (
- emits_warning,
- emits_warning_on,
- uses_deprecated,
- eq_,
- ne_,
- le_,
- is_,
- is_not_,
- startswith_,
- assert_raises,
- assert_raises_message,
- AssertsCompiledSQL,
- ComparesTables,
- AssertsExecutionResults,
- expect_deprecated,
- expect_warnings,
- in_,
- not_in_,
- eq_ignore_whitespace,
- eq_regex,
- is_true,
- is_false,
-)
-
-from .util import (
- run_as_contextmanager,
- rowset,
- fail,
- provide_metadata,
- adict,
- force_drop_names,
- teardown_events,
-)
-
crashes = skip
-
-from .config import db
-from .config import requirements as requires
-
-from . import mock
from __future__ import absolute_import
-from . import util as testutil
-from sqlalchemy import pool, orm, util
-from sqlalchemy.engine import default, url
-from sqlalchemy.util import decorator, compat
-from sqlalchemy import types as sqltypes, schema, exc as sa_exc
-import warnings
+import contextlib
import re
-from .exclusions import db_spec
+import warnings
+
from . import assertsql
from . import config
-from .util import fail
-import contextlib
from . import mock
+from . import util as testutil
+from .exclusions import db_spec
+from .util import fail
+from .. import exc as sa_exc
+from .. import orm
+from .. import pool
+from .. import schema
+from .. import types as sqltypes
+from .. import util
+from ..engine import default
+from ..engine import url
+from ..util import compat
+from ..util import decorator
def expect_warnings(*messages, **kw):
print(repr(result))
self.assert_list(result, class_, objects)
- def assert_list(self, result, class_, list):
+ def assert_list(self, result, class_, list_):
self.assert_(
- len(result) == len(list),
+ len(result) == len(list_),
"result list is not the same size as test list, "
+ "for class "
+ class_.__name__,
)
- for i in range(0, len(list)):
- self.assert_row(class_, result[i], list[i])
+ for i in range(0, len(list_)):
+ self.assert_row(class_, result[i], list_[i])
def assert_row(self, class_, rowobj, desc):
self.assert_(
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from ..engine.default import DefaultDialect
-from .. import util
-import re
import collections
import contextlib
+import re
+
from .. import event
-from sqlalchemy.schema import _DDLCompiles
-from sqlalchemy.engine.util import _distill_params
-from sqlalchemy.engine import url
+from .. import util
+from ..engine import url
+from ..engine.default import DefaultDialect
+from ..engine.util import _distill_params
+from ..schema import _DDLCompiles
class AssertRule(object):
from __future__ import absolute_import
+import re
+import warnings
import weakref
+
from . import config
from .util import decorator
-from .. import event, pool
-import re
-import warnings
+from .. import event
+from .. import pool
class ConnectionKiller(object):
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import sqlalchemy as sa
-from sqlalchemy import exc as sa_exc
+from .. import exc as sa_exc
+
_repr_stack = set()
import operator
import re
-from sqlalchemy.util.compat import inspect_getargspec
-
from . import config
from .. import util
from ..util import decorator
+from ..util.compat import inspect_getargspec
def skip_if(predicate, reason=None):
return OrPredicate([Predicate.as_predicate(db) for db in dbs])
-def open():
+def open(): # noqa
return skip_if(BooleanPredicate(False, "mark as execute"))
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
+import sys
+
+import sqlalchemy as sa
+from . import assertions
from . import config
-from . import assertions, schema
+from . import schema
+from .engines import drop_all_tables
+from .entities import BasicEntity
+from .entities import ComparableEntity
from .util import adict
+from .. import event
from .. import util
-from .engines import drop_all_tables
-from .entities import BasicEntity, ComparableEntity
-import sys
-import sqlalchemy as sa
-from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
+from ..ext.declarative import declarative_base
+from ..ext.declarative import DeclarativeMeta
+
# whether or not we use unittest changes things dramatically,
# as far as how py.test collection works.
)
-from sqlalchemy import event
-
-
class RemovesEvents(object):
@util.memoized_property
def _event_fns(self):
"""Import stub for mock library.
"""
from __future__ import absolute_import
+
from ..util import py33
+
if py33:
- from unittest.mock import MagicMock, Mock, call, patch, ANY
+ from unittest.mock import MagicMock
+ from unittest.mock import Mock
+ from unittest.mock import call
+ from unittest.mock import patch
+ from unittest.mock import ANY
else:
try:
- from mock import MagicMock, Mock, call, patch, ANY
+ from mock import MagicMock # noqa
+ from mock import Mock # noqa
+ from mock import call # noqa
+ from mock import patch # noqa
+ from mock import ANY # noqa
except ImportError:
raise ImportError(
"SQLAlchemy's test suite requires the "
import os
import sys
+
bootstrap_file = locals()["bootstrap_file"]
to_bootstrap = locals()["to_bootstrap"]
import os
import sys
-from nose.plugins import Plugin
import nose
+from nose.plugins import Plugin
+
fixtures = None
from __future__ import absolute_import
-import sys
import re
+import sys
+
py3k = sys.version_info >= (3, 0)
# late imports, has to happen after config as well
# as nose plugins like coverage
- global util, fixtures, engines, exclusions, assertions, warnings, profiling, config, testing
+ global util, fixtures, engines, exclusions, assertions
+ global warnings, profiling, config, testing
from sqlalchemy import testing # noqa
from sqlalchemy.testing import fixtures, engines, exclusions # noqa
from sqlalchemy.testing import assertions, warnings, profiling # noqa
# pytest junit plugin, which is tripped up by the brackets
# and periods, so sanitize
- alpha_name = re.sub("[_\[\]\.]+", "_", cfg.name)
- alpha_name = re.sub("_+$", "", alpha_name)
+ alpha_name = re.sub(r"[_\[\]\.]+", "_", cfg.name)
+ alpha_name = re.sub(r"_+$", "", alpha_name)
name = "%s_%s" % (cls.__name__, alpha_name)
subcls = type(
name,
# assume we're a package, use traditional import
from . import plugin_base
-import pytest
import argparse
-import inspect
import collections
+import inspect
import os
+import pytest
+
+
try:
import xdist # noqa
dest,
default=False,
required=False,
- help=None,
+ help=None, # noqa
):
super(CallableAction, self).__init__(
option_strings=option_strings,
"""
+import collections
+import contextlib
import os
+import pstats
import sys
-from .util import gc_collect
+
from . import config
-import pstats
-import collections
-import contextlib
+from .util import gc_collect
+from ..util import jython
+from ..util import pypy
+from ..util import update_wrapper
+from ..util import win32
+
try:
import cProfile
except ImportError:
cProfile = None
-from ..util import jython, pypy, win32, update_wrapper
_current_test = None
-from sqlalchemy.engine import url as sa_url
-from sqlalchemy import create_engine
-from sqlalchemy import text
-from sqlalchemy import exc
-from sqlalchemy.util import compat
-from . import config, engines
import collections
+import logging
import os
import time
-import logging
+
+from . import config
+from . import engines
+from .. import create_engine
+from .. import exc
+from .. import text
+from ..engine import url as sa_url
+from ..util import compat
+
log = logging.getLogger(__name__)
template_db,
)
time.sleep(0.5)
+ except:
+ raise
else:
break
try:
# typically when this happens, we can't KILL the session anyway,
# so let the cleanup process drop the DBs
- # for row in conn.execute("select session_id from sys.dm_exec_sessions "
+ # for row in conn.execute(
+ # "select session_id from sys.dm_exec_sessions "
# "where database_id=db_id('%s')" % ident):
# log.info("killing SQL server sesssion %s", row['session_id'])
# conn.execute("kill %s" % row['session_id'])
-from . import fixtures
-from . import profiling
-from .. import util
-import types
from collections import deque
import contextlib
+import types
+
from . import config
-from sqlalchemy import MetaData
-from sqlalchemy import create_engine
-from sqlalchemy.orm import Session
+from . import fixtures
+from . import profiling
+from .. import create_engine
+from .. import MetaData
+from .. import util
+from ..orm import Session
class ReplayFixtureTest(fixtures.TestBase):
dbapi_session = ReplayableSession()
creator = config.db.pool._creator
- recorder = lambda: dbapi_session.recorder(creator())
+
+ def recorder():
+ return dbapi_session.recorder(creator())
+
engine = create_engine(
config.db.url, creator=recorder, use_native_hstore=False
)
self.teardown_engine()
engine.dispose()
- player = lambda: dbapi_session.player()
+ def player():
+ return dbapi_session.player()
+
engine = create_engine(
config.db.url, creator=player, use_native_hstore=False
)
@property
def sane_rowcount_w_returning(self):
return exclusions.fails_if(
- lambda config: not config.db.dialect.supports_sane_rowcount_returning,
+ lambda config: not (
+ config.db.dialect.supports_sane_rowcount_returning
+ ),
"driver doesn't support 'sane' rowcount when returning is on",
)
present in a subquery in the WHERE clause.
This is an ANSI-standard syntax that apparently MySQL can't handle,
- such as:
+ such as::
+
+ UPDATE documents SET flag=1 WHERE documents.title IN
+ (SELECT max(documents.title) AS title
+ FROM documents GROUP BY documents.user_id
+ )
- UPDATE documents SET flag=1 WHERE documents.title IN
- (SELECT max(documents.title) AS title
- FROM documents GROUP BY documents.user_id
- )
"""
return exclusions.open()
def _has_cextensions(self):
try:
- from sqlalchemy import cresultproxy, cprocessors
+ from sqlalchemy import cresultproxy, cprocessors # noqa
return True
except ImportError:
"""
-from .plugin.noseplugin import NoseSQLAlchemy
-
import nose
+from .plugin.noseplugin import NoseSQLAlchemy
+
def main():
nose.main(addplugins=[NoseSQLAlchemy()])
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from . import exclusions
-from .. import schema, event
from . import config
+from . import exclusions
+from .. import event
+from .. import schema
+
-__all__ = "Table", "Column"
+__all__ = ["Table", "Column"]
table_options = {}
-from sqlalchemy.testing.suite.test_cte import *
-from sqlalchemy.testing.suite.test_dialect import *
-from sqlalchemy.testing.suite.test_ddl import *
-from sqlalchemy.testing.suite.test_insert import *
-from sqlalchemy.testing.suite.test_sequence import *
-from sqlalchemy.testing.suite.test_select import *
-from sqlalchemy.testing.suite.test_results import *
-from sqlalchemy.testing.suite.test_update_delete import *
-from sqlalchemy.testing.suite.test_reflection import *
-from sqlalchemy.testing.suite.test_types import *
+from .test_cte import * # noqa
+from .test_ddl import * # noqa
+from .test_dialect import * # noqa
+from .test_insert import * # noqa
+from .test_reflection import * # noqa
+from .test_results import * # noqa
+from .test_select import * # noqa
+from .test_sequence import * # noqa
+from .test_types import * # noqa
+from .test_update_delete import * # noqa
-from .. import fixtures, config
+from .. import config
+from .. import fixtures
from ..assertions import eq_
-
-from sqlalchemy import Integer, String, select
-from sqlalchemy import ForeignKey
-from sqlalchemy import testing
-
-from ..schema import Table, Column
+from ..schema import Column
+from ..schema import Table
+from ... import ForeignKey
+from ... import Integer
+from ... import select
+from ... import String
+from ... import testing
class CTETest(fixtures.TablesTest):
-from .. import fixtures, config, util
-from ..config import requirements
+from .. import config
+from .. import fixtures
+from .. import util
from ..assertions import eq_
-
-from sqlalchemy import Table, Column, Integer, String
+from ..config import requirements
+from ... import Column
+from ... import Integer
+from ... import String
+from ... import Table
class TableDDLTest(fixtures.TestBase):
-from .. import fixtures, config
-from ..config import requirements
-from sqlalchemy import exc
-from sqlalchemy import Integer, String, select, literal_column
from .. import assert_raises
-from ..schema import Table, Column
-from .. import provide_metadata
+from .. import config
from .. import eq_
+from .. import fixtures
+from .. import provide_metadata
+from ..config import requirements
+from ..schema import Column
+from ..schema import Table
+from ... import exc
+from ... import Integer
+from ... import literal_column
+from ... import select
+from ... import String
class ExceptionTest(fixtures.TablesTest):
-from .. import fixtures, config
-from ..config import requirements
-from .. import exclusions
-from ..assertions import eq_
+from .. import config
from .. import engines
-
-from sqlalchemy import Integer, String, select, literal_column, literal
-
-from ..schema import Table, Column
+from .. import fixtures
+from ..assertions import eq_
+from ..config import requirements
+from ..schema import Column
+from ..schema import Table
+from ... import Integer
+from ... import literal
+from ... import literal_column
+from ... import select
+from ... import String
class LastrowidTest(fixtures.TablesTest):
-import sqlalchemy as sa
-from sqlalchemy import exc as sa_exc
-from sqlalchemy import types as sql_types
-from sqlalchemy import inspect
-from sqlalchemy import MetaData, Integer, String, func
-from sqlalchemy.engine.reflection import Inspector
-from sqlalchemy.testing import engines, fixtures
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing import eq_, is_, assert_raises_message
-from sqlalchemy import testing
-from .. import config
import operator
-from sqlalchemy.schema import DDL, Index
-from sqlalchemy import event
-from sqlalchemy.sql.elements import quoted_name
-from sqlalchemy import ForeignKey
import re
+import sqlalchemy as sa
+from .. import assert_raises_message
+from .. import config
+from .. import engines
+from .. import eq_
+from .. import fixtures
+from .. import is_
+from ..schema import Column
+from ..schema import Table
+from ... import event
+from ... import exc as sa_exc
+from ... import ForeignKey
+from ... import inspect
+from ... import Integer
+from ... import MetaData
+from ... import String
+from ... import testing
+from ... import types as sql_types
+from ...engine.reflection import Inspector
+from ...schema import DDL
+from ...schema import Index
+from ...sql.elements import quoted_name
+
+
metadata, users = None, None
{"comment": "id comment", "name": "id"},
{"comment": "data % comment", "name": "data"},
{
- "comment": r"""Comment types type speedily ' " \ '' Fun!""",
+ "comment": (
+ r"""Comment types type speedily ' " \ '' Fun!"""
+ ),
"name": "d2",
},
],
-from .. import fixtures, config
-from ..config import requirements
-from .. import exclusions
-from ..assertions import eq_
+import datetime
+
+from .. import config
from .. import engines
+from .. import fixtures
+from ..assertions import eq_
+from ..config import requirements
+from ..schema import Column
+from ..schema import Table
+from ... import DateTime
+from ... import func
+from ... import Integer
+from ... import select
+from ... import sql
+from ... import String
from ... import testing
-
-from sqlalchemy import Integer, String, select, util, sql, DateTime, text, func
-import datetime
-from ..schema import Table, Column
+from ... import text
class RowFetchTest(fixtures.TablesTest):
-from sqlalchemy.dialects.mssql.base import MSDialect
-from sqlalchemy.dialects.oracle.base import OracleDialect
-from .. import fixtures, config
-from ..assertions import eq_, in_
-
-from sqlalchemy import util, case, null, true, false, or_
-from sqlalchemy import Integer, String, select, func, bindparam, union, tuple_
-from sqlalchemy import testing
-from sqlalchemy import literal_column
-
-from ..schema import Table, Column
+from .. import config
+from .. import fixtures
+from ..assertions import eq_
+from ..assertions import in_
+from ..schema import Column
+from ..schema import Table
+from ... import bindparam
+from ... import case
+from ... import false
+from ... import func
+from ... import Integer
+from ... import literal_column
+from ... import null
+from ... import select
+from ... import String
+from ... import testing
+from ... import true
+from ... import tuple_
+from ... import union
+from ... import util
class CollateTest(fixtures.TablesTest):
-from .. import fixtures, config
-from ..config import requirements
+from .. import config
+from .. import fixtures
from ..assertions import eq_
+from ..config import requirements
+from ..schema import Column
+from ..schema import Table
+from ... import Integer
+from ... import MetaData
+from ... import schema
+from ... import Sequence
+from ... import String
from ... import testing
-from ... import Integer, String, Sequence, schema, MetaData
-
-from ..schema import Table, Column
-
class SequenceTest(fixtures.TablesTest):
__requires__ = ("sequences",)
# coding: utf-8
-from .. import fixtures, config
+import datetime
+import decimal
+
+from .. import config
+from .. import fixtures
from ..assertions import eq_
from ..config import requirements
-from sqlalchemy import Integer, Unicode, UnicodeText, select, TIMESTAMP
-from sqlalchemy import (
- Date,
- DateTime,
- Time,
- MetaData,
- String,
- Text,
- Numeric,
- Float,
- literal,
- Boolean,
- cast,
- null,
- JSON,
- and_,
- type_coerce,
- BigInteger,
-)
-from ..schema import Table, Column
+from ..schema import Column
+from ..schema import Table
+from ... import and_
+from ... import BigInteger
+from ... import Boolean
+from ... import cast
+from ... import Date
+from ... import DateTime
+from ... import Float
+from ... import Integer
+from ... import JSON
+from ... import literal
+from ... import MetaData
+from ... import null
+from ... import Numeric
+from ... import select
+from ... import String
from ... import testing
-import decimal
-import datetime
-from ...util import u
+from ... import Text
+from ... import Time
+from ... import TIMESTAMP
+from ... import type_coerce
+from ... import Unicode
+from ... import UnicodeText
from ... import util
+from ...ext.declarative import declarative_base
+from ...orm import Session
+from ...util import u
class _LiteralRoundTripFixture(object):
if util.py3k:
assert isinstance(row[0], int)
else:
- assert isinstance(row[0], (long, int))
+ assert isinstance(row[0], (long, int)) # noqa
class NumericTest(_LiteralRoundTripFixture, fixtures.TestBase):
)
def test_eval_none_flag_orm(self):
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm import Session
Base = declarative_base()
-from .. import fixtures, config
+from .. import config
+from .. import fixtures
from ..assertions import eq_
-
-from sqlalchemy import Integer, String
-from ..schema import Table, Column
+from ..schema import Column
+from ..schema import Table
+from ... import Integer
+from ... import String
class SimpleUpdateDeleteTest(fixtures.TablesTest):
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from ..util import jython, pypy, defaultdict, decorator, py2k
import decimal
import gc
-import time
import random
import sys
+import time
import types
+from ..util import decorator
+from ..util import defaultdict
+from ..util import jython
+from ..util import py2k
+from ..util import pypy
+
+
if jython:
def jython_gc_collect(*args):
from __future__ import absolute_import
import warnings
-from .. import exc as sa_exc
+
from . import assertions
+from .. import exc as sa_exc
def setup_filters():
"JSON",
]
-from .sql.type_api import (
- adapt_type,
- TypeEngine,
- TypeDecorator,
- Variant,
- to_instance,
- UserDefinedType,
-)
-from .sql.sqltypes import (
- ARRAY,
- BIGINT,
- BINARY,
- BLOB,
- BOOLEAN,
- BigInteger,
- Binary,
- _Binary,
- Boolean,
- CHAR,
- CLOB,
- Concatenable,
- DATE,
- DATETIME,
- DECIMAL,
- Date,
- DateTime,
- Enum,
- FLOAT,
- Float,
- Indexable,
- INT,
- INTEGER,
- Integer,
- Interval,
- JSON,
- LargeBinary,
- MatchType,
- NCHAR,
- NVARCHAR,
- NullType,
- NULLTYPE,
- NUMERIC,
- Numeric,
- PickleType,
- REAL,
- SchemaType,
- SMALLINT,
- SmallInteger,
- String,
- STRINGTYPE,
- TEXT,
- TIME,
- TIMESTAMP,
- Text,
- Time,
- Unicode,
- UnicodeText,
- VARBINARY,
- VARCHAR,
-)
+from .sql.sqltypes import _Binary # noqa
+from .sql.sqltypes import ARRAY # noqa
+from .sql.sqltypes import BIGINT # noqa
+from .sql.sqltypes import BigInteger # noqa
+from .sql.sqltypes import BINARY # noqa
+from .sql.sqltypes import Binary # noqa
+from .sql.sqltypes import BLOB # noqa
+from .sql.sqltypes import BOOLEAN # noqa
+from .sql.sqltypes import Boolean # noqa
+from .sql.sqltypes import CHAR # noqa
+from .sql.sqltypes import CLOB # noqa
+from .sql.sqltypes import Concatenable # noqa
+from .sql.sqltypes import DATE # noqa
+from .sql.sqltypes import Date # noqa
+from .sql.sqltypes import DATETIME # noqa
+from .sql.sqltypes import DateTime # noqa
+from .sql.sqltypes import DECIMAL # noqa
+from .sql.sqltypes import Enum # noqa
+from .sql.sqltypes import FLOAT # noqa
+from .sql.sqltypes import Float # noqa
+from .sql.sqltypes import Indexable # noqa
+from .sql.sqltypes import INT # noqa
+from .sql.sqltypes import INTEGER # noqa
+from .sql.sqltypes import Integer # noqa
+from .sql.sqltypes import Interval # noqa
+from .sql.sqltypes import JSON # noqa
+from .sql.sqltypes import LargeBinary # noqa
+from .sql.sqltypes import MatchType # noqa
+from .sql.sqltypes import NCHAR # noqa
+from .sql.sqltypes import NULLTYPE # noqa
+from .sql.sqltypes import NullType # noqa
+from .sql.sqltypes import NUMERIC # noqa
+from .sql.sqltypes import Numeric # noqa
+from .sql.sqltypes import NVARCHAR # noqa
+from .sql.sqltypes import PickleType # noqa
+from .sql.sqltypes import REAL # noqa
+from .sql.sqltypes import SchemaType # noqa
+from .sql.sqltypes import SMALLINT # noqa
+from .sql.sqltypes import SmallInteger # noqa
+from .sql.sqltypes import String # noqa
+from .sql.sqltypes import STRINGTYPE # noqa
+from .sql.sqltypes import TEXT # noqa
+from .sql.sqltypes import Text # noqa
+from .sql.sqltypes import TIME # noqa
+from .sql.sqltypes import Time # noqa
+from .sql.sqltypes import TIMESTAMP # noqa
+from .sql.sqltypes import Unicode # noqa
+from .sql.sqltypes import UnicodeText # noqa
+from .sql.sqltypes import VARBINARY # noqa
+from .sql.sqltypes import VARCHAR # noqa
+from .sql.type_api import adapt_type # noqa
+from .sql.type_api import to_instance # noqa
+from .sql.type_api import TypeDecorator # noqa
+from .sql.type_api import TypeEngine # noqa
+from .sql.type_api import UserDefinedType # noqa
+from .sql.type_api import Variant # noqa
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-from .compat import (
- callable,
- cmp,
- reduce,
- threading,
- py3k,
- py33,
- py36,
- py2k,
- jython,
- pypy,
- cpython,
- win32,
- pickle,
- dottedgetter,
- parse_qsl,
- namedtuple,
- next,
- reraise,
- raise_from_cause,
- text_type,
- safe_kwarg,
- string_types,
- int_types,
- binary_type,
- nested,
- quote_plus,
- with_metaclass,
- print_,
- itertools_filterfalse,
- u,
- ue,
- b,
- unquote_plus,
- unquote,
- b64decode,
- b64encode,
- byte_buffer,
- itertools_filter,
- iterbytes,
- StringIO,
- inspect_getargspec,
- zip_longest,
-)
-from ._collections import (
- KeyedTuple,
- ImmutableContainer,
- immutabledict,
- Properties,
- OrderedProperties,
- ImmutableProperties,
- OrderedDict,
- OrderedSet,
- IdentitySet,
- OrderedIdentitySet,
- column_set,
- column_dict,
- ordered_column_set,
- populate_column_dict,
- unique_list,
- UniqueAppender,
- PopulateDict,
- EMPTY_SET,
- to_list,
- to_set,
- to_column_set,
- update_copy,
- flatten_iterator,
- has_intersection,
- LRUCache,
- ScopedRegistry,
- ThreadLocalRegistry,
- WeakSequence,
- coerce_generator_arg,
- lightweight_named_tuple,
- collections_abc,
- has_dupes,
-)
+from collections import defaultdict # noqa
+from contextlib import contextmanager # noqa
+from functools import partial # noqa
+from functools import update_wrapper # noqa
-from .langhelpers import (
- iterate_attributes,
- class_hierarchy,
- portable_instancemethod,
- unbound_method_to_callable,
- getargspec_init,
- format_argspec_init,
- format_argspec_plus,
- get_func_kwargs,
- get_cls_kwargs,
- decorator,
- as_interface,
- memoized_property,
- memoized_instancemethod,
- md5_hex,
- group_expirable_memoized_property,
- dependencies,
- decode_slice,
- monkeypatch_proxied_specials,
- asbool,
- bool_or_str,
- coerce_kw_type,
- duck_type_collection,
- assert_arg_type,
- symbol,
- dictlike_iteritems,
- classproperty,
- set_creation_order,
- warn_exception,
- warn,
- NoneType,
- constructor_copy,
- methods_equivalent,
- chop_traceback,
- asint,
- generic_repr,
- counter,
- PluginLoader,
- hybridproperty,
- hybridmethod,
- safe_reraise,
- quoted_token_parser,
- get_callable_argspec,
- only_once,
- attrsetter,
- ellipses_string,
- warn_limited,
- map_bits,
- MemoizedSlots,
- EnsureKWArgType,
- wrap_callable,
-)
+from ._collections import coerce_generator_arg # noqa
+from ._collections import collections_abc # noqa
+from ._collections import column_dict # noqa
+from ._collections import column_set # noqa
+from ._collections import EMPTY_SET # noqa
+from ._collections import flatten_iterator # noqa
+from ._collections import has_dupes # noqa
+from ._collections import has_intersection # noqa
+from ._collections import IdentitySet # noqa
+from ._collections import ImmutableContainer # noqa
+from ._collections import immutabledict # noqa
+from ._collections import ImmutableProperties # noqa
+from ._collections import KeyedTuple # noqa
+from ._collections import lightweight_named_tuple # noqa
+from ._collections import LRUCache # noqa
+from ._collections import ordered_column_set # noqa
+from ._collections import OrderedDict # noqa
+from ._collections import OrderedIdentitySet # noqa
+from ._collections import OrderedProperties # noqa
+from ._collections import OrderedSet # noqa
+from ._collections import populate_column_dict # noqa
+from ._collections import PopulateDict # noqa
+from ._collections import Properties # noqa
+from ._collections import ScopedRegistry # noqa
+from ._collections import ThreadLocalRegistry # noqa
+from ._collections import to_column_set # noqa
+from ._collections import to_list # noqa
+from ._collections import to_set # noqa
+from ._collections import unique_list # noqa
+from ._collections import UniqueAppender # noqa
+from ._collections import update_copy # noqa
+from ._collections import WeakSequence # noqa
+from .compat import b # noqa
+from .compat import b64decode # noqa
+from .compat import b64encode # noqa
+from .compat import binary_type # noqa
+from .compat import byte_buffer # noqa
+from .compat import callable # noqa
+from .compat import cmp # noqa
+from .compat import cpython # noqa
+from .compat import dottedgetter # noqa
+from .compat import inspect_getargspec # noqa
+from .compat import int_types # noqa
+from .compat import iterbytes # noqa
+from .compat import itertools_filter # noqa
+from .compat import itertools_filterfalse # noqa
+from .compat import jython # noqa
+from .compat import namedtuple # noqa
+from .compat import nested # noqa
+from .compat import next # noqa
+from .compat import parse_qsl # noqa
+from .compat import pickle # noqa
+from .compat import print_ # noqa
+from .compat import py2k # noqa
+from .compat import py33 # noqa
+from .compat import py36 # noqa
+from .compat import py3k # noqa
+from .compat import pypy # noqa
+from .compat import quote_plus # noqa
+from .compat import raise_from_cause # noqa
+from .compat import reduce # noqa
+from .compat import reraise # noqa
+from .compat import safe_kwarg # noqa
+from .compat import string_types # noqa
+from .compat import StringIO # noqa
+from .compat import text_type # noqa
+from .compat import threading # noqa
+from .compat import u # noqa
+from .compat import ue # noqa
+from .compat import unquote # noqa
+from .compat import unquote_plus # noqa
+from .compat import win32 # noqa
+from .compat import with_metaclass # noqa
+from .compat import zip_longest # noqa
+from .deprecations import deprecated # noqa
+from .deprecations import inject_docstring_text # noqa
+from .deprecations import pending_deprecation # noqa
+from .deprecations import warn_deprecated # noqa
+from .deprecations import warn_pending_deprecation # noqa
+from .langhelpers import as_interface # noqa
+from .langhelpers import asbool # noqa
+from .langhelpers import asint # noqa
+from .langhelpers import assert_arg_type # noqa
+from .langhelpers import attrsetter # noqa
+from .langhelpers import bool_or_str # noqa
+from .langhelpers import chop_traceback # noqa
+from .langhelpers import class_hierarchy # noqa
+from .langhelpers import classproperty # noqa
+from .langhelpers import coerce_kw_type # noqa
+from .langhelpers import constructor_copy # noqa
+from .langhelpers import counter # noqa
+from .langhelpers import decode_slice # noqa
+from .langhelpers import decorator # noqa
+from .langhelpers import dependencies # noqa
+from .langhelpers import dictlike_iteritems # noqa
+from .langhelpers import duck_type_collection # noqa
+from .langhelpers import ellipses_string # noqa
+from .langhelpers import EnsureKWArgType # noqa
+from .langhelpers import format_argspec_init # noqa
+from .langhelpers import format_argspec_plus # noqa
+from .langhelpers import generic_repr # noqa
+from .langhelpers import get_callable_argspec # noqa
+from .langhelpers import get_cls_kwargs # noqa
+from .langhelpers import get_func_kwargs # noqa
+from .langhelpers import getargspec_init # noqa
+from .langhelpers import group_expirable_memoized_property # noqa
+from .langhelpers import hybridmethod # noqa
+from .langhelpers import hybridproperty # noqa
+from .langhelpers import iterate_attributes # noqa
+from .langhelpers import map_bits # noqa
+from .langhelpers import md5_hex # noqa
+from .langhelpers import memoized_instancemethod # noqa
+from .langhelpers import memoized_property # noqa
+from .langhelpers import MemoizedSlots # noqa
+from .langhelpers import methods_equivalent # noqa
+from .langhelpers import monkeypatch_proxied_specials # noqa
+from .langhelpers import NoneType # noqa
+from .langhelpers import only_once # noqa
+from .langhelpers import PluginLoader # noqa
+from .langhelpers import portable_instancemethod # noqa
+from .langhelpers import quoted_token_parser # noqa
+from .langhelpers import safe_reraise # noqa
+from .langhelpers import set_creation_order # noqa
+from .langhelpers import symbol # noqa
+from .langhelpers import unbound_method_to_callable # noqa
+from .langhelpers import warn # noqa
+from .langhelpers import warn_exception # noqa
+from .langhelpers import warn_limited # noqa
+from .langhelpers import wrap_callable # noqa
-from .deprecations import (
- warn_deprecated,
- warn_pending_deprecation,
- deprecated,
- pending_deprecation,
- inject_docstring_text,
-)
# things that used to be not always available,
# but are now as of current support Python versions
-from collections import defaultdict
-from functools import partial
-from functools import update_wrapper
-from contextlib import contextmanager
"""Collection classes and helpers."""
from __future__ import absolute_import
-import weakref
+
import operator
-from .compat import (
- threading,
- itertools_filterfalse,
- string_types,
- binary_types,
- collections_abc,
-)
-from . import py2k
import types
+import weakref
+
+from .compat import binary_types
+from .compat import collections_abc
+from .compat import itertools_filterfalse
+from .compat import py2k
+from .compat import string_types
+from .compat import threading
EMPTY_SET = frozenset()
def __add__(self, other):
return list(self) + list(other)
- def __setitem__(self, key, object):
- self._data[key] = object
+ def __setitem__(self, key, obj):
+ self._data[key] = obj
def __getitem__(self, key):
return self._data[key]
def iteritems(self):
return iter(self.items())
- def __setitem__(self, key, object):
+ def __setitem__(self, key, obj):
if key not in self:
try:
self._list.append(key)
# work around Python pickle loads() with
# dict subclass (seems to ignore __setstate__?)
self._list = [key]
- dict.__setitem__(self, key, object)
+ dict.__setitem__(self, key, obj)
def __delitem__(self, key):
dict.__delitem__(self, key)
def has_intersection(set_, iterable):
- """return True if any items of set_ are present in iterable.
+ r"""return True if any items of set\_ are present in iterable.
Goes through special effort to ensure __hash__ is not called
on items in iterable that don't support it.
import collections
import contextlib
-import sys
import operator
+import sys
import time
+
py36 = sys.version_info >= (3, 6)
py33 = sys.version_info >= (3, 3)
py35 = sys.version_info >= (3, 5)
contextmanager = contextlib.contextmanager
dottedgetter = operator.attrgetter
namedtuple = collections.namedtuple
-next = next
+next = next # noqa
ArgSpec = collections.namedtuple(
"ArgSpec", ["args", "varargs", "keywords", "defaults"]
try:
import threading
except ImportError:
- import dummy_threading as threading
+ import dummy_threading as threading # noqa
# work around http://bugs.python.org/issue2646
if py265:
- safe_kwarg = lambda arg: arg
+ safe_kwarg = lambda arg: arg # noqa
else:
safe_kwarg = str
return s
if py32:
- callable = callable
+ callable = callable # noqa
else:
- def callable(fn):
+ def callable(fn): # noqa
return hasattr(fn, "__call__")
else:
import base64
- import ConfigParser as configparser
+ import ConfigParser as configparser # noqa
import itertools
- from StringIO import StringIO
- from cStringIO import StringIO as byte_buffer
- from inspect import getargspec as inspect_getfullargspec
- from itertools import izip_longest as zip_longest
- from urllib import quote_plus, unquote_plus, quote, unquote
- from urlparse import parse_qsl
+ from StringIO import StringIO # noqa
+ from cStringIO import StringIO as byte_buffer # noqa
+ from inspect import getargspec as inspect_getfullargspec # noqa
+ from itertools import izip_longest as zip_longest # noqa
+ from urllib import quote # noqa
+ from urllib import quote_plus # noqa
+ from urllib import unquote # noqa
+ from urllib import unquote_plus # noqa
+ from urlparse import parse_qsl # noqa
try:
import cPickle as pickle
except ImportError:
- import pickle
+ import pickle # noqa
- string_types = (basestring,)
+ string_types = (basestring,) # noqa
binary_types = (bytes,)
binary_type = str
- text_type = unicode
- int_types = int, long
+ text_type = unicode # noqa
+ int_types = int, long # noqa
inspect_getargspec = inspect_getfullargspec
- callable = callable
- cmp = cmp
- reduce = reduce
+ callable = callable # noqa
+ cmp = cmp # noqa
+ reduce = reduce # noqa
b64encode = base64.b64encode
b64decode = base64.b64decode
if fp is None:
return
for arg in enumerate(args):
- if not isinstance(arg, basestring):
+ if not isinstance(arg, basestring): # noqa
arg = str(arg)
fp.write(arg)
# strings - we only use u() with
# literal source strings, and all our source files with non-ascii
# in them (all are tests) are utf-8 encoded.
- return unicode(s, "utf-8")
+ return unicode(s, "utf-8") # noqa
def ue(s):
- return unicode(s, "unicode_escape")
+ return unicode(s, "unicode_escape") # noqa
# not as nice as that of Py3K, but at least preserves
# the code line where the issue occurred
else:
- from inspect import formatargspec as inspect_formatargspec
+ from inspect import formatargspec as inspect_formatargspec # noqa
if win32 or jython:
if py33:
import collections.abc as collections_abc
else:
- import collections as collections_abc
+ import collections as collections_abc # noqa
@contextlib.contextmanager
"""
exits = []
- vars = []
+ vars_ = []
exc = (None, None, None)
try:
for mgr in managers:
- exit = mgr.__exit__
+ exit_ = mgr.__exit__
enter = mgr.__enter__
- vars.append(enter())
- exits.append(exit)
- yield vars
+ vars_.append(enter())
+ exits.append(exit_)
+ yield vars_
except:
exc = sys.exc_info()
finally:
while exits:
- exit = exits.pop()
+ exit_ = exits.pop() # noqa
try:
- if exit(*exc):
+ if exit_(*exc):
exc = (None, None, None)
except:
exc = sys.exc_info()
"""Helpers related to deprecation of functions, methods, classes, other
functionality."""
-from .. import exc
-import warnings
import re
+import textwrap
+import warnings
+
from .langhelpers import decorator
+from .. import exc
def warn_deprecated(msg, stacklevel=3):
return decorated
-import textwrap
-
-
def _dedent_docstring(text):
split_text = text.split("\n", 1)
if len(split_text) == 1:
modules, classes, hierarchies, attributes, functions, and methods.
"""
+from functools import update_wrapper
+import hashlib
import inspect
import itertools
import operator
import sys
import types
import warnings
-from functools import update_wrapper
-from .. import exc
-import hashlib
-from . import compat
+
from . import _collections
+from . import compat
+from .. import exc
def md5_hex(x):
def oneshot(self, *args, **kw):
result = fn(self, *args, **kw)
- memo = lambda *a, **kw: result
+
+ def memo(*a, **kw):
+ return result
+
memo.__name__ = fn.__name__
memo.__doc__ = fn.__doc__
self.__dict__[fn.__name__] = memo
def oneshot(*args, **kw):
result = fn(*args, **kw)
- memo = lambda *a, **kw: result
+
+ def memo(*a, **kw):
+ return result
+
memo.__name__ = fn.__name__
memo.__doc__ = fn.__doc__
setattr(self, key, memo)
def dependency_for(modulename, add_to_all=False):
def decorate(obj):
- # TODO: would be nice to improve on this import silliness,
- # unfortunately importlib doesn't work that great either
tokens = modulename.split(".")
mod = compat.import_(
".".join(tokens[0:-1]), globals(), locals(), [tokens[-1]]
class EnsureKWArgType(type):
- """Apply translation of functions to accept **kw arguments if they
+ r"""Apply translation of functions to accept \**kw arguments if they
don't already.
"""
from collections import deque
from time import time as _time
+
from .compat import threading
"""Topological sorting algorithms."""
-from ..exc import CircularDependencyError
from .. import util
+from ..exc import CircularDependencyError
+
__all__ = ["sort", "sort_as_subsets", "find_cycles"]
database in process.
"""
-from sqlalchemy.testing import provision
import logging
import sys
+from sqlalchemy.testing import provision
+
+
logging.basicConfig()
logging.getLogger(provision.__name__).setLevel(logging.INFO)
-import os
-import platform
-import re
-import sys
from distutils.command.build_ext import build_ext
from distutils.errors import CCompilerError
from distutils.errors import DistutilsExecError
from distutils.errors import DistutilsPlatformError
-from setuptools import Distribution as _Distribution, Extension
-from setuptools import setup
+import os
+import platform
+import re
+import sys
+
+from setuptools import Distribution as _Distribution
+from setuptools import Extension
from setuptools import find_packages
+from setuptools import setup
from setuptools.command.test import test as TestCommand
+
cmdclass = {}
if sys.version_info < (2, 7):
raise Exception("SQLAlchemy requires Python 2.7 or higher.")
installs SQLAlchemy's testing plugin into the local environment.
"""
+import os
import sys
+
import nose
-import os
+
if not sys.flags.no_user_site:
sys.path.insert(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib')
)
+
# use bootstrapping so that test plugins are loaded
# without touching the main library before coverage starts
bootstrap_file = os.path.join(
exec(code, globals(), locals())
-from noseplugin import NoseSQLAlchemy
+from noseplugin import NoseSQLAlchemy # noqa
nose.main(addplugins=[NoseSQLAlchemy()])
+from sqlalchemy import Column
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy.engine import default
-from sqlalchemy.testing import fixtures, AssertsExecutionResults, profiling
-from sqlalchemy import MetaData, Table, Column, Integer, String, select
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import profiling
+
t1 = t2 = None
-from sqlalchemy.testing import eq_
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- clear_mappers,
- sessionmaker,
- aliased,
- Session,
- subqueryload,
-)
-from sqlalchemy.orm.mapper import _mapper_registry
-from sqlalchemy.orm.session import _sessions
-from sqlalchemy import testing
-from sqlalchemy.testing import engines
-from sqlalchemy import MetaData, Integer, String, ForeignKey, Unicode, select
-import sqlalchemy as sa
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.sql import column
-from sqlalchemy.processors import (
- to_decimal_processor_factory,
- to_unicode_processor_factory,
-)
-from sqlalchemy.testing.util import gc_collect
import decimal
import gc
-from sqlalchemy.testing import fixtures
-from sqlalchemy import util
-import weakref
import itertools
-
import multiprocessing
+import weakref
+
+import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy import Unicode
+from sqlalchemy import util
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm.mapper import _mapper_registry
+from sqlalchemy.orm.session import _sessions
+from sqlalchemy.processors import to_decimal_processor_factory
+from sqlalchemy.processors import to_unicode_processor_factory
+from sqlalchemy.sql import column
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import gc_collect
class A(fixtures.ComparableEntity):
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.orm import (
- mapper,
- relationship,
- sessionmaker,
- Session,
- defer,
- joinedload,
- defaultload,
- selectinload,
- Load,
- configure_mappers,
- Bundle,
-)
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import profiling
+from sqlalchemy.orm import Bundle
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import defaultload
+from sqlalchemy.orm import defer
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import Load
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import selectinload
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
from sqlalchemy.testing import fixtures
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy import inspect
+from sqlalchemy.testing import profiling
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class MergeTest(fixtures.MappedTest):
-from sqlalchemy.testing import fixtures, AssertsExecutionResults, profiling
-from sqlalchemy.pool import QueuePool
from sqlalchemy import pool as pool_module
+from sqlalchemy.pool import QueuePool
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import profiling
+
pool = None
-from sqlalchemy import (
- MetaData,
- Table,
- Column,
- String,
- Unicode,
- Integer,
- create_engine,
-)
-from sqlalchemy.testing import fixtures, AssertsExecutionResults, profiling
+import sys
+
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import Unicode
+from sqlalchemy.engine.result import RowProxy
+from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import profiling
from sqlalchemy.util import u
-from sqlalchemy.engine.result import RowProxy
-import sys
+
NUM_FIELDS = 10
NUM_RECORDS = 1000
from __future__ import unicode_literals
+import datetime
+
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import Date
+from sqlalchemy import DateTime
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import join
+from sqlalchemy import outerjoin
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import Table
+from sqlalchemy import Time
+from sqlalchemy import Unicode
+from sqlalchemy.testing import replay_fixture
+
+
"""Benchmark for SQLAlchemy.
An adaptation of Robert Brewers' ZooMark speed tests. """
-import datetime
-from sqlalchemy import (
- Table,
- Column,
- Integer,
- Unicode,
- Date,
- DateTime,
- Time,
- Float,
- Sequence,
- ForeignKey,
- select,
- join,
- and_,
- outerjoin,
- func,
-)
-from sqlalchemy.testing import replay_fixture
-
ITERATIONS = 1
from __future__ import unicode_literals
+import datetime
+
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import Date
+from sqlalchemy import DateTime
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import Table
+from sqlalchemy import Time
+from sqlalchemy import Unicode
+from sqlalchemy.orm import mapper
+from sqlalchemy.testing import replay_fixture
+
+
"""Benchmark for SQLAlchemy.
An adaptation of Robert Brewers' ZooMark speed tests. """
-import datetime
-from sqlalchemy import (
- Table,
- Column,
- Integer,
- Unicode,
- Date,
- DateTime,
- Time,
- Float,
- Sequence,
- ForeignKey,
- select,
- and_,
- func,
-)
-from sqlalchemy.orm import mapper
-from sqlalchemy.testing import replay_fixture
-
ITERATIONS = 1
Zoo = Animal = session = None
list(
self.session.query(Zoo).filter(
and_(
- Zoo.Founded != None, # noqa
- Zoo.Founded < func.now(),
- )
+ Zoo.Founded != None, Zoo.Founded < func.now()
+ ) # noqa
)
)
)
-from sqlalchemy.util import topological
-from sqlalchemy.testing import assert_raises, eq_
-from sqlalchemy.testing.util import conforms_partial_ordering
from sqlalchemy import exc
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.util import conforms_partial_ordering
+from sqlalchemy.util import topological
class DependencySortTest(fixtures.TestBase):
"""Test event registration and listening."""
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- is_,
- is_not_,
-)
-from sqlalchemy import event, exc
+from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import testing
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
from sqlalchemy.testing.util import gc_collect
-from sqlalchemy.testing.mock import Mock, call
-from sqlalchemy import testing
class EventsTest(fixtures.TestBase):
from sqlalchemy import exc as sa_exceptions
-from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import eq_
from sqlalchemy.engine import default
-from sqlalchemy.util import u, compat
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.util import compat
+from sqlalchemy.util import u
class Error(Exception):
"""test the inspection registry system."""
-from sqlalchemy.testing import eq_, assert_raises_message
-from sqlalchemy import exc, util
-from sqlalchemy import inspection, inspect
+from sqlalchemy import exc
+from sqlalchemy import inspect
+from sqlalchemy import inspection
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from __future__ import print_function
-from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import config
+
import doctest
import logging
-import sys
-import re
import os
+import re
+import sys
+
+from sqlalchemy.testing import config
+from sqlalchemy.testing import fixtures
class DocTest(fixtures.TestBase):
import copy
+import inspect
import sys
-from sqlalchemy import util, sql, exc, testing
-from sqlalchemy.testing import assert_raises, assert_raises_message, fixtures
-from sqlalchemy.testing import eq_, in_, is_, ne_, fails_if, mock
-from sqlalchemy.testing import expect_warnings
-from sqlalchemy.testing.util import picklers, gc_collect
-from sqlalchemy.util import classproperty, WeakSequence, get_callable_argspec
+from sqlalchemy import exc
+from sqlalchemy import sql
+from sqlalchemy import testing
+from sqlalchemy import util
from sqlalchemy.sql import column
-from sqlalchemy.util import langhelpers, compat
-import inspect
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fails_if
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import mock
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.util import gc_collect
+from sqlalchemy.testing.util import picklers
+from sqlalchemy.util import classproperty
+from sqlalchemy.util import compat
+from sqlalchemy.util import get_callable_argspec
+from sqlalchemy.util import langhelpers
+from sqlalchemy.util import WeakSequence
class _KeyedTupleTest(object):
class LRUTest(fixtures.TestBase):
def test_lru(self):
class item(object):
- def __init__(self, id):
- self.id = id
+ def __init__(self, id_):
+ self.id = id_
def __str__(self):
return "item id %d" % self.id
lru = util.LRUCache(10, threshold=0.2)
- for id in range(1, 20):
- lru[id] = item(id)
+ for id_ in range(1, 20):
+ lru[id_] = item(id_)
# first couple of items should be gone
assert 1 not in lru
installs SQLAlchemy's testing plugin into the local environment.
"""
-import sys
import os
+import sys
+
if not sys.flags.no_user_site:
# this is needed so that test scenarios like "python setup.py test"
# -*- encoding: utf-8
-from sqlalchemy.testing import eq_, is_
+from sqlalchemy import Column
+from sqlalchemy import delete
+from sqlalchemy import extract
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import insert
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import MetaData
+from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import schema
-from sqlalchemy.sql import table, column, quoted_name
-from sqlalchemy.dialects import mssql
-from sqlalchemy.dialects.mssql import mxodbc
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
+from sqlalchemy import select
+from sqlalchemy import Sequence
from sqlalchemy import sql
-from sqlalchemy import (
- Integer,
- String,
- Table,
- Column,
- select,
- MetaData,
- update,
- delete,
- insert,
- extract,
- union,
- func,
- PrimaryKeyConstraint,
- UniqueConstraint,
- Index,
- Sequence,
- literal,
-)
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import union
+from sqlalchemy import UniqueConstraint
+from sqlalchemy import update
+from sqlalchemy.dialects import mssql
from sqlalchemy.dialects.mssql import base
+from sqlalchemy.dialects.mssql import mxodbc
+from sqlalchemy.sql import column
+from sqlalchemy.sql import quoted_name
+from sqlalchemy.sql import table
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
t = table("sometable", column("foo"))
- for expr, compile in [
+ for expr, compiled in [
(
select([literal("x"), literal("y")]),
"SELECT 'x' AS anon_1, 'y' AS anon_2",
),
(t.c.foo.in_([None]), "sometable.foo IN (NULL)"),
]:
- self.assert_compile(expr, compile, dialect=mxodbc_dialect)
+ self.assert_compile(expr, compiled, dialect=mxodbc_dialect)
def test_in_with_subqueries(self):
"""Test removal of legacy behavior that converted "x==subquery"
# -*- encoding: utf-8
-from sqlalchemy.testing import eq_, engines
-from sqlalchemy import *
+from sqlalchemy import Column
+from sqlalchemy import engine_from_config
+from sqlalchemy import event
from sqlalchemy import exc
-from sqlalchemy.dialects.mssql import pyodbc, pymssql, adodbapi
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy.dialects.mssql import adodbapi
+from sqlalchemy.dialects.mssql import base
+from sqlalchemy.dialects.mssql import pymssql
+from sqlalchemy.dialects.mssql import pyodbc
from sqlalchemy.engine import url
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import assert_warnings
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
-from sqlalchemy import testing
-from sqlalchemy.testing import (
- assert_raises_message,
- assert_warnings,
- expect_warnings,
-)
from sqlalchemy.testing.mock import Mock
-from sqlalchemy.dialects.mssql import base
-from sqlalchemy import Integer, String, Table, Column
-from sqlalchemy import event
class ParseConnectTest(fixtures.TestBase):
# -*- encoding: utf-8
-from sqlalchemy.testing import eq_, engines
-from sqlalchemy.sql import table, column
-from sqlalchemy.databases import mssql
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL, assertions
+from sqlalchemy import and_
+from sqlalchemy import Column
+from sqlalchemy import DDL
+from sqlalchemy import desc
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.util import ue
from sqlalchemy import util
-from sqlalchemy.testing.assertsql import CursorSQL, DialectSQL
-from sqlalchemy import (
- Integer,
- String,
- Table,
- Column,
- select,
- MetaData,
- func,
- PrimaryKeyConstraint,
- desc,
- DDL,
- ForeignKey,
- or_,
- and_,
-)
-from sqlalchemy import event
+from sqlalchemy.databases import mssql
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import CursorSQL
+from sqlalchemy.testing.assertsql import DialectSQL
+from sqlalchemy.util import ue
+
metadata = None
cattable = None
# -*- encoding: utf-8
-from sqlalchemy.testing import eq_, is_, in_
-from sqlalchemy import *
-from sqlalchemy import types, schema, event
-from sqlalchemy.databases import mssql
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL, ComparesTables
+from sqlalchemy import Column
+from sqlalchemy import DDL
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import Index
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import schema
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.engine.reflection import Inspector
+from sqlalchemy import types
from sqlalchemy import util
-from sqlalchemy.dialects.mssql.information_schema import CoerceUnicode, tables
+from sqlalchemy.databases import mssql
from sqlalchemy.dialects.mssql import base
+from sqlalchemy.dialects.mssql.information_schema import CoerceUnicode
+from sqlalchemy.dialects.mssql.information_schema import tables
+from sqlalchemy.engine.reflection import Inspector
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import ComparesTables
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
# -*- encoding: utf-8
-from sqlalchemy.testing import eq_, engines, pickleable, assert_raises_message
-from sqlalchemy.testing import is_, is_not_
+import codecs
import datetime
+import decimal
import os
-from sqlalchemy import (
- Table,
- Column,
- MetaData,
- Float,
- Integer,
- String,
- Boolean,
- Sequence,
- Numeric,
- select,
- Date,
- Time,
- DateTime,
- DefaultClause,
- PickleType,
- text,
- Text,
- UnicodeText,
- LargeBinary,
-)
-from sqlalchemy.dialects.mssql import TIMESTAMP, ROWVERSION
-from sqlalchemy import types, schema
-from sqlalchemy import util
-from sqlalchemy.databases import mssql
-from sqlalchemy.dialects.mssql.base import TIME, _MSDate
-from sqlalchemy.dialects.mssql.base import MS_2005_VERSION, MS_2008_VERSION
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- ComparesTables,
-)
+
+import sqlalchemy as sa
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import Date
+from sqlalchemy import DateTime
+from sqlalchemy import DefaultClause
+from sqlalchemy import Float
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import LargeBinary
+from sqlalchemy import MetaData
+from sqlalchemy import Numeric
+from sqlalchemy import PickleType
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import Text
+from sqlalchemy import text
+from sqlalchemy import Time
+from sqlalchemy import types
+from sqlalchemy import UnicodeText
+from sqlalchemy.databases import mssql
+from sqlalchemy.dialects.mssql import ROWVERSION
+from sqlalchemy.dialects.mssql import TIMESTAMP
+from sqlalchemy.dialects.mssql.base import _MSDate
+from sqlalchemy.dialects.mssql.base import MS_2005_VERSION
+from sqlalchemy.dialects.mssql.base import MS_2008_VERSION
+from sqlalchemy.dialects.mssql.base import TIME
+from sqlalchemy.sql import sqltypes
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import ComparesTables
from sqlalchemy.testing import emits_warning_on
-import decimal
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing import pickleable
from sqlalchemy.util import b
-from sqlalchemy import inspect
-from sqlalchemy.sql import sqltypes
-import sqlalchemy as sa
-import codecs
class TimeTypeTest(fixtures.TestBase):
self._test_round_trip(type_(100), data, expected=paddedstream)
- def _load_stream(self, name, len=3000):
+ def _load_stream(self, name, len_=3000):
fp = open(
os.path.join(os.path.dirname(__file__), "..", "..", name), "rb"
)
- stream = fp.read(len)
+ stream = fp.read(len_)
fp.close()
return stream
# coding: utf-8
-from sqlalchemy.testing import eq_, assert_raises_message, expect_warnings
-from sqlalchemy import sql, exc, schema, types as sqltypes
-from sqlalchemy import (
- Table,
- MetaData,
- Column,
- select,
- String,
- Index,
- Integer,
- ForeignKey,
- PrimaryKeyConstraint,
- extract,
- VARCHAR,
- NVARCHAR,
- Unicode,
- UnicodeText,
- NUMERIC,
- DECIMAL,
- Numeric,
- Float,
- FLOAT,
- TIMESTAMP,
- DATE,
- DATETIME,
- TIME,
- DateTime,
- Time,
- Date,
- Interval,
- NCHAR,
- CHAR,
- CLOB,
- TEXT,
- Boolean,
- BOOLEAN,
- LargeBinary,
- BLOB,
- SmallInteger,
- INT,
- func,
- cast,
- literal,
-)
-
-from sqlalchemy.dialects.mysql import insert
+from sqlalchemy import BLOB
+from sqlalchemy import BOOLEAN
+from sqlalchemy import Boolean
+from sqlalchemy import cast
+from sqlalchemy import CHAR
+from sqlalchemy import CLOB
+from sqlalchemy import Column
+from sqlalchemy import DATE
+from sqlalchemy import Date
+from sqlalchemy import DATETIME
+from sqlalchemy import DateTime
+from sqlalchemy import DECIMAL
+from sqlalchemy import exc
+from sqlalchemy import extract
+from sqlalchemy import FLOAT
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import INT
+from sqlalchemy import Integer
+from sqlalchemy import Interval
+from sqlalchemy import LargeBinary
+from sqlalchemy import literal
+from sqlalchemy import MetaData
+from sqlalchemy import NCHAR
+from sqlalchemy import NUMERIC
+from sqlalchemy import Numeric
+from sqlalchemy import NVARCHAR
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import SmallInteger
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import TEXT
+from sqlalchemy import TIME
+from sqlalchemy import Time
+from sqlalchemy import TIMESTAMP
+from sqlalchemy import types as sqltypes
+from sqlalchemy import Unicode
+from sqlalchemy import UnicodeText
+from sqlalchemy import VARCHAR
from sqlalchemy.dialects.mysql import base as mysql
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
-from sqlalchemy.sql import table, column
+from sqlalchemy.dialects.mysql import insert
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
from sqlalchemy.sql.expression import literal_column
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
# coding: utf-8
-from sqlalchemy.testing import eq_
-from sqlalchemy import *
-from sqlalchemy.engine.url import make_url
-from sqlalchemy.testing import fixtures, expect_warnings
+import datetime
+
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import DateTime
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy.dialects import mysql
+from sqlalchemy.engine.url import make_url
from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
from ...engine import test_execute
-import datetime
-from sqlalchemy.dialects import mysql
class DialectTest(fixtures.TestBase):
"""
import contextlib
-from sqlalchemy import Column, Integer, ForeignKey, update
-from sqlalchemy.orm import relationship, Session, joinedload
+from sqlalchemy import Column
from sqlalchemy import exc
-
-from sqlalchemy.testing import fixtures
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
from sqlalchemy import testing
+from sqlalchemy import update
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import fixtures
class MySQLForUpdateLockingTest(fixtures.DeclarativeMappedTest):
-from sqlalchemy.testing.assertions import eq_, assert_raises
-from sqlalchemy.testing import fixtures
-from sqlalchemy import exc, testing
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import exc
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
from sqlalchemy.dialects.mysql import insert
-from sqlalchemy import Table, Column, Boolean, Integer, String, func
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import eq_
class OnDuplicateTest(fixtures.TablesTest):
stmt = insert(foos)
update_condition = foos.c.updated_once == False
- # The following statements show importance of the columns update ordering
- # as old values being referenced in UPDATE clause are getting replaced one
- # by one from left to right with their new values.
+ # The following statements show importance of the columns update
+ # ordering as old values being referenced in UPDATE clause are
+ # getting replaced one by one from left to right with their new
+ # values.
stmt1 = stmt.on_duplicate_key_update(
[
(
# coding: utf-8
-from sqlalchemy.testing import eq_, is_
-from sqlalchemy import *
-from sqlalchemy.testing import fixtures
+from sqlalchemy import all_
+from sqlalchemy import and_
+from sqlalchemy import any_
+from sqlalchemy import Boolean
+from sqlalchemy import cast
+from sqlalchemy import Column
+from sqlalchemy import false
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import true
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
class IdiosyncrasyTest(fixtures.TestBase):
# coding: utf-8
-from sqlalchemy.testing import eq_, is_
-from sqlalchemy import (
- Column,
- Table,
- DDL,
- MetaData,
- TIMESTAMP,
- DefaultClause,
- String,
- Integer,
- Text,
- UnicodeText,
- SmallInteger,
- NCHAR,
- LargeBinary,
- DateTime,
- select,
- UniqueConstraint,
- Unicode,
- BigInteger,
- Index,
- ForeignKey,
-)
-from sqlalchemy.schema import CreateIndex
+import re
+
+from sqlalchemy import BigInteger
+from sqlalchemy import Column
+from sqlalchemy import DateTime
+from sqlalchemy import DDL
+from sqlalchemy import DefaultClause
from sqlalchemy import event
-from sqlalchemy import sql
from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Index
from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import LargeBinary
+from sqlalchemy import MetaData
+from sqlalchemy import NCHAR
+from sqlalchemy import select
+from sqlalchemy import SmallInteger
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import Text
+from sqlalchemy import TIMESTAMP
+from sqlalchemy import Unicode
+from sqlalchemy import UnicodeText
+from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.mysql import base as mysql
from sqlalchemy.dialects.mysql import reflection as _reflection
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
-from sqlalchemy import testing
-from sqlalchemy.testing import assert_raises_message, expect_warnings
-import re
+from sqlalchemy.schema import CreateIndex
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
class TypeReflectionTest(fixtures.TestBase):
"nullable": False,
"default": None
if explicit_defaults_for_timestamp
- else "%(current_timestamp)s ON UPDATE %(current_timestamp)s"
+ else (
+ "%(current_timestamp)s "
+ "ON UPDATE %(current_timestamp)s"
+ )
% {"current_timestamp": current_timestamp},
},
{"name": "s", "nullable": False, "default": current_timestamp},
else False,
"default": None
if explicit_defaults_for_timestamp
- else "%(current_timestamp)s ON UPDATE %(current_timestamp)s"
+ else (
+ "%(current_timestamp)s "
+ "ON UPDATE %(current_timestamp)s"
+ )
% {"current_timestamp": current_timestamp},
},
{
# coding: utf-8
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, is_
-from sqlalchemy import *
-from sqlalchemy import sql, exc, schema
-from sqlalchemy.util import u
-from sqlalchemy import util
-from sqlalchemy.dialects.mysql import base as mysql
-from sqlalchemy.testing import (
- fixtures,
- AssertsCompiledSQL,
- AssertsExecutionResults,
-)
-from sqlalchemy import testing
+from collections import OrderedDict
import datetime
import decimal
+
+from sqlalchemy import BOOLEAN
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import DefaultClause
+from sqlalchemy import Enum
+from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import TIMESTAMP
from sqlalchemy import types as sqltypes
-from collections import OrderedDict
+from sqlalchemy import UnicodeText
+from sqlalchemy import util
+from sqlalchemy.dialects.mysql import base as mysql
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.util import u
class TypesTest(
# latin-1 stuff forcing its way in ?
eq_(
- t2.c.value.type.enums[0:2],
- [u("réveillé"), u("drôle")], # u'S’il') # eh ?
- )
+ t2.c.value.type.enums[0:2], [u("réveillé"), u("drôle")]
+ ) # u'S’il') # eh ?
eq_(
- t2.c.value2.type.enums[0:2],
- [u("réveillé"), u("drôle")], # u'S’il') # eh ?
- )
+ t2.c.value2.type.enums[0:2], [u("réveillé"), u("drôle")]
+ ) # u'S’il') # eh ?
def test_enum_compile(self):
e1 = Enum("x", "y", "z", name="somename")
# coding: utf-8
-from sqlalchemy.testing import eq_
-from sqlalchemy import types as sqltypes, exc, schema
-from sqlalchemy.sql import table, column
from sqlalchemy import and_
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
-from sqlalchemy import testing
-from sqlalchemy import (
- Integer,
- Text,
- LargeBinary,
- Unicode,
- UniqueConstraint,
- Index,
- MetaData,
- select,
- inspect,
- ForeignKey,
- String,
- func,
- TypeDecorator,
- bindparam,
- Numeric,
- TIMESTAMP,
- CHAR,
- text,
- literal_column,
- VARCHAR,
- create_engine,
- Date,
- NVARCHAR,
- ForeignKeyConstraint,
- Sequence,
- Float,
- DateTime,
- cast,
- UnicodeText,
- union,
- except_,
- type_coerce,
- or_,
- outerjoin,
- DATE,
- NCHAR,
- outparam,
- PrimaryKeyConstraint,
- FLOAT,
-)
-from sqlalchemy.util import u, b
-from sqlalchemy import util
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.dialects.oracle import cx_oracle, base as oracle
-from sqlalchemy.engine import default
-import decimal
-from sqlalchemy.engine import url
-from sqlalchemy.testing.schema import Table, Column
-import datetime
-import os
+from sqlalchemy import bindparam
+from sqlalchemy import exc
+from sqlalchemy import except_
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import outerjoin
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import Sequence
from sqlalchemy import sql
-from sqlalchemy.testing.mock import Mock
+from sqlalchemy import String
+from sqlalchemy import text
+from sqlalchemy import type_coerce
+from sqlalchemy import TypeDecorator
+from sqlalchemy import union
+from sqlalchemy.dialects.oracle import base as oracle
+from sqlalchemy.dialects.oracle import cx_oracle
+from sqlalchemy.engine import default
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
# coding: utf-8
-from sqlalchemy.testing import eq_
+from sqlalchemy import bindparam
+from sqlalchemy import create_engine
from sqlalchemy import exc
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
+from sqlalchemy import Float
+from sqlalchemy import Integer
+from sqlalchemy import literal_column
+from sqlalchemy import outparam
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import create_engine
-from sqlalchemy import bindparam, outparam
-from sqlalchemy import (
- text,
- Float,
- Integer,
- String,
- select,
- literal_column,
- Unicode,
- UnicodeText,
- Sequence,
-)
-from sqlalchemy.util import u
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy.dialects.oracle import cx_oracle, base as oracle
+from sqlalchemy import text
+from sqlalchemy import Unicode
+from sqlalchemy import UnicodeText
+from sqlalchemy.dialects.oracle import base as oracle
+from sqlalchemy.dialects.oracle import cx_oracle
from sqlalchemy.engine import url
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import u
class DialectTest(fixtures.TestBase):
# coding: utf-8
-from sqlalchemy.testing import eq_, is_
from sqlalchemy import exc
-from sqlalchemy.sql import table
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
+from sqlalchemy import FLOAT
+from sqlalchemy import ForeignKey
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import Index
+from sqlalchemy import inspect
+from sqlalchemy import INTEGER
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Numeric
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import (
- Integer,
- Text,
- LargeBinary,
- Unicode,
- UniqueConstraint,
- Index,
- MetaData,
- select,
- inspect,
- ForeignKey,
- String,
- func,
- TypeDecorator,
- bindparam,
- Numeric,
- TIMESTAMP,
- CHAR,
- text,
- literal_column,
- VARCHAR,
- create_engine,
- Date,
- NVARCHAR,
- ForeignKeyConstraint,
- Sequence,
- Float,
- DateTime,
- cast,
- UnicodeText,
- union,
- except_,
- type_coerce,
- or_,
- outerjoin,
- DATE,
- NCHAR,
- outparam,
- PrimaryKeyConstraint,
- FLOAT,
- INTEGER,
-)
-from sqlalchemy.dialects.oracle.base import (
- NUMBER,
- BINARY_DOUBLE,
- BINARY_FLOAT,
- DOUBLE_PRECISION,
-)
+from sqlalchemy import text
+from sqlalchemy import Unicode
+from sqlalchemy import UniqueConstraint
+from sqlalchemy.dialects.oracle.base import BINARY_DOUBLE
+from sqlalchemy.dialects.oracle.base import BINARY_FLOAT
+from sqlalchemy.dialects.oracle.base import DOUBLE_PRECISION
+from sqlalchemy.dialects.oracle.base import NUMBER
from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class MultiSchemaTest(fixtures.TestBase, AssertsCompiledSQL):
# coding: utf-8
-from sqlalchemy.testing import eq_
-from sqlalchemy import types as sqltypes, exc, schema
-from sqlalchemy.sql import table, column
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
-from sqlalchemy import testing
-from sqlalchemy import (
- Integer,
- Text,
- LargeBinary,
- Unicode,
- UniqueConstraint,
- Index,
- MetaData,
- select,
- inspect,
- ForeignKey,
- String,
- func,
- TypeDecorator,
- bindparam,
- Numeric,
- TIMESTAMP,
- CHAR,
- text,
- SmallInteger,
- literal_column,
- VARCHAR,
- create_engine,
- Date,
- NVARCHAR,
- ForeignKeyConstraint,
- Sequence,
- Float,
- DateTime,
- cast,
- UnicodeText,
- union,
- except_,
- type_coerce,
- or_,
- outerjoin,
- DATE,
- NCHAR,
- outparam,
- PrimaryKeyConstraint,
- FLOAT,
-)
-from sqlalchemy.sql.sqltypes import NullType
-from sqlalchemy.util import u, b
-from sqlalchemy import util
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.dialects.oracle import cx_oracle, base as oracle
-from sqlalchemy.engine import default
-import decimal
-from sqlalchemy.engine import url
-from sqlalchemy.testing.schema import Table, Column
import datetime
+import decimal
import os
-from sqlalchemy import sql
-from sqlalchemy.testing.mock import Mock
-from sqlalchemy.testing import mock
+
+from sqlalchemy import bindparam
+from sqlalchemy import cast
+from sqlalchemy import CHAR
+from sqlalchemy import DATE
+from sqlalchemy import Date
+from sqlalchemy import DateTime
from sqlalchemy import event
+from sqlalchemy import FLOAT
+from sqlalchemy import Float
+from sqlalchemy import Integer
+from sqlalchemy import LargeBinary
+from sqlalchemy import MetaData
+from sqlalchemy import NCHAR
+from sqlalchemy import Numeric
+from sqlalchemy import NVARCHAR
+from sqlalchemy import select
+from sqlalchemy import SmallInteger
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy import Text
+from sqlalchemy import text
+from sqlalchemy import TIMESTAMP
+from sqlalchemy import TypeDecorator
+from sqlalchemy import types as sqltypes
+from sqlalchemy import Unicode
+from sqlalchemy import UnicodeText
+from sqlalchemy import util
+from sqlalchemy import VARCHAR
+from sqlalchemy.dialects.oracle import base as oracle
+from sqlalchemy.dialects.oracle import cx_oracle
+from sqlalchemy.sql import column
+from sqlalchemy.sql.sqltypes import NullType
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.engines import testing_engine
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import b
+from sqlalchemy.util import u
class DialectTypesTest(fixtures.TestBase, AssertsCompiledSQL):
[("nan",), ("nan",)],
)
- # needs https://github.com/oracle/python-cx_Oracle/issues/184#issuecomment-391399292
+ # needs https://github.com/oracle/python-cx_Oracle/
+ # issues/184#issuecomment-391399292
@testing.provide_metadata
def _dont_test_numeric_nan_decimal(self):
m = self.metadata
# coding: utf-8
-from sqlalchemy.testing.assertions import (
- AssertsCompiledSQL,
- is_,
- assert_raises,
- assert_raises_message,
- expect_warnings,
-)
-from sqlalchemy.testing import engines, fixtures
+from sqlalchemy import and_
+from sqlalchemy import cast
+from sqlalchemy import Column
+from sqlalchemy import delete
+from sqlalchemy import Enum
+from sqlalchemy import exc
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import null
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy import (
- Sequence,
- Table,
- Column,
- Integer,
- update,
- String,
- func,
- MetaData,
- Enum,
- Index,
- and_,
- delete,
- select,
- cast,
- text,
- Text,
- null,
-)
+from sqlalchemy import Text
+from sqlalchemy import text
from sqlalchemy import types as sqltypes
-from sqlalchemy.dialects.postgresql import ExcludeConstraint, array
-from sqlalchemy import exc, schema
+from sqlalchemy import update
from sqlalchemy.dialects import postgresql
+from sqlalchemy.dialects.postgresql import aggregate_order_by
+from sqlalchemy.dialects.postgresql import ARRAY as PG_ARRAY
+from sqlalchemy.dialects.postgresql import array
+from sqlalchemy.dialects.postgresql import array_agg as pg_array_agg
+from sqlalchemy.dialects.postgresql import ExcludeConstraint
+from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.dialects.postgresql import TSRANGE
-from sqlalchemy.orm import mapper, aliased, Session
-from sqlalchemy.sql import table, column, operators, literal_column
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
+from sqlalchemy.sql import column
+from sqlalchemy.sql import literal_column
+from sqlalchemy.sql import operators
+from sqlalchemy.sql import table
from sqlalchemy.sql import util as sql_util
-from sqlalchemy.util import u, OrderedDict
-from sqlalchemy.dialects.postgresql import aggregate_order_by, insert
-from sqlalchemy.dialects.postgresql import array_agg as pg_array_agg
-from sqlalchemy.dialects.postgresql import ARRAY as PG_ARRAY
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import assert_raises_message
+from sqlalchemy.testing.assertions import AssertsCompiledSQL
+from sqlalchemy.testing.assertions import expect_warnings
+from sqlalchemy.testing.assertions import is_
+from sqlalchemy.util import OrderedDict
+from sqlalchemy.util import u
class SequenceTest(fixtures.TestBase, AssertsCompiledSQL):
# coding: utf-8
-from sqlalchemy.testing.assertions import (
- eq_,
- assert_raises,
- assert_raises_message,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
-from sqlalchemy.testing import engines, fixtures
-from sqlalchemy import testing
import datetime
-from sqlalchemy import (
- Table,
- Column,
- select,
- MetaData,
- text,
- Integer,
- String,
- Sequence,
- Numeric,
- DateTime,
- BigInteger,
- func,
- extract,
- SmallInteger,
- TypeDecorator,
- literal,
- cast,
- bindparam,
-)
-from sqlalchemy import exc, schema
-from sqlalchemy.dialects.postgresql import base as postgresql
import logging
import logging.handlers
-from sqlalchemy.testing.mock import Mock
+
+from sqlalchemy import BigInteger
+from sqlalchemy import bindparam
+from sqlalchemy import cast
+from sqlalchemy import Column
+from sqlalchemy import DateTime
+from sqlalchemy import dialects
+from sqlalchemy import exc
+from sqlalchemy import extract
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import MetaData
+from sqlalchemy import Numeric
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import SmallInteger
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import TypeDecorator
+from sqlalchemy.dialects.postgresql import base as postgresql
from sqlalchemy.engine import engine_from_config
from sqlalchemy.engine import url
-from sqlalchemy.testing import is_
+from sqlalchemy.testing import engines
from sqlalchemy.testing import expect_deprecated
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import assert_raises_message
+from sqlalchemy.testing.assertions import AssertsCompiledSQL
+from sqlalchemy.testing.assertions import AssertsExecutionResults
+from sqlalchemy.testing.assertions import eq_
+from sqlalchemy.testing.mock import Mock
from ...engine import test_execute
-from sqlalchemy import dialects
class DialectTest(fixtures.TestBase):
# coding: utf-8
-from sqlalchemy.testing.assertions import eq_, assert_raises
-from sqlalchemy.testing import fixtures
+from sqlalchemy import Column
+from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import schema
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy import Table, Column, Integer, String
-from sqlalchemy import exc, schema, types as sqltypes, sql
+from sqlalchemy import types as sqltypes
from sqlalchemy.dialects.postgresql import insert
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import eq_
class OnConflictTest(fixtures.TablesTest):
# coding: utf-8
-from sqlalchemy.testing import (
- AssertsExecutionResults,
- eq_,
- assert_raises_message,
- AssertsCompiledSQL,
- expect_warnings,
- assert_raises,
-)
-from sqlalchemy import (
- Table,
- Column,
- MetaData,
- Integer,
- String,
- bindparam,
- Sequence,
- ForeignKey,
- text,
- select,
- func,
- extract,
- literal_column,
- tuple_,
- DateTime,
- Time,
- literal,
- and_,
- Date,
- or_,
-)
-from sqlalchemy.testing import engines, fixtures
-from sqlalchemy.testing.assertsql import DialectSQL, CursorSQL
-from sqlalchemy import testing
+import datetime
+
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import Date
+from sqlalchemy import DateTime
from sqlalchemy import exc
+from sqlalchemy import extract
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import Time
+from sqlalchemy import tuple_
from sqlalchemy.dialects import postgresql
-import datetime
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import CursorSQL
+from sqlalchemy.testing.assertsql import DialectSQL
+
matchtable = cattable = None
# coding: utf-8
-from sqlalchemy.engine import reflection
-from sqlalchemy.sql.schema import CheckConstraint
-from sqlalchemy.testing.assertions import (
- eq_,
- assert_raises,
- AssertsExecutionResults,
-)
-from sqlalchemy.testing import fixtures
-from sqlalchemy import testing
-from sqlalchemy import inspect
-from sqlalchemy import (
- Table,
- Column,
- MetaData,
- Integer,
- String,
- PrimaryKeyConstraint,
- ForeignKey,
- join,
- Sequence,
- UniqueConstraint,
- Index,
-)
-from sqlalchemy import exc
+import itertools
+from operator import itemgetter
+import re
+
import sqlalchemy as sa
+from sqlalchemy import Column
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Index
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import join
+from sqlalchemy import MetaData
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import UniqueConstraint
+from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql import base as postgresql
-from sqlalchemy.dialects.postgresql import ARRAY, INTERVAL, INTEGER, TSRANGE
from sqlalchemy.dialects.postgresql import ExcludeConstraint
-import re
-from operator import itemgetter
-import itertools
+from sqlalchemy.dialects.postgresql import INTEGER
+from sqlalchemy.dialects.postgresql import INTERVAL
+from sqlalchemy.dialects.postgresql import TSRANGE
+from sqlalchemy.engine import reflection
+from sqlalchemy.sql.schema import CheckConstraint
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import AssertsExecutionResults
+from sqlalchemy.testing.assertions import eq_
class ForeignTableReflectionTest(fixtures.TablesTest, AssertsExecutionResults):
# coding: utf-8
-from sqlalchemy.testing.assertions import (
- eq_,
- assert_raises,
- assert_raises_message,
- is_,
- AssertsExecutionResults,
- AssertsCompiledSQL,
- ComparesTables,
-)
-from sqlalchemy.testing import engines, fixtures
-from sqlalchemy import testing
-from sqlalchemy.sql import sqltypes
import datetime
-from sqlalchemy import (
- Table,
- MetaData,
- Column,
- Integer,
- Enum,
- Float,
- select,
- func,
- DateTime,
- Numeric,
- exc,
- String,
- cast,
- REAL,
- TypeDecorator,
- Unicode,
- Text,
- null,
- text,
- column,
- ARRAY,
- any_,
- all_,
-)
-from sqlalchemy.sql import operators
-from sqlalchemy import types
-import sqlalchemy as sa
-from sqlalchemy.dialects import postgresql
-from sqlalchemy.dialects.postgresql import (
- HSTORE,
- hstore,
- array,
- INT4RANGE,
- INT8RANGE,
- NUMRANGE,
- DATERANGE,
- TSRANGE,
- TSTZRANGE,
- JSON,
- JSONB,
-)
import decimal
-from sqlalchemy import util
-from sqlalchemy.testing.util import round_decimal
-from sqlalchemy import inspect
+
+import sqlalchemy as sa
+from sqlalchemy import any_
+from sqlalchemy import ARRAY
+from sqlalchemy import cast
+from sqlalchemy import Column
+from sqlalchemy import column
+from sqlalchemy import DateTime
+from sqlalchemy import Enum
from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import Float
+from sqlalchemy import func
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import null
+from sqlalchemy import Numeric
+from sqlalchemy import REAL
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import Text
+from sqlalchemy import text
+from sqlalchemy import TypeDecorator
+from sqlalchemy import types
+from sqlalchemy import Unicode
+from sqlalchemy import util
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.dialects.postgresql import array
+from sqlalchemy.dialects.postgresql import DATERANGE
+from sqlalchemy.dialects.postgresql import HSTORE
+from sqlalchemy.dialects.postgresql import hstore
+from sqlalchemy.dialects.postgresql import INT4RANGE
+from sqlalchemy.dialects.postgresql import INT8RANGE
+from sqlalchemy.dialects.postgresql import JSON
+from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.dialects.postgresql import NUMRANGE
+from sqlalchemy.dialects.postgresql import TSRANGE
+from sqlalchemy.dialects.postgresql import TSTZRANGE
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
+from sqlalchemy.sql import operators
+from sqlalchemy.sql import sqltypes
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import assert_raises_message
+from sqlalchemy.testing.assertions import AssertsCompiledSQL
+from sqlalchemy.testing.assertions import AssertsExecutionResults
+from sqlalchemy.testing.assertions import ComparesTables
+from sqlalchemy.testing.assertions import eq_
+from sqlalchemy.testing.assertions import is_
+from sqlalchemy.testing.util import round_decimal
+
tztable = notztable = metadata = table = None
self.tables.data_table.insert(), {"range": self._data_str}
)
# select
- range = self.tables.data_table.c.range
- data = testing.db.execute(select([range + range])).fetchall()
+ range_ = self.tables.data_table.c.range
+ data = testing.db.execute(select([range_ + range_])).fetchall()
eq_(data, [(self._data_obj(),)])
def test_intersection_result(self):
self.tables.data_table.insert(), {"range": self._data_str}
)
# select
- range = self.tables.data_table.c.range
- data = testing.db.execute(select([range * range])).fetchall()
+ range_ = self.tables.data_table.c.range
+ data = testing.db.execute(select([range_ * range_])).fetchall()
eq_(data, [(self._data_obj(),)])
def test_difference_result(self):
self.tables.data_table.insert(), {"range": self._data_str}
)
# select
- range = self.tables.data_table.c.range
- data = testing.db.execute(select([range - range])).fetchall()
+ range_ = self.tables.data_table.c.range
+ data = testing.db.execute(select([range_ - range_])).fetchall()
eq_(data, [(self._data_obj().__class__(empty=True),)])
+from sqlalchemy import dialects
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_not_
-from sqlalchemy import dialects
class ImportStarTest(fixtures.TestBase):
-from sqlalchemy.testing import eq_, assert_raises_message
+from sqlalchemy import Column
from sqlalchemy import exc
+from sqlalchemy import Float
+from sqlalchemy import func
+from sqlalchemy import insert
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import types as sqltypes
+from sqlalchemy import Unicode
+from sqlalchemy import update
+from sqlalchemy import VARCHAR
from sqlalchemy.databases import firebird
from sqlalchemy.exc import ProgrammingError
-from sqlalchemy.sql import table, column
-from sqlalchemy import types as sqltypes
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
-from sqlalchemy import testing
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import engines
-from sqlalchemy import (
- String,
- VARCHAR,
- NVARCHAR,
- Unicode,
- Integer,
- func,
- insert,
- update,
- MetaData,
- select,
- Table,
- Column,
- text,
- Sequence,
- Float,
-)
-from sqlalchemy import schema
-from sqlalchemy.testing.mock import Mock, call
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
class DomainReflectionTest(fixtures.TestBase, AssertsExecutionResults):
-from sqlalchemy import *
-from sqlalchemy.testing import eq_
+from sqlalchemy import Column
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Table
from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.mock import Mock
)
eq_(
+ # fmt: off
[
c[2]
- for c in dbapi.connect.return_value.cursor.return_value.execute.mock_calls
+ for c in dbapi.connect.return_value.cursor.
+ return_value.execute.mock_calls
],
+ # fmt: on
[
{"direct": True},
{"direct": True},
{"direct": True},
{"direct": False},
{"direct": True},
- ],
+ ]
)
-from sqlalchemy.testing import eq_
from sqlalchemy.connectors import pyodbc
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
#!coding: utf-8
"""SQLite-specific tests."""
-import os
import datetime
+import os
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- is_,
- expect_warnings,
-)
-from sqlalchemy import (
- Table,
- select,
- bindparam,
- Column,
- MetaData,
- func,
- extract,
- ForeignKey,
- text,
- DefaultClause,
- and_,
- create_engine,
- UniqueConstraint,
- Index,
- PrimaryKeyConstraint,
- CheckConstraint,
-)
-from sqlalchemy.types import Integer, String, Boolean, DateTime, Date, Time
-from sqlalchemy import types as sqltypes
-from sqlalchemy import event, inspect
-from sqlalchemy.util import u, ue
-from sqlalchemy import exc, sql, schema, pool, util
-from sqlalchemy.dialects.sqlite import (
- base as sqlite,
- pysqlite as pysqlite_dialect,
-)
-from sqlalchemy.engine.url import make_url
-from sqlalchemy.testing import (
- fixtures,
- AssertsCompiledSQL,
- AssertsExecutionResults,
- engines,
-)
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import CheckConstraint
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import DefaultClause
+from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import extract
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import inspect
+from sqlalchemy import MetaData
+from sqlalchemy import pool
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import sql
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.schema import CreateTable, FetchedValue
+from sqlalchemy import text
+from sqlalchemy import types as sqltypes
+from sqlalchemy import UniqueConstraint
+from sqlalchemy import util
+from sqlalchemy.dialects.sqlite import base as sqlite
+from sqlalchemy.dialects.sqlite import pysqlite as pysqlite_dialect
from sqlalchemy.engine.reflection import Inspector
+from sqlalchemy.engine.url import make_url
+from sqlalchemy.schema import CreateTable
+from sqlalchemy.schema import FetchedValue
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
+from sqlalchemy.types import Boolean
+from sqlalchemy.types import Date
+from sqlalchemy.types import DateTime
+from sqlalchemy.types import Integer
+from sqlalchemy.types import String
+from sqlalchemy.types import Time
+from sqlalchemy.util import u
+from sqlalchemy.util import ue
class TestTypes(fixtures.TestBase, AssertsExecutionResults):
-from sqlalchemy.testing.suite import *
+from sqlalchemy.testing.suite import * # noqa
-from sqlalchemy import extract, select
+from sqlalchemy import extract
+from sqlalchemy import select
from sqlalchemy import sql
from sqlalchemy.databases import sybase
-from sqlalchemy.testing import (
- assert_raises_message,
- fixtures,
- AssertsCompiledSQL,
-)
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import fixtures
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
"""tests the "bind" attribute/argument across schema and SQL,
including the deprecated versions of these arguments"""
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy import engine, exc
-from sqlalchemy import MetaData, ThreadLocalMetaData
-from sqlalchemy import Integer, text
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
import sqlalchemy as sa
+from sqlalchemy import engine
+from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import ThreadLocalMetaData
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class BindTest(fixtures.TestBase):
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy.schema import (
- DDL,
- CheckConstraint,
- AddConstraint,
- DropConstraint,
-)
-from sqlalchemy import create_engine
-from sqlalchemy import MetaData, Integer, String, event, exc, text
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
import sqlalchemy as tsa
+from sqlalchemy import create_engine
+from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy.schema import AddConstraint
+from sqlalchemy.schema import CheckConstraint
+from sqlalchemy.schema import DDL
+from sqlalchemy.schema import DropConstraint
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import engines
-from sqlalchemy.testing import AssertsCompiledSQL, eq_
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class DDLEventTest(fixtures.TestBase):
engine = create_engine(
testing.db.name + "://", strategy="mock", executor=executor
)
- engine.dialect.identifier_preparer = tsa.sql.compiler.IdentifierPreparer(
- engine.dialect
- )
+ # fmt: off
+ engine.dialect.identifier_preparer = \
+ tsa.sql.compiler.IdentifierPreparer(
+ engine.dialect
+ )
+ # fmt: on
return engine
def test_tokens(self):
# coding: utf-8
-import weakref
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- config,
- is_,
- is_not_,
- le_,
- expect_warnings,
-)
+from contextlib import contextmanager
import re
-from sqlalchemy.testing.util import picklers
-from sqlalchemy.testing.util import gc_collect
-from sqlalchemy.interfaces import ConnectionProxy
-from sqlalchemy import (
- MetaData,
- Integer,
- String,
- INT,
- VARCHAR,
- func,
- bindparam,
- select,
- event,
- TypeDecorator,
- create_engine,
- Sequence,
- LargeBinary,
-)
-from sqlalchemy.sql import column, literal
-from sqlalchemy.testing.schema import Table, Column
+import weakref
+
import sqlalchemy as tsa
+from sqlalchemy import bindparam
+from sqlalchemy import create_engine
+from sqlalchemy import event
+from sqlalchemy import func
+from sqlalchemy import INT
+from sqlalchemy import Integer
+from sqlalchemy import LargeBinary
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import engines
+from sqlalchemy import TypeDecorator
from sqlalchemy import util
-from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.dialects.oracle.zxjdbc import ReturningParam
-from sqlalchemy.engine import result as _result, default
+from sqlalchemy import VARCHAR
+from sqlalchemy.engine import default
from sqlalchemy.engine.base import Engine
+from sqlalchemy.interfaces import ConnectionProxy
+from sqlalchemy.sql import column
+from sqlalchemy.sql import literal
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import config
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
-from sqlalchemy.testing.mock import Mock, call, patch
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
from sqlalchemy.testing import mock
-from contextlib import contextmanager
-from sqlalchemy.util import nested
from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.engines import testing_engine
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import gc_collect
+from sqlalchemy.testing.util import picklers
+from sqlalchemy.util import nested
users, metadata, users_autoinc = None, None, None
-from sqlalchemy.testing import eq_, assert_raises_message, eq_regex
-from sqlalchemy import select
+import logging.handlers
+
import sqlalchemy as tsa
+from sqlalchemy import select
+from sqlalchemy import util
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import engines
-import logging.handlers
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import eq_regex
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock
from sqlalchemy.testing.util import lazy_gc
-from sqlalchemy import util
class LogParamsTest(fixtures.TestBase):
-from sqlalchemy.testing import assert_raises, eq_, is_
-import sqlalchemy.engine.url as url
-from sqlalchemy import create_engine, engine_from_config, exc, pool
-from sqlalchemy.engine.default import DefaultDialect
import sqlalchemy as tsa
-from sqlalchemy.testing import fixtures
+from sqlalchemy import create_engine
+from sqlalchemy import engine_from_config
+from sqlalchemy import exc
+from sqlalchemy import pool
from sqlalchemy import testing
-from sqlalchemy.testing.mock import Mock, MagicMock, call
-from sqlalchemy.testing import mock
-from sqlalchemy.dialects import registry
from sqlalchemy.dialects import plugins
+from sqlalchemy.dialects import registry
+from sqlalchemy.engine.default import DefaultDialect
+import sqlalchemy.engine.url as url
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import MagicMock
+from sqlalchemy.testing.mock import Mock
+
dialect = None
+import collections
+import random
import threading
import time
-from sqlalchemy import pool, select, event
+import weakref
+
import sqlalchemy as tsa
+from sqlalchemy import event
+from sqlalchemy import pool
+from sqlalchemy import select
from sqlalchemy import testing
-from sqlalchemy.testing.util import gc_collect, lazy_gc
-from sqlalchemy.testing import eq_, assert_raises, is_not_, is_
-from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
-import random
-from sqlalchemy.testing.mock import Mock, call, patch, ANY
-import weakref
-import collections
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing.engines import testing_engine
+from sqlalchemy.testing.mock import ANY
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.util import gc_collect
+from sqlalchemy.testing.util import lazy_gc
+
join_timeout = 10
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import assert_raises_message, eq_
class _BooleanProcessorTest(fixtures.TestBase):
-from sqlalchemy.testing import (
- eq_,
- ne_,
- assert_raises,
- expect_warnings,
- assert_raises_message,
-)
import time
-from sqlalchemy import (
- select,
- MetaData,
- Integer,
- String,
- create_engine,
- pool,
- exc,
- util,
-)
-from sqlalchemy.testing.schema import Table, Column
+
import sqlalchemy as tsa
-from sqlalchemy.engine import url
+from sqlalchemy import create_engine
+from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import pool
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import mock
+from sqlalchemy import util
+from sqlalchemy.engine import url
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import mock
+from sqlalchemy.testing import ne_
from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.testing.mock import Mock, call, patch
-from sqlalchemy import event
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
import unicodedata
+
import sqlalchemy as sa
-from sqlalchemy import schema, inspect, sql
-from sqlalchemy import (
- MetaData,
- Integer,
- String,
- Index,
- ForeignKey,
- UniqueConstraint,
- FetchedValue,
- DefaultClause,
-)
-from sqlalchemy.testing import (
- ComparesTables,
- engines,
- AssertsCompiledSQL,
- fixtures,
- skip,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing import (
- eq_,
- eq_regex,
- is_true,
- assert_raises,
- assert_raises_message,
-)
+from sqlalchemy import DefaultClause
+from sqlalchemy import FetchedValue
+from sqlalchemy import ForeignKey
+from sqlalchemy import Index
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import schema
+from sqlalchemy import sql
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.util import ue
+from sqlalchemy import UniqueConstraint
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import ComparesTables
from sqlalchemy.testing import config
-from sqlalchemy.testing import mock
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import eq_regex
from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_true
+from sqlalchemy.testing import mock
+from sqlalchemy.testing import skip
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import ue
+
metadata, users = None, None
1,
)
if (
- testing.requires.unique_constraint_reflection_no_index_overlap.enabled
+ # fmt: off
+ testing.requires.
+ unique_constraint_reflection_no_index_overlap.enabled
+ # fmt: on
):
eq_(
len(
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- ne_,
- expect_warnings,
-)
import sys
+
+from sqlalchemy import create_engine
from sqlalchemy import event
-from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy import (
- create_engine,
- MetaData,
- INT,
- VARCHAR,
- Sequence,
- select,
- Integer,
- String,
- func,
- text,
- exc,
-)
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
+from sqlalchemy import exc
+from sqlalchemy import func
+from sqlalchemy import INT
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import VARCHAR
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.engines import testing_engine
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
users, metadata = None, None
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- expect_warnings,
- is_,
-)
-from sqlalchemy.testing import assertions
-from sqlalchemy.ext import declarative as decl
-from sqlalchemy.ext.hybrid import hybrid_property
-from sqlalchemy import exc
import sqlalchemy as sa
-from sqlalchemy import testing, util
-from sqlalchemy import (
- MetaData,
- Integer,
- String,
- ForeignKey,
- ForeignKeyConstraint,
- Index,
- UniqueConstraint,
- CheckConstraint,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- relationship,
- create_session,
- class_mapper,
- joinedload,
- configure_mappers,
- backref,
- clear_mappers,
- column_property,
- composite,
- Session,
- properties,
- deferred,
-)
-from sqlalchemy.util import with_metaclass
-from sqlalchemy.ext.declarative import declared_attr, synonym_for
-from sqlalchemy.testing import fixtures, mock
-from sqlalchemy.orm.events import MapperEvents
-from sqlalchemy.orm import mapper
+from sqlalchemy import CheckConstraint
from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import Index
from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy import UniqueConstraint
+from sqlalchemy import util
+from sqlalchemy.ext import declarative as decl
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.ext.declarative import synonym_for
+from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import composite
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import properties
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm.events import MapperEvents
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import assertions
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import with_metaclass
+
Base = None
+import weakref
+
+from sqlalchemy import exc
+from sqlalchemy import MetaData
+from sqlalchemy.ext.declarative import clsregistry
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing.util import gc_collect
-from sqlalchemy.testing import assert_raises_message, is_, eq_
-from sqlalchemy import exc, MetaData
-from sqlalchemy.ext.declarative import clsregistry
-import weakref
class MockClass(object):
-from sqlalchemy.testing import (
- eq_,
- le_,
- assert_raises,
- assert_raises_message,
- is_,
- is_true,
- is_false,
-)
-from sqlalchemy.ext import declarative as decl
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- relationship,
- create_session,
- class_mapper,
- configure_mappers,
- clear_mappers,
- polymorphic_union,
- deferred,
- Session,
- mapper,
-)
-from sqlalchemy.ext.declarative import (
- declared_attr,
- AbstractConcreteBase,
- ConcreteBase,
- has_inherited_table,
-)
-from sqlalchemy.testing import fixtures, mock
+from sqlalchemy.ext import declarative as decl
+from sqlalchemy.ext.declarative import AbstractConcreteBase
+from sqlalchemy.ext.declarative import ConcreteBase
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.ext.declarative import has_inherited_table
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_false
+from sqlalchemy.testing import is_true
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm.test_events import _RemoveListeners
+
Base = None
"(SELECT cca.id AS id, cca.x AS x, cca.y AS y, "
"cca.something_id AS something_id, 'ccb' AS type FROM cca) "
"AS pjoin WHERE EXISTS (SELECT 1 FROM something "
- "WHERE something.id = pjoin.something_id AND something.id = :id_1)",
+ "WHERE something.id = pjoin.something_id "
+ "AND something.id = :id_1)",
)
self.assert_compile(
"(SELECT cca.id AS id, cca.x AS x, cca.y AS y, "
"cca.something_id AS something_id, 'ccb' AS type FROM cca) "
"AS pjoin WHERE EXISTS (SELECT 1 FROM something "
- "WHERE something.id = pjoin.something_id AND something.id = :id_1)",
+ "WHERE something.id = pjoin.something_id AND "
+ "something.id = :id_1)",
)
def test_abstract_in_hierarchy(self):
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- is_,
- expect_warnings,
-)
-from sqlalchemy.ext import declarative as decl
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey, select, func
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- relationship,
- create_session,
- class_mapper,
- configure_mappers,
- clear_mappers,
- deferred,
- column_property,
- Session,
- base as orm_base,
- synonym,
-)
-from sqlalchemy.util import classproperty
-from sqlalchemy.ext.declarative import declared_attr, declarative_base
+from sqlalchemy.ext import declarative as decl
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy.orm import base as orm_base
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
from sqlalchemy.orm import events as orm_events
-from sqlalchemy.testing import fixtures, mock
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import synonym
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
+from sqlalchemy.util import classproperty
+
Base = None
def test_correct_for_proxies(self):
from sqlalchemy.ext.hybrid import hybrid_property
- from sqlalchemy.ext import hybrid
from sqlalchemy import inspect
class Mixin(object):
s = Session()
self.assert_compile(
s.query(Base.data_syn).filter(Base.data_syn == "foo"),
- "SELECT test.data AS test_data FROM test WHERE test.data = :data_1",
+ "SELECT test.data AS test_data FROM test "
+ "WHERE test.data = :data_1",
dialect="default",
)
self.assert_compile(
@declared_attr.cascading
def my_attr(cls):
if decl.has_inherited_table(cls):
- id = Column(ForeignKey("a.my_attr"), primary_key=True)
- asserted["b"].add(id)
+ id_ = Column(ForeignKey("a.my_attr"), primary_key=True)
+ asserted["b"].add(id_)
else:
- id = Column(Integer, primary_key=True)
- asserted["a"].add(id)
- return id
+ id_ = Column(Integer, primary_key=True)
+ asserted["a"].add(id_)
+ return id_
class A(Base, Mixin):
__tablename__ = "a"
-from sqlalchemy.testing import eq_, assert_raises
-from sqlalchemy.ext import declarative as decl
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import relationship, create_session, clear_mappers, Session
+from sqlalchemy.ext import declarative as decl
+from sqlalchemy.ext.declarative.base import _DeferredMapperConfig
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
-from sqlalchemy.ext.declarative.base import _DeferredMapperConfig
class DeclarativeReflectionBase(fixtures.TablesTest):
-from sqlalchemy.testing import eq_, assert_raises, is_
import copy
import pickle
-from sqlalchemy import Integer, ForeignKey, String, or_, MetaData
-from sqlalchemy.orm import (
- relationship,
- configure_mappers,
- mapper,
- Session,
- collections,
- sessionmaker,
- aliased,
- clear_mappers,
- create_session,
-)
from sqlalchemy import exc
-from sqlalchemy.orm.collections import collection, attribute_mapped_collection
-from sqlalchemy.ext.associationproxy import association_proxy
-from sqlalchemy.ext.associationproxy import _AssociationList
-from sqlalchemy.testing import assert_raises_message
-from sqlalchemy.testing.util import gc_collect
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing.mock import Mock, call
-from sqlalchemy.testing.assertions import expect_warnings
+from sqlalchemy.engine import default
+from sqlalchemy.ext.associationproxy import _AssociationList
+from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
-from sqlalchemy.engine import default
-from sqlalchemy import inspect
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import collections
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm.collections import attribute_mapped_collection
+from sqlalchemy.orm.collections import collection
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.assertions import expect_warnings
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import gc_collect
class DictCollection(dict):
if obj not in self.session:
self.session.add(obj)
self.session.flush()
- id, type_ = obj.id, type(obj)
+ id_, type_ = obj.id, type(obj)
self.session.expunge_all()
- return self.session.query(type_).get(id)
+ return self.session.query(type_).get(id_)
def _test_sequence_ops(self):
Parent, Child = self.Parent, self.Child
if obj not in session:
session.add(obj)
session.flush()
- id, type_ = obj.id, type(obj)
+ id_, type_ = obj.id, type(obj)
session.expunge_all()
- return session.query(type_).get(id)
+ return session.query(type_).get(id_)
p = Parent("p")
def roundtrip(self, obj):
self.session.add(obj)
self.session.flush()
- id, type_ = obj.id, type(obj)
+ id_, type_ = obj.id, type(obj)
self.session.expunge_all()
- return self.session.query(type_).get(id)
+ return self.session.query(type_).get(id_)
def test_lazy_list(self):
Parent, Child = self.Parent, self.Child
@classmethod
def setup_mappers(cls):
- users, Keyword, UserKeyword, singular, userkeywords, User, keywords, Singular = (
+ (
+ users,
+ Keyword,
+ UserKeyword,
+ singular,
+ userkeywords,
+ User,
+ keywords,
+ Singular,
+ ) = (
cls.tables.users,
cls.classes.Keyword,
cls.classes.UserKeyword,
-from sqlalchemy.testing import fixtures
-from ..orm._fixtures import FixtureTest
-from sqlalchemy.ext.automap import automap_base
-from sqlalchemy.orm import relationship, interfaces, configure_mappers
-from sqlalchemy.ext.automap import generate_relationship
-from sqlalchemy.testing.mock import Mock, patch
-from sqlalchemy import String, Integer, ForeignKey, MetaData
-from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-
-from sqlalchemy import create_engine
+import random
import threading
import time
-import random
+
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy.ext.automap import automap_base
+from sqlalchemy.ext.automap import generate_relationship
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import interfaces
+from sqlalchemy.orm import relationship
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from ..orm._fixtures import FixtureTest
class AutomapTest(fixtures.MappedTest):
-from sqlalchemy.orm import (
- Session,
- subqueryload,
- mapper,
- relationship,
- lazyload,
- backref,
- aliased,
- Load,
- defaultload,
-)
-from sqlalchemy.testing import eq_, is_, is_not_
-from sqlalchemy.testing import assert_raises_message
+import contextlib
+import itertools
+
+from sqlalchemy import bindparam
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import func
from sqlalchemy import testing
-from test.orm import _fixtures
from sqlalchemy.ext import baked
-from sqlalchemy import bindparam, func
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import defaultload
from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import Load
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
from sqlalchemy.orm.query import Query
-import itertools
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
from sqlalchemy.testing import mock
from sqlalchemy.testing.assertsql import CompiledSQL
-import contextlib
-from sqlalchemy import exc as sa_exc
+from test.orm import _fixtures
class BakedTest(_fixtures.FixtureTest):
-from sqlalchemy import *
-from sqlalchemy.types import TypeEngine
-from sqlalchemy.sql.expression import (
- ClauseElement,
- ColumnClause,
- FunctionElement,
- Select,
- BindParameter,
- ColumnElement,
-)
-
-from sqlalchemy.schema import DDLElement, CreateColumn, CreateTable
-from sqlalchemy.ext.compiler import compiles, deregister
+from sqlalchemy import Column
+from sqlalchemy import column
+from sqlalchemy import desc
from sqlalchemy import exc
-from sqlalchemy.testing import eq_
-from sqlalchemy.sql import table, column
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Numeric
+from sqlalchemy import select
+from sqlalchemy import Table
+from sqlalchemy import table
+from sqlalchemy.ext.compiler import compiles
+from sqlalchemy.ext.compiler import deregister
+from sqlalchemy.schema import CreateColumn
+from sqlalchemy.schema import CreateTable
+from sqlalchemy.schema import DDLElement
+from sqlalchemy.sql.expression import BindParameter
+from sqlalchemy.sql.expression import ClauseElement
+from sqlalchemy.sql.expression import ColumnClause
+from sqlalchemy.sql.expression import FunctionElement
+from sqlalchemy.sql.expression import Select
from sqlalchemy.testing import assert_raises_message
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.types import TypeEngine
class UserDefinedTest(fixtures.TestBase, AssertsCompiledSQL):
pass
@compiles(MyType, "sqlite")
- def visit_type(type, compiler, **kw):
+ def visit_sqlite_type(type_, compiler, **kw):
return "SQLITE_FOO"
@compiles(MyType, "postgresql")
- def visit_type(type, compiler, **kw):
+ def visit_pg_type(type_, compiler, **kw):
return "POSTGRES_FOO"
from sqlalchemy.dialects.sqlite import base as sqlite
try:
@compiles(Select)
- def compile(element, compiler, **kw):
+ def compile_(element, compiler, **kw):
return "OVERRIDE"
s1 = select([t1])
__visit_name__ = "drop_thingy"
@compiles(AddThingy, "sqlite")
- def visit_add_thingy(thingy, compiler, **kw):
+ def visit_add_thingy_sqlite(thingy, compiler, **kw):
return "ADD SPECIAL SL THINGY"
@compiles(AddThingy)
)
@compiles(DropThingy, "sqlite")
- def visit_drop_thingy(thingy, compiler, **kw):
+ def visit_drop_thingy_sqlite(thingy, compiler, **kw):
return "DROP SPECIAL SL THINGY"
self.assert_compile(
return "utcnow()"
@compiles(MyUtcFunction, "postgresql")
- def visit_myfunc(element, compiler, **kw):
+ def visit_myfunc_pg(element, compiler, **kw):
return "timezone('utc', current_timestamp)"
self.assert_compile(
return element.name
@compiles(Sub1)
- def visit_base(element, compiler, **kw):
+ def visit_sub1(element, compiler, **kw):
return "FOO" + element.name
self.assert_compile(
)
@compiles(Sub1)
- def visit_base(element, compiler, **kw):
+ def visit_sub1(element, compiler, **kw):
return "FOO" + element.name
self.assert_compile(
t1 = table("t1", column("c1"), column("c2"))
@compiles(Select, "sqlite")
- def compile(element, compiler, **kw):
+ def compile_(element, compiler, **kw):
return "OVERRIDE"
s1 = select([t1])
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, ne_
-from sqlalchemy import util
import sqlalchemy as sa
-from sqlalchemy.orm import class_mapper
+from sqlalchemy import event
+from sqlalchemy import util
+from sqlalchemy.ext import instrumentation
from sqlalchemy.orm import attributes
-from sqlalchemy.orm.attributes import (
- set_attribute,
- get_attribute,
- del_attribute,
-)
-from sqlalchemy.orm.instrumentation import is_instrumented
+from sqlalchemy.orm import class_mapper
from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import events
+from sqlalchemy.orm.attributes import del_attribute
+from sqlalchemy.orm.attributes import get_attribute
+from sqlalchemy.orm.attributes import set_attribute
+from sqlalchemy.orm.instrumentation import is_instrumented
+from sqlalchemy.orm.instrumentation import manager_of_class
+from sqlalchemy.orm.instrumentation import register_class
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy.ext import instrumentation
-from sqlalchemy.orm.instrumentation import register_class, manager_of_class
+from sqlalchemy.testing import ne_
from sqlalchemy.testing.util import decorator
-from sqlalchemy.orm import events
-from sqlalchemy import event
@decorator
)
if base is object:
- assert (
- Foo
- not in instrumentation._instrumentation_factory._state_finders
+ assert Foo not in (
+ instrumentation._instrumentation_factory._state_finders
)
else:
- assert (
- Foo
- in instrumentation._instrumentation_factory._state_finders
+ assert Foo in (
+ instrumentation._instrumentation_factory._state_finders
)
f = Foo()
import datetime
import os
-from sqlalchemy import *
+
+from sqlalchemy import Column
+from sqlalchemy import DateTime
from sqlalchemy import event
-from sqlalchemy import sql, util
-from sqlalchemy.orm import *
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import util
from sqlalchemy.ext.horizontal_shard import ShardedSession
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import selectinload
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import operators
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import provision
from sqlalchemy.testing.engines import testing_engine
-from sqlalchemy.testing import eq_
-from sqlalchemy import testing
+
# TODO: ShardTest can be turned into a base for further subclasses
assert inspect(t).deleted is (t.temperature >= 80)
-from sqlalchemy.testing import provision
-
-
class DistinctEngineShardTest(ShardTest, fixtures.TestBase):
def _init_dbs(self):
db1 = testing_engine(
-from sqlalchemy import func, Integer, Numeric, String, ForeignKey
-from sqlalchemy.orm import relationship, Session, aliased, persistence
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.ext.declarative import declarative_base
+from decimal import Decimal
+
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import Numeric
+from sqlalchemy import String
from sqlalchemy.ext import hybrid
-from sqlalchemy.testing import (
- eq_,
- is_,
- AssertsCompiledSQL,
- assert_raises_message,
-)
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import persistence
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy import inspect
-from decimal import Decimal
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.schema import Column
class PropertyComparatorTest(fixtures.TestBase, AssertsCompiledSQL):
-from sqlalchemy.testing import assert_raises
import sqlalchemy as sa
+from sqlalchemy import inspect
+from sqlalchemy import Integer
from sqlalchemy import testing
-from sqlalchemy import Integer, Text
-from sqlalchemy.sql.sqltypes import ARRAY, JSON
-from sqlalchemy.testing.schema import Column
+from sqlalchemy import Text
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.ext.indexable import index_property
from sqlalchemy.orm import Session
+from sqlalchemy.sql.sqltypes import ARRAY
+from sqlalchemy.sql.sqltypes import JSON
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy.ext.indexable import index_property
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.testing import eq_, ne_, is_, in_, not_in_
-from sqlalchemy import inspect
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing import not_in_
+from sqlalchemy.testing.schema import Column
class IndexPropertyTest(fixtures.TestBase):
-from sqlalchemy import Integer, ForeignKey, String, func
-from sqlalchemy.types import PickleType, TypeDecorator, VARCHAR
-from sqlalchemy.orm import mapper, Session, composite, column_property
-from sqlalchemy.orm.mapper import Mapper
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.mutable import MutableComposite
+from sqlalchemy.ext.mutable import MutableDict
+from sqlalchemy.ext.mutable import MutableList
+from sqlalchemy.ext.mutable import MutableSet
from sqlalchemy.orm import attributes
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import composite
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
from sqlalchemy.orm.instrumentation import ClassManager
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing import eq_, assert_raises_message, assert_raises
-from sqlalchemy.testing.util import picklers
+from sqlalchemy.orm.mapper import Mapper
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy.ext.mutable import MutableComposite
-from sqlalchemy.ext.mutable import MutableDict, MutableList, MutableSet
from sqlalchemy.testing import mock
-from sqlalchemy import event
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import picklers
+from sqlalchemy.types import PickleType
+from sqlalchemy.types import TypeDecorator
+from sqlalchemy.types import VARCHAR
class Foo(fixtures.BasicEntity):
-from sqlalchemy import Integer, ForeignKey, String, MetaData
-from sqlalchemy.orm import relationship, mapper, create_session
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import testing
from sqlalchemy.ext.orderinglist import ordering_list
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import picklers
session.add(s1)
session.flush()
- id = s1.id
+ id_ = s1.id
session.expunge_all()
del s1
- srt = session.query(Slide).get(id)
+ srt = session.query(Slide).get(id_)
self.assert_(srt.bullets)
self.assert_(len(srt.bullets) == 4)
session.add(s1)
session.flush()
- id = s1.id
+ id_ = s1.id
session.expunge_all()
del s1
- srt = session.query(Slide).get(id)
+ srt = session.query(Slide).get(id_)
self.assert_(srt.bullets)
self.assert_(len(srt.bullets) == 5)
session.flush()
session.expunge_all()
- srt = session.query(Slide).get(id)
+ srt = session.query(Slide).get(id_)
titles = ["s1/b1", "s1/b2", "s1/b100", "s1/b4", "raw", "raw2"]
found = [b.text for b in srt.bullets]
eq_(titles, found)
session.add(s1)
session.flush()
- id = s1.id
+ id_ = s1.id
session.expunge_all()
del s1
- srt = session.query(Slide).get(id)
+ srt = session.query(Slide).get(id_)
self.assert_(srt.bullets)
self.assert_(len(srt.bullets) == 6)
session.add(s1)
session.flush()
- id = s1.id
+ id_ = s1.id
session.expunge_all()
del s1
- srt = session.query(Slide).get(id)
+ srt = session.query(Slide).get(id_)
self.assert_(srt.bullets)
self.assert_(len(srt.bullets) == 3)
self.assert_(new_bullet.position == 1)
self.assert_(len(s1.bullets) == 3)
- id = s1.id
+ id_ = s1.id
session.flush()
session.expunge_all()
- srt = session.query(Slide).get(id)
+ srt = session.query(Slide).get(id_)
self.assert_(srt.bullets)
self.assert_(len(srt.bullets) == 3)
# coding: utf-8
-from sqlalchemy.ext import serializer
+from sqlalchemy import desc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import join
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- select,
- desc,
- func,
- util,
- MetaData,
- literal_column,
- join,
-)
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import (
- relationship,
- sessionmaker,
- scoped_session,
- class_mapper,
- mapper,
- joinedload,
- configure_mappers,
- aliased,
-)
-from sqlalchemy.testing import eq_, AssertsCompiledSQL
-from sqlalchemy.util import u, ue
+from sqlalchemy.ext import serializer
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import scoped_session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import ue
def pickle_protocols():
-from sqlalchemy import MetaData, Integer, String, ForeignKey
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import util
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import (
- attributes,
- mapper,
- relationship,
- backref,
- configure_mappers,
-)
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+
__all__ = ()
@classmethod
def _setup_stock_mapping(cls):
- Node, composite_pk_table, users, Keyword, items, Dingaling, order_items, item_keywords, Item, User, dingalings, Address, keywords, CompositePk, nodes, Order, orders, addresses = (
+ (
+ Node,
+ composite_pk_table,
+ users,
+ Keyword,
+ items,
+ Dingaling,
+ order_items,
+ item_keywords,
+ Item,
+ User,
+ dingalings,
+ Address,
+ keywords,
+ CompositePk,
+ nodes,
+ Order,
+ orders,
+ addresses,
+ ) = (
cls.classes.Node,
cls.tables.composite_pk_table,
cls.tables.users,
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.orm import (
- relationship,
- mapper,
- create_session,
- polymorphic_union,
-)
-
-from sqlalchemy.testing import AssertsCompiledSQL, fixtures
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import relationship
+from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import config
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class Company(fixtures.ComparableEntity):
-from sqlalchemy import *
-from sqlalchemy.orm import *
-from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOONE
-
-from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm.interfaces import MANYTOONE
+from sqlalchemy.orm.interfaces import ONETOMANY
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
def produce_test(parent, child, direction):
-from sqlalchemy import *
-from sqlalchemy import util
-from sqlalchemy.orm import *
-
-from sqlalchemy.testing.util import function_named
-from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
from sqlalchemy.testing import eq_
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import function_named
class ABCTest(fixtures.MappedTest):
"""
-from sqlalchemy.testing import eq_
-from sqlalchemy import *
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy import Unicode
from sqlalchemy import util
-from sqlalchemy.orm import *
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import join
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import Query
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.orm.interfaces import MANYTOONE
from sqlalchemy.testing import AssertsExecutionResults
-from sqlalchemy import testing
-from sqlalchemy.testing.util import function_named
-from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
from sqlalchemy.testing import eq_
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import function_named
class AttrSettable(object):
for jointype in ["join1", "join2", "join3", "join4"]:
for data in (True, False):
- func = _generate_test(jointype, data)
- setattr(RelationshipTest3, func.__name__, func)
+ _fn = _generate_test(jointype, data)
+ setattr(RelationshipTest3, _fn.__name__, _fn)
del func
class ManyToManyPolyTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
- global base_item_table, item_table, base_item_collection_table, collection_table
+ global base_item_table, item_table
+ global base_item_collection_table, collection_table
base_item_table = Table(
"base_item",
metadata,
-import warnings
-from sqlalchemy.testing import eq_, is_, assert_raises, assert_raises_message
-from sqlalchemy import *
-from sqlalchemy import exc as sa_exc, util, event
-from sqlalchemy.orm import *
-from sqlalchemy.orm.util import instance_str
-from sqlalchemy.orm import exc as orm_exc, attributes
-from sqlalchemy.testing.assertsql import AllOf, CompiledSQL, RegexSQL, Or
-from sqlalchemy.sql import table, column
+from sqlalchemy import Boolean
+from sqlalchemy import case
+from sqlalchemy import column
+from sqlalchemy import event
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import table
from sqlalchemy import testing
+from sqlalchemy import util
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import composite
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import object_mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import synonym
+from sqlalchemy.orm.util import instance_str
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy import inspect
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.testing.util import gc_collect
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.assertsql import Or
+from sqlalchemy.testing.assertsql import RegexSQL
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class O2MTest(fixtures.MappedTest):
# the 'primaryjoin' looks just like "Sub"'s "get" clause
# (based on the Base id), and foreign_keys since that join
# condition doesn't actually have any fks in it
- # 'sub':relationship(Sub, primaryjoin=base.c.id==related.c.sub_id,
+ # 'sub':relationship(Sub,
+ # primaryjoin=base.c.id==related.c.sub_id,
# foreign_keys=related.c.sub_id)
# now we can use this:
"sub": relationship(Sub)
r"On mapper Mapper\|Employee\|employees, "
"primary key column 'persons.id' is being "
"combined with distinct primary key column 'employees.eid' "
- "in attribute 'id'. Use explicit properties to give "
+ "in attribute 'id'. Use explicit properties to give "
"each column its own mapped attribute name.",
self._do_test,
True,
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
-from sqlalchemy import *
-from sqlalchemy.orm import *
-from sqlalchemy.orm import exc as orm_exc
-from sqlalchemy.testing import *
-import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures
+from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import attributes
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class Employee(object):
class ConcreteTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
- global managers_table, engineers_table, hackers_table, companies, employees_table
+ global managers_table, engineers_table, hackers_table
+ global companies, employees_table
companies = Table(
"companies",
metadata,
+from sqlalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import eq_
-from sqlalchemy import *
-from sqlalchemy.orm import *
-
-from sqlalchemy import testing
from sqlalchemy.testing import fixtures
-from sqlalchemy import *
-from sqlalchemy.orm import *
-
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import fixtures
-from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class PolymorphicCircularTest(fixtures.MappedTest):
-from sqlalchemy import String, Integer, Column, ForeignKey
-from sqlalchemy.orm import (
- relationship,
- Session,
- joinedload,
- selectin_polymorphic,
- selectinload,
- with_polymorphic,
- backref,
-)
-from sqlalchemy.testing import fixtures
+from sqlalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import selectin_polymorphic
+from sqlalchemy.orm import selectinload
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import with_polymorphic
from sqlalchemy.testing import eq_
-from sqlalchemy.testing.assertsql import AllOf, CompiledSQL, EachOf, Or
-from ._poly_fixtures import (
- Company,
- Person,
- Engineer,
- Manager,
- _Polymorphic,
- GeometryFixtureBase,
-)
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.assertsql import EachOf
+from sqlalchemy.testing.assertsql import Or
+from ._poly_fixtures import _Polymorphic
+from ._poly_fixtures import Company
+from ._poly_fixtures import Engineer
+from ._poly_fixtures import GeometryFixtureBase
+from ._poly_fixtures import Manager
+from ._poly_fixtures import Person
class BaseAndSubFixture(object):
AllOf(
EachOf(
CompiledSQL(
- "SELECT asub.id AS asub_id, a.id AS a_id, a.type AS a_type, "
+ "SELECT asub.id AS asub_id, a.id AS a_id, "
+ "a.type AS a_type, "
"asub.asubdata AS asub_asubdata FROM a JOIN asub "
- "ON a.id = asub.id WHERE a.id IN ([EXPANDING_primary_keys]) "
+ "ON a.id = asub.id "
+ "WHERE a.id IN ([EXPANDING_primary_keys]) "
"ORDER BY a.id",
{"primary_keys": [2]},
),
"""tests basic polymorphic mapper loading/saving, minimal relationships"""
-from sqlalchemy.testing import eq_, is_, assert_raises, assert_raises_message
-from sqlalchemy import *
-from sqlalchemy.orm import *
-from sqlalchemy.orm import exc as orm_exc
from sqlalchemy import exc as sa_exc
-from sqlalchemy.testing.schema import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.testing.util import function_named
-from test.orm import _fixtures
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import polymorphic_union
+from sqlalchemy.orm import relationship
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.util import function_named
class Person(fixtures.ComparableEntity):
for lazy_relationship in [True, False]:
for redefine_colprop in [True, False]:
- for with_polymorphic in ["unions", "joins", "auto", "none"]:
- if with_polymorphic == "unions":
+ for with_polymorphic_ in ["unions", "joins", "auto", "none"]:
+ if with_polymorphic_ == "unions":
for include_base in [True, False]:
_generate_round_trip_test(
include_base,
lazy_relationship,
redefine_colprop,
- with_polymorphic,
+ with_polymorphic_,
)
else:
_generate_round_trip_test(
False,
lazy_relationship,
redefine_colprop,
- with_polymorphic,
+ with_polymorphic_,
)
-from sqlalchemy import func, desc, select
-from sqlalchemy.orm import (
- interfaces,
- create_session,
- joinedload,
- joinedload_all,
- subqueryload,
- subqueryload_all,
- aliased,
- class_mapper,
- with_polymorphic,
-)
+from sqlalchemy import desc
from sqlalchemy import exc as sa_exc
-
+from sqlalchemy import func
+from sqlalchemy import select
from sqlalchemy import testing
-from sqlalchemy.testing import assert_raises, eq_
-
-from ._poly_fixtures import (
- Company,
- Person,
- Engineer,
- Manager,
- Boss,
- Machine,
- Paperwork,
- _Polymorphic,
- _PolymorphicPolymorphic,
- _PolymorphicUnions,
- _PolymorphicJoins,
- _PolymorphicAliasedJoins,
-)
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import subqueryload_all
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
+from ._poly_fixtures import _Polymorphic
+from ._poly_fixtures import _PolymorphicAliasedJoins
+from ._poly_fixtures import _PolymorphicJoins
+from ._poly_fixtures import _PolymorphicPolymorphic
+from ._poly_fixtures import _PolymorphicUnions
+from ._poly_fixtures import Boss
+from ._poly_fixtures import Company
+from ._poly_fixtures import Engineer
+from ._poly_fixtures import Machine
+from ._poly_fixtures import Manager
+from ._poly_fixtures import Paperwork
+from ._poly_fixtures import Person
class _PolymorphicTestBase(object):
from datetime import datetime
-from sqlalchemy import *
-from sqlalchemy.orm import *
-from sqlalchemy import testing
+from sqlalchemy import DateTime
+from sqlalchemy import Float
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import LargeBinary
+from sqlalchemy import String
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import fixtures
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class InheritTest(fixtures.MappedTest):
-from sqlalchemy.orm import (
- create_session,
- relationship,
- mapper,
- contains_eager,
- joinedload,
- subqueryload,
- subqueryload_all,
- Session,
- aliased,
- with_polymorphic,
- joinedload_all,
- backref,
-)
-
-from sqlalchemy import Integer, String, ForeignKey, select, func
-from sqlalchemy.engine import default
-
-from sqlalchemy.testing import AssertsCompiledSQL, fixtures
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing import assert_raises, eq_, is_
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import contains_eager
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import subqueryload_all
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class Company(fixtures.ComparableEntity):
-from sqlalchemy import String, Integer, ForeignKey, select
-from sqlalchemy.orm import mapper, Session
-
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-
-from sqlalchemy.testing import fixtures, eq_
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class InheritingSelectablesTest(fixtures.MappedTest):
-from sqlalchemy.testing import eq_
-from sqlalchemy import *
-from sqlalchemy.orm import *
-
-from sqlalchemy import testing
-from test.orm import _fixtures
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import Bundle
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class SingleInheritanceTest(testing.AssertsCompiledSQL, fixtures.MappedTest):
pass
def test_of_type(self):
- JuniorEngineer, Company, companies, Manager, Employee, employees, Engineer = (
+ (
+ JuniorEngineer,
+ Company,
+ companies,
+ Manager,
+ Employee,
+ employees,
+ Engineer,
+ ) = (
self.classes.JuniorEngineer,
self.classes.Company,
self.tables.companies,
)
def test_relationship_to_subclass(self):
- JuniorEngineer, Company, companies, Manager, Employee, employees, Engineer = (
+ (
+ JuniorEngineer,
+ Company,
+ companies,
+ Manager,
+ Employee,
+ employees,
+ Engineer,
+ ) = (
self.classes.JuniorEngineer,
self.classes.Company,
self.tables.companies,
-from sqlalchemy import Integer, String, ForeignKey, func, desc, and_, or_
-from sqlalchemy.orm import (
- interfaces,
- relationship,
- mapper,
- clear_mappers,
- create_session,
- joinedload,
- joinedload_all,
- subqueryload,
- subqueryload_all,
- polymorphic_union,
- aliased,
- class_mapper,
- with_polymorphic,
-)
-from sqlalchemy import exc as sa_exc
-from sqlalchemy.engine import default
-
-from sqlalchemy.testing import AssertsCompiledSQL, fixtures
+from sqlalchemy import and_
+from sqlalchemy import or_
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing import assert_raises, eq_
-
-from ._poly_fixtures import (
- Company,
- Person,
- Engineer,
- Manager,
- Boss,
- Machine,
- Paperwork,
- _PolymorphicFixtureBase,
- _Polymorphic,
- _PolymorphicPolymorphic,
- _PolymorphicUnions,
- _PolymorphicJoins,
- _PolymorphicAliasedJoins,
-)
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import eq_
+from ._poly_fixtures import _Polymorphic
+from ._poly_fixtures import _PolymorphicAliasedJoins
+from ._poly_fixtures import _PolymorphicFixtureBase
+from ._poly_fixtures import _PolymorphicJoins
+from ._poly_fixtures import _PolymorphicPolymorphic
+from ._poly_fixtures import _PolymorphicUnions
+from ._poly_fixtures import Boss
+from ._poly_fixtures import Engineer
+from ._poly_fixtures import Manager
+from ._poly_fixtures import Person
class _WithPolymorphicBase(_PolymorphicFixtureBase):
-from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey, func, select
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, relationship, create_session
-from sqlalchemy.testing import fixtures
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class AssociationTest(fixtures.MappedTest):
import datetime
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey, table, text
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, relationship, backref, create_session
+from sqlalchemy import text
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class EagerTest(fixtures.MappedTest):
sa.and_(
tests.c.owner_id == 1,
sa.or_(
- options.c.someoption == None, # noqa
- options.c.someoption == False,
+ options.c.someoption == None,
+ options.c.someoption == False, # noqa
),
)
)
sa.and_(
tests.c.owner_id == 1,
sa.or_(
- options.c.someoption == None, # noqa
- options.c.someoption == False,
+ options.c.someoption == None,
+ options.c.someoption == False, # noqa
),
)
).outerjoin("owner_option")
self.comment = comment
def test_basic(self):
- Comment, Derived, derived, comments, DerivedII, Base, base, derivedII = (
+ (
+ Comment,
+ Derived,
+ derived,
+ comments,
+ DerivedII,
+ Base,
+ base,
+ derivedII,
+ ) = (
self.classes.Comment,
self.classes.Derived,
self.tables.derived,
pass
def test_one(self):
- Part, inherited_part, design_types, DesignType, parts, design, Design, InheritedPart = (
+ (
+ Part,
+ inherited_part,
+ design_types,
+ DesignType,
+ parts,
+ design,
+ Design,
+ InheritedPart,
+ ) = (
self.classes.Part,
self.tables.inherited_part,
self.tables.design_types,
import pickle
-from sqlalchemy.orm import attributes, instrumentation, exc as orm_exc
-from sqlalchemy.orm.collections import collection
-from sqlalchemy.orm.interfaces import AttributeExtension
-from sqlalchemy import exc as sa_exc
-from sqlalchemy.testing import (
- eq_,
- ne_,
- assert_raises,
- assert_raises_message,
- is_true,
- is_false,
- is_,
-)
-from sqlalchemy.testing import fixtures
-from sqlalchemy.testing.util import gc_collect, all_partial_orderings
-from sqlalchemy.util import jython
+
from sqlalchemy import event
+from sqlalchemy import exc as sa_exc
from sqlalchemy import testing
-from sqlalchemy.testing.mock import Mock, call
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import instrumentation
+from sqlalchemy.orm.collections import collection
+from sqlalchemy.orm.interfaces import AttributeExtension
from sqlalchemy.orm.state import InstanceState
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_false
+from sqlalchemy.testing import is_true
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.util import all_partial_orderings
+from sqlalchemy.testing.util import gc_collect
+
# global for pickling tests
MyTest = None
classes[2], "attrib", uselist=False, useobject=False
)
- def set(state, value, oldvalue, initiator):
+ def set_(state, value, oldvalue, initiator):
canary.append(value)
def events_a():
- event.listen(classes[0].attrib, "set", set, propagate=True)
+ event.listen(classes[0].attrib, "set", set_, propagate=True)
def teardown():
classes[:] = [None, None, None]
"""
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy import Integer, String, ForeignKey, Sequence, exc as sa_exc
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- class_mapper,
- backref,
- sessionmaker,
- Session,
-)
-from sqlalchemy.orm import attributes, exc as orm_exc
from sqlalchemy import testing
-from sqlalchemy.testing import eq_, is_
-from sqlalchemy.testing import fixtures
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import is_
from test.orm import _fixtures
-from sqlalchemy.testing import assert_raises_message
-from sqlalchemy import MetaData, Integer, ForeignKey
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import mapper, create_session
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures, eq_, engines, is_
-from sqlalchemy.orm import relationship, Session, backref, sessionmaker
-from test.orm import _fixtures
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from test.orm import _fixtures
class BindIntegrationTest(_fixtures.FixtureTest):
+from sqlalchemy import FetchedValue
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
from sqlalchemy.testing import eq_
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.testing import mock
from sqlalchemy.testing import fixtures
-from sqlalchemy import Integer, String, ForeignKey, FetchedValue
-from sqlalchemy.orm import mapper, Session
+from sqlalchemy.testing import mock
from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
-from sqlalchemy.testing import fixtures, eq_
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import Bundle, Session
-from sqlalchemy.testing import AssertsCompiledSQL
-from sqlalchemy import Integer, select, ForeignKey, String, func
-from sqlalchemy.orm import mapper, relationship, aliased
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import Bundle
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.sql.elements import ClauseList
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class BundleTest(fixtures.MappedTest, AssertsCompiledSQL):
import copy
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- exc as sa_exc,
- util,
- select,
- func,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- sessionmaker,
- class_mapper,
- backref,
- Session,
- util as orm_util,
- configure_mappers,
-)
-from sqlalchemy.orm.attributes import instance_state
-from sqlalchemy.orm import attributes, exc as orm_exc, object_mapper
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy import util
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import object_mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import util as orm_util
+from sqlalchemy.orm.attributes import instance_state
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
@classmethod
def setup_mappers(cls):
- users, Dingaling, Order, User, dingalings, Address, orders, addresses = (
+ (
+ users,
+ Dingaling,
+ Order,
+ User,
+ dingalings,
+ Address,
+ orders,
+ addresses,
+ ) = (
cls.tables.users,
cls.classes.Dingaling,
cls.classes.Order,
A,
a,
properties={
- # if no backref here, delete-orphan failed until [ticket:427] was
- # fixed
+ # if no backref here, delete-orphan failed until #
+ # [ticket:427] was fixed
"bs": relationship(
B,
secondary=atob,
__mapper_args__ = {"polymorphic_identity": "java_language"}
def test_cascade_iterator_polymorphic(self):
- Company, Employee, Engineer, Language, JavaLanguage, MavenBuild = self.classes(
+ (
+ Company,
+ Employee,
+ Engineer,
+ Language,
+ JavaLanguage,
+ MavenBuild,
+ ) = self.classes(
"Company",
"Employee",
"Engineer",
eq_(set([rec[0] for rec in it]), set([maven_build, lang]))
def test_delete_orphan_round_trip(self):
- Company, Employee, Engineer, Language, JavaLanguage, MavenBuild = self.classes(
+ (
+ Company,
+ Employee,
+ Engineer,
+ Language,
+ JavaLanguage,
+ MavenBuild,
+ ) = self.classes(
"Company",
"Employee",
"Engineer",
-from sqlalchemy.testing import eq_, ne_
from operator import and_
+import sqlalchemy as sa
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import util
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import instrumentation
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
import sqlalchemy.orm.collections as collections
from sqlalchemy.orm.collections import collection
-
-import sqlalchemy as sa
-from sqlalchemy import Integer, String, ForeignKey, text
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy import util, exc as sa_exc
-from sqlalchemy.orm import (
- create_session,
- mapper,
- relationship,
- attributes,
- instrumentation,
-)
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy import testing
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class Canary(sa.orm.interfaces.AttributeExtension):
@classmethod
def dictable_entity(cls, a=None, b=None, c=None):
- id = cls._entity_id = cls._entity_id + 1
- return cls.Entity(a or str(id), b or "value %s" % id, c)
+ id_ = cls._entity_id = cls._entity_id + 1
+ return cls.Entity(a or str(id_), b or "value %s" % id, c)
def _test_adapter(self, typecallable, creator=None, to_set=None):
if creator is None:
-from sqlalchemy import *
+from sqlalchemy import Column
from sqlalchemy import exc as sa_exc
-from sqlalchemy.orm import *
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import Unicode
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import fixtures
-from sqlalchemy import testing
class CompileTest(fixtures.ORMTest):
-from sqlalchemy.testing import assert_raises, assert_raises_message
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey, select
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- CompositeProperty,
- aliased,
- persistence,
-)
-from sqlalchemy.orm import composite, Session, configure_mappers
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import composite
+from sqlalchemy.orm import CompositeProperty
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import persistence
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class PointTest(fixtures.MappedTest, testing.AssertsCompiledSQL):
graphs = cls.tables.graphs
class Version(cls.Comparable):
- def __init__(self, id, version):
- self.id = id
+ def __init__(self, id_, version):
+ self.id = id_
self.version = version
def __composite_values__(self):
T1/T2.
"""
-from sqlalchemy import testing
+from itertools import count
+
+from sqlalchemy import bindparam
from sqlalchemy import event
-from sqlalchemy.testing import mock
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- backref,
- create_session,
- sessionmaker,
- Session,
-)
-from sqlalchemy.testing import eq_, is_
-from sqlalchemy.testing.assertsql import RegexSQL, CompiledSQL, AllOf
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from itertools import count
-from sqlalchemy import select
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.assertsql import RegexSQL
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class SelfReferentialTest(fixtures.MappedTest):
)
-from sqlalchemy import bindparam
-
-
class PostUpdateOnUpdateTest(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
-from test.orm import _fixtures
+import sqlalchemy as sa
from sqlalchemy import testing
-from sqlalchemy.orm import mapper, relationship, create_session
from sqlalchemy import util
-import sqlalchemy as sa
-from sqlalchemy.testing import eq_, assert_raises_message
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from test.orm import _fixtures
class DefaultStrategyOptionsTest(_fixtures.FixtureTest):
self.assert_sql_count(testing.db, go, 0)
def _downgrade_fixture(self):
- users, Keyword, items, order_items, orders, Item, User, Address, keywords, item_keywords, Order, addresses = (
+ (
+ users,
+ Keyword,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ keywords,
+ item_keywords,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.items,
return create_session()
def _upgrade_fixture(self):
- users, Keyword, items, order_items, orders, Item, User, Address, keywords, item_keywords, Order, addresses = (
+ (
+ users,
+ Keyword,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ keywords,
+ item_keywords,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.items,
import sqlalchemy as sa
-from sqlalchemy import Integer, String, ForeignKey, event
-from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, relationship, create_session
-from sqlalchemy.testing import fixtures
+from sqlalchemy import event
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class TriggerDefaultsTest(fixtures.MappedTest):
import sqlalchemy as sa
-from sqlalchemy import testing, util
-from sqlalchemy.orm import (
- mapper,
- deferred,
- defer,
- undefer,
- Load,
- load_only,
- undefer_group,
- create_session,
- synonym,
- relationship,
- Session,
- joinedload,
- defaultload,
- aliased,
- contains_eager,
- with_polymorphic,
- query_expression,
- with_expression,
- subqueryload,
-)
-from sqlalchemy.testing import eq_, AssertsCompiledSQL, assert_raises_message
-from test.orm import _fixtures
-from sqlalchemy.testing.schema import Column
-from sqlalchemy import Integer, ForeignKey
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import testing
+from sqlalchemy import util
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import contains_eager
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defaultload
+from sqlalchemy.orm import defer
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import Load
+from sqlalchemy.orm import load_only
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import query_expression
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import synonym
+from sqlalchemy.orm import undefer
+from sqlalchemy.orm import undefer_group
+from sqlalchemy.orm import with_expression
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-
-
-from .inheritance._poly_fixtures import (
- Company,
- Person,
- Engineer,
- Manager,
- Boss,
- Machine,
- Paperwork,
- _Polymorphic,
-)
+from sqlalchemy.testing.schema import Column
+from test.orm import _fixtures
+from .inheritance._poly_fixtures import _Polymorphic
+from .inheritance._poly_fixtures import Boss
+from .inheritance._poly_fixtures import Company
+from .inheritance._poly_fixtures import Manager
+from .inheritance._poly_fixtures import Person
class DeferredTest(AssertsCompiledSQL, _fixtures.FixtureTest):
{"id_1": 7},
),
(
- "SELECT orders.user_id AS orders_user_id, orders.description "
+ "SELECT orders.user_id AS orders_user_id, "
+ "orders.description "
"AS orders_description, orders.isopen AS orders_isopen, "
- "orders.id AS orders_id, orders.address_id AS orders_address_id "
- "FROM orders WHERE :param_1 = orders.user_id ORDER BY orders.id",
+ "orders.id AS orders_id, orders.address_id "
+ "AS orders_address_id "
+ "FROM orders WHERE :param_1 = orders.user_id "
+ "ORDER BY orders.id",
{"param_1": 7},
),
],
{"id_1": 7},
),
(
- "SELECT orders.user_id AS orders_user_id, orders.description "
+ "SELECT orders.user_id AS orders_user_id, "
+ "orders.description "
"AS orders_description, orders.isopen AS orders_isopen, "
- "orders.id AS orders_id, orders.address_id AS orders_address_id, "
- "anon_1.users_id AS anon_1_users_id FROM (SELECT users.id AS "
+ "orders.id AS orders_id, "
+ "orders.address_id AS orders_address_id, "
+ "anon_1.users_id AS anon_1_users_id "
+ "FROM (SELECT users.id AS "
"users_id FROM users WHERE users.id = :id_1) AS anon_1 "
"JOIN orders ON anon_1.users_id = orders.user_id ORDER BY "
"anon_1.users_id, orders.id",
[
(
"SELECT users.id AS users_id, users.name AS users_name, "
- "orders_1.user_id AS orders_1_user_id, orders_1.description AS "
- "orders_1_description, orders_1.isopen AS orders_1_isopen, "
+ "orders_1.user_id AS orders_1_user_id, "
+ "orders_1.description AS orders_1_description, "
+ "orders_1.isopen AS orders_1_isopen, "
"orders_1.id AS orders_1_id, orders_1.address_id AS "
"orders_1_address_id FROM users "
"LEFT OUTER JOIN orders AS orders_1 ON users.id = "
"SELECT users.id AS users_id, users.name AS users_name, "
"orders_1.user_id AS orders_1_user_id, "
"lower(orders_1.description) AS lower_1, "
- "orders_1.isopen AS orders_1_isopen, orders_1.id AS orders_1_id, "
+ "orders_1.isopen AS orders_1_isopen, "
+ "orders_1.id AS orders_1_id, "
"orders_1.address_id AS orders_1_address_id, "
"orders_1.description AS orders_1_description FROM users "
"LEFT OUTER JOIN orders AS orders_1 ON users.id = "
"orders_1.id AS orders_1_id FROM users "
"LEFT OUTER JOIN addresses AS addresses_1 "
"ON users.id = addresses_1.user_id "
- "LEFT OUTER JOIN orders AS orders_1 ON users.id = orders_1.user_id",
+ "LEFT OUTER JOIN orders AS orders_1 "
+ "ON users.id = orders_1.user_id",
)
and in modern use illustrates trivial use cases that don't need
an additional test suite.
-
"""
-from sqlalchemy import Integer, String, ForeignKey, func, text
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import mapper, relationship, create_session, sessionmaker
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import text
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import sessionmaker
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class QueryAlternativesTest(fixtures.MappedTest):
- '''Collects modern idioms for Queries
+ r'''Collects modern idioms for Queries
The docstring for each test case serves as miniature documentation about
the deprecated use case, and the test body illustrates (and covers) the
cases remain useful to readers even after the deprecated method has been
removed from the modern codebase.
- Format:
+ Format::
- def test_deprecated_thing(self):
- """Query.methodname(old, arg, **signature)
+ def test_deprecated_thing(self):
+ """Query.methodname(old, arg, **signature)
- output = session.query(User).deprecatedmethod(inputs)
+ output = session.query(User).deprecatedmethod(inputs)
- """
+ """
- # 0.4+
- output = session.query(User).newway(inputs)
- assert output is correct
+ # 0.4+
+ output = session.query(User).newway(inputs)
+ assert output is correct
- # 0.5+
- output = session.query(User).evennewerway(inputs)
- assert output is correct
+ # 0.5+
+ output = session.query(User).evennewerway(inputs)
+ assert output is correct
'''
# 0.5.0
maxes = list(session.query(Address).values(func.max(Address.bounces)))
- max = maxes[0][0]
- assert max == 10
+ max_ = maxes[0][0]
+ assert max_ == 10
- max = session.query(func.max(Address.bounces)).one()[0]
- assert max == 10
+ max_ = session.query(func.max(Address.bounces)).one()[0]
+ assert max_ == 10
def test_apply_min(self):
"""Query.apply_min(col)
# 0.5.0
mins = list(session.query(Address).values(func.min(Address.bounces)))
- min = mins[0][0]
- assert min == 0
+ min_ = mins[0][0]
+ assert min_ == 0
- min = session.query(func.min(Address.bounces)).one()[0]
- assert min == 0
+ min_ = session.query(func.min(Address.bounces)).one()[0]
+ assert min_ == 0
def test_apply_avg(self):
"""Query.apply_avg(col)
assert avg == 11
def test_count_by(self):
- """Query.count_by(*args, **params)
+ r"""Query.count_by(\*args, \**params)
num = session.query(Address).count_by(purpose='Personal')
assert num == 3, num
def test_count_whereclause(self):
- """Query.count(whereclause=None, params=None, **kwargs)
+ r"""Query.count(whereclause=None, params=None, \**kwargs)
num = session.query(Address).count(address_table.c.bounces > 1)
assert num == 1, num
def test_execute(self):
- """Query.execute(clauseelement, params=None, *args, **kwargs)
+ r"""Query.execute(clauseelement, params=None, \*args, \**kwargs)
users = session.query(User).execute(users_table.select())
assert len(users) == 4
def test_get_by(self):
- """Query.get_by(*args, **params)
+ r"""Query.get_by(\*args, \**params)
user = session.query(User).get_by(name='ed')
assert user.name == "fred"
def test_instances_entities(self):
- """Query.instances(cursor, *mappers_or_columns, **kwargs)
+ r"""Query.instances(cursor, \*mappers_or_columns, \**kwargs)
sel = users_table.join(addresses_table).select(use_labels=True)
res = session.query(User).instances(sel.execute(), Address)
assert isinstance(cola, User) and isinstance(colb, Address)
def test_join_by(self):
- """Query.join_by(*args, **params)
+ r"""Query.join_by(\*args, \**params)
TODO
"""
assert user.id == 1
def test_select(self):
- """Query.select(arg=None, **kwargs)
+ r"""Query.select(arg=None, \**kwargs)
users = session.query(User).select(users_table.c.name != None)
assert len(users) == 4
def test_select_by(self):
- """Query.select_by(*args, **params)
+ r"""Query.select_by(\*args, \**params)
users = session.query(User).select_by(name='fred')
- # 0.3 magic join on *_by methods
+ # 0.3 magic join on \*_by methods
users = session.query(User).select_by(email_address='fred@the.fred')
"""
assert len(users) == 1
def test_selectfirst(self):
- """Query.selectfirst(arg=None, **kwargs)
+ r"""Query.selectfirst(arg=None, \**kwargs)
bounced = session.query(Address).selectfirst(
addresses_table.c.bounces > 0)
assert bounced.bounces > 0
def test_selectfirst_by(self):
- """Query.selectfirst_by(*args, **params)
+ r"""Query.selectfirst_by(\*args, \**params)
onebounce = session.query(Address).selectfirst_by(bounces=1)
assert onebounce_user.name == "jack"
def test_selectone(self):
- """Query.selectone(arg=None, **kwargs)
+ r"""Query.selectone(arg=None, \**kwargs)
ed = session.query(User).selectone(users_table.c.name == 'ed')
)
def test_select_statement(self):
- """Query.select_statement(statement, **params)
+ r"""Query.select_statement(statement, \**params)
users = session.query(User).select_statement(users_table.select())
assert len(users) == 4
def test_select_text(self):
- """Query.select_text(text, **params)
+ r"""Query.select_text(text, \**params)
users = session.query(User).select_text('SELECT * FROM users_table')
assert len(users) == 4
def test_select_whereclause(self):
- """Query.select_whereclause(whereclause=None, params=None, **kwargs)
+ r"""Query.select_whereclause(whereclause=None, params=None, \**kwargs)
users = session,query(User).select_whereclause(users.c.name=='ed')
-from sqlalchemy.orm import descriptor_props, aliased
+from sqlalchemy import Column
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import descriptor_props
from sqlalchemy.orm.interfaces import PropComparator
from sqlalchemy.orm.properties import ColumnProperty
from sqlalchemy.sql import column
-from sqlalchemy import Column, Integer, func, String
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.util import partial
-from sqlalchemy.testing import fixtures
from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.util import partial
class TestDescriptor(descriptor_props.DescriptorProperty):
-from sqlalchemy import testing, desc, select, func, exc, cast, Integer
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- Query,
- attributes,
- exc as orm_exc,
- Session,
- backref,
- configure_mappers,
-)
+from sqlalchemy import cast
+from sqlalchemy import desc
+from sqlalchemy import exc
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import testing
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Query
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.orm.dynamic import AppenderMixin
-from sqlalchemy.testing import (
- AssertsCompiledSQL,
- assert_raises_message,
- assert_raises,
- eq_,
- is_,
-)
-from test.orm import _fixtures
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import is_
from sqlalchemy.testing.assertsql import CompiledSQL
+from test.orm import _fixtures
class _DynamicFixture(object):
eq_(
testing.db.scalar(
select([func.count("*")]).where(
- addresses.c.user_id == None # noqa
- )
+ addresses.c.user_id == None
+ ) # noqa
),
6,
)
eq_(
testing.db.scalar(
select([func.count("*")]).where(
- addresses.c.user_id != None # noqa
- )
+ addresses.c.user_id != None
+ ) # noqa
),
0,
)
"""tests of joined-eager loaded attributes"""
-from sqlalchemy.testing import eq_, is_, is_not_, in_
+import datetime
+
import sqlalchemy as sa
+from sqlalchemy import and_
+from sqlalchemy import Date
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.orm import (
- joinedload,
- deferred,
- undefer,
- joinedload_all,
- backref,
- Session,
- defaultload,
- Load,
- load_only,
- contains_eager,
-)
-from sqlalchemy import (
- Integer,
- String,
- Date,
- ForeignKey,
- and_,
- select,
- func,
- text,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- lazyload,
- aliased,
- column_property,
-)
+from sqlalchemy import text
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import contains_eager
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defaultload
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import Load
+from sqlalchemy.orm import load_only
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import undefer
from sqlalchemy.sql import operators
-from sqlalchemy.testing import assert_raises, assert_raises_message
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
from sqlalchemy.testing.assertsql import CompiledSQL
-from sqlalchemy.testing import fixtures, expect_warnings
-from test.orm import _fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.util import OrderedDict as odict
-import datetime
+from test.orm import _fixtures
class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
self.assert_sql_count(testing.db, go, 1)
def test_options_pathing(self):
- users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords = (
+ (
+ users,
+ Keyword,
+ orders,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.orders,
"""Eager loading with two relationships simultaneously,
from the same table, using aliases."""
- addresses, items, order_items, orders, Item, User, Address, Order, users = (
+ (
+ addresses,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ users,
+ ) = (
self.tables.addresses,
self.tables.items,
self.tables.order_items,
def test_limit(self):
"""Limit operations combined with lazy-load relationships."""
- users, items, order_items, orders, Item, User, Address, Order, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
'wrapped' select statement resulting from the combination of
eager loading and limit/offset clauses."""
- addresses, items, order_items, orders, Item, User, Address, Order, users = (
+ (
+ addresses,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ users,
+ ) = (
self.tables.addresses,
self.tables.items,
self.tables.order_items,
"""test that the subquery wrapping only occurs with
limit/offset and m2m or o2m joins present."""
- users, items, order_items, Order, Item, User, Address, orders, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ Address,
+ orders,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
)
def test_wide(self):
- users, items, order_items, Order, Item, User, Address, orders, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ Address,
+ orders,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
# test eager join chaining to the "nested" join on the left,
# a new feature as of [ticket:2369]
- users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords = (
+ (
+ users,
+ Keyword,
+ orders,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.orders,
User,
users,
properties={
- "orders": relationship(Order, backref="user") # o2m, m2o
- },
+ "orders": relationship(Order, backref="user")
+ }, # o2m, m2o
)
mapper(
Order,
]
def test_mapper_configured(self):
- users, items, order_items, Order, Item, User, Address, orders, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ Address,
+ orders,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
self.assert_sql_count(testing.db, go, 1)
def test_options(self):
- users, items, order_items, Order, Item, User, Address, orders, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ Address,
+ orders,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
@classmethod
def setup_mappers(cls):
- users, Keyword, items, order_items, orders, Item, User, Address, keywords, Order, item_keywords, addresses = (
+ (
+ users,
+ Keyword,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ keywords,
+ Order,
+ item_keywords,
+ addresses,
+ ) = (
cls.tables.users,
cls.classes.Keyword,
cls.tables.items,
"""Evaluating SQL expressions on ORM objects"""
-from sqlalchemy import String, Integer, bindparam
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.testing import fixtures
-
-from sqlalchemy import and_, or_, not_
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import not_
+from sqlalchemy import or_
+from sqlalchemy import String
from sqlalchemy.orm import evaluator
from sqlalchemy.orm import mapper
-
-from sqlalchemy.orm import relationship, Session
-from sqlalchemy import ForeignKey
-from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.testing import assert_raises_message
-from sqlalchemy.testing import is_
-from sqlalchemy import inspect
from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+
compiler = evaluator.EvaluatorCompiler()
-from sqlalchemy.testing import assert_raises_message, assert_raises
import sqlalchemy as sa
+from sqlalchemy import event
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String
from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- class_mapper,
- Mapper,
- column_property,
- query,
- Session,
- sessionmaker,
- attributes,
- configure_mappers,
-)
-from sqlalchemy.orm.instrumentation import ClassManager
-from sqlalchemy.orm import instrumentation, events
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import events
from sqlalchemy.orm import EXT_SKIP
+from sqlalchemy.orm import instrumentation
+from sqlalchemy.orm import Mapper
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import query
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.mapper import _mapper_registry
-from sqlalchemy.testing import eq_, is_not_, assert_raises
-from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing.mock import ANY
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
from test.orm import _fixtures
-from sqlalchemy import event
-from sqlalchemy.testing.mock import Mock, call, ANY
class _RemoveListeners(object):
m = mapper(
User,
users,
- properties={"addresses": relationship(lambda: ImNotAClass)},
+ properties={
+ # intentionally non-existent class to ensure
+ # the lambda is not called, simulates a class from
+ # a not-yet-imported module
+ "addresses": relationship(lambda: ImNotAClass) # noqa
+ },
)
event.listen(User, "before_insert", lambda *a, **kw: None)
assert not m.configured
"""Attribute/instance expiration, deferral of attributes, etc."""
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
-from sqlalchemy.testing.util import gc_collect
import sqlalchemy as sa
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import FetchedValue
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey, exc as sa_exc, FetchedValue
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- attributes,
- deferred,
- exc as orm_exc,
- defer,
- undefer,
- strategies,
- state,
- lazyload,
- backref,
- Session,
-)
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defer
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import make_transient_to_detached
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import strategies
+from sqlalchemy.orm import undefer
+from sqlalchemy.sql import select
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import gc_collect
from test.orm import _fixtures
-from sqlalchemy.sql import select
-from sqlalchemy.orm import make_transient_to_detached
class ExpireTest(_fixtures.FixtureTest):
sess.add(e1)
assert e1.name == "engineer1"
- def test_no_instance_key(self):
+ def test_no_instance_key_pk_absent(self):
Engineer = self.classes.Engineer
# same as test_no_instance_key, but the PK columns
+import sqlalchemy as sa
+from sqlalchemy import and_
+from sqlalchemy import asc
+from sqlalchemy import cast
+from sqlalchemy import desc
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import literal_column
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.testing import (
- fixtures,
- eq_,
- is_,
- assert_raises,
- assert_raises_message,
- AssertsCompiledSQL,
-)
-from sqlalchemy import (
- exc as sa_exc,
- util,
- Integer,
- Table,
- String,
- ForeignKey,
- select,
- func,
- and_,
- asc,
- desc,
- inspect,
- literal_column,
- cast,
- exists,
- text,
-)
-from sqlalchemy.orm import (
- configure_mappers,
- Session,
- mapper,
- create_session,
- relationship,
- column_property,
- joinedload_all,
- contains_eager,
- contains_alias,
- joinedload,
- clear_mappers,
- backref,
- relation,
- aliased,
-)
-from sqlalchemy.sql import table, column
+from sqlalchemy import text
+from sqlalchemy import util
from sqlalchemy.engine import default
-import sqlalchemy as sa
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import contains_alias
+from sqlalchemy.orm import contains_eager
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relation
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm.util import join
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing.schema import Column
-
from test.orm import _fixtures
-from sqlalchemy.orm.util import join
-
class QueryTest(_fixtures.FixtureTest):
run_setup_mappers = "once"
@classmethod
def setup_mappers(cls):
- Node, composite_pk_table, users, Keyword, items, Dingaling, order_items, item_keywords, Item, User, dingalings, Address, keywords, CompositePk, nodes, Order, orders, addresses = (
+ (
+ Node,
+ composite_pk_table,
+ users,
+ Keyword,
+ items,
+ Dingaling,
+ order_items,
+ item_keywords,
+ Item,
+ User,
+ dingalings,
+ Address,
+ keywords,
+ CompositePk,
+ nodes,
+ Order,
+ orders,
+ addresses,
+ ) = (
cls.classes.Node,
cls.tables.composite_pk_table,
cls.tables.users,
-from sqlalchemy.testing import eq_
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey, MetaData, func
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import mapper, relationship, create_session
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
assert query.order_by(Foo.bar)[0].bar == 0
assert query.order_by(sa.desc(Foo.bar))[0].bar == 99
- def test_offset(self):
+ def test_offset_order_by(self):
Foo = self.classes.Foo
query = create_session().query(Foo)
"""test the current state of the hasparent() flag."""
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy import Integer, String, ForeignKey, Sequence, exc as sa_exc
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- sessionmaker,
- class_mapper,
- backref,
- Session,
-)
-from sqlalchemy.orm import attributes, exc as orm_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
from sqlalchemy import testing
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
"""basic tests of lazy loaded attributes"""
-from sqlalchemy import testing
-from sqlalchemy.orm import mapper, relationship, create_session, immediateload
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import immediateload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import eq_
from test.orm import _fixtures
"""test the inspection registry system."""
-from sqlalchemy.testing import eq_, assert_raises_message, is_
-from sqlalchemy import exc, util
-from sqlalchemy import inspect
-from test.orm import _fixtures
-from sqlalchemy.orm import (
- class_mapper,
- synonym,
- Session,
- aliased,
- relationship,
-)
+from sqlalchemy import exc
from sqlalchemy import ForeignKey
-from sqlalchemy.orm.attributes import instance_state, NO_VALUE
+from sqlalchemy import inspect
from sqlalchemy import testing
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import synonym
+from sqlalchemy.orm.attributes import instance_state
+from sqlalchemy.orm.attributes import NO_VALUE
from sqlalchemy.orm.util import identity_key
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import is_
+from test.orm import _fixtures
class TestORMInspection(_fixtures.FixtureTest):
-from sqlalchemy.testing import assert_raises, assert_raises_message
import sqlalchemy as sa
-from sqlalchemy import MetaData, Integer, ForeignKey, util, event
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- attributes,
- class_mapper,
- clear_mappers,
- instrumentation,
- events,
-)
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.testing import eq_, ne_
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import util
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import instrumentation
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy import testing
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class InitTest(fixtures.ORMTest):
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
-import operator
-from sqlalchemy import *
-from sqlalchemy import exc as sa_exc, util
-from sqlalchemy.sql import compiler, table, column
+import sqlalchemy as sa
+from sqlalchemy import and_
+from sqlalchemy import desc
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import lateral
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import not_
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import true
from sqlalchemy.engine import default
-from sqlalchemy.orm import *
-from sqlalchemy.orm import attributes
-
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import join
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import outerjoin
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import synonym
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
-
-import sqlalchemy as sa
-from sqlalchemy import testing
-from sqlalchemy.testing import AssertsCompiledSQL, engines
+from sqlalchemy.testing import fixtures
from sqlalchemy.testing.schema import Column
from test.orm import _fixtures
-from sqlalchemy.testing import fixtures
-
-from sqlalchemy.orm.util import join, outerjoin, with_parent
-
class QueryTest(_fixtures.FixtureTest):
run_setup_mappers = "once"
@classmethod
def setup_mappers(cls):
- Node, composite_pk_table, users, Keyword, items, Dingaling, order_items, item_keywords, Item, User, dingalings, Address, keywords, CompositePk, nodes, Order, orders, addresses = (
+ (
+ Node,
+ composite_pk_table,
+ users,
+ Keyword,
+ items,
+ Dingaling,
+ order_items,
+ item_keywords,
+ Item,
+ User,
+ dingalings,
+ Address,
+ keywords,
+ CompositePk,
+ nodes,
+ Order,
+ orders,
+ addresses,
+ ) = (
cls.classes.Node,
cls.tables.composite_pk_table,
cls.tables.users,
self.assert_compile(
sess.query(User).join(oalias1.user),
"SELECT users.id AS users_id, users.name AS users_name "
- "FROM orders AS orders_1 JOIN users ON users.id = orders_1.user_id",
+ "FROM orders AS orders_1 JOIN users "
+ "ON users.id = orders_1.user_id",
)
def test_single_prop_4(self):
def test_overlapping_paths(self):
User = self.classes.User
- for aliased in (True, False):
+ for aliased_ in (True, False):
# load a user who has an order that contains item id 3 and address
# id 1 (order 3, owned by jack)
result = (
create_session()
.query(User)
- .join("orders", "items", aliased=aliased)
+ .join("orders", "items", aliased=aliased_)
.filter_by(id=3)
- .join("orders", "address", aliased=aliased)
+ .join("orders", "address", aliased=aliased_)
.filter_by(id=1)
.all()
)
"SELECT users.id AS users_id, users.name AS users_name, "
"users_1.id AS users_1_id, users_1.name AS users_1_name "
"FROM users, "
- "users AS users_1 JOIN addresses ON users_1.id = addresses.user_id",
+ "users AS users_1 JOIN addresses "
+ "ON users_1.id = addresses.user_id",
)
def test_join_explicit_left_multiple_adapted(self):
"SELECT users_1.id AS users_1_id, users_1.name AS users_1_name, "
"users_2.id AS users_2_id, users_2.name AS users_2_name "
"FROM users AS users_1, "
- "users AS users_2 JOIN addresses ON users_2.id = addresses.user_id",
+ "users AS users_2 JOIN addresses "
+ "ON users_2.id = addresses.user_id",
)
def test_join_entity_from_multiple_from_clause(self):
def test_reset_joinpoint(self):
User = self.classes.User
- for aliased in (True, False):
+ for aliased_ in (True, False):
# load a user who has an order that contains item id 3 and address
# id 1 (order 3, owned by jack)
result = (
create_session()
.query(User)
- .join("orders", "items", aliased=aliased)
+ .join("orders", "items", aliased=aliased_)
.filter_by(id=3)
.reset_joinpoint()
- .join("orders", "address", aliased=aliased)
+ .join("orders", "address", aliased=aliased_)
.filter_by(id=1)
.all()
)
result = (
create_session()
.query(User)
- .join("orders", "items", aliased=aliased, isouter=True)
+ .join("orders", "items", aliased=aliased_, isouter=True)
.filter_by(id=3)
.reset_joinpoint()
- .join("orders", "address", aliased=aliased, isouter=True)
+ .join("orders", "address", aliased=aliased_, isouter=True)
.filter_by(id=1)
.all()
)
result = (
create_session()
.query(User)
- .outerjoin("orders", "items", aliased=aliased)
+ .outerjoin("orders", "items", aliased=aliased_)
.filter_by(id=3)
.reset_joinpoint()
- .outerjoin("orders", "address", aliased=aliased)
+ .outerjoin("orders", "address", aliased=aliased_)
.filter_by(id=1)
.all()
)
"""basic tests of lazy loaded attributes"""
-from sqlalchemy.testing import assert_raises
import datetime
-from sqlalchemy.orm import attributes, exc as orm_exc, configure_mappers
+
import sqlalchemy as sa
-from sqlalchemy.orm.interfaces import MapperOption
-from sqlalchemy import testing, and_, bindparam
-from sqlalchemy import Integer, String, ForeignKey, SmallInteger, Boolean
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import Boolean
+from sqlalchemy import ForeignKey
from sqlalchemy import ForeignKeyConstraint
-from sqlalchemy.types import TypeDecorator
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
+from sqlalchemy import Integer
from sqlalchemy import orm
-from sqlalchemy.orm import mapper, relationship, create_session, Session
-from sqlalchemy.testing import eq_, is_true, is_false
+from sqlalchemy import SmallInteger
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm.interfaces import MapperOption
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
-from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing import is_false
+from sqlalchemy.testing import is_true
from sqlalchemy.testing import mock
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.types import TypeDecorator
+from test.orm import _fixtures
class LazyTest(_fixtures.FixtureTest):
def test_limit(self):
"""test limit operations combined with lazy-load relationships."""
- users, items, order_items, orders, Item, User, Address, Order, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
assert self.static.user_all_result[1:3] == result
def test_distinct(self):
- users, items, order_items, orders, Item, User, Address, Order, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
-from sqlalchemy import *
-from sqlalchemy.orm import *
-
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.testing import eq_, AssertsExecutionResults, assert_raises
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.orm.attributes import instance_state
-from sqlalchemy.orm.exc import FlushError
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+
engine = testing.db
# pendings don't autoflush
assert c3.parent is None
- def test_autoflush_on_pending(self):
+ def test_autoflush_load_on_pending_on_pending(self):
Child.parent.property.load_on_pending = True
c3 = Child()
sess.add(c3)
-from . import _fixtures
-from sqlalchemy.orm import loading, Session, aliased
-from sqlalchemy.testing.assertions import (
- eq_,
- assert_raises,
- assert_raises_message,
-)
-from sqlalchemy.util import KeyedTuple
-from sqlalchemy.testing import mock
-from sqlalchemy import select
from sqlalchemy import exc
+from sqlalchemy import select
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import loading
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import assert_raises_message
+from sqlalchemy.testing.assertions import eq_
+from sqlalchemy.util import KeyedTuple
+from . import _fixtures
+
# class GetFromIdentityTest(_fixtures.FixtureTest):
# class LoadOnIdentTest(_fixtures.FixtureTest):
+from sqlalchemy import exc
+from sqlalchemy import testing
from sqlalchemy.engine import default
-from sqlalchemy.databases import *
-from sqlalchemy.orm import mapper
-from sqlalchemy.orm import Session
from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
-from sqlalchemy.testing import AssertsCompiledSQL, eq_
+from sqlalchemy.orm import Session
from sqlalchemy.testing import assert_raises_message
-from sqlalchemy import exc
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from test.orm import _fixtures
-from sqlalchemy import testing
class LegacyLockModeTest(_fixtures.FixtureTest):
-from sqlalchemy.testing import assert_raises, assert_raises_message, eq_
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- Session,
- exc as orm_exc,
- sessionmaker,
- backref,
-)
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class M2MTest(fixtures.MappedTest):
"""test that a mapper can have two eager relationships to the same table, via
two different association tables. aliases are required."""
- place_input, transition, Transition, PlaceThingy, place, place_thingy, Place, place_output = (
+ (
+ place_input,
+ transition,
+ Transition,
+ PlaceThingy,
+ place,
+ place_thingy,
+ Place,
+ place_output,
+ ) = (
self.tables.place_input,
self.tables.transition,
self.classes.Transition,
"""General mapper operations with an emphasis on selecting/loading."""
-from sqlalchemy.testing import assert_raises, assert_raises_message
+import logging
+import logging.handlers
+
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import (
- MetaData,
- Integer,
- String,
- ForeignKey,
- func,
- util,
- select,
-)
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import util
from sqlalchemy.engine import default
-from sqlalchemy.orm import (
- mapper,
- relationship,
- backref,
- create_session,
- class_mapper,
- configure_mappers,
- reconstructor,
- aliased,
- deferred,
- synonym,
- attributes,
- column_property,
- composite,
- dynamic_loader,
- comparable_property,
- Session,
-)
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import comparable_property
+from sqlalchemy.orm import composite
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import dynamic_loader
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import reconstructor
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import synonym
from sqlalchemy.orm.persistence import _sort_states
-from sqlalchemy.testing import eq_, AssertsCompiledSQL, is_
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing.assertsql import CompiledSQL
-import logging
-import logging.handlers
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from test.orm import _fixtures
class MapperTest(_fixtures.FixtureTest, AssertsCompiledSQL):
"""
class Foo(object):
- def __init__(self, id):
- self.id = id
+ def __init__(self, id_):
+ self.id = id_
m = MetaData()
foo_t = Table("foo", m, Column("id", String, primary_key=True))
if util.py2k:
def __lt__(self, other):
- assert not isinstance(other, basestring)
+ assert not isinstance(other, basestring) # noqa
return int(self) < other
- foos = [Foo(id="f%d" % i) for i in range(5)]
+ foos = [Foo(id_="f%d" % i) for i in range(5)]
states = [attributes.instance_state(f) for f in foos]
for s in states[0:3]:
self.sql_count_(4, go)
def test_eager_degrade_deep(self):
- users, Keyword, items, order_items, orders, Item, User, Address, keywords, item_keywords, Order, addresses = (
+ (
+ users,
+ Keyword,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ keywords,
+ item_keywords,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.items,
class DeepOptionsTest(_fixtures.FixtureTest):
@classmethod
def setup_mappers(cls):
- users, Keyword, items, order_items, Order, Item, User, keywords, item_keywords, orders = (
+ (
+ users,
+ Keyword,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ orders,
+ ) = (
cls.tables.users,
cls.classes.Keyword,
cls.tables.items,
session = create_session()
human = (
- session.query(Human)
- .options(sa.orm.joinedload("thing")) # noqa
- .first()
- )
+ session.query(Human).options(sa.orm.joinedload("thing")).first()
+ ) # noqa
session.expunge_all()
thing = session.query(Thing).options(sa.orm.undefer("name")).first()
self._test(thing)
session = create_session()
human = (
- session.query(Human)
- .options(sa.orm.joinedload("thing")) # noqa
- .first()
- )
+ session.query(Human).options(sa.orm.joinedload("thing")).first()
+ ) # noqa
thing = session.query(Thing).options(sa.orm.undefer("name")).first()
self._test(thing)
session = create_session()
result = (
- session.query(Human)
- .add_entity(Thing) # noqa
- .join("thing")
- .first()
- )
+ session.query(Human).add_entity(Thing).join("thing").first()
+ ) # noqa
session.expunge_all()
thing = session.query(Thing).options(sa.orm.undefer("name")).first()
self._test(thing)
session = create_session()
result = (
- session.query(Human)
- .add_entity(Thing) # noqa
- .join("thing")
- .first()
- )
+ session.query(Human).add_entity(Thing).join("thing").first()
+ ) # noqa
thing = session.query(Thing).options(sa.orm.undefer("name")).first()
self._test(thing)
# sa.exc.ArgumentError, mapper, NoWeakrefSupport, t2)
class _ValueBase(object):
- def __init__(self, value="abc", id=None):
- self.id = id
+ def __init__(self, value="abc", id_=None):
+ self.id = id_
self.value = value
def __bool__(self):
ht2, ht1 = (self.tables.ht2, self.tables.ht1)
class H1(self._ValueBase):
- def __init__(self, value, id, h2s):
+ def __init__(self, value, id_, h2s):
self.value = value
- self.id = id
+ self.id = id_
self.h2s = h2s
class H2(self._ValueBase):
- def __init__(self, value, id):
+ def __init__(self, value, id_):
self.value = value
- self.id = id
+ self.id = id_
mapper(H1, ht1, properties={"h2s": relationship(H2, backref="h1")})
mapper(H2, ht2)
H1(
"abc",
1,
- h2s=[H2("abc", id=1), H2("def", id=2), H2("def", id=3)],
+ h2s=[H2("abc", id_=1), H2("def", id_=2), H2("def", id_=3)],
),
H1(
"def",
2,
- h2s=[H2("abc", id=4), H2("abc", id=5), H2("def", id=6)],
+ h2s=[H2("abc", id_=4), H2("abc", id_=5), H2("def", id_=6)],
),
]
)
-from sqlalchemy.testing import assert_raises_message
-import sqlalchemy as sa
-from sqlalchemy import Integer, PickleType, String, ForeignKey, Text
import operator
+
+import sqlalchemy as sa
+from sqlalchemy import and_
+from sqlalchemy import case
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import PickleType
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.util import OrderedSet
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- PropComparator,
- synonym,
- comparable_property,
- sessionmaker,
- attributes,
- Session,
- backref,
- configure_mappers,
- foreign,
- deferred,
- defer,
-)
+from sqlalchemy import Text
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import comparable_property
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defer
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import foreign
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import PropComparator
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import synonym
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.orm.interfaces import MapperOption
-from sqlalchemy.testing import eq_, in_, not_in_
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import not_in_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import OrderedSet
from test.orm import _fixtures
-from sqlalchemy import event, and_, case
-from sqlalchemy.testing.schema import Table, Column
class MergeTest(_fixtures.FixtureTest):
"""
-from sqlalchemy.testing import (
- fixtures,
- eq_,
- ne_,
- assert_raises,
- assert_raises_message,
-)
import sqlalchemy as sa
-from sqlalchemy import testing, Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, relationship, create_session, Session
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
from sqlalchemy.orm.session import make_transient
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
-from sqlalchemy.orm import (
- Session,
- aliased,
- with_polymorphic,
- contains_eager,
- joinedload,
- subqueryload,
- relationship,
- subqueryload_all,
- joinedload_all,
-)
from sqlalchemy import and_
-from sqlalchemy import testing, exc as sa_exc
-from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import assert_raises, assert_raises_message, eq_
-from sqlalchemy.testing.schema import Column
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import testing
from sqlalchemy.engine import default
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import contains_eager
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import subqueryload_all
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import CompiledSQL
from sqlalchemy.testing.entities import ComparableEntity
-from sqlalchemy import Integer, String, ForeignKey
-from .inheritance._poly_fixtures import (
- Company,
- Person,
- Engineer,
- Manager,
- Boss,
- Machine,
- Paperwork,
- _PolymorphicFixtureBase,
- _Polymorphic,
- _PolymorphicPolymorphic,
- _PolymorphicUnions,
- _PolymorphicJoins,
- _PolymorphicAliasedJoins,
-)
-from sqlalchemy.testing.assertsql import AllOf, CompiledSQL
+from sqlalchemy.testing.schema import Column
+from .inheritance._poly_fixtures import _PolymorphicAliasedJoins
+from .inheritance._poly_fixtures import _PolymorphicJoins
+from .inheritance._poly_fixtures import _PolymorphicPolymorphic
+from .inheritance._poly_fixtures import _PolymorphicUnions
+from .inheritance._poly_fixtures import Boss
+from .inheritance._poly_fixtures import Company
+from .inheritance._poly_fixtures import Engineer
+from .inheritance._poly_fixtures import Machine
+from .inheritance._poly_fixtures import Manager
+from .inheritance._poly_fixtures import Person
class _PolymorphicTestBase(object):
-import sqlalchemy as sa
-from sqlalchemy import testing
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, relationship, create_session
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class O2OTest(fixtures.MappedTest):
-from sqlalchemy import inspect
-from sqlalchemy.orm import (
- attributes,
- mapper,
- relationship,
- backref,
- configure_mappers,
- create_session,
- synonym,
- Session,
- class_mapper,
- aliased,
- column_property,
- joinedload_all,
- joinedload,
- Query,
- util as orm_util,
- Load,
- defer,
- defaultload,
- lazyload,
-)
-from sqlalchemy.orm.query import QueryContext
-from sqlalchemy.orm import strategy_options
import sqlalchemy as sa
+from sqlalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.assertions import eq_, assert_raises_message
-from test.orm import _fixtures
-from sqlalchemy import Column, Integer, String, ForeignKey
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defaultload
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import Load
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import strategy_options
from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import util as orm_util
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import assert_raises_message
+from sqlalchemy.testing.assertions import eq_
+from test.orm import _fixtures
class QueryTest(_fixtures.FixtureTest):
-from sqlalchemy.testing import eq_
-from sqlalchemy.util import pickle
-import sqlalchemy as sa
import copy
+
+import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.util import picklers
-from sqlalchemy.testing import assert_raises_message
-from sqlalchemy import Integer, String, ForeignKey, exc, MetaData
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- sessionmaker,
- attributes,
- interfaces,
- clear_mappers,
- exc as orm_exc,
- configure_mappers,
- Session,
- lazyload_all,
- lazyload,
- aliased,
- subqueryload,
-)
-from sqlalchemy.orm import state as sa_state
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
from sqlalchemy.orm import instrumentation
-from sqlalchemy.orm.collections import (
- attribute_mapped_collection,
- column_mapped_collection,
-)
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import state as sa_state
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.orm.collections import attribute_mapped_collection
+from sqlalchemy.orm.collections import column_mapped_collection
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.pickleable import Address
+from sqlalchemy.testing.pickleable import Child1
+from sqlalchemy.testing.pickleable import Child2
+from sqlalchemy.testing.pickleable import Dingaling
+from sqlalchemy.testing.pickleable import EmailUser
+from sqlalchemy.testing.pickleable import Order
+from sqlalchemy.testing.pickleable import Parent
+from sqlalchemy.testing.pickleable import Screen
+from sqlalchemy.testing.pickleable import User
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import picklers
+from sqlalchemy.util import pickle
from test.orm import _fixtures
-from sqlalchemy.testing.pickleable import (
- User,
- Address,
- Dingaling,
- Order,
- Child1,
- Child2,
- Parent,
- Screen,
- EmailUser,
-)
-
-from sqlalchemy.orm import with_polymorphic
-
-from .inheritance._poly_fixtures import (
- Company,
- Person,
- Engineer,
- Manager,
- Boss,
- Machine,
- Paperwork,
- _Polymorphic,
-)
+from .inheritance._poly_fixtures import _Polymorphic
+from .inheritance._poly_fixtures import Company
+from .inheritance._poly_fixtures import Engineer
+from .inheritance._poly_fixtures import Manager
+from .inheritance._poly_fixtures import Person
class PickleTest(fixtures.MappedTest):
)
mapper(Address, addresses)
mapper(
- Order, orders, properties={"address": relationship(Address)} # m2o
- )
+ Order, orders, properties={"address": relationship(Address)}
+ ) # m2o
def test_tuple_labeling(self):
users = self.tables.users
-from sqlalchemy import (
- testing,
- null,
- exists,
- text,
- union,
- literal,
- literal_column,
- func,
- between,
- Unicode,
- desc,
- and_,
- bindparam,
- select,
- distinct,
- or_,
- collate,
- insert,
- Integer,
- String,
- Boolean,
- exc as sa_exc,
- util,
- cast,
- MetaData,
- ForeignKey,
-)
-from sqlalchemy.sql import operators, expression
-from sqlalchemy import column, table
+import contextlib
+
+import sqlalchemy as sa
+from sqlalchemy import and_
+from sqlalchemy import between
+from sqlalchemy import bindparam
+from sqlalchemy import Boolean
+from sqlalchemy import cast
+from sqlalchemy import collate
+from sqlalchemy import column
+from sqlalchemy import desc
+from sqlalchemy import distinct
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import insert
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import null
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import Unicode
+from sqlalchemy import union
+from sqlalchemy import util
from sqlalchemy.engine import default
-from sqlalchemy.orm import (
- attributes,
- mapper,
- relationship,
- create_session,
- synonym,
- Session,
- aliased,
- column_property,
- joinedload_all,
- joinedload,
- Query,
- Bundle,
- subqueryload,
- backref,
- lazyload,
- defer,
-)
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import Bundle
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defer
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import joinedload_all
+from sqlalchemy.orm import lazyload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Query
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import synonym
+from sqlalchemy.orm.util import join
+from sqlalchemy.orm.util import with_parent
+from sqlalchemy.sql import expression
+from sqlalchemy.sql import operators
+from sqlalchemy.testing import assert_warnings
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing import mock
+from sqlalchemy.testing.assertions import assert_raises
+from sqlalchemy.testing.assertions import assert_raises_message
+from sqlalchemy.testing.assertions import eq_
+from sqlalchemy.testing.assertions import eq_ignore_whitespace
+from sqlalchemy.testing.assertions import expect_warnings
from sqlalchemy.testing.assertsql import CompiledSQL
-from sqlalchemy.testing.schema import Table, Column
-import sqlalchemy as sa
-from sqlalchemy.testing.assertions import (
- eq_,
- assert_raises,
- assert_raises_message,
- expect_warnings,
- eq_ignore_whitespace,
-)
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL, assert_warnings
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
-from sqlalchemy.orm.util import join, with_parent
-import contextlib
-from sqlalchemy.testing import mock, is_, is_not_
-from sqlalchemy import inspect
class QueryTest(_fixtures.FixtureTest):
q = session.query(User.id).filter(User.id == 7).label("foo")
self.assert_compile(
session.query(q),
- "SELECT (SELECT users.id FROM users WHERE users.id = :id_1) AS foo",
+ "SELECT (SELECT users.id FROM users "
+ "WHERE users.id = :id_1) AS foo",
)
def test_as_scalar(self):
"SELECT (SELECT max(addresses.email_address) AS max_1 FROM "
"addresses WHERE addresses.user_id = users_1.id) AS anon_1, "
"users_1.id AS users_1_id, users_1.name AS users_1_name, "
- "users.id AS users_id FROM users AS users_1, users ORDER BY anon_1",
+ "users.id AS users_id FROM users AS users_1, "
+ "users ORDER BY anon_1",
)
def test_order_by_column_unlabeled_prop_attr_aliased_one(self):
@classmethod
def setup_mappers(cls):
- users, Keyword, items, order_items, orders, Item, User, Address, keywords, Order, item_keywords, addresses = (
+ (
+ users,
+ Keyword,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ keywords,
+ Order,
+ item_keywords,
+ addresses,
+ ) = (
cls.tables.users,
cls.classes.Keyword,
cls.tables.items,
self.assert_compile(
q,
"SELECT users_1.name AS users_1_name FROM "
- "users AS users_1 JOIN addresses ON users_1.id = addresses.user_id",
+ "users AS users_1 JOIN addresses "
+ "ON users_1.id = addresses.user_id",
)
-from sqlalchemy.testing import (
- assert_raises_message,
- eq_,
- AssertsCompiledSQL,
- is_,
-)
+from sqlalchemy import and_
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy.orm import foreign
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import relationships
+from sqlalchemy.orm import remote
+from sqlalchemy.orm.interfaces import MANYTOONE
+from sqlalchemy.orm.interfaces import ONETOMANY
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy.orm import relationships, foreign, remote, relationship
-from sqlalchemy import (
- MetaData,
- Table,
- Column,
- ForeignKey,
- Integer,
- select,
- ForeignKeyConstraint,
- exc,
- func,
- and_,
- String,
- Boolean,
-)
-from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOONE, MANYTOMANY
+from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
**kw
)
- cls.left = Table(
- "lft",
- m,
- Column("id", Integer, primary_key=True),
- Column("x", Integer),
- Column("y", Integer),
- )
- cls.right = Table(
- "rgt",
- m,
- Column("id", Integer, primary_key=True),
- Column("lid", Integer, ForeignKey("lft.id")),
- Column("x", Integer),
- Column("y", Integer),
- )
-
def _join_fixture_o2m_o_side_none(self, **kw):
return relationships.JoinCondition(
self.left,
-from sqlalchemy.testing import assert_raises, assert_raises_message
import datetime
+
import sqlalchemy as sa
-from sqlalchemy import testing
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- MetaData,
- and_,
- select,
- func,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- relation,
- backref,
- create_session,
- configure_mappers,
- clear_mappers,
- sessionmaker,
- attributes,
- Session,
- composite,
- column_property,
- foreign,
- remote,
- synonym,
- joinedload,
- subqueryload,
-)
-from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOONE
-from sqlalchemy.testing import eq_, startswith_, AssertsCompiledSQL, is_, in_
-from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
+from sqlalchemy import and_
from sqlalchemy import exc
-from sqlalchemy.orm import exc as orm_exc
-from sqlalchemy import inspect
+from sqlalchemy import ForeignKey
from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import func
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import testing
from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import composite
+from sqlalchemy.orm import configure_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import foreign
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relation
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import remote
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import synonym
+from sqlalchemy.orm.interfaces import MANYTOONE
+from sqlalchemy.orm.interfaces import ONETOMANY
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import startswith_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from test.orm import _fixtures
class _RelationshipErrors(object):
this is a very unusual case::
- company employee
- ---------- ----------
- company_id <--- company_id ------+
- name ^ |
- +------------+
+ company employee
+ ---------- ----------
+ company_id <--- company_id ------+
+ name ^ |
+ +------------+
- emp_id <---------+
- name |
- reports_to_id ---+
+ emp_id <---------+
+ name |
+ reports_to_id ---+
employee joins to its sub-employees
both on reports_to_id, *and on company_id to itself*.
secondary=j,
primaryjoin=and_(a.c.b_id == b.c.id, a.c.id == c.c.a_id),
secondaryjoin=d.c.id == b.c.d_id,
- # primaryjoin=and_(a.c.b_id == j.c.b_id, a.c.id == j.c.c_a_id),
- # secondaryjoin=d.c.id == j.c.b_d_id,
uselist=False,
viewonly=True,
),
-from sqlalchemy.testing import assert_raises, assert_raises_message
import sqlalchemy as sa
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import query
+from sqlalchemy.orm import relationship
from sqlalchemy.orm import scoped_session
-from sqlalchemy import Integer, String, ForeignKey
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, relationship, query
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class ScopedSessionTest(fixtures.MappedTest):
"""Generic mapping to Select statements"""
-from sqlalchemy.testing import assert_raises, assert_raises_message
import sqlalchemy as sa
+from sqlalchemy import column
+from sqlalchemy import Integer
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import String, Integer, select, column
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import mapper, Session
-from sqlalchemy.testing import eq_, AssertsCompiledSQL
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
# TODO: more tests mapping to selects
-from sqlalchemy.testing import eq_, is_, is_not_, is_true
+import sqlalchemy as sa
+from sqlalchemy import bindparam
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy import Integer, String, ForeignKey, bindparam
-from sqlalchemy.orm import (
- selectinload,
- selectinload_all,
- mapper,
- relationship,
- clear_mappers,
- create_session,
- aliased,
- joinedload,
- deferred,
- undefer,
- Session,
- subqueryload,
- defaultload,
-)
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import defaultload
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import selectinload
+from sqlalchemy.orm import selectinload_all
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import undefer
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing import is_true
from sqlalchemy.testing import mock
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
-import sqlalchemy as sa
-
-from sqlalchemy.orm import with_polymorphic
-
-from .inheritance._poly_fixtures import (
- _Polymorphic,
- Person,
- Engineer,
- Paperwork,
- Machine,
- MachineType,
- Company,
-)
+from .inheritance._poly_fixtures import _Polymorphic
+from .inheritance._poly_fixtures import Company
+from .inheritance._poly_fixtures import Engineer
+from .inheritance._poly_fixtures import Machine
+from .inheritance._poly_fixtures import MachineType
+from .inheritance._poly_fixtures import Paperwork
+from .inheritance._poly_fixtures import Person
class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
self._do_mapper_test(self._pathing_runs)
def _do_options_test(self, configs):
- users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords = (
+ (
+ users,
+ Keyword,
+ orders,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.orders,
self._do_query_tests(options, count)
def _do_mapper_test(self, configs):
- users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords = (
+ (
+ users,
+ Keyword,
+ orders,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.orders,
"""Eager loading with two relationships simultaneously,
from the same table, using aliases."""
- addresses, items, order_items, orders, Item, User, Address, Order, users = (
+ (
+ addresses,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ users,
+ ) = (
self.tables.addresses,
self.tables.items,
self.tables.order_items,
def test_limit(self):
"""Limit operations combined with lazy-load relationships."""
- users, items, order_items, orders, Item, User, Address, Order, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- assertions,
- is_true,
- is_,
-)
-from sqlalchemy.testing.util import gc_collect
-from sqlalchemy.testing import pickleable
-from sqlalchemy.util import pickle
-import inspect
-from sqlalchemy.orm import (
- create_session,
- sessionmaker,
- attributes,
- make_transient,
- make_transient_to_detached,
- Session,
-)
import sqlalchemy as sa
-from sqlalchemy.testing import engines, config
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import Sequence
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy import Integer, String, Sequence
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- backref,
- joinedload,
- exc as orm_exc,
- object_session,
- was_deleted,
-)
-from sqlalchemy.util import pypy
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import make_transient
+from sqlalchemy.orm import make_transient_to_detached
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import object_session
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm import was_deleted
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import assertions
+from sqlalchemy.testing import config
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from test.orm import _fixtures
-from sqlalchemy import event, ForeignKey
-from sqlalchemy.util.compat import inspect_getargspec
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_true
from sqlalchemy.testing import mock
+from sqlalchemy.testing import pickleable
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import gc_collect
+from sqlalchemy.util import pickle
+from sqlalchemy.util import pypy
+from sqlalchemy.util.compat import inspect_getargspec
+from test.orm import _fixtures
class ExecutionTest(_fixtures.FixtureTest):
# o is still in local scope here, so still present
self.assert_(len(s.identity_map) == 1)
- id = o.id
+ id_ = o.id
del o
eq_(prune(), 1)
self.assert_(len(s.identity_map) == 0)
- u = s.query(User).get(id)
+ u = s.query(User).get(id_)
eq_(prune(), 0)
self.assert_(len(s.identity_map) == 1)
u.name = "squiznart"
eq_(prune(), 1)
self.assert_(len(s.identity_map) == 0)
- u = s.query(User).get(id)
+ u = s.query(User).get(id_)
s.delete(u)
del u
eq_(prune(), 0)
-from sqlalchemy.testing import eq_, is_, is_not_, is_true
+import sqlalchemy as sa
+from sqlalchemy import bindparam
+from sqlalchemy import ForeignKey
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy import Integer, String, ForeignKey, bindparam, inspect
-from sqlalchemy.orm import (
- backref,
- subqueryload,
- subqueryload_all,
- mapper,
- relationship,
- clear_mappers,
- create_session,
- lazyload,
- aliased,
- joinedload,
- deferred,
- undefer,
- eagerload_all,
- Session,
-)
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
-from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import clear_mappers
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import deferred
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import subqueryload
+from sqlalchemy.orm import subqueryload_all
+from sqlalchemy.orm import undefer
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing import is_true
+from sqlalchemy.testing.assertsql import CompiledSQL
from sqlalchemy.testing.entities import ComparableEntity
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
-import sqlalchemy as sa
-
-from sqlalchemy.orm import with_polymorphic
-
-from .inheritance._poly_fixtures import (
- _Polymorphic,
- Person,
- Engineer,
- Paperwork,
- Page,
- Machine,
- MachineType,
- Company,
-)
+from .inheritance._poly_fixtures import _Polymorphic
+from .inheritance._poly_fixtures import Company
+from .inheritance._poly_fixtures import Engineer
+from .inheritance._poly_fixtures import Machine
+from .inheritance._poly_fixtures import MachineType
+from .inheritance._poly_fixtures import Page
+from .inheritance._poly_fixtures import Paperwork
+from .inheritance._poly_fixtures import Person
class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
self._do_mapper_test(self._pathing_runs)
def _do_options_test(self, configs):
- users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords = (
+ (
+ users,
+ Keyword,
+ orders,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.orders,
self._do_query_tests(options, count)
def _do_mapper_test(self, configs):
- users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords = (
+ (
+ users,
+ Keyword,
+ orders,
+ items,
+ order_items,
+ Order,
+ Item,
+ User,
+ keywords,
+ item_keywords,
+ ) = (
self.tables.users,
self.classes.Keyword,
self.tables.orders,
"""Eager loading with two relationships simultaneously,
from the same table, using aliases."""
- addresses, items, order_items, orders, Item, User, Address, Order, users = (
+ (
+ addresses,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ users,
+ ) = (
self.tables.addresses,
self.tables.items,
self.tables.order_items,
def test_limit(self):
"""Limit operations combined with lazy-load relationships."""
- users, items, order_items, orders, Item, User, Address, Order, addresses = (
+ (
+ users,
+ items,
+ order_items,
+ orders,
+ Item,
+ User,
+ Address,
+ Order,
+ addresses,
+ ) = (
self.tables.users,
self.tables.items,
self.tables.order_items,
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from test.orm import _fixtures
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import class_mapper
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import sync
+from sqlalchemy.orm import unitofwork
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
-from sqlalchemy import Integer, String, ForeignKey, func
-from sqlalchemy.orm import (
- mapper,
- relationship,
- backref,
- create_session,
- unitofwork,
- attributes,
- Session,
- class_mapper,
- sync,
- exc as orm_exc,
-)
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class AssertsUOW(object):
from __future__ import with_statement
-from sqlalchemy import (
- testing,
- exc as sa_exc,
- event,
- String,
- Column,
- Table,
- select,
- func,
-)
-from sqlalchemy.sql import elements
+
+from sqlalchemy import Column
+from sqlalchemy import event
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import func
+from sqlalchemy import inspect
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import session as _session
+from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.util import identity_key
-from sqlalchemy.testing import (
- fixtures,
- engines,
- eq_,
- assert_raises,
- assert_raises_message,
- assert_warnings,
- mock,
- expect_warnings,
- is_,
- is_not_,
- is_true,
-)
-from sqlalchemy.orm import (
- exc as orm_exc,
- Session,
- mapper,
- sessionmaker,
- create_session,
- relationship,
- attributes,
- session as _session,
-)
+from sqlalchemy.sql import elements
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import assert_warnings
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.testing import is_true
+from sqlalchemy.testing import mock
from sqlalchemy.testing.util import gc_collect
from test.orm._fixtures import FixtureTest
-from sqlalchemy import inspect
class SessionTransactionTest(fixtures.RemovesEvents, FixtureTest):
# coding: utf-8
"""Tests unitofwork operations."""
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
import datetime
-from sqlalchemy.util import OrderedDict
import sqlalchemy as sa
-from sqlalchemy.util import u, ue
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- Enum,
- literal_column,
- event,
- Boolean,
- select,
- func,
-)
+from sqlalchemy import Boolean
+from sqlalchemy import Enum
+from sqlalchemy import event
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal_column
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table
-from sqlalchemy.testing.schema import Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- create_session,
- column_property,
- Session,
- exc as orm_exc,
-)
+from sqlalchemy.orm import column_property
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import OrderedDict
+from sqlalchemy.util import u
+from sqlalchemy.util import ue
from test.orm import _fixtures
-from sqlalchemy.testing.assertsql import AllOf, CompiledSQL
class UnitOfWorkTest(object):
session.flush()
session.expunge_all()
- id = m.primary_key_from_instance(u)
+ id_ = m.primary_key_from_instance(u)
- u = session.query(User).get(id)
+ u = session.query(User).get(id_)
assert u.name == "multitester"
user_rows = (
eq_(list(address_rows[0].values()), [u.id, u.foo_id, "lala@hey.com"])
session.expunge_all()
- u = session.query(User).get(id)
+ u = session.query(User).get(id_)
assert u.name == "imnew"
def test_history_get(self):
-from sqlalchemy.testing import eq_, assert_raises_message
+from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import FetchedValue
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import util
+from sqlalchemy.orm import attributes
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import unitofwork
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import config
from sqlalchemy.testing import engines
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from test.orm import _fixtures
-from sqlalchemy import exc, util
-from sqlalchemy.testing import fixtures, config
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- func,
- literal,
- FetchedValue,
- text,
- select,
-)
-from sqlalchemy.orm import (
- mapper,
- relationship,
- backref,
- create_session,
- unitofwork,
- attributes,
- Session,
- exc as orm_exc,
-)
-from sqlalchemy.testing.mock import Mock, patch
-from sqlalchemy.testing.assertsql import AllOf, CompiledSQL
-from sqlalchemy import event
class AssertsUOW(object):
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, is_
-from sqlalchemy.testing import fixtures
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- or_,
- exc,
- select,
- func,
- Boolean,
- case,
- text,
- column,
-)
-from sqlalchemy.orm import (
- mapper,
- relationship,
- backref,
- Session,
- joinedload,
- synonym,
- query,
-)
+from sqlalchemy import Boolean
+from sqlalchemy import case
+from sqlalchemy import column
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy.orm import backref
+from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import synonym
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
-
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class UpdateDeleteTest(fixtures.MappedTest):
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy.orm import util as orm_util
from sqlalchemy import Column
-from sqlalchemy import util
+from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
-from sqlalchemy.orm import aliased, with_polymorphic, synonym
-from sqlalchemy.orm import mapper, create_session, Session
+from sqlalchemy import util
+from sqlalchemy.ext.hybrid import hybrid_method
+from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.orm import aliased
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import synonym
+from sqlalchemy.orm import util as orm_util
+from sqlalchemy.orm import with_polymorphic
+from sqlalchemy.orm.path_registry import PathRegistry
+from sqlalchemy.orm.path_registry import RootRegistry
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
from test.orm import _fixtures
-from sqlalchemy.testing import eq_, is_
-from sqlalchemy.orm.path_registry import PathRegistry, RootRegistry
-from sqlalchemy import inspect
-from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
-from sqlalchemy.testing import AssertsCompiledSQL
-
from .inheritance import _poly_fixtures
-from test.orm import _fixtures
-from sqlalchemy.testing import (
- fixtures,
- assert_raises,
- eq_,
- ne_,
- assert_raises_message,
-)
-from sqlalchemy.orm import mapper, Session, validates, relationship
-from sqlalchemy.orm import collections
-from sqlalchemy.testing.mock import Mock, call
from sqlalchemy import exc
+from sqlalchemy.orm import collections
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import validates
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing.mock import call
+from sqlalchemy.testing.mock import Mock
+from test.orm import _fixtures
class ValidatorTest(_fixtures.FixtureTest):
import datetime
+import uuid
+
import sqlalchemy as sa
-from sqlalchemy.testing import engines, config
+from sqlalchemy import Date
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import orm
+from sqlalchemy import select
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.mock import patch
-from sqlalchemy import (
- Integer,
- String,
- Date,
- ForeignKey,
- orm,
- exc,
- select,
- TypeDecorator,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.orm import (
- mapper,
- relationship,
- Session,
- create_session,
- sessionmaker,
- exc as orm_exc,
-)
-from sqlalchemy.testing import (
- eq_,
- assert_raises,
- assert_raises_message,
- fixtures,
-)
-from sqlalchemy.testing.assertsql import CompiledSQL
-import uuid
+from sqlalchemy import TypeDecorator
from sqlalchemy import util
+from sqlalchemy.orm import create_session
+from sqlalchemy.orm import exc as orm_exc
+from sqlalchemy.orm import mapper
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import config
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
def make_uuid():
pass
@compiles(IncDefault)
- def compile(element, compiler, **kw):
+ def compile_(element, compiler, **kw):
# cache the counter value on the statement
# itself so the assertsql system gets the same
# value when it compiles the statement a second time
from __future__ import print_function
+import logging
+import random
+import sys
+
import gevent.monkey
-gevent.monkey.patch_all() # noqa
+from sqlalchemy import create_engine
+from sqlalchemy import event
-import logging
+
+gevent.monkey.patch_all() # noqa
logging.basicConfig() # noqa
# logging.getLogger("sqlalchemy.pool").setLevel(logging.INFO)
-from sqlalchemy import event
-import random
-import sys
-from sqlalchemy import create_engine
-import traceback
engine = create_engine(
"mysql+pymysql://scott:tiger@localhost/test", pool_size=50, max_overflow=0
+from decimal import Decimal
+import os
+import random
import warnings
+from sqlalchemy import __version__
+from sqlalchemy import Column
+from sqlalchemy import create_engine
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import Numeric
+from sqlalchemy import String
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from sqlalchemy.orm import Session
+
+
warnings.filterwarnings("ignore", r".*Decimal objects natively") # noqa
# speed up cdecimal if available
except ImportError:
pass
-from sqlalchemy import __version__
-from sqlalchemy import (
- Column,
- Integer,
- create_engine,
- ForeignKey,
- String,
- Numeric,
-)
-
-from sqlalchemy.orm import Session, relationship
-
-from sqlalchemy.ext.declarative import declarative_base
-import random
-import os
-from decimal import Decimal
Base = declarative_base()
"""
-from sqlalchemy import util
import sys
-from sqlalchemy.testing.requirements import SuiteRequirements
+
+from sqlalchemy import util
from sqlalchemy.testing import exclusions
-from sqlalchemy.testing.exclusions import (
- skip,
- skip_if,
- only_if,
- only_on,
- fails_on_everything_except,
- fails_on,
- fails_if,
- succeeds_if,
- SpecPredicate,
- against,
- LambdaPredicate,
- requires_tag,
-)
+from sqlalchemy.testing.exclusions import against
+from sqlalchemy.testing.exclusions import fails_if
+from sqlalchemy.testing.exclusions import fails_on
+from sqlalchemy.testing.exclusions import fails_on_everything_except
+from sqlalchemy.testing.exclusions import LambdaPredicate
+from sqlalchemy.testing.exclusions import only_if
+from sqlalchemy.testing.exclusions import only_on
+from sqlalchemy.testing.exclusions import skip_if
+from sqlalchemy.testing.exclusions import SpecPredicate
+from sqlalchemy.testing.exclusions import succeeds_if
+from sqlalchemy.testing.requirements import SuiteRequirements
def no_support(db, reason):
[
LambdaPredicate(
lambda config: against(config, "mssql"),
- "SQL Server drivers / odbc seem to change their mind on this",
+ "SQL Server drivers / odbc seem to change "
+ "their mind on this",
),
LambdaPredicate(
lambda config: config.db.dialect.supports_native_boolean,
present in a subquery in the WHERE clause.
This is an ANSI-standard syntax that apparently MySQL can't handle,
- such as:
+ such as::
+
+ UPDATE documents SET flag=1 WHERE documents.title IN
+ (SELECT max(documents.title) AS title
+ FROM documents GROUP BY documents.user_id
+ )
- UPDATE documents SET flag=1 WHERE documents.title IN
- (SELECT max(documents.title) AS title
- FROM documents GROUP BY documents.user_id
- )
"""
return fails_if(
self._mysql_not_mariadb_103,
"sybase+pyodbc",
None,
None,
- "Don't know how do get these values through FreeTDS + Sybase",
+ "Don't know how do get these values through "
+ "FreeTDS + Sybase",
),
("firebird", None, None, "Precision must be from 1 to 18"),
]
-from sqlalchemy.testing import assert_raises, eq_, assert_raises_message
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
-from sqlalchemy import (
- testing,
- exc,
- case,
- select,
- literal_column,
- text,
- and_,
- Integer,
- cast,
- String,
- Column,
- Table,
- MetaData,
-)
-from sqlalchemy.sql import table, column
+from sqlalchemy import and_
+from sqlalchemy import case
+from sqlalchemy import cast
+from sqlalchemy import Column
+from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+
info_table = None
"""
-from sqlalchemy.testing import (
- eq_,
- is_,
- assert_raises,
- assert_raises_message,
- eq_ignore_whitespace,
-)
-from sqlalchemy import testing
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
-from sqlalchemy import (
- Integer,
- String,
- MetaData,
- Table,
- Column,
- select,
- func,
- not_,
- cast,
- text,
- tuple_,
- exists,
- update,
- bindparam,
- literal,
- and_,
- null,
- type_coerce,
- alias,
- or_,
- literal_column,
- Float,
- TIMESTAMP,
- Numeric,
- Date,
- Text,
- union,
- except_,
- intersect,
- union_all,
- Boolean,
- distinct,
- join,
- outerjoin,
- asc,
- desc,
- over,
- subquery,
- case,
- true,
- CheckConstraint,
- Sequence,
-)
import decimal
-from sqlalchemy.util import u
-from sqlalchemy import exc, sql, util, types, schema
-from sqlalchemy.sql import table, column, label
-from sqlalchemy.sql.expression import ClauseList, _literal_as_text, HasPrefixes
+
+from sqlalchemy import alias
+from sqlalchemy import and_
+from sqlalchemy import asc
+from sqlalchemy import bindparam
+from sqlalchemy import Boolean
+from sqlalchemy import case
+from sqlalchemy import cast
+from sqlalchemy import CheckConstraint
+from sqlalchemy import Column
+from sqlalchemy import Date
+from sqlalchemy import desc
+from sqlalchemy import distinct
+from sqlalchemy import exc
+from sqlalchemy import except_
+from sqlalchemy import exists
+from sqlalchemy import Float
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import intersect
+from sqlalchemy import join
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import not_
+from sqlalchemy import null
+from sqlalchemy import Numeric
+from sqlalchemy import or_
+from sqlalchemy import outerjoin
+from sqlalchemy import over
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import subquery
+from sqlalchemy import Table
+from sqlalchemy import Text
+from sqlalchemy import text
+from sqlalchemy import TIMESTAMP
+from sqlalchemy import true
+from sqlalchemy import tuple_
+from sqlalchemy import type_coerce
+from sqlalchemy import types
+from sqlalchemy import union
+from sqlalchemy import union_all
+from sqlalchemy import util
+from sqlalchemy.dialects import mysql
+from sqlalchemy.dialects import oracle
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.dialects import sqlite
+from sqlalchemy.dialects import sybase
+from sqlalchemy.dialects.postgresql.base import PGCompiler
+from sqlalchemy.dialects.postgresql.base import PGDialect
from sqlalchemy.engine import default
-from sqlalchemy.dialects import (
- mysql,
- mssql,
- postgresql,
- oracle,
- sqlite,
- sybase,
-)
-from sqlalchemy.dialects.postgresql.base import PGCompiler, PGDialect
from sqlalchemy.ext.compiler import compiles
+from sqlalchemy.sql import column
from sqlalchemy.sql import compiler
+from sqlalchemy.sql import label
+from sqlalchemy.sql import table
+from sqlalchemy.sql.expression import _literal_as_text
+from sqlalchemy.sql.expression import ClauseList
+from sqlalchemy.sql.expression import HasPrefixes
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import eq_ignore_whitespace
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.util import u
+
table1 = table(
"mytable",
"zips", column("zipcode"), column("latitude"), column("longitude")
)
places = table("places", column("id"), column("nm"))
- zip = "12345"
+ zipcode = "12345"
qlat = (
- select([zips.c.latitude], zips.c.zipcode == zip)
+ select([zips.c.latitude], zips.c.zipcode == zipcode)
.correlate(None)
.as_scalar()
)
qlng = (
- select([zips.c.longitude], zips.c.zipcode == zip)
+ select([zips.c.longitude], zips.c.zipcode == zipcode)
.correlate(None)
.as_scalar()
)
zips.c.zipcode,
func.latlondist(qlat, qlng).label("dist"),
],
- zips.c.zipcode == zip,
+ zips.c.zipcode == zipcode,
order_by=["dist", places.c.nm],
)
pass
@compiles(MyType)
- def compile(element, compiler, **kw):
+ def compile_(element, compiler, **kw):
raise exc.CompileError("Couldn't compile type")
return MyType
-from sqlalchemy.testing import assert_raises, assert_raises_message
-from sqlalchemy import (
- Table,
- Integer,
- String,
- Column,
- PrimaryKeyConstraint,
- ForeignKeyConstraint,
- ForeignKey,
- UniqueConstraint,
- Index,
- MetaData,
- CheckConstraint,
- func,
- text,
-)
-from sqlalchemy import exc, schema
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
+from sqlalchemy import CheckConstraint
+from sqlalchemy import Column
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import schema
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import UniqueConstraint
from sqlalchemy.engine import default
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import engines
-from sqlalchemy.testing.assertions import expect_warnings
from sqlalchemy.testing import eq_
-from sqlalchemy.testing.assertsql import (
- AllOf,
- RegexSQL,
- CompiledSQL,
- DialectSQL,
-)
-from sqlalchemy.sql import table, column
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.assertions import expect_warnings
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.assertsql import DialectSQL
+from sqlalchemy.testing.assertsql import RegexSQL
class ConstraintGenTest(fixtures.TestBase, AssertsExecutionResults):
-from sqlalchemy.testing import fixtures, eq_
-from sqlalchemy.testing import AssertsCompiledSQL, assert_raises_message
-from sqlalchemy.sql import (
- table,
- column,
- select,
- func,
- literal,
- exists,
- and_,
- bindparam,
-)
from sqlalchemy.dialects import mssql
from sqlalchemy.engine import default
from sqlalchemy.exc import CompileError
+from sqlalchemy.sql import and_
+from sqlalchemy.sql import bindparam
+from sqlalchemy.sql import column
+from sqlalchemy.sql import exists
+from sqlalchemy.sql import func
+from sqlalchemy.sql import literal
+from sqlalchemy.sql import select
+from sqlalchemy.sql import table
from sqlalchemy.sql.elements import quoted_name
from sqlalchemy.sql.visitors import cloned_traverse
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
class CTETest(fixtures.TestBase, AssertsCompiledSQL):
def test_recursive_union_no_alias_two(self):
"""
- pg's example:
+ pg's example::
WITH RECURSIVE t(n) AS (
VALUES (1)
-from sqlalchemy.testing import fixtures
-from sqlalchemy.sql.ddl import SchemaGenerator, SchemaDropper
-from sqlalchemy import MetaData, Table, Column, Integer, Sequence, ForeignKey
+from sqlalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
from sqlalchemy import schema
+from sqlalchemy import Sequence
+from sqlalchemy import Table
+from sqlalchemy.sql.ddl import SchemaDropper
+from sqlalchemy.sql.ddl import SchemaGenerator
+from sqlalchemy.testing import fixtures
from sqlalchemy.testing.mock import Mock
-from sqlalchemy.testing import (
- eq_,
- assert_raises_message,
- assert_raises,
- AssertsCompiledSQL,
- expect_warnings,
-)
import datetime
-from sqlalchemy.schema import CreateSequence, DropSequence, CreateTable
-from sqlalchemy.sql import select, text, literal_column
+import itertools
+
import sqlalchemy as sa
+from sqlalchemy import Boolean
+from sqlalchemy import cast
+from sqlalchemy import DateTime
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import MetaData
+from sqlalchemy import Sequence
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import engines
-from sqlalchemy import (
- MetaData,
- Integer,
- String,
- ForeignKey,
- Boolean,
- exc,
- Sequence,
- func,
- literal,
- Unicode,
- cast,
- DateTime,
-)
-from sqlalchemy.types import TypeDecorator, TypeEngine
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import Unicode
+from sqlalchemy import util
from sqlalchemy.dialects import sqlite
+from sqlalchemy.schema import CreateSequence
+from sqlalchemy.schema import CreateTable
+from sqlalchemy.schema import DropSequence
+from sqlalchemy.sql import literal_column
+from sqlalchemy.sql import select
+from sqlalchemy.sql import text
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
-from sqlalchemy.util import u, b
-from sqlalchemy import util
from sqlalchemy.testing import mock
-import itertools
-from sqlalchemy.testing.assertsql import CompiledSQL, AllOf, EachOf
+from sqlalchemy.testing.assertsql import AllOf
+from sqlalchemy.testing.assertsql import CompiledSQL
+from sqlalchemy.testing.assertsql import EachOf
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.types import TypeDecorator
+from sqlalchemy.types import TypeEngine
+from sqlalchemy.util import b
+from sqlalchemy.util import u
+
t = f = f2 = ts = currenttime = metadata = default_generator = None
#! coding:utf-8
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- delete,
- select,
- and_,
- or_,
- exists,
-)
+from sqlalchemy import and_
+from sqlalchemy import delete
+from sqlalchemy import exc
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import testing
from sqlalchemy.dialects import mysql
from sqlalchemy.engine import default
-from sqlalchemy import testing
-from sqlalchemy import exc
-from sqlalchemy.testing import (
- AssertsCompiledSQL,
- fixtures,
- eq_,
- assert_raises_message,
-)
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class _DeleteTestBase(object):
-from sqlalchemy.testing import eq_, is_
import datetime
-from sqlalchemy import (
- func,
- select,
- Integer,
- literal,
- DateTime,
- Table,
- Column,
- Sequence,
- MetaData,
- extract,
- Date,
- String,
- bindparam,
- literal_column,
- ARRAY,
- Numeric,
- Boolean,
-)
-from sqlalchemy.sql import table, column
-from sqlalchemy import sql, util
-from sqlalchemy.sql.compiler import BIND_TEMPLATES
-from sqlalchemy.testing.engines import all_dialects
-from sqlalchemy import types as sqltypes
-from sqlalchemy.sql import functions
-from sqlalchemy.sql.functions import GenericFunction, FunctionElement
import decimal
+
+from sqlalchemy import ARRAY
+from sqlalchemy import bindparam
+from sqlalchemy import Boolean
+from sqlalchemy import Column
+from sqlalchemy import Date
+from sqlalchemy import DateTime
+from sqlalchemy import extract
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import Numeric
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL, engines
-from sqlalchemy.dialects import sqlite, postgresql, mysql, oracle
-from sqlalchemy.testing import assert_raises_message, assert_raises
+from sqlalchemy import types as sqltypes
+from sqlalchemy import util
+from sqlalchemy.dialects import mysql
+from sqlalchemy.dialects import oracle
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.dialects import sqlite
+from sqlalchemy.sql import column
+from sqlalchemy.sql import functions
+from sqlalchemy.sql import table
+from sqlalchemy.sql.compiler import BIND_TEMPLATES
+from sqlalchemy.sql.functions import FunctionElement
+from sqlalchemy.sql.functions import GenericFunction
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.engines import all_dialects
+
table1 = table(
"mytable",
type = Date()
@compiles(myfunc)
- def compile(elem, compiler, **kw):
+ def compile_(elem, compiler, **kw):
return compiler.process(func.current_date())
conn = testing.db.connect()
assert t.select().execute().first()["value"] == 5
r = t.insert(values=dict(value=func.length("sfsaafsda"))).execute()
- id = r.inserted_primary_key[0]
- assert t.select(t.c.id == id).execute().first()["value"] == 9
+ id_ = r.inserted_primary_key[0]
+ assert t.select(t.c.id == id_).execute().first()["value"] == 9
t.update(values={t.c.value: func.length("asdf")}).execute()
assert t.select().execute().first()["value"] == 4
t2.insert().execute()
t2.update(
values={t2.c.value: func.length("asfdaasdf"), t2.c.stuff: "foo"}
).execute()
+
eq_(select([t2.c.value, t2.c.stuff]).execute().first(), (9, "foo"))
@testing.fails_on_everything_except("postgresql")
-from sqlalchemy.sql import table, column, ClauseElement, operators
-from sqlalchemy.sql.expression import _clone, _from_objects
-from sqlalchemy import (
- func,
- select,
- Integer,
- Table,
- Column,
- MetaData,
- extract,
- String,
- bindparam,
- tuple_,
- and_,
- union,
- text,
- case,
- ForeignKey,
- literal_column,
-)
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- AssertsCompiledSQL,
-)
-from sqlalchemy import testing
-from sqlalchemy.sql.visitors import (
- ClauseVisitor,
- CloningVisitor,
- cloned_traverse,
- ReplacingCloningVisitor,
-)
-from sqlalchemy.sql import visitors
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import case
+from sqlalchemy import Column
from sqlalchemy import exc
+from sqlalchemy import extract
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import tuple_
+from sqlalchemy import union
+from sqlalchemy.sql import ClauseElement
+from sqlalchemy.sql import column
+from sqlalchemy.sql import operators
+from sqlalchemy.sql import table
from sqlalchemy.sql import util as sql_util
-from sqlalchemy.testing import (
- eq_,
- is_,
- is_not_,
- assert_raises,
- assert_raises_message,
-)
+from sqlalchemy.sql import visitors
+from sqlalchemy.sql.expression import _clone
+from sqlalchemy.sql.expression import _from_objects
+from sqlalchemy.sql.visitors import ClauseVisitor
+from sqlalchemy.sql.visitors import cloned_traverse
+from sqlalchemy.sql.visitors import CloningVisitor
+from sqlalchemy.sql.visitors import ReplacingCloningVisitor
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+
A = B = t1 = t2 = t3 = table1 = table2 = table3 = table4 = None
assert CustomObj.__visit_name__ == Column.__visit_name__ == "column"
foo, bar = CustomObj("foo", String), CustomObj("bar", String)
- bin = foo == bar
- set(ClauseVisitor().iterate(bin))
- assert set(ClauseVisitor().iterate(bin)) == set([foo, bar, bin])
+ bin_ = foo == bar
+ set(ClauseVisitor().iterate(bin_))
+ assert set(ClauseVisitor().iterate(bin_)) == set([foo, bar, bin_])
class BinaryEndpointTraversalTest(fixtures.TestBase):
#! coding:utf-8
-from sqlalchemy import (
- Column,
- Integer,
- MetaData,
- String,
- Table,
- bindparam,
- exc,
- func,
- insert,
- select,
- column,
- text,
- table,
- Sequence,
-)
-from sqlalchemy.dialects import mysql, postgresql
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import column
+from sqlalchemy import exc
+from sqlalchemy import func
+from sqlalchemy import insert
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import table
+from sqlalchemy import text
+from sqlalchemy.dialects import mysql
+from sqlalchemy.dialects import postgresql
from sqlalchemy.engine import default
-from sqlalchemy.testing import (
- AssertsCompiledSQL,
- assert_raises_message,
- fixtures,
- eq_,
- expect_warnings,
- assert_raises,
-)
from sqlalchemy.sql import crud
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
class _InsertTestBase(object):
-from sqlalchemy.testing import eq_, assert_raises_message, is_
+from sqlalchemy import and_
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import INT
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Sequence
+from sqlalchemy import sql
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures, engines
-from sqlalchemy import (
- exc,
- sql,
- String,
- Integer,
- MetaData,
- and_,
- ForeignKey,
- VARCHAR,
- INT,
- Sequence,
- func,
-)
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import VARCHAR
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class InsertExecTest(fixtures.TablesTest):
result = engine.execute(table_.insert(), **values)
ret = values.copy()
- for col, id in zip(
+ for col, id_ in zip(
table_.primary_key, result.inserted_primary_key
):
- ret[col.key] = id
+ ret[col.key] = id_
if result.lastrow_has_defaults():
criterion = and_(
*[
- col == id
- for col, id in zip(
+ col == id_
+ for col, id_ in zip(
table_.primary_key, result.inserted_primary_key
)
]
"""test the inspection registry system."""
+from sqlalchemy import Column
from sqlalchemy import inspect
-from sqlalchemy import Table, Column, Integer, MetaData
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Table
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
version 3.7.16 no longer has this limitation.
"""
-from sqlalchemy import (
- Table,
- Column,
- Integer,
- MetaData,
- ForeignKey,
- select,
- exists,
- union,
-)
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
+from sqlalchemy import Column
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import union
from sqlalchemy import util
from sqlalchemy.engine import default
-from sqlalchemy import testing
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import fixtures
m = MetaData()
-from sqlalchemy import (
- exc as exceptions,
- select,
- MetaData,
- Integer,
- or_,
- bindparam,
-)
+from sqlalchemy import bindparam
+from sqlalchemy import exc as exceptions
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import select
from sqlalchemy.engine import default
-from sqlalchemy.sql import table, column
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
from sqlalchemy.sql.elements import _truncated_label
-from sqlalchemy.testing import (
- AssertsCompiledSQL,
- assert_raises,
- engines,
- fixtures,
- eq_,
-)
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+
IDENT_LENGTH = 29
-from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import AssertsCompiledSQL, assert_raises_message
-from sqlalchemy.sql import select, func
+from sqlalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import join
+from sqlalchemy import lateral
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import true
from sqlalchemy.engine import default
-from sqlalchemy import exc
-from sqlalchemy import Table, Integer, String, ForeignKey, Column, true
-from sqlalchemy import lateral, outerjoin, join
+from sqlalchemy.sql import func
+from sqlalchemy.sql import select
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import fixtures
class LateralTest(fixtures.TablesTest, AssertsCompiledSQL):
-from sqlalchemy.testing import assert_raises
-from sqlalchemy.testing import assert_raises_message
-from sqlalchemy.testing import emits_warning
+from contextlib import contextmanager
import pickle
-from sqlalchemy import (
- Integer,
- String,
- UniqueConstraint,
- CheckConstraint,
- ForeignKey,
- MetaData,
- Sequence,
- ForeignKeyConstraint,
- PrimaryKeyConstraint,
- ColumnDefault,
- Index,
- event,
- events,
- Unicode,
- types as sqltypes,
- bindparam,
- Table,
- Column,
- Boolean,
- Enum,
- func,
- text,
- TypeDecorator,
- BLANK_SCHEMA,
- ARRAY,
-)
-from sqlalchemy import schema, exc
-from sqlalchemy.engine import default
-from sqlalchemy.sql import elements, naming
+
import sqlalchemy as tsa
-from sqlalchemy.testing import fixtures
+from sqlalchemy import ARRAY
+from sqlalchemy import bindparam
+from sqlalchemy import BLANK_SCHEMA
+from sqlalchemy import Boolean
+from sqlalchemy import CheckConstraint
+from sqlalchemy import Column
+from sqlalchemy import ColumnDefault
+from sqlalchemy import Enum
+from sqlalchemy import event
+from sqlalchemy import exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import ForeignKeyConstraint
+from sqlalchemy import func
+from sqlalchemy import Index
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import PrimaryKeyConstraint
+from sqlalchemy import schema
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.testing import ComparesTables, AssertsCompiledSQL
-from sqlalchemy.testing import eq_, is_, mock, is_true, is_false
-from contextlib import contextmanager
+from sqlalchemy import text
+from sqlalchemy import TypeDecorator
+from sqlalchemy import types as sqltypes
+from sqlalchemy import Unicode
+from sqlalchemy import UniqueConstraint
from sqlalchemy import util
-from sqlalchemy.testing import engines
+from sqlalchemy.engine import default
+from sqlalchemy.sql import elements
+from sqlalchemy.sql import naming
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import ComparesTables
+from sqlalchemy.testing import emits_warning
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_false
+from sqlalchemy.testing import is_true
+from sqlalchemy.testing import mock
class MetaDataTest(fixtures.TestBase, ComparesTables):
(
name,
metadata,
- schema,
+ schema_,
quote_schema,
exp_schema,
exp_quote_schema,
]
):
kw = {}
- if schema is not None:
- kw["schema"] = schema
+ if schema_ is not None:
+ kw["schema"] = schema_
if quote_schema is not None:
kw["quote_schema"] = quote_schema
t = Table(name, metadata, **kw)
from sqlalchemy.sql import select
class MyColumn(Column):
- def _constructor(self, name, type, **kw):
+ def _constructor(self, name, type_, **kw):
kw["name"] = name
- return MyColumn(type, **kw)
+ return MyColumn(type_, **kw)
- def __init__(self, type, **kw):
- Column.__init__(self, type, **kw)
+ def __init__(self, type_, **kw):
+ Column.__init__(self, type_, **kw)
def my_goofy_thing(self):
return "hi"
s = compiler.visit_column(element, **kw)
return s + "-"
- id = MyColumn(Integer, primary_key=True)
- id.name = "id"
+ id_ = MyColumn(Integer, primary_key=True)
+ id_.name = "id"
name = MyColumn(String)
name.name = "name"
- t1 = Table("foo", MetaData(), id, name)
+ t1 = Table("foo", MetaData(), id_, name)
# goofy thing
eq_(t1.c.name.my_goofy_thing(), "hi")
from sqlalchemy.sql import select
class MyColumn(Column):
- def __init__(self, type, **kw):
- Column.__init__(self, type, **kw)
+ def __init__(self, type_, **kw):
+ Column.__init__(self, type_, **kw)
- id = MyColumn(Integer, primary_key=True)
- id.name = "id"
+ id_ = MyColumn(Integer, primary_key=True)
+ id_.name = "id"
name = MyColumn(String)
name.name = "name"
- t1 = Table("foo", MetaData(), id, name)
+ t1 = Table("foo", MetaData(), id_, name)
assert_raises_message(
TypeError,
"Could not create a copy of this <class "
from sqlalchemy.ext.compiler import compiles, deregister
@compiles(schema.CreateColumn)
- def compile(element, compiler, **kw):
+ def compile_(element, compiler, **kw):
column = element.element
if "special" not in column.info:
-from sqlalchemy.testing import fixtures, eq_, is_, is_not_
-from sqlalchemy import testing
-from sqlalchemy.testing import assert_raises_message
-from sqlalchemy.testing import expect_warnings
-from sqlalchemy.sql import (
- column,
- desc,
- asc,
- literal,
- collate,
- null,
- true,
- false,
- any_,
- all_,
-)
-from sqlalchemy.sql import sqltypes
-from sqlalchemy.sql.expression import (
- BinaryExpression,
- ClauseList,
- Grouping,
- UnaryExpression,
- select,
- union,
- func,
- tuple_,
-)
-from sqlalchemy.sql import operators, table
+import datetime
import operator
-from sqlalchemy import String, Integer, LargeBinary
+
+from sqlalchemy import and_
+from sqlalchemy import between
from sqlalchemy import exc
+from sqlalchemy import Integer
+from sqlalchemy import LargeBinary
+from sqlalchemy import literal_column
+from sqlalchemy import not_
+from sqlalchemy import or_
+from sqlalchemy import String
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import util
+from sqlalchemy.dialects import firebird
+from sqlalchemy.dialects import mssql
+from sqlalchemy.dialects import mysql
+from sqlalchemy.dialects import oracle
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.dialects import sqlite
from sqlalchemy.engine import default
-from sqlalchemy.sql.elements import _literal_as_text, Label
-from sqlalchemy.schema import Column, Table, MetaData
+from sqlalchemy.schema import Column
+from sqlalchemy.schema import MetaData
+from sqlalchemy.schema import Table
+from sqlalchemy.sql import all_
+from sqlalchemy.sql import any_
+from sqlalchemy.sql import asc
+from sqlalchemy.sql import collate
+from sqlalchemy.sql import column
from sqlalchemy.sql import compiler
-from sqlalchemy.types import (
- TypeEngine,
- TypeDecorator,
- UserDefinedType,
- Boolean,
- MatchType,
- Indexable,
- Concatenable,
- ARRAY,
- JSON,
- DateTime,
-)
-from sqlalchemy.dialects import (
- mysql,
- firebird,
- postgresql,
- oracle,
- sqlite,
- mssql,
-)
-from sqlalchemy import util
-import datetime
-import collections
-from sqlalchemy import text, literal_column
-from sqlalchemy import and_, not_, between, or_
+from sqlalchemy.sql import desc
+from sqlalchemy.sql import false
+from sqlalchemy.sql import literal
+from sqlalchemy.sql import null
+from sqlalchemy.sql import operators
+from sqlalchemy.sql import sqltypes
+from sqlalchemy.sql import table
+from sqlalchemy.sql import true
+from sqlalchemy.sql.elements import _literal_as_text
+from sqlalchemy.sql.elements import Label
+from sqlalchemy.sql.expression import BinaryExpression
+from sqlalchemy.sql.expression import ClauseList
+from sqlalchemy.sql.expression import func
+from sqlalchemy.sql.expression import Grouping
+from sqlalchemy.sql.expression import select
+from sqlalchemy.sql.expression import tuple_
+from sqlalchemy.sql.expression import UnaryExpression
+from sqlalchemy.sql.expression import union
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
+from sqlalchemy.types import ARRAY
+from sqlalchemy.types import Boolean
+from sqlalchemy.types import Concatenable
+from sqlalchemy.types import DateTime
+from sqlalchemy.types import Indexable
+from sqlalchemy.types import JSON
+from sqlalchemy.types import MatchType
+from sqlalchemy.types import TypeDecorator
+from sqlalchemy.types import TypeEngine
+from sqlalchemy.types import UserDefinedType
class LoopOperate(operators.ColumnOperators):
class JSONIndexOpTest(fixtures.TestBase, testing.AssertsCompiledSQL):
def setUp(self):
class MyTypeCompiler(compiler.GenericTypeCompiler):
- def visit_mytype(self, type, **kw):
+ def visit_mytype(self, type_, **kw):
return "MYTYPE"
- def visit_myothertype(self, type, **kw):
+ def visit_myothertype(self, type_, **kw):
return "MYOTHERTYPE"
class MyCompiler(compiler.SQLCompiler):
class ArrayIndexOpTest(fixtures.TestBase, testing.AssertsCompiledSQL):
def setUp(self):
class MyTypeCompiler(compiler.GenericTypeCompiler):
- def visit_mytype(self, type, **kw):
+ def visit_mytype(self, type_, **kw):
return "MYTYPE"
- def visit_myothertype(self, type, **kw):
+ def visit_myothertype(self, type_, **kw):
return "MYOTHERTYPE"
class MyCompiler(compiler.SQLCompiler):
-from sqlalchemy.testing import (
- eq_,
- assert_raises_message,
- assert_raises,
- is_,
- in_,
- not_in_,
-)
+from sqlalchemy import and_
+from sqlalchemy import asc
+from sqlalchemy import bindparam
+from sqlalchemy import cast
+from sqlalchemy import desc
+from sqlalchemy import exc
+from sqlalchemy import except_
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import INT
+from sqlalchemy import Integer
+from sqlalchemy import intersect
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import not_
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import sql
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures, engines
-from sqlalchemy import (
- exc,
- sql,
- func,
- select,
- String,
- Integer,
- MetaData,
- and_,
- ForeignKey,
- union,
- intersect,
- except_,
- union_all,
- VARCHAR,
- INT,
- text,
- bindparam,
- literal,
- not_,
- literal_column,
- desc,
- asc,
- TypeDecorator,
- or_,
- cast,
- tuple_,
-)
+from sqlalchemy import text
+from sqlalchemy import tuple_
+from sqlalchemy import TypeDecorator
+from sqlalchemy import union
+from sqlalchemy import union_all
+from sqlalchemy import VARCHAR
from sqlalchemy.engine import default
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+
# ongoing - these are old tests. those which are of general use
# to test a dialect are being slowly migrated to
-from sqlalchemy import (
- MetaData,
- Table,
- Column,
- Integer,
- select,
- ForeignKey,
- Index,
- CheckConstraint,
- inspect,
- column,
-)
-from sqlalchemy import sql, schema, types as sqltypes
-from sqlalchemy.sql import compiler
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL, eq_
+from sqlalchemy import CheckConstraint
+from sqlalchemy import Column
+from sqlalchemy import column
+from sqlalchemy import ForeignKey
+from sqlalchemy import Index
+from sqlalchemy import inspect
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import schema
+from sqlalchemy import select
+from sqlalchemy import sql
+from sqlalchemy import Table
from sqlalchemy import testing
-from sqlalchemy.sql.elements import quoted_name, _anonymous_label
-from sqlalchemy.testing.util import picklers
from sqlalchemy.engine import default
+from sqlalchemy.sql import compiler
+from sqlalchemy.sql.elements import _anonymous_label
+from sqlalchemy.sql.elements import quoted_name
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.util import picklers
class QuoteExecTest(fixtures.TestBase):
"""test the quoting of labels.
If labels aren't quoted, a query in postgresql in particular will
- fail since it produces:
-
- SELECT
- LaLa.lowercase, LaLa."UPPERCASE", LaLa."MixedCase", LaLa."ASC"
- FROM (
- SELECT DISTINCT
- "WorstCase1".lowercase AS lowercase,
- "WorstCase1"."UPPERCASE" AS UPPERCASE,
- "WorstCase1"."MixedCase" AS MixedCase,
- "WorstCase1"."ASC" AS ASC
- FROM "WorstCase1"
- ) AS LaLa
+ fail since it produces::
+
+ SELECT
+ LaLa.lowercase, LaLa."UPPERCASE", LaLa."MixedCase", LaLa."ASC"
+ FROM (
+ SELECT DISTINCT
+ "WorstCase1".lowercase AS lowercase,
+ "WorstCase1"."UPPERCASE" AS UPPERCASE,
+ "WorstCase1"."MixedCase" AS MixedCase,
+ "WorstCase1"."ASC" AS ASC
+ FROM "WorstCase1"
+ ) AS LaLa
where the "UPPERCASE" column of "LaLa" doesn't exist.
"""
-from sqlalchemy.testing import (
- eq_,
- assert_raises_message,
- assert_raises,
- in_,
- not_in_,
- is_,
- ne_,
- le_,
-)
+from contextlib import contextmanager
+import operator
+
+from sqlalchemy import CHAR
+from sqlalchemy import column
+from sqlalchemy import exc
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import INT
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import sql
+from sqlalchemy import String
+from sqlalchemy import table
from sqlalchemy import testing
-from sqlalchemy.testing import fixtures, engines
+from sqlalchemy import text
+from sqlalchemy import type_coerce
+from sqlalchemy import TypeDecorator
from sqlalchemy import util
-from sqlalchemy import (
- exc,
- sql,
- func,
- select,
- String,
- Integer,
- MetaData,
- ForeignKey,
- VARCHAR,
- INT,
- CHAR,
- text,
- type_coerce,
- literal_column,
- TypeDecorator,
- table,
- column,
- literal,
-)
+from sqlalchemy import VARCHAR
+from sqlalchemy.engine import default
from sqlalchemy.engine import result as _result
-from sqlalchemy.testing.schema import Table, Column
-import operator
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import assertions
-from sqlalchemy import exc as sa_exc
-from sqlalchemy.testing.mock import patch, Mock
-from contextlib import contextmanager
-from sqlalchemy.engine import default
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import in_
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import le_
+from sqlalchemy.testing import ne_
+from sqlalchemy.testing import not_in_
+from sqlalchemy.testing.mock import Mock
+from sqlalchemy.testing.mock import patch
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class ResultProxyTest(fixtures.TablesTest):
-from sqlalchemy.testing import eq_
+import itertools
+
+from sqlalchemy import Boolean
+from sqlalchemy import exc as sa_exc
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
from sqlalchemy.types import TypeDecorator
-from sqlalchemy.testing import (
- fixtures,
- AssertsExecutionResults,
- engines,
- assert_raises_message,
-)
-from sqlalchemy import exc as sa_exc
-from sqlalchemy import (
- MetaData,
- String,
- Integer,
- Boolean,
- func,
- select,
- Sequence,
-)
-import itertools
+
table = GoofyType = seq = None
pass
@compiles(IncDefault)
- def compile(element, compiler, **kw):
+ def compile_(element, compiler, **kw):
return str(next(counter))
Table(
-from sqlalchemy import *
-from sqlalchemy.testing import fixtures, AssertsExecutionResults
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
class FoundRowsTest(fixtures.TestBase, AssertsExecutionResults):
"""Test various algorithmic properties of selectables."""
-from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, is_
-from sqlalchemy import *
-from sqlalchemy.testing import (
- fixtures,
- AssertsCompiledSQL,
- AssertsExecutionResults,
-)
-from sqlalchemy.sql import elements
-from sqlalchemy import testing
-from sqlalchemy.sql import util as sql_util, visitors, expression
+from sqlalchemy import alias
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import Boolean
+from sqlalchemy import cast
+from sqlalchemy import Column
from sqlalchemy import exc
-from sqlalchemy.sql import table, column, null
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import join
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import not_
+from sqlalchemy import null
+from sqlalchemy import or_
+from sqlalchemy import outerjoin
+from sqlalchemy import select
+from sqlalchemy import Sequence
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import type_coerce
+from sqlalchemy import TypeDecorator
+from sqlalchemy import union
from sqlalchemy import util
-from sqlalchemy.schema import Column, Table, MetaData
+from sqlalchemy.sql import column
+from sqlalchemy.sql import elements
+from sqlalchemy.sql import expression
+from sqlalchemy.sql import table
+from sqlalchemy.sql import util as sql_util
+from sqlalchemy.sql import visitors
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+
metadata = MetaData()
table1 = Table(
assert s.c.b is not None
self.assert_compile(
s.select(),
- "SELECT b FROM (SELECT (SELECT table1.col1 AS a FROM table1) AS b)",
+ "SELECT b FROM "
+ "(SELECT (SELECT table1.col1 AS a FROM table1) AS b)",
)
s2 = select([s.label("c")])
def test_annotated_visit(self):
table1 = table("table1", column("col1"), column("col2"))
- bin = table1.c.col1 == bindparam("foo", value=None)
- assert str(bin) == "table1.col1 = :foo"
+ bin_ = table1.c.col1 == bindparam("foo", value=None)
+ assert str(bin_) == "table1.col1 = :foo"
def visit_binary(b):
b.right = table1.c.col2
- b2 = visitors.cloned_traverse(bin, {}, {"binary": visit_binary})
+ b2 = visitors.cloned_traverse(bin_, {}, {"binary": visit_binary})
assert str(b2) == "table1.col1 = table1.col2"
b3 = visitors.cloned_traverse(
- bin._annotate({}), {}, {"binary": visit_binary}
+ bin_._annotate({}), {}, {"binary": visit_binary}
)
assert str(b3) == "table1.col1 = table1.col2"
def test_deannotate(self):
table1 = table("table1", column("col1"), column("col2"))
- bin = table1.c.col1 == bindparam("foo", value=None)
+ bin_ = table1.c.col1 == bindparam("foo", value=None)
- b2 = sql_util._deep_annotate(bin, {"_orm_adapt": True})
+ b2 = sql_util._deep_annotate(bin_, {"_orm_adapt": True})
b3 = sql_util._deep_deannotate(b2)
- b4 = sql_util._deep_deannotate(bin)
+ b4 = sql_util._deep_deannotate(bin_)
for elem in (b2._annotations, b2.left._annotations):
assert "_orm_adapt" in elem
):
assert elem == {}
- assert b2.left is not bin.left
- assert b3.left is not b2.left and b2.left is not bin.left
- assert b4.left is bin.left # since column is immutable
+ assert b2.left is not bin_.left
+ assert b3.left is not b2.left and b2.left is not bin_.left
+ assert b4.left is bin_.left # since column is immutable
# deannotate copies the element
assert (
- bin.right is not b2.right
+ bin_.right is not b2.right
and b2.right is not b3.right
and b3.right is not b4.right
)
-from sqlalchemy.testing import fixtures
-from sqlalchemy.testing import AssertsCompiledSQL, assert_raises_message
-from sqlalchemy.sql import select, func, text
-from sqlalchemy.engine import default
-from sqlalchemy import exc
-from sqlalchemy import Table, Integer, String, Column
+from sqlalchemy import Column
+from sqlalchemy import Integer
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import tablesample
+from sqlalchemy.engine import default
+from sqlalchemy.sql import func
+from sqlalchemy.sql import select
+from sqlalchemy.sql import text
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import fixtures
class TableSampleTest(fixtures.TablesTest, AssertsCompiledSQL):
"""Test the TextClause and related constructs."""
-from sqlalchemy.testing import (
- fixtures,
- AssertsCompiledSQL,
- eq_,
- assert_raises_message,
- expect_warnings,
- assert_warnings,
-)
-from sqlalchemy import (
- text,
- select,
- Integer,
- String,
- Float,
- bindparam,
- and_,
- func,
- literal_column,
- exc,
- MetaData,
- Table,
- Column,
- asc,
- func,
- desc,
- union,
- literal,
-)
-from sqlalchemy.types import NullType
-from sqlalchemy.sql import table, column, util as sql_util
+from sqlalchemy import and_
+from sqlalchemy import asc
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import desc
+from sqlalchemy import exc
+from sqlalchemy import Float
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import literal_column
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
+from sqlalchemy import text
+from sqlalchemy import union
from sqlalchemy import util
+from sqlalchemy.sql import column
+from sqlalchemy.sql import table
+from sqlalchemy.sql import util as sql_util
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import assert_warnings
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
+from sqlalchemy.testing import fixtures
+from sqlalchemy.types import NullType
+
table1 = table(
"mytable",
-from sqlalchemy import (
- Table,
- Column,
- String,
- func,
- MetaData,
- select,
- TypeDecorator,
- cast,
-)
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL
+from sqlalchemy import cast
+from sqlalchemy import Column
+from sqlalchemy import func
+from sqlalchemy import MetaData
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy import testing
+from sqlalchemy import TypeDecorator
+from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
class _ExprFixture(object):
# coding: utf-8
-from sqlalchemy.testing import (
- eq_,
- is_,
- is_not_,
- assert_raises,
- assert_raises_message,
- expect_warnings,
-)
-import decimal
import datetime
+import decimal
+import importlib
+import operator
import os
-from sqlalchemy import (
- Unicode,
- MetaData,
- PickleType,
- Boolean,
- TypeDecorator,
- Integer,
- Interval,
- Float,
- Numeric,
- Text,
- CHAR,
- String,
- distinct,
- select,
- bindparam,
- and_,
- func,
- Date,
- LargeBinary,
- literal,
- cast,
- text,
- Enum,
- type_coerce,
- VARCHAR,
- Time,
- DateTime,
- BigInteger,
- SmallInteger,
- BOOLEAN,
- BLOB,
- NCHAR,
- NVARCHAR,
- CLOB,
- TIME,
- DATE,
- DATETIME,
- TIMESTAMP,
- SMALLINT,
- INTEGER,
- DECIMAL,
- NUMERIC,
- FLOAT,
- REAL,
- ARRAY,
- JSON,
-)
-from sqlalchemy.sql import ddl
-from sqlalchemy.sql import visitors
+
+from sqlalchemy import and_
+from sqlalchemy import ARRAY
+from sqlalchemy import BigInteger
+from sqlalchemy import bindparam
+from sqlalchemy import BLOB
+from sqlalchemy import BOOLEAN
+from sqlalchemy import Boolean
+from sqlalchemy import cast
+from sqlalchemy import CHAR
+from sqlalchemy import CLOB
+from sqlalchemy import DATE
+from sqlalchemy import Date
+from sqlalchemy import DATETIME
+from sqlalchemy import DateTime
+from sqlalchemy import DECIMAL
+from sqlalchemy import dialects
+from sqlalchemy import distinct
+from sqlalchemy import Enum
+from sqlalchemy import exc
+from sqlalchemy import FLOAT
+from sqlalchemy import Float
+from sqlalchemy import func
from sqlalchemy import inspection
-from sqlalchemy import exc, types, util, dialects
-from sqlalchemy.util import OrderedDict
-from sqlalchemy.sql import operators, column, table, null
-from sqlalchemy.schema import CheckConstraint, AddConstraint
-from sqlalchemy.engine import default
-from sqlalchemy.testing.schema import Table, Column
+from sqlalchemy import INTEGER
+from sqlalchemy import Integer
+from sqlalchemy import Interval
+from sqlalchemy import JSON
+from sqlalchemy import LargeBinary
+from sqlalchemy import literal
+from sqlalchemy import MetaData
+from sqlalchemy import NCHAR
+from sqlalchemy import NUMERIC
+from sqlalchemy import Numeric
+from sqlalchemy import NVARCHAR
+from sqlalchemy import PickleType
+from sqlalchemy import REAL
+from sqlalchemy import select
+from sqlalchemy import SMALLINT
+from sqlalchemy import SmallInteger
+from sqlalchemy import String
from sqlalchemy import testing
-from sqlalchemy.testing import (
- AssertsCompiledSQL,
- AssertsExecutionResults,
- engines,
- pickleable,
-)
-from sqlalchemy.testing.util import picklers
-from sqlalchemy.testing.util import round_decimal
+from sqlalchemy import Text
+from sqlalchemy import text
+from sqlalchemy import TIME
+from sqlalchemy import Time
+from sqlalchemy import TIMESTAMP
+from sqlalchemy import type_coerce
+from sqlalchemy import TypeDecorator
+from sqlalchemy import types
+from sqlalchemy import Unicode
+from sqlalchemy import util
+from sqlalchemy import VARCHAR
+from sqlalchemy.engine import default
+from sqlalchemy.schema import AddConstraint
+from sqlalchemy.schema import CheckConstraint
+from sqlalchemy.sql import column
+from sqlalchemy.sql import ddl
+from sqlalchemy.sql import null
+from sqlalchemy.sql import operators
+from sqlalchemy.sql import sqltypes
+from sqlalchemy.sql import table
+from sqlalchemy.sql import visitors
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import AssertsExecutionResults
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_
+from sqlalchemy.testing import is_not_
from sqlalchemy.testing import mock
-from sqlalchemy.sql import column
-import operator
-import importlib
+from sqlalchemy.testing import pickleable
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.testing.util import picklers
+from sqlalchemy.testing.util import round_decimal
+from sqlalchemy.util import OrderedDict
class AdaptTest(fixtures.TestBase):
):
yield True, subcl, [typ]
- from sqlalchemy.sql import sqltypes
-
for is_down_adaption, typ, target_adaptions in adaptions():
if typ in (types.TypeDecorator, types.TypeEngine, types.Variant):
continue
"""
- def _fixture(self, metadata, type, data):
- t = Table("t", metadata, Column("val", type))
+ def _fixture(self, metadata, type_, data):
+ t = Table("t", metadata, Column("val", type_))
metadata.create_all()
t.insert().execute(val=data)
# coding: utf-8
"""verrrrry basic unicode column name testing"""
-from sqlalchemy import *
-from sqlalchemy.testing import fixtures, engines, eq_
+from sqlalchemy import desc
+from sqlalchemy import ForeignKey
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
from sqlalchemy import testing
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy.util import u, ue
+from sqlalchemy.testing import engines
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
+from sqlalchemy.util import u
+from sqlalchemy.util import ue
class UnicodeSchemaTest(fixtures.TestBase):
repr(t),
(
"Table('\\u6e2c\\u8a66', MetaData(bind=None), "
- "Column('\\u6e2c\\u8a66_id', Integer(), table=<\u6e2c\u8a66>), "
+ "Column('\\u6e2c\\u8a66_id', Integer(), "
+ "table=<\u6e2c\u8a66>), "
"schema=None)"
),
)
-from sqlalchemy import (
- Integer,
- String,
- ForeignKey,
- and_,
- or_,
- func,
- literal,
- update,
- table,
- bindparam,
- column,
- select,
- exc,
- exists,
- text,
- MetaData,
-)
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import column
+from sqlalchemy import exc
+from sqlalchemy import exists
+from sqlalchemy import ForeignKey
+from sqlalchemy import func
+from sqlalchemy import Integer
+from sqlalchemy import literal
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import select
+from sqlalchemy import String
+from sqlalchemy import table
from sqlalchemy import testing
+from sqlalchemy import text
+from sqlalchemy import update
+from sqlalchemy import util
from sqlalchemy.dialects import mysql
from sqlalchemy.engine import default
-from sqlalchemy.testing import (
- AssertsCompiledSQL,
- eq_,
- fixtures,
- assert_raises_message,
- assert_raises,
-)
-from sqlalchemy.testing.schema import Table, Column
-from sqlalchemy import util
+from sqlalchemy.testing import assert_raises
+from sqlalchemy.testing import assert_raises_message
+from sqlalchemy.testing import AssertsCompiledSQL
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing.schema import Column
+from sqlalchemy.testing.schema import Table
class _UpdateFromTestBase(object):
-from sqlalchemy.testing import fixtures, is_true, is_false, eq_
-from sqlalchemy import MetaData, Table, Column, Integer, String
-from sqlalchemy import and_, or_, bindparam
-from sqlalchemy.sql.elements import ClauseList, ColumnElement
+from sqlalchemy import and_
+from sqlalchemy import bindparam
+from sqlalchemy import Column
+from sqlalchemy import Integer
+from sqlalchemy import MetaData
+from sqlalchemy import or_
+from sqlalchemy import String
+from sqlalchemy import Table
from sqlalchemy.sql import operators
from sqlalchemy.sql import util as sql_util
+from sqlalchemy.sql.elements import ClauseList
+from sqlalchemy.sql.elements import ColumnElement
+from sqlalchemy.testing import eq_
+from sqlalchemy.testing import fixtures
+from sqlalchemy.testing import is_false
+from sqlalchemy.testing import is_true
class CompareClausesTest(fixtures.TestBase):