Commits

Mike Bayer committed 5699328

- add changelog
- support python 3 in place - #1

Comments (0)

Files changed (8)

docs/build/changelog.rst

+==============
+Changelog
+==============
+.. changelog::
+    :version: 0.9.1
+
+    .. change::
+        :tags: bug
+        :tickets: 1
+
+      Fixed issue where errant "py2k" comment was present, replaced
+      with a compat conditional.
+
+    .. change::
+    	:tags: feature
+
+      Removed the need for the 2to3 tool on Python 3.
+
+.. changelog::
+    :version: 0.9.0
+    :released: Sun Jan 8 2012
+
+    .. change::
+    	:tags:
+
+      Initial release.
 
 # Add any Sphinx extension module names here, as strings. They can be extensions
 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode']
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'changelog']
 
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']
    front
    tutorial
    api
-
+   changelog
 
 
 Indices and tables

docs/build/requirements.txt

+changelog
+
-from setuptools import setup, find_packages
-import sys
+from setuptools import setup
 import os
 import re
 
-extra = {}
-if sys.version_info >= (3, 0):
-    extra.update(
-        use_2to3=True,
-    )
-
 v = open(os.path.join(os.path.dirname(__file__), 'sqlsoup.py'))
 VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
 v.close()
       install_requires=[
           'SQLAlchemy>=0.7.0',
       ],
-      **extra
 )
                             object_session, attributes
 from sqlalchemy.orm.interfaces import MapperExtension, EXT_CONTINUE
 from sqlalchemy.sql import expression
+import sys
+
+py2k = sys.version_info < (3, 0)
+
+if py2k:
+    string_types = basestring,
+else:
+    string_types = string_types = str,
 
 __version__ = '0.9.0'
 __all__ = ['SQLSoupError', 'SQLSoup', 'SelectableClassType', 'TableClassType', 'Session']
 
     def _default__init__(ext, mapper):
         def __init__(self, **kwargs):
-            for key, value in kwargs.iteritems():
+            for key, value in kwargs.items():
                 setattr(self, key, value)
         return __init__
 
 class SelectableClassType(type):
     """Represent a SQLSoup mapping to a :class:`sqlalchemy.sql.expression.Selectable`
     construct, such as a table or SELECT statement.
-    
+
     """
 
     def insert(cls, **kwargs):
 class TableClassType(SelectableClassType):
     """Represent a SQLSoup mapping to a :class:`sqlalchemy.schema.Table`
     construct.
-    
+
     This object is produced automatically when a table-name
     attribute is accessed from a :class:`.SQLSoup` instance.
-    
+
     """
     def insert(cls, **kwargs):
         o = cls()
 
     def relate(cls, propname, *args, **kwargs):
         """Produce a relationship between this mapped table and another
-        one. 
-        
+        one.
+
         This makes usage of SQLAlchemy's :func:`sqlalchemy.orm.relationship`
         construct.
-        
+
         """
         class_mapper(cls)._configure_property(propname, relationship(*args, **kwargs))
 
 def _class_for_table(session, engine, selectable, base_cls, mapper_kwargs):
     selectable = expression._clause_element_as_expr(selectable)
     mapname = 'Mapped' + _selectable_name(selectable)
-    # Py2K
-    if isinstance(mapname, unicode): 
-        engine_encoding = engine.dialect.encoding 
+
+    if py2k and isinstance(mapname, unicode):
+        engine_encoding = engine.dialect.encoding
         mapname = mapname.encode(engine_encoding)
-    # end Py2K
 
     if isinstance(selectable, Table):
         klass = TableClassType(mapname, (base_cls,), {})
             raise TypeError('unable to compare with %s' % o.__class__)
         return t1, t2
 
-    # python2/python3 compatible system of 
+    # python2/python3 compatible system of
     # __cmp__ - __lt__ + __eq__
 
     def __lt__(self, o):
     def __init__(self, engine_or_metadata, base=object, session=None):
         """Initialize a new :class:`.SQLSoup`.
 
-        :param engine_or_metadata: a string database URL, :class:`.Engine` 
+        :param engine_or_metadata: a string database URL, :class:`.Engine`
           or :class:`.MetaData` object to associate with. If the
           argument is a :class:`.MetaData`, it should be *bound*
           to an :class:`.Engine`.
-        :param base: a class which will serve as the default class for 
+        :param base: a class which will serve as the default class for
           returned mapped classes.  Defaults to ``object``.
         :param session: a :class:`.ScopedSession` or :class:`.Session` with
           which to associate ORM operations for this :class:`.SQLSoup` instance.
-          If ``None``, a :class:`.ScopedSession` that's local to this 
+          If ``None``, a :class:`.ScopedSession` that's local to this
           module is used.
 
         """
 
         self.session = session or Session
