[z3-checkins] r27040 - in z3/sqlos/branch/jinty-sqlobject2/src/sqlos: . interfaces

jinty at codespeak.net jinty at codespeak.net
Wed May 10 12:48:33 CEST 2006


Author: jinty
Date: Wed May 10 12:48:30 2006
New Revision: 27040

Added:
   z3/sqlos/branch/jinty-sqlobject2/src/sqlos/interfaces.py   (contents, props changed)
Removed:
   z3/sqlos/branch/jinty-sqlobject2/src/sqlos/adapter.py
   z3/sqlos/branch/jinty-sqlobject2/src/sqlos/interfaces/
Modified:
   z3/sqlos/branch/jinty-sqlobject2/src/sqlos/__init__.py
   z3/sqlos/branch/jinty-sqlobject2/src/sqlos/connection.py
   z3/sqlos/branch/jinty-sqlobject2/src/sqlos/zsqlobject.py
Log:
Armageddon - Rip out stuff thats not going to be useful with SQLObject2. Of course that leaves this branch completely broken.

Modified: z3/sqlos/branch/jinty-sqlobject2/src/sqlos/__init__.py
==============================================================================
--- z3/sqlos/branch/jinty-sqlobject2/src/sqlos/__init__.py	(original)
+++ z3/sqlos/branch/jinty-sqlobject2/src/sqlos/__init__.py	Wed May 10 12:48:30 2006
@@ -9,25 +9,3 @@
 """
 $Id$
 """
-
-from datetime import datetime, date
-from sqlobject.sqlbuilder import registerConverter
-
-# sqlos.SQLOS is softly deprecated, will go away sometime
-# (after at least one major release with deprecation warnings)
-# import directly from sqlos.zsqlobject
-from sqlos.zsqlobject import SQLOS
-
-
-## XXX: What are these?? I am sure there are no tests for them. - jinty
-def DateTimeConverter(value, db=None):
-    return repr(value.isoformat())
-
-registerConverter(datetime, DateTimeConverter)
-
-def DateConverter(value, db=None):
-    if isinstance(value, datetime):
-        return repr(value.date().isoformat())
-    return repr(value.isoformat())
-
-registerConverter(date, DateConverter)

