Source

jython-db4o / db4o / db4o.py

Full commit
'''Lowlevel db4o access, returning native db4o objects
requres: db4o jar in the classpath
'''
__author__ = 'Sean Summers <SeanSummers@gmail.com>'

BLACKLIST = ('java.', 'com.db4o.')

import com.db4o.config.ConfigScope
import com.db4o.Db4oEmbedded.newConfiguration
import com.db4o.Db4oEmbedded.openFile
import com.db4o.internal.StoredClassImpl

def readonlyConfiguration():
    ''' create a read only DB4O configuration object (to feed db()) '''
    config = com.db4o.Db4oEmbedded.newConfiguration()
    cf = config.file()
    cf.readOnly(True)
    cf.lockDatabaseFile(False)
    cf.recoveryMode(True)
    try:
        cf.generateCommitTimestamps(True) # >=8.0
    except AttributeError:
        cf.generateVersionNumbers(com.db4o.config.ConfigScope.GLOBALLY)   # <8.0
    cf.generateUUIDs(com.db4o.config.ConfigScope.GLOBALLY)
    co = config.common()
    co.callbacks(False)
    co.callConstructors(False) ## ??
    co.detectSchemaChanges(False)
    co.testConstructors(False)
    try: # >=8.0
        cid = config.idSystem()
        cid.useStackedBTreeSystem()
    except:
        pass
    return config

def db(db4ofilename, db4oConfig = None):
    ''' return db4o container for a file, optionally with a configuration (readonly, if not provided) '''
    if not db4oConfig: db4oConfig = readonlyConfiguration()
    return com.db4o.Db4oEmbedded.openFile(db4oConfig, db4ofilename)

def dbClasses(db, blacklist = BLACKLIST):
    ''' generate StoredClass list for a given db4o container, filtering out blacklist '''
    return (c for c in db.storedClasses() if not c.name.startswith(blacklist))

def objClass(db, o):
    ''' return StoredClass for a given class name '''
    return o if isinstance(o, com.db4o.internal.StoredClassImpl) else db.storedClass(o)

def objClassFields(db, o):
    ''' return instance fields for a given StoredClass '''
    return objClass(db, o).storedFields

def objClasspath(db, o):
    ''' generate full class lineage for a given StoredClass '''
    c = objClass(db, o)
    while c:
        yield c
        c = c.parentStoredClass

def objFields(db, o):
    ''' return all fields for a given StoredClass (including parent fields [heritage order]) '''
    fields = []
    [fields.extend(cls.storedFields) for cls in reversed(tuple(objClasspath(db, o)))]
    return tuple(fields)

def objByID(db, oid, depth = 2):
    ''' return an activated object by ID '''
    obj = db.getByID(oid)
    db.activate(obj, depth)
    return obj

def objAll(db):
    ''' return all objects stored in this container '''
    return db.queryByExample(None)

def objIDs(db, o = None):
    ''' return a list of all object IDs in this container, for a specified class (or all) '''
    return objClass(db, o).IDs
    
def objCount(db, o = None):
    ''' return a count of objects in this container, for a specified class (or all) '''
    return len(objIDs(db, o) if o else objAll(db).IDs)