# -*- coding: iso-8859-1 -*-
#-----------------------------------------------------------------------------
# Modeling Framework: an Object-Relational Bridge for python
#
# Copyright (c) 2001-2004 Sbastien Bigaret <sbigaret@users.sourceforge.net>
# All rights reserved.
#
# This file is part of the Modeling Framework.
#
# This code is distributed under a "3-clause BSD"-style license;
# see the LICENSE file for details.
#-----------------------------------------------------------------------------
"""
Database
Defined Constants
'DistantPastTimeInterval': the lowest possible timestamp
Exceptions:
'GeneralDatabaseException'
Notifications:
ObjectStore.ObjectsChangedInStoreNotification
CVS information
$Id: Database.py 932 2004-07-20 06:21:57Z sbigaret $
"""
__version__='$Revision: 932 $'[11:-2]
from time import time
# Framework
import SnapshotsHandling
from logging import trace
from NotificationFramework import NotificationCenter
NC=NotificationCenter
from utils import staticmethod
# Notifications
from Modeling.ObjectStore import ObjectsChangedInStoreNotification
from Modeling.ObjectStore import InvalidatedKey
# Constants
DistantPastTimeInterval = SnapshotsHandling.DistantPastTimeInterval
# Exception
class GeneralDatabaseException(Exception):
pass
## Do not access this variable directly ; please remember that there is no
## way to re-enable snapshot refcounting after it has been disabled
__isSnapshotRefCountingEnabled=1
from threading import RLock
isSnapshotRefCountingEnabled_lock=RLock()
lock=isSnapshotRefCountingEnabled_lock.acquire
unlock=isSnapshotRefCountingEnabled_lock.release
# ``static methods''
def databaseForAdaptor(anAdaptor):
"Database factory -- Equivalent to 'Database(anAdaptor=anAdaptor)'"
return Database(anAdaptor=anAdaptor)
def databaseForModel(aModel):
"Database factory -- Equivalent to 'Database(aModel=aModel)'"
return Database(aModel=aModel)
def isSnapshotRefCountingEnabled():
"""
Tells whether snapshot refCounting is enabled in 'Databases' instances.
Note that once it has been disabled, the snapshot refcounting **cannot** be
re-enabled.
"""
lock()
try:
return __isSnapshotRefCountingEnabled
finally:
unlock()
def disableSnapshotRefCounting():
"""
Disables the snapshot refcounting in 'Databases' instances. Note that once
it has been disabled, the snapshot refcounting **cannot** be re-enabled.
"""
lock()
try:
global __isSnapshotRefCountingEnabled
__isSnapshotRefCountingEnabled=0
finally:
unlock()
from Modeling.utils import base_object
class Database(base_object):
"""
Key features:
- corresponds to one DB server
- holds snapshots for the whole app.
- cache for cached entities
Snapshots and timestamps
While a Database object holds the snapshots and
their timestamp, it is not the Database object's responsability to make
decisions on whether a snapshot should be updated in a particular
situation, or whatever decisions of that kind. Instead, other methods, such
as AdaptorChannel.fetcObject() (refer to the documentation), make such
decisions and then inform the Database (e.g. by actually recording
snapshots)
Snapshots and referenceCounting:
__TBD
Snapshots related methods
- decrementSnapshotCountForGlobalID
- forgetAllSnapshots
- forgetSnapshotForGlobalID
- forgetSnapshotsForGlobalIDs
- incrementSnapshotCountForGlobalID
- recordSnapshotForGlobalID
- recordSnapshotForSourceGlobalID (toMany snapshots)
- recordSnapshots
- recordToManySnapshots (toMany snapshots)
- setTimestampToNow
- snapshotForGlobalID
- snapshotForSourceGlobalID (toMany snapshots)
- snapshots
"""
## __TBD Implementation Note:
## __TBD This class needs a lock per instance, since it is designed to be
## __TBD called e.g. by any object needing snapshots
# Static methods
databaseForAdaptor=staticmethod(databaseForAdaptor)
databaseForModel=staticmethod(databaseForModel)
isSnapshotRefCountingEnabled=staticmethod(isSnapshotRefCountingEnabled)
disableSnapshotRefCounting=staticmethod(disableSnapshotRefCounting)
# /end static
def __init__(self, anAdaptor=None, aModel=None):
"""
Initializer for Database. Parameters 'anAdaptor' and 'aModel' are
mutually exclusive: one, and only one, must be supplied at
initialization time. If this condition is not fulfilled 'AttributeError'
is raised.
"""
trace('anAdaptor=%s aModel=%s'%(anAdaptor, aModel))
self.__instanceLock=RLock()
if (anAdaptor is not None and aModel is not None) or\
(anAdaptor is None and aModel is None):
raise AttributeError, 'Database initializer accepts one and only one '\
'parameter'
self._models=[]
self._dbContexts=[]
self.__snapshots=Database.SnapshotsTable()
#self.__snapshots={} # GlobalID -> snapshot (dictionary)
#self.__snapshotsRefCount={} # GlobalID -> refCount
#self._timestamps={} # GlobalID -> timestamp
if anAdaptor is not None:
self._adaptor=anAdaptor
else:
self._models.append(aModel)
from Modeling.Adaptor import adaptorWithModel
self._adaptor=adaptorWithModel(aModel)
# initializes the adaptor
connDict=aModel.connectionDictionary()
trace('Initializing Adaptor %s with connectionDict: %s'\
%(repr(self._adaptor), str(connDict)))
self._adaptor.setConnectionDictionary(connDict)
def adaptor(self):
"""
Returns the underlying 'Adaptor' object
"""
self.lock()
try:
return self._adaptor
finally:
self.unlock()
def addModel(self, aModel):
"""
Shortcut for 'addModelIfCompatible'
"""
self.lock()
try:
return self.addModelIfCompatible(aModel)
finally:
self.unlock()
def addModelIfCompatible(self, aModel):
"""
Before adding the model to the Database object, checks whether:
- 'aModel' 's adaptorName is the same than previously registered models'
- the underlying adaptor answers positively to message 'canServiceModel'
for 'aModel'
If one of these checks fails, 'aModel' is not added and the method returns
'0' (zero, i.e. false). Otherwise returns '1' (true) and adds 'aModel' to
the list of registered models (if 'aModel' was already registered, it is
not re-inserted but still, '1' is returned).
"""
self.lock()
try:
if aModel in self._models:
return 1
if not self._adaptor.canServiceModel(aModel):
return 0
if self._models and self.models[0].adaptorName()!=aModel.adaptorName():
return 0
self._models.append(aModel)
return 1
finally:
self.unlock()
def decrementSnapshotCountForGlobalID(self, aGlobalID):
"""
Decrement the corresponding snapshot's refCount ; if the refCount reaches
0 (zero) after decrementation, the corresponding snapshot is deleted.
If snapshot refcounting is disabled, this method does nothing.
This method gets automatically called
(see DatabaseContext.editingContextDidForgetObjectWithGlobalID())
"""
self.lock()
try:
trace('decrement %s'%str(aGlobalID))
self.__snapshots.decrementSnapshotCountForGlobalID(aGlobalID)
finally:
self.unlock()
def entityForObject(self, aDatabaseObject):
"""
"""
self.lock()
try:
for model in self._models:
entity=model.entityForObject(aDatabaseObject)
if entity: return entity
return None
finally:
self.unlock()
def entityNamed(self, entityName):
"""
Searches for the corresponding 'Entity' in the registered models and
returns it, or 'None' if it cannot be found.
"""
self.lock()
try:
for model in self._models:
entity=model.entityNamed(entityName)
if entity: return entity
return None
finally:
self.unlock()
def forgetAllSnapshots(self):
"""
"""
self.lock()
try:
_notifDict={InvalidatedKey: self.__snapshots.globalIDs()}
self.__snapshots.forgetAllSnapshots()
NC.postNotification(ObjectsChangedInStoreNotification,
self, _notifDict)
finally:
self.unlock()
def forgetSnapshotForGlobalID(self, aGlobalID):
"""
Removes the snapshot registered for 'aGlobalID'. Raises 'ValueError' if
no snapshots were registered for 'aGlobalID'
"""
self.lock()
try:
#self.__snapshots.incrementSnapshotCountForGlobalID(aGlobalID)
NC.postNotification(ObjectsChangedInStoreNotification,
self, {InvalidatedKey: aGlobalID})
finally:
self.unlock()
def forgetSnapshotsForGlobalIDs(self, globalIDs):
"""
Removes the snapshots registered for 'globalIDs'. Raises 'ValueError' if
no snapshots were registered for at least one of GlobalID among
'globalIDs' ; WARNING: in that case, it is possible that some snapshots
get actually forgotten before the exception is raised.
"""
self.lock()
try:
for gID in globalIDs:
self.forgetSnapshotForGlobalID(gID)
NC.postNotification(ObjectsChangedInStoreNotification,
self, {InvalidatedKey: globalIDs})
finally:
self.unlock()
def handleDroppedConnection(self):
"""
"""
self.lock()
try:
self._adaptor.handleDroppedConnection()
for context in self._dbContexts:
context.handleDroppedConnection()
finally:
self.unlock()
def incrementSnapshotCountForGlobalID(self, aGlobalID):
"""
Increment the refCount for the corresponding snapshot by one.
If snapshot refcounting is disabled, this method does nothing.
"""
self.lock()
try:
trace('increment %s'%str(aGlobalID))
self.__snapshots.incrementSnapshotCountForGlobalID(aGlobalID)
finally:
self.unlock()
def invalidateResultCache(self):
"""
Entity Caching is not supported yet
"""
self.lock()
try:
self.__unimplemented__()
finally:
self.unlock()
def invalidateResultCacheForEntityNamed(self, aName):
"""
Entity Caching is not supported yet
"""
self.lock()
try:
self.__unimplemented__()
finally:
self.unlock()
def lock(self):
"""
Releases the lock for this Database object
"""
self.__instanceLock.acquire()
def models(self):
"""
Returns the list of models managed by this 'Database' object
"""
self.lock()
try:
return tuple(self._models)
finally:
self.unlock()
def recordSnapshotForGlobalID(self, snapshot, aGlobalID):
"""
Records 'snapshot' for 'aGlobalID' ; the snapshot is time-stamped
using the so-called current timestamp (see setTimestampToNow(), which is
called by this method, as a side-effect)
"""
self.lock()
try:
self.__snapshots.recordSnapshotForGlobalID(snapshot, aGlobalID)
finally:
self.unlock()
def recordSnapshotForSourceGlobalID(self, gids, aGlobalID, aName):
"""
"""
self.lock()
try:
self.__snapshots.recordSnapshotForSourceGlobalID(gids, aGlobalID, aName)
finally:
self.unlock()
def recordSnapshots(self, snapshots):
"""
Records the supplied snapshots.
The snapshots are time-stamped using the current timestamp (calls
setTimestampToNow())
Parameter:
snapshots -- a dictionary whose keys are 'GlobalID' and
values=corresponding snapshots
"""
self.lock()
try:
self.__snapshots.recordSnapshots(snapshots)
finally:
self.unlock()
def recordToManySnapshots(self, snapshots):
"""
Records the snapshots for a toMany relationship.
Parameter:
snapshots -- a dictionary with GlobalIDs as keys and dictionary as
values, the latter dictionary having relationships' names as keys and a
list of GlobalIDs as values.
"""
self.lock()
try:
self.__snapshots.recordToManySnapshots(snapshots)
finally:
self.unlock()
def registerContext(self, aDBContext):
"""
Registers the supplied 'DatabaseContext' in the receiver.
Silently returns if 'aDBContext' was already registered.
"""
self.lock()
try:
if aDBContext not in self._dbContexts:
self._dbContexts.append(aDBContext)
finally:
self.unlock()
def registeredContexts(self):
"""
Returns the registered 'DatabaseContext' objects
"""
self.lock()
try:
return tuple(self._dbContexts)
finally:
self.unlock()
def removeModel(self, aModel):
"""
Remove 'aModel' from the list of models this Database object services.
"""
self.lock()
try:
self._models.remove(aModel)
finally:
self.unlock()
def resultCacheForEntityNamed(self, aName):
"""
Entity Caching is not supported yet
"""
self.lock()
try:
self.__unimplemented__()
finally:
self.unlock()
def setResultCache(self, cache, aName):
"""
Entity Caching is not supported yet
"""
self.lock()
try:
self.__unimplemented__()
finally:
self.unlock()
def setTimestampToNow(self):
"""
Sets the current timestamp to 'time.time()', so that snapshots
subsequently recorded are tagged with that current timestamp.
"""
self.lock()
try:
self.__snapshots.setTimestampToNow()
finally:
self.unlock()
def snapshotCountForGlobalID(self, aGlobalID):
"""
See also: incrementSnapshotCountForGlobalID,
decrementSnapshotCountForGlobalID()
"""
return self.__snapshots.snapshotCountForGlobalID(aGlobalID)
def snapshotForGlobalID(self, aGlobalID, timestamp=DistantPastTimeInterval):
"""
Returns the registered snapshot for the supplied GlobalID, if any.
Returns 'None' if none can be found, or if the registered snapshot's
timestamp is lower than the supplied one.
"""
self.lock()
try:
return self.__snapshots.snapshotForGlobalID(aGlobalID, timestamp)
finally:
self.unlock()
def snapshotForSourceGlobalID(self, aGlobalID, aName,
timestamp=DistantPastTimeInterval):
"""
"""
self.lock()
try:
return self.__snapshots.snapshotForSourceGlobalID(aGlobalID, aName, timestamp)
finally:
self.unlock()
def snapshots(self):
"""
Returns a dictionary containing all registered snapshots, where keys
are 'GlobalIDs' and values=the corresponding snapshot.
"""
self.lock()
try:
return self.__snapshots.snapshots()
finally:
self.unlock()
def timestampForGlobalID(self, aGlobalID):
"""
Returns the current timestamp assigned to the snapshot for 'aGlobalID',
or 'DistantPastTimeInterval' if no snapshot exists for 'aGlobalID'.
"""
self.lock()
try:
return self.__snapshots.timestampForGlobalID(aGlobalID)
finally:
self.unlock()
def timestampForSourceGlobalID(self, aGlobalID, aName):
"""
Returns the current timestamp assigned to the snapshot for 'aGlobalID',
or 'DistantPastTimeInterval' if no snapshot exists for 'aGlobalID'.
"""
self.lock()
try:
return self.__snapshots.timestampForSourceGlobalID(aGlobalID, aName)
finally:
self.unlock()
def unlock(self):
"""
Releases the lock for this Database object
"""
self.__instanceLock.release()
def unregisterContext(self, aDBContext):
"""
Unregisters the supplied DatabaseContext from the receiver.
Raises 'ValueError'
"""
self.lock()
try:
self._dbContexts.remove(aDBContext)
finally:
self.unlock()
def __unimplemented__(self):
"Raises Unimplemented..."
raise 'Unimplemented', 'Not supported yet'
class SnapshotsTable(SnapshotsHandling.SnapshotsTable):
"""
Internally used to handle snapshots, so that this is handled as a whole
Most methods are left undocumented here since they actually perform what
their corresponding methods in 'Database' claim to do.
"""
def isSnapshotRefCountingEnabled(self):
"""
Overrides 'SnapshotsHandling.SnapshotsTable.disableSnapshotRefCounting()'
so that thios functionality is bound to the module's method
'isSnapshotRefCountingEnabled()'
"""
return isSnapshotRefCountingEnabled()
def disableSnapshotRefCounting(self):
"""
Overrides 'SnapshotsHandling.SnapshotsTable.disableSnapshotRefCounting()'
and raises unconditionnally since this functionality is controlled at
module level.
See: module's 'disableSnapshotRefCounting()'
"""
raise RuntimeWarning, "shouldn't be called, use module Database's"\
"dedicated method instead"
|