
package performa.orm;

import java.io.*;
import java.util.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import oneit.logging.*;
import oneit.objstore.*;
import oneit.objstore.assocs.*;
import oneit.objstore.rdbms.*;
import oneit.objstore.utils.*;
import oneit.sql.*;
import oneit.utils.resource.*;
import oneit.utils.*;
import oneit.utils.threading.*;



/**
 * IMPORTANT!!!! Autogenerated class, DO NOT EDIT!!!!!
 * Template: Infrastructure8.2[oneit.objstore.PersistenceMgrTemplate.xsl]
 */
public class AttachmentPersistenceMgr extends ObjectPersistenceMgr
{
    private static final LoggingArea AttachmentPersistence = LoggingArea.createLoggingArea(ObjectPersistenceMgr.OBJECT_PERSISTENCE, "Attachment");

    // Private attributes corresponding to business object data
    private String dummyAttachmentName;
    private BinaryContent dummyAttachmentFile;
    

    // Static constants corresponding to attribute helpers
    private static final DefaultAttributeHelper HELPER_AttachmentName = DefaultAttributeHelper.INSTANCE;
    private static final BLOBAttributeHelper HELPER_AttachmentFile = BLOBAttributeHelper.INSTANCE;
    



    public AttachmentPersistenceMgr ()
    {
        dummyAttachmentName = (String)(HELPER_AttachmentName.initialise (dummyAttachmentName));
        dummyAttachmentFile = (BinaryContent)(HELPER_AttachmentFile.initialise (dummyAttachmentFile));
        
    }

    private String  SELECT_COLUMNS = "{PREFIX}tl_attachment.object_id as id, {PREFIX}tl_attachment.object_LAST_UPDATED_DATE as LAST_UPDATED_DATE, {PREFIX}tl_attachment.object_CREATED_DATE as CREATED_DATE, {PREFIX}tl_attachment.attachment_name, {PREFIX}tl_attachment.attachment_file, {PREFIX}tl_attachment.email_message_id,  1 AS commasafe ";
    private String SELECT_JOINS = "";