-        self.base=base
+        self.base = base
 
         if isinstance(engine_or_metadata, MetaData):
             self._metadata = engine_or_metadata
-        elif isinstance(engine_or_metadata, (basestring, Engine)):
+        elif isinstance(engine_or_metadata, string_types + (Engine, )):
             self._metadata = MetaData(engine_or_metadata)
         else:
-            raise ArgumentError("invalid engine or metadata argument %r" % 
+            raise ArgumentError("invalid engine or metadata argument %r" %
                                 engine_or_metadata)
 
         self._cache = {}
         """Execute a SQL statement.
 
         The statement may be a string SQL string,
-        an :func:`sqlalchemy.sql.expression.select` construct, or a 
-        :func:`sqlalchemy.sql.expression.text` 
+        an :func:`sqlalchemy.sql.expression.select` construct, or a
+        :func:`sqlalchemy.sql.expression.text`
         construct.
 
         """
         """
         self.session.expunge_all()
 
-    def map_to(self, attrname, tablename=None, selectable=None, 
+    def map_to(self, attrname, tablename=None, selectable=None,
                     schema=None, base=None, mapper_args=util.immutabledict()):
         """Configure a mapping to the given attrname.
 
-        This is the "master" method that can be used to create any 
+        This is the "master" method that can be used to create any
         configuration.
 
         :param attrname: String attribute name which will be
             ))
 
         if tablename is not None:
-            if not isinstance(tablename, basestring):
+            if not isinstance(tablename, string_types):
                 raise ArgumentError("'tablename' argument must be a string."
                                     )
             if selectable is not None:
                 raise ArgumentError("'tablename' and 'selectable' "
                                     "arguments are mutually exclusive")
 
-            selectable = Table(tablename, 
-                                        self._metadata, 
-                                        autoload=True, 
-                                        autoload_with=self.bind, 
+            selectable = Table(tablename,
+                                        self._metadata,
+                                        autoload=True,
+                                        autoload_with=self.bind,
                                         schema=schema or self.schema)
         elif schema:
             raise ArgumentError("'tablename' argument is required when "
         )
 
     def with_labels(self, selectable, base=None, **mapper_args):
-        """Map a selectable directly, wrapping the 
+        """Map a selectable directly, wrapping the
         selectable in a subquery with labels.
 
         The class and its mapping are not cached and will
                             select(use_labels=True).
                             alias('foo'), base=base, **mapper_args)
 
-    def join(self, left, right, onclause=None, isouter=False, 
+    def join(self, left, right, onclause=None, isouter=False,
                 base=None, **mapper_args):
         """Create an :func:`.expression.join` and map to it.
 
         return self.map(j, base=base, **mapper_args)
 
     def entity(self, attr, schema=None):
-        """Return the named entity from this :class:`.SQLSoup`, or 
+        """Return the named entity from this :class:`.SQLSoup`, or
         create if not present.
 
         For more generalized mapping, see :meth:`.map_to`.
         """
         try:
             return self._cache[attr]
-        except KeyError, ke:
+        except KeyError:
             return self.map_to(attr, tablename=attr, schema=schema)
 
     def __getattr__(self, attr):
     try:
         callable_(*args, **kw)
         success = False
-    except except_cls, e:
+    except except_cls:
         success = True
 
     # assert outside the block so it works for AssertionError too !
     try:
         callable_(*args, **kwargs)
         assert False, "Callable did not raise an exception"
-    except except_cls, e:
+    except except_cls as e:
         assert re.search(msg, str(e)), "%r !~ %s" % (msg, e)
-        print str(e)
+        print(str(e))

tests/test_sqlsoup.py

             sqlsoup.ArgumentError,
             "'tablename' or 'selectable' argument is "
                                     "required.",
-            db.map_to, 'users', 
+            db.map_to, 'users',
         )
 
     def test_map_to_string_not_selectable(self):
     def test_bad_names(self):
         db = sqlsoup.SQLSoup(engine)
 
-        # print db.bad_names.c.id
-
-        print db.bad_names.c.query
+        str(db.bad_names.c.query)
 
     def test_load(self):
         db = sqlsoup.SQLSoup(engine)
         MappedUsers = db.users
         users = db.users.all()
         users.sort()