Deleted: /z3/sqlos/branch/jinty-sqlobject2/src/sqlos/adapter.py
==============================================================================
--- /z3/sqlos/branch/jinty-sqlobject2/src/sqlos/adapter.py	Wed May 10 12:48:30 2006
+++ (empty file)
@@ -1,162 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004 Enfold Systems LLC. All rights reserved.
-# Copyright (c) 2005-2006 Brian Sutherland. All rights reserved.
-#
-# This software is distributed under the terms of the Zope Public
-# License (ZPL) v2.1. See COPYING.txt for more information.
-#
-##############################################################################
-"""Connection adapters for sqlos.
-
-These adapters adapt Zope RDB Connections to SQLObject connections by
-sub-classing the SQLObject connection classes.
-
-$Id$
-"""
-
-__metaclass__ = type
-
-from sqlobject.dbconnection import DBAPI
-from sqlobject import _mysql, _postgres, _sqlite
-from sqlobject.converters import registerConverter
-from sqlobject.mysql import mysqlconnection
-from zope.app.rdb.interfaces import DatabaseException
-from zope.app.container.interfaces import INameChooser
-from zope.interface import implements
-
-from sqlos.interfaces import ISQLObject
-from sqlos._transaction import cache_manager
-
-# TODO: it is probably possible to optimize this by not creating a
-# ConnectionAdapter every adapter lookup, but rather caching one per thread,
-# and stuffing the connection into it using a factory function. Probably there
-# would be one factory function per adapter type and we could get rid of the
-# cache property on the ConnectionAdapter.
-
-class ConnectionAdapter:
-
-    def __init__(self, connection):
-        DBAPI.__init__(self)
-        self._connection = connection
-        self.autoCommit = None
-        self.debug = 0
-        self.supportTransactions = False
-
-    def _get_cache(self):
-        return cache_manager.cache
-    def _set_cache(self, val):
-        pass # don't let ourselves be overridden
-    cache = property(_get_cache, _set_cache)
-
-    def makeConnection(self):
-        return self._connection
-
-    def getConnection(self):
-        # we override this because we really don't care about sqlobjects idea
-        # of threadsafe pool of db connections. zope.app.rdb takes care of
-        # that for us
-        return self.makeConnection()
-
-    def releaseConnection(self, conn, explicit=False):
-        # we simply lobotomize this method because zope.app.rdb
-        # takes care of all commits/rollbacks as well as all threading issues
-        # with connections
-        pass
-
-    def close(self):
-        # there is no sane way of doing this I can see. It would be nice to
-        # raise an error here, but sqlobject.dbconnection registers this method
-        # to be called when python exits.
-        pass
-
-    def _executeRetry(self, conn, cursor, query):
-        try:
-            return cursor.execute(query)
-        except Exception, exc:
-            raise DatabaseException(str(exc.args))
-
-    def _runWithConnection(self, meth, *args):
-        conn = self.getConnection()
-        try:
-            try:
-                val = meth(conn, *args)
-            except DatabaseException:
-                raise # We may have already raised Database exception in
-                      # _executeRetry, so we re-raise it
-            except Exception, exc:
-                raise DatabaseException, tuple(exc.args)
-        finally:
-            self.releaseConnection(conn)
-        return val
-
-    def printDebug(self, conn, s, name, type='query'):
-        # XXX this is a quick hack to get it to work - jinty
-        if name == 'Pool' and self.debug != 'Pool':
-            return
-        if type == 'query':
-            sep = ': '
-        else:
-            sep = '->'
-            s = repr(s)
-        spaces = ' '*(8-len(name))
-        if self.debugThreading:
-            threadName = threading.currentThread().getName()
-            threadName = (':' + threadName + ' '*(8-len(threadName)))
-        else:
-            threadName = ''
-        print '%(threadName)s/%(name)s%(spaces)s%(sep)s %(s)s' % locals()
-
-
-class MySQLAdapter(ConnectionAdapter, _mysql.builder()):
-
-    def __init__(self, connection):
-        if getattr(self, 'module', None) == None:
-            import MySQLdb
-            self.module = MySQLdb
-            mysqlconnection.MySQLdb = MySQLdb
-        super(MySQLAdapter, self).__init__(connection)
-
-    def _executeRetry(*args, **kw):
-        try:
-            return mysqlconnection.MySQLConnection._executeRetry(*args, **kw)
-        except Exception, exc:
-            raise DatabaseException(str(exc.args))
-
-
-class PostgresAdapter(ConnectionAdapter, _postgres.builder()):
-
-    def __init__(self, connection):
-        #The import is needed, as sqlobject uses self.module.Binary uppon
-        #startup. But until now we dont define .module. There is definitely
-        #need for a better solution. Propably the other adapters need this as
-        #well, but i cant test them, as i dont have them.
-        #Andres Freund - 2005-10-17
-        if getattr(self, 'module', None) == None:
-            import psycopg
-            self.module = psycopg
-            #This is needed, because psycopg provides a optimized
-            #Binary() function which sqlobject dont get along with. This is
-            #normally done in sqlobject.postgres.pgconnection __init__ but we
-            #dont call that.
-            from sqlobject.postgres import pgconnection
-            registerConverter(type(psycopg.Binary('')),
-                              pgconnection.PsycoBinaryConverter)
-
-
-        super(PostgresAdapter, self).__init__(connection)
-        self.supportTransactions = True
-
-
-class SQLiteAdapter(ConnectionAdapter, _sqlite.builder()):
-
-    def __init__(self, connection):
-        #see above
-        if getattr(self, 'module', None) == None:
-            try:
-                from pysqlite2 import dbapi2 as sqlite
-            except ImportError:
-                import sqlite
-            self.module  = sqlite
-        super(SQLiteAdapter, self).__init__(connection)
-        self.supportTransactions = True

