from Ft.Server.Server import FtServerServerException, Error
from Ft.Server.Common import ResourceTypes
from Ft.Server import FTSERVER_NAMESPACE
from Ft.Xml.XLink import XLINK_NAMESPACE
from Ft.Server.Server.Drivers.FtssDriver import DataStoreContainer

FTSS_CONTAIMENT_TABLE = 'ftss_containment'

class PostgresContainer(DataStoreContainer):
    """
    Implements simple containment as a table in Postgres:
    
    parent   /  child
    ------------------
    /parent1 |  child1
    /parent2 |  child2
    """
    def __init__(self,db):
        """
        Used if instanciated directly in order to do initialization
        """
        self._db = db
    
    def initialize(self):
        """
        Initialize the table
        """                
        self._db.query("CREATE TABLE %s (parent text, child text)"%(FTSS_CONTAIMENT_TABLE))
        self._db.query("CREATE UNIQUE INDEX %s_PC_idx ON %s (parent,child)"%(FTSS_CONTAIMENT_TABLE,FTSS_CONTAIMENT_TABLE))
        self._db.query("CREATE INDEX %s_P_idx ON %s (parent)"%(FTSS_CONTAIMENT_TABLE,FTSS_CONTAIMENT_TABLE))
    
    def fetchChildren(self,parent):
        """
        Returns a list of child uris for the given parent.  Parent is a PathImp
        """
        try:
            data = self._db.query("SELECT child FROM %s WHERE parent = '%s'"%(FTSS_CONTAIMENT_TABLE,parent.absolutePath)).getresult()
        except AttributeError:
            return []
        if not data:
            return []
        return [dataItem[0] for dataItem in data]
        
    def manageChildren(self,parent,child,add=True):
        """
        Adds/remove the child specified by the given path to the parent (path - a PathImp)
        """
        if add:
            self._db.query("INSERT INTO %s (parent,child) VALUES ('%s','%s')"%(FTSS_CONTAIMENT_TABLE,parent.absolutePath,child))
        else:            
            self._db.query("DELETE FROM %s where parent = '%s' and child = '%s'"%(FTSS_CONTAIMENT_TABLE,parent.absolutePath,child))
        