-        eq_(users, [MappedUsers(name=u'Joe Student',
-            email=u'student@example.edu', password=u'student',
+        eq_(users, [MappedUsers(name='Joe Student',
+            email='student@example.ed', password='student',
             classname=None, admin=0),
-            MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
+            MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1)])
 
     def test_order_by(self):
         db = sqlsoup.SQLSoup(engine)
         MappedUsers = db.users
         users = db.users.order_by(db.users.name).all()
-        eq_(users, [MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
-            classname=None, admin=1), MappedUsers(name=u'Joe Student',
-            email=u'student@example.edu', password=u'student',
+        eq_(users, [MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
+            classname=None, admin=1), MappedUsers(name='Joe Student',
+            email='student@example.ed', password='student',
             classname=None, admin=0)])
 
     def test_whereclause(self):
         db = sqlsoup.SQLSoup(engine)
         MappedUsers = db.users
         where = or_(db.users.name == 'Bhargan Basepair', db.users.email
-                    == 'student@example.edu')
+                    == 'student@example.ed')
         users = \
             db.users.filter(where).order_by(desc(db.users.name)).all()
-        eq_(users, [MappedUsers(name=u'Joe Student',
-            email=u'student@example.edu', password=u'student',
+        eq_(users, [MappedUsers(name='Joe Student',
+            email='student@example.ed', password='student',
             classname=None, admin=0),
-            MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
+            MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1)])
 
     def test_first(self):
         MappedUsers = db.users
         user = db.users.filter(db.users.name == 'Bhargan Basepair'
                                ).one()
-        eq_(user, MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
+        eq_(user, MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1))
         db.rollback()
         user = db.users.get('Bhargan Basepair')
-        eq_(user, MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
+        eq_(user, MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1))
         db.rollback()
         user = db.users.filter_by(name='Bhargan Basepair').one()
-        eq_(user, MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
+        eq_(user, MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1))
         db.rollback()
 
         loan = db.loans.filter_by(book_id=2,
                                   user_name='Bhargan Basepair').one()
         eq_(loan, loan_insert)
-        l2 = MappedLoans(book_id=2, user_name=u'Bhargan Basepair',
+        l2 = MappedLoans(book_id=2, user_name='Bhargan Basepair',
                          loan_date=loan.loan_date)
         eq_(loan, l2)
         db.expunge(l2)
         db.users.filter_by(name='Bhargan Basepair'
                            ).update(dict(name='Some New Name'))
         u1 = db.users.filter_by(name='Some New Name').one()
-        eq_(u1, MappedUsers(name=u'Some New Name',
-            email=u'basepair@example.edu', password=u'basepair',
+        eq_(u1, MappedUsers(name='Some New Name',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1))
 
     def test_map_table(self):
         users = Table('users', db._metadata, autoload=True)
         MappedUsers = db.map(users)
         users = MappedUsers.order_by(db.users.name).all()
-        eq_(users, [MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
-            classname=None, admin=1), MappedUsers(name=u'Joe Student',
-            email=u'student@example.edu', password=u'student',
+        eq_(users, [MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
+            classname=None, admin=1), MappedUsers(name='Joe Student',
+            email='student@example.ed', password='student',
             classname=None, admin=0)])
 
     def test_mapped_join(self):
         join1 = MappedJoin = db.join(db.users, db.loans, isouter=True)
         mj = join1.filter_by(name='Joe Student').all()
         eq_(mj, [MappedJoin(
-            name=u'Joe Student',
-            email=u'student@example.edu',
-            password=u'student',
+            name='Joe Student',
+            email='student@example.ed',
+            password='student',
             classname=None,
             admin=0,
             book_id=1,
-            user_name=u'Joe Student',
+            user_name='Joe Student',
             loan_date=datetime.datetime(2006, 7, 12, 0, 0),
             )])
         db.rollback()
         join2 = MappedJoin = db.join(join1, db.books)
         mj = join2.all()
         eq_(mj, [MappedJoin(
-            name=u'Joe Student',
-            email=u'student@example.edu',
-            password=u'student',
+            name='Joe Student',
+            email='student@example.ed',
+            password='student',
             classname=None,
             admin=0,
             book_id=1,
-            user_name=u'Joe Student',
+            user_name='Joe Student',
             loan_date=datetime.datetime(2006, 7, 12, 0, 0),
             id=1,
-            title=u'Mustards I Have Known',
-            published_year=u'1989',
-            authors=u'Jones',
+            title='Mustards I Have Known',
+            published_year='1989',
+            authors='Jones',
             )])
         eq_(db.with_labels(join1).c.keys(), [
-            u'users_name',
-            u'users_email',
-            u'users_password',
-            u'users_classname',
-            u'users_admin',
-            u'loans_book_id',
-            u'loans_user_name',
-            u'loans_loan_date',
+            'users_name',
+            'users_email',
+            'users_password',
+            'users_classname',
+            'users_admin',
+            'loans_book_id',
+            'loans_user_name',
+            'loans_loan_date',
             ])
         labeled_loans = db.with_labels(db.loans)
         eq_(db.join(db.users, labeled_loans, isouter=True).c.keys(), [
-            u'name',
-            u'email',
-            u'password',
-            u'classname',
-            u'admin',
-            u'loans_book_id',
-            u'loans_user_name',
-            u'loans_loan_date',
+            'name',
+            'email',
+            'password',
+            'classname',
+            'admin',
+            'loans_book_id',
+            'loans_user_name',
+            'loans_loan_date',
             ])
 
     def test_relations(self):
         MappedLoans = db.loans
         MappedUsers = db.users
         eq_(db.users.get('Joe Student').loans, [MappedLoans(book_id=1,
-            user_name=u'Joe Student', loan_date=datetime.datetime(2006,
+            user_name='Joe Student', loan_date=datetime.datetime(2006,
             7, 12, 0, 0))])
         db.rollback()
         eq_(db.users.filter(~db.users.loans.any()).all(),
-            [MappedUsers(name=u'Bhargan Basepair',
-            email='basepair@example.edu', password=u'basepair',
+            [MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
             classname=None, admin=1)])
         db.rollback()
         del db._cache['users']
         s = s.alias('years_with_count')
         years_with_count = db.map(s, primary_key=[s.c.published_year])
         eq_(years_with_count.filter_by(published_year='1989').all(),
-            [MappedBooks(published_year=u'1989', n=1)])
+            [MappedBooks(published_year='1989', n=1)])
 
     def test_raw_sql(self):
         db = sqlsoup.SQLSoup(engine)
         rp = db.execute('select name, email from users order by name')
-        eq_(rp.fetchall(), [('Bhargan Basepair', 'basepair@example.edu'
-            ), ('Joe Student', 'student@example.edu')])
+        eq_(rp.fetchall(), [('Bhargan Basepair', 'basepair@example.ed'
+            ), ('Joe Student', 'student@example.ed')])
 
         # test that execute() shares the same transactional context as
         # the session
             [('foo bar', )])
         db.rollback()
         eq_(db.execute('select distinct email from users').fetchall(),
-            [(u'basepair@example.edu', ), (u'student@example.edu', )])
+            [('basepair@example.ed', ), ('student@example.ed', )])
 
     def test_connection(self):
         db = sqlsoup.SQLSoup(engine)
         conn = db.connection()
         rp = conn.execute('select name, email from users order by name')
-        eq_(rp.fetchall(), [('Bhargan Basepair', 'basepair@example.edu'
-            ), ('Joe Student', 'student@example.edu')])
+        eq_(rp.fetchall(), [('Bhargan Basepair', 'basepair@example.ed'
+            ), ('Joe Student', 'student@example.ed')])
 
     def test_entity(self):
         db = sqlsoup.SQLSoup(engine)
         MappedUsers = db.users
         users = \
             db.users.filter_by(classname=None).order_by(db.users.name).all()
-        eq_(users, [MappedUsers(name=u'Bhargan Basepair',
-            email=u'basepair@example.edu', password=u'basepair',
-            classname=None, admin=1), MappedUsers(name=u'Joe Student',
-            email=u'student@example.edu', password=u'student',
+        eq_(users, [MappedUsers(name='Bhargan Basepair',
+            email='basepair@example.ed', password='basepair',
+            classname=None, admin=1), MappedUsers(name='Joe Student',
+            email='student@example.ed', password='student',
             classname=None, admin=0)])
 
     def test_no_pk_reflected(self):
 
 
 _ddl = \
-    u"""
+    """
 CREATE TABLE books (
     id                   integer PRIMARY KEY, -- auto-increments in sqlite
     title                text NOT NULL,
    id int primary key,
    query  varchar(100)
 )
-""".split(';'
-        )
+""".split(';')
+
 _data = \
     """
 insert into users(name, email, password, admin)
-values('Bhargan Basepair', 'basepair@example.edu', 'basepair', 1);
+values('Bhargan Basepair', 'basepair@example.ed', 'basepair', 1);
 insert into users(name, email, password, admin)
-values('Joe Student', 'student@example.edu', 'student', 0);
+values('Joe Student', 'student@example.ed', 'student', 0);
 
 insert into books(title, published_year, authors)
 values('Mustards I Have Known', '1989', 'Jones');