Modified: z3/sqlos/branch/jinty-sqlobject2/src/sqlos/connection.py
==============================================================================
--- z3/sqlos/branch/jinty-sqlobject2/src/sqlos/connection.py	(original)
+++ z3/sqlos/branch/jinty-sqlobject2/src/sqlos/connection.py	Wed May 10 12:48:30 2006
@@ -10,26 +10,12 @@
 """
 Connection management.
 
-This module defines the connection descriptor used as the connection in a
-a sqlos SQLObject. This is responsible for getting the Zope connection and
-adapting it to look like a SQLObject connection.
-
-Connections are cached as experience has shown that all the utility and
-adapter utilities have a significant effect on speed.
-
 $Id: factory.py 5216 2004-06-21 18:33:07Z dreamcatcher $
 """
 __metaclass__ = type
 
-import warnings
-
-from zope.component import ComponentLookupError
-import zope.component
-from zope.app.rdb.interfaces import IZopeDatabaseAdapter
 from zope.thread import local
 
-from sqlos.interfaces import IZopeSQLConnection, IConnectionName
-
 class ConnectionCache(local):
     """A per thread cache for adapted connections."""
 
@@ -72,43 +58,3 @@
         True
     """
     conn_cache.clear()
-
-
-class SQLObjectWarning(UserWarning):
-    pass
-
-
-class ConnectionDescriptor:
-
-    def __init__(self, name=None):
-        self.name = name
-
-    def __get__(self, inst, cls=None):
-        # get and cache the connection name
-        name = self.name
-        if name is None:
-            try:
-                ut = zope.component.getUtility(IConnectionName)
-            except ComponentLookupError:
-                return self
-            if ut is None:
-                warnings.warn("Couldn't find ISQLConnectionName utility. "
-                              "Please verify your setup.",
-                              SQLObjectWarning, 2)
-                return
-            name = ut.name
-        # try get the connection from the cache, or make a new one
-        conn = conn_cache.queryConnection(name)
-        if conn is None:
-            zda = zope.component.getUtility(IZopeDatabaseAdapter, name)
-            try:
-                conn = IZopeSQLConnection(zda())
-            except ComponentLookupError:
-                return self
-            conn_cache.setConnection(name, conn)
-        return conn
-
-    def __set__(self, inst, value):
-        # Ignore, so we don't get overriden.
-        # We always use the connections from the IZopeDatabaseAdapter utility.
-        pass

Added: z3/sqlos/branch/jinty-sqlobject2/src/sqlos/interfaces.py
==============================================================================
--- (empty file)
+++ z3/sqlos/branch/jinty-sqlobject2/src/sqlos/interfaces.py	Wed May 10 12:48:30 2006
@@ -0,0 +1,80 @@
+##############################################################################
+#
+# Copyright (c) 2004 Enfold Systems LLC. All rights reserved.
+#
+# This software is distributed under the terms of the Zope Public
+# License (ZPL) v2.1. See COPYING.txt for more information.
+#
+##############################################################################
+"""
+$Id: adapter.py 5212 2004-06-21 18:09:05Z philikon $
+"""
+
+from zope.schema import TextLine
+from zope.interface import Interface, Attribute
+from zope.interface import Attribute
+from zope.app.container.constraints import ItemTypePrecondition
+from zope.app.annotation.interfaces import IAttributeAnnotatable
+from zope.app.container.interfaces import IContainerNamesContainer
+from zope.app.container.interfaces import IReadContainer, IContainer
+
+class ISQLObjectReadContainer(IReadContainer, IAttributeAnnotatable):
+    """ An SQLObject Container """
+
+
+class ISQLObjectContainer(IContainer, IContainerNamesContainer,
+                          IAttributeAnnotatable):
+    """ An SQLObject Container """
+
+    def __setitem__(name, obj):
+        """Add a new object"""
+
+    __setitem__.precondition = ItemTypePrecondition()
+
+
+class IIsolatedSQLContainer(ISQLObjectContainer):
+    # TODO Attribute -> zope.schema.* - jinty
+    container_id = Attribute("The id of the containers, this is a filter on the"
+                             "database table.")
+
+    
+class IConnectionName(Interface):
+    """A marker interface for providing a connection name"""
+
+    name = TextLine(
+        title=u"Connection Name",
+        required=True
+        )
+
+    
+class IISQLObject(IReadSQLObjectClass, IWriteSQLObjectClass):
+    """Class methods for SQLObject classes."""
+
+
+class IISQLObjectIsolated(IISQLObject):
+    """Support for using this class in isolated containers.
+
+    This interface is necessary to move the SQL query logic to the SQLOS class
+    as it can be implemented in various ways in the class.
+    """
+
+    def countByDomain(domain):
+        """Return the number of objects which are in the domain."""
+
+    def selectByDomain(domain):
+        """Returns an iterator of objects in the domain.
+
+        similar to select()
+        """
+
+
+class ISQLObject(Interface):
+    """Marker interface for SQLObjects.
+    
+    Hopefully one day this will be a real interface in SQLObject.
+    """
+    
+    
+class ISQLObjectIsolated(ISQLObject):
+
+    domains = Attribute("A _tuple_ of containers_ids which contain this object")

Modified: z3/sqlos/branch/jinty-sqlobject2/src/sqlos/zsqlobject.py
==============================================================================
--- z3/sqlos/branch/jinty-sqlobject2/src/sqlos/zsqlobject.py	(original)
+++ z3/sqlos/branch/jinty-sqlobject2/src/sqlos/zsqlobject.py	Wed May 10 12:48:30 2006
@@ -24,64 +24,3 @@
         >>> syncUpdateAll()
     """
     _transaction.dirty_object_registry.syncUpdateAll()