    public BaseBusinessClass fetchByID(ObjectID id, PersistentSetCollection allPSets, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, StorageException
    {
        Set<BaseBusinessClass>    resultByIDs = fetchByIDs(Collections.singleton (id), allPSets, context, sqlMgr);

        if (resultByIDs.isEmpty ())
        {
            return null;
        }
        else if (resultByIDs.size () > 1)
        {
            throw new StorageException ("Multiple results for id:" + id);
        }
        else
        {
            return resultByIDs.iterator ().next ();
        }
    }



    public Set<BaseBusinessClass> fetchByIDs(Set<ObjectID> ids, PersistentSetCollection allPSets, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, StorageException
    {
        Set<BaseBusinessClass>    results = new HashSet ();
        Set<Long> idsToFetch = new HashSet ();

        for (ObjectID id : ids)
        {
            if (context.containsObject(id)) // Check for cached version
            {
                BaseBusinessClass objectToReturn = context.getObjectToReplace(id, Attachment.REFERENCE_Attachment);

                if (objectToReturn instanceof Attachment)
                {
                    LogMgr.log (AttachmentPersistence, LogLevel.TRACE, "Cache hit for id:", id);
                    results.add (objectToReturn);
                }
                else
                {
                    throw new StorageException ("Cache collision for id:" + id + " with object " + objectToReturn + "while fetching a Attachment");
                }
            }

            PersistentSet tl_attachmentPSet = allPSets.getPersistentSet(id, "tl_attachment", PersistentSetStatus.FETCHED);
            
            

             // Check for persistent sets already prefetched
            if (false  || !tl_attachmentPSet.containsAttrib(BaseBusinessClass.FIELD_ObjectLastModified) ||
                    !tl_attachmentPSet.containsAttrib(Attachment.FIELD_AttachmentName)||
                    !tl_attachmentPSet.containsAttrib(Attachment.FIELD_AttachmentFile)||
                    !tl_attachmentPSet.containsAttrib(Attachment.SINGLEREFERENCE_EmailMessage))
            {
                // We will need to retrieve it
                idsToFetch.add (id.longValue());
            }
            else
            {
                LogMgr.log (AttachmentPersistence, LogLevel.DEBUG2, "Persistent set preloaded id:", id);
        
                /* Non Polymorphic */
                Attachment result = new Attachment ();

                result.setFromPersistentSets(id, allPSets);
                context.addRetrievedObject(result);

                results.add (result);
            
            }
        }

        if (idsToFetch.size () > 0)
        {
            String  query = "SELECT " + SELECT_COLUMNS +
                            "FROM {PREFIX}tl_attachment " +
                            "WHERE " + SELECT_JOINS + "{PREFIX}tl_attachment.object_id IN ?";

            BaseBusinessClass[] resultsFetched = loadQuery (allPSets, sqlMgr, context, query, new Object[] { idsToFetch }, null, false);

            for (BaseBusinessClass objFetched : resultsFetched)
            {
                results.add (objFetched);
            }
        }


        return results;
    }



    public BaseBusinessClass[] getReferencedObjects(ObjectID _objectID, String refName, PersistentSetCollection allPSets, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, StorageException
    {
        if (false)
        {
            throw new RuntimeException ();
        }
        else if (refName.equals (Attachment.SINGLEREFERENCE_EmailMessage))
        {
            String  query = "SELECT " + SELECT_COLUMNS +
                            "FROM {PREFIX}tl_attachment " +
                            "WHERE " + SELECT_JOINS + "email_message_id = ?";

            BaseBusinessClass[] results = loadQuery (allPSets, sqlMgr, context, query, new Object[] { _objectID.longID () }, null, false);

            return results;
        }
        else
        {
            throw new IllegalArgumentException ("Illegal reference type:" + refName);
        }
    }



    public void update(BaseBusinessClass obj, PersistentSetCollection allPSets, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, ConcurrentUpdateConflictException, StorageException
    {
        EqualityResult  test = EqualityResult.compare (obj, obj.getBackup ());
        ObjectID        objectID = obj.getID ();

        if (!test.areAttributesEqual () || !test.areSingleAssocsEqual () || obj.getForcedSave())
        {
            PersistentSet tl_attachmentPSet = allPSets.getPersistentSet(objectID, "tl_attachment");
            

            
            if (tl_attachmentPSet.getStatus () != PersistentSetStatus.PROCESSED &&
                tl_attachmentPSet.getStatus () != PersistentSetStatus.DEFERRED)
            {
                int rowsUpdated = executeStatement (sqlMgr, 
                                                           "UPDATE {PREFIX}tl_attachment " +
                                                           "SET attachment_name = ?, attachment_file = ?, email_message_id = ?  , object_LAST_UPDATED_DATE = " + sqlMgr.getPortabilityServices ().getTimestampExpression () + " " +
                                                                
                                                           "WHERE tl_attachment.object_id = ? AND " + getConcurrencyCheck (sqlMgr, "object_LAST_UPDATED_DATE", obj.getObjectLastModified ()) + " ",
                                                           CollectionUtils.listEntry (HELPER_AttachmentName.getForSQL(dummyAttachmentName, tl_attachmentPSet.getAttrib (Attachment.FIELD_AttachmentName))).listEntry (HELPER_AttachmentFile.getForSQL(dummyAttachmentFile, tl_attachmentPSet.getAttrib (Attachment.FIELD_AttachmentFile))).listEntry (SQLManager.CheckNull((Long)(tl_attachmentPSet.getAttrib (Attachment.SINGLEREFERENCE_EmailMessage)))).listEntry (objectID.longID ()).listEntry (obj.getObjectLastModified ()).toList().toArray());

                if (rowsUpdated != 1)
                {
                    // Error, either a concurrency error or a not-exists error
                    ResultSet r = executeQuery (sqlMgr, 
                                                       "SELECT object_id, object_LAST_UPDATED_DATE FROM {PREFIX}tl_attachment WHERE object_id = ?",
                                                       new Object[] { objectID.longID () });

                    if (r.next ())
                    {
                        Date                d = new java.util.Date (r.getTimestamp (2).getTime());
                        String              errorMsg = QueryBuilder.buildQueryString ("Concurrent update error:[?] for row:[?] objDate:[?] dbDate:[?]", 
                                                                         new Object[] { "tl_attachment", objectID.longID (), obj.getObjectLastModified (), d },
                                                                         sqlMgr.getPortabilityServices ());
                                                                         
                        LogMgr.log (AttachmentPersistence, LogLevel.BUSINESS1, errorMsg);
                        throw new ConcurrentUpdateConflictException (obj, "tl_attachment");
                    }
                    else
                    {
                        String  errorMsg = "Attempt to update nonexistent row in table:tl_attachment for row:" + objectID + " objDate:" + obj.getObjectLastModified ();

                        LogMgr.log (AttachmentPersistence, LogLevel.BUSINESS1, errorMsg);
                        throw new RuntimeException (errorMsg);
                    }
                }

                tl_attachmentPSet.setStatus (PersistentSetStatus.PROCESSED);
            }
            
        }
        else
        {
            LogMgr.log (AttachmentPersistence, LogLevel.DEBUG1, "Skipping update since no attribs or simple assocs changed on ", objectID);
        }
    }



    public void delete(BaseBusinessClass obj, PersistentSetCollection allPSets, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, ConcurrentUpdateConflictException, StorageException
    {
        ObjectID        objectID = obj.getID ();
        PersistentSet tl_attachmentPSet = allPSets.getPersistentSet(objectID, "tl_attachment");
        

        LogMgr.log (AttachmentPersistence, LogLevel.DEBUG2, "Deleting:", objectID);

        
        if (tl_attachmentPSet.getStatus () != PersistentSetStatus.PROCESSED &&
            tl_attachmentPSet.getStatus () != PersistentSetStatus.DEFERRED)
        {
            int rowsDeleted = executeStatement (sqlMgr, 
                                                       "DELETE " +
                                                       "FROM {PREFIX}tl_attachment " +
                                                       "WHERE tl_attachment.object_id = ? AND " + sqlMgr.getPortabilityServices ().getTruncatedTimestampColumn ("object_LAST_UPDATED_DATE") + " = " + sqlMgr.getPortabilityServices ().getTruncatedTimestampParam("?") + " ",
                                                       new Object[] { objectID.longID(), obj.getObjectLastModified () });

            if (rowsDeleted != 1)
            {
                // Error, either a concurrency error or a not-exists error
                ResultSet r = executeQuery (sqlMgr, 
                                                   "SELECT object_id FROM {PREFIX}tl_attachment WHERE object_id = ?",
                                                   new Object[] { objectID.longID() });

                if (r.next ())
                {
                    throw new ConcurrentUpdateConflictException (obj, "tl_attachment");
                }
                else
                {
                    String  errorMsg = "Attempt to delete nonexistent row in table:tl_attachment for row:" + objectID;

                    LogMgr.log (AttachmentPersistence, LogLevel.SYSTEMERROR1, errorMsg);
                    throw new RuntimeException (errorMsg);
                }
            }

            tl_attachmentPSet.setStatus (PersistentSetStatus.PROCESSED);
        }
        
    }


    



    public BaseBusinessClass[] loadQuery (PersistentSetCollection allPSets, SQLManager sqlMgr, RDBMSPersistenceContext context, String query, Object[] params, Integer maxRows, boolean truncateExtra) throws SQLException, StorageException
    {
        LinkedHashMap<ObjectID, Attachment> results = new LinkedHashMap ();
        
        ResultSet   r = executeQuery (sqlMgr, query, params);

        while (r.next())
        {
            ThreadUtils.checkInterrupted ();
            
            ObjectID    objectID = new ObjectID (Attachment.REFERENCE_Attachment.getObjectIDSpace (), r.getLong ("id"));
            Attachment resultElement;

            if (maxRows != null && !results.containsKey (objectID) && results.size () >= maxRows)
            {
                if (truncateExtra)
                {
                    break;
                }
                else
                {
                    throw new SearchRowsExceededException ("Maximum rows exceeded:" + maxRows);
                }
            }

            if (context.containsObject(objectID))
            {
                BaseBusinessClass   cachedElement = context.getObjectToReplace(objectID, Attachment.REFERENCE_Attachment);

                if (cachedElement instanceof Attachment)
                {
                    LogMgr.log (AttachmentPersistence, LogLevel.TRACE, "Cache hit for id:", objectID);
                    resultElement = (Attachment)cachedElement;
                }
                else
                {
                    throw new StorageException ("Cache collision for id:" + objectID + " with object " + cachedElement + "while fetching a Attachment");
                }
            }
            else
            {
                PersistentSet tl_attachmentPSet = allPSets.getPersistentSet(objectID, "tl_attachment", PersistentSetStatus.FETCHED);
                
                createPersistentSetFromRS(allPSets, r, objectID);

                

                        resultElement = new Attachment ();

                        resultElement.setFromPersistentSets(objectID, allPSets);
                        context.addRetrievedObject(resultElement);

                
            }

            results.put (objectID, resultElement);
        }

        

        BaseBusinessClass[] resultsArr = new BaseBusinessClass[results.size ()];

        return results.values ().toArray (resultsArr);
    }



    public BaseBusinessClass[] find(String searchType, PersistentSetCollection allPSets, Hashtable criteria, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, StorageException
    {
        LogMgr.log (AttachmentPersistence, LogLevel.DEBUG2, "Search executing:", searchType, " criteria:", criteria);
        String  customParamFilter = (String)criteria.get (SEARCH_CustomFilter);
        String  customOrderBy = (String)criteria.get (SEARCH_OrderBy);
        String  customTables = (String)criteria.get (SEARCH_CustomExtraTables);
        Boolean  noCommaBeforeCustomExtraTables = (Boolean)criteria.get (SEARCH_CustomExtraTablesNoComma);

        if (searchType.equals (SEARCH_CustomSQL))
        {
            Set<ObjectID>                     processedIDs = new HashSet();
            SearchParamTransform    tx = new SearchParamTransform (criteria);
            Object[]                searchParams;

            customParamFilter = StringUtils.replaceParams (customParamFilter, tx);
            searchParams = tx.getParamsArray();

            if (customOrderBy != null) 
            {
                customOrderBy = " ORDER BY " + customOrderBy;
            }
            else
            {
                customOrderBy = "";
            }


            ResultSet   r;
            String      concatCustomTableWith = CollectionUtils.equals(noCommaBeforeCustomExtraTables, true) ?  " " : ", ";
            String      tables = StringUtils.subBlanks(customTables) == null ? " " : concatCustomTableWith + customTables + " ";


            String  query = "SELECT " + SELECT_COLUMNS +
                                    "FROM {PREFIX}tl_attachment " + tables +
                                    "WHERE " + SELECT_JOINS + " " + customParamFilter + customOrderBy;

            BaseBusinessClass[] results = loadQuery (allPSets, sqlMgr, context, query, searchParams, null, false);

            return results;
        }
        
        else
        {
            throw new IllegalArgumentException ("Illegal search type:" + searchType);
            
            
        }
    }

    private void createPersistentSetFromRS(PersistentSetCollection allPSets, ResultSet r, ObjectID objectID) throws SQLException
    {
        PersistentSet tl_attachmentPSet = allPSets.getPersistentSet(objectID, "tl_attachment", PersistentSetStatus.FETCHED);
        
            // Object Modified
            tl_attachmentPSet.setAttrib(BaseBusinessClass.FIELD_ObjectLastModified, r.getTimestamp ("LAST_UPDATED_DATE"));

            // Object Created
            tl_attachmentPSet.setAttrib(BaseBusinessClass.FIELD_ObjectCreated, r.getTimestamp ("CREATED_DATE"));

        tl_attachmentPSet.setAttrib(Attachment.FIELD_AttachmentName, HELPER_AttachmentName.getFromRS(dummyAttachmentName, r, "attachment_name"));
        tl_attachmentPSet.setAttrib(Attachment.FIELD_AttachmentFile, HELPER_AttachmentFile.getFromRS(dummyAttachmentFile, r, "attachment_file"));
        
        tl_attachmentPSet.setAttrib(Attachment.SINGLEREFERENCE_EmailMessage, r.getObject ("email_message_id"));
        
    }


    public void create(BaseBusinessClass obj, PersistentSetCollection allPSets, RDBMSPersistenceContext context, SQLManager sqlMgr) throws SQLException, StorageException
    {
        ObjectID    objectID = obj.getID ();
        PersistentSet tl_attachmentPSet = allPSets.getPersistentSet(objectID, "tl_attachment");
        

        
        if (tl_attachmentPSet.getStatus () != PersistentSetStatus.PROCESSED &&
            tl_attachmentPSet.getStatus () != PersistentSetStatus.DEFERRED)
        {
            executeStatement (sqlMgr, 
                                     "INSERT INTO {PREFIX}tl_attachment " +
                                     "  (attachment_name, attachment_file,  email_message_id,  object_id, object_LAST_UPDATED_DATE, object_CREATED_DATE) " +
                                     "VALUES " +
                                     "  (?, ?,  ?,   ?,  " + sqlMgr.getPortabilityServices ().getTimestampExpression () + ",  " + sqlMgr.getPortabilityServices ().getTimestampExpression () + ")",
                                     CollectionUtils.listEntry (HELPER_AttachmentName.getForSQL(dummyAttachmentName, tl_attachmentPSet.getAttrib (Attachment.FIELD_AttachmentName))).listEntry (HELPER_AttachmentFile.getForSQL(dummyAttachmentFile, tl_attachmentPSet.getAttrib (Attachment.FIELD_AttachmentFile))) .listEntry (SQLManager.CheckNull((Long)(tl_attachmentPSet.getAttrib (Attachment.SINGLEREFERENCE_EmailMessage)))) .listEntry (objectID.longID ()).toList().toArray());

            tl_attachmentPSet.setStatus (PersistentSetStatus.PROCESSED);
        }
        
    }
}
