########################################################################
#
# File Name:            Dbm.py
#
# Documentation:        http://docs.4suite.org/4Rdf/Drivers/Dbm.py.html
#
"""
A simple persistent back end
WWW: http://4suite.org/4RDF         e-mail: support@4suite.org

Copyright (c) 1999,2000 Fourthought Inc, USA.   All Rights Reserved.
See  http://4suite.org/COPYRIGHT  for license and copyright information
"""

from Ft.Rdf.Drivers import Memory
from Ft.Lib import DbmDatabase

# Management functions
def ExistsDb(dbName):
    name = 'ft__%s' % dbName
    if name in DbmDatabase.GetAllDatabaseNames():
        db = DbmDatabase.Database(name)
        if filter(lambda x:x[:6] == 'ftrdf_', db.getAllTableNames()):
            return 1
    return 0
        

def CreateDb(dbName):
    name = 'ft__%s' % dbName
    if name not in DbmDatabase.GetAllDatabaseNames():
        db = DbmDatabase.CreateDatabase(name)
    else:
        db = DbmDatabase.Database(name)
        
    db.createTable('ftrdf_bindings')
    statements = db.createTable('ftrdf_statements')
    statements['unsorted'] = []
    db.commit()
    return DbAdapter(dbName)

def GetDb(dbName):
    return DbAdapter(dbName)

def DestroyDb(dbName):
    name = 'ft__%s' % dbName
    db = DbmDatabase.Database(name)
    for tn in db.getAllTableNames():
        if tn[:6] == 'ftrdf_':
            db.dropTable(tn)

# The RDF Adapter interface
class DbAdapter(Memory.DbAdapter):
    def __init__(self, name):
        self._name = 'ft__%s' % name
        self._db = None

    def begin(self):
        self._db = DbmDatabase.Database(self._name)
        self._statements = self._db.getTable('ftrdf_statements')['unsorted']
        self._bound = self._db.getTable('ftrdf_bindings')
        return

    def commit(self):
        self._db.getTable('ftrdf_statements')['unsorted'] = self._statements
        self._db.commit()
        self._db = None
        return

    def rollback(self):
        self._db.rollback()
        self._db = None
        return