-
-
-class SQLOS(SQLObject):
-    """Subclass SQLObject to enable ``lazy updates`` by default,
-    as well as adding knowledge to register ``dirty`` objects
-    with SQLObjectTransactionManager so they get sync'd on transaction
-    boundaries.
-
-    First, make a test data base:
-
-        >>> from sqlos import testing
-        >>> testdb = testing.TestDB([SQLOS])
-
-    Test the interface:
-
-        >>> s = SQLOS()
-        >>> from zope.interface.verify import verifyObject
-        >>> verifyObject(ISQLObject, s)
-        True
-
-    And finally call tearDown and cleanup:
-
-        >>> testdb.tearDown()
-    """
-    implements(ISQLObject)
-    _connection = ConnectionDescriptor()
-
-    class sqlmeta:
-        lazyUpdate = True
-
-    def _set_dirty(self, value):
-        if value:
-            _transaction.dirty_object_registry.register(self)
-        self._dirty = value
-
-    def _get_dirty(self):
-        return self._dirty
-
-    dirty = property(_get_dirty, _set_dirty)
-
-    def get(self, id, connection=None, selectResults=None):
-        # While interacting with zope, we may end up having
-        # objects in the cache that have a __parent__ set.
-        # This may be confusing when expect to get a object
-        # which has no __parent__ and thats not what you get.
-        val = super(SQLOS, self).get(id, connection=connection,
-                                    selectResults=selectResults)
-        if getattr(val, '__parent__', None) is not None:
-            val.__parent__ = None
-            val.__name__ = None
-        return val
-    get = classmethod(get)
-
-    def __repr__(self):
-        return '<%s at 0x%x>' % (self.__class__.__name__, id(self))
-
-    def setConnection(self, connection):
-        if connection is not None:
-            self._connection = connection
-
-    setConnection = classmethod(setConnection)


More information about the z3-checkins mailing list