/*
 * $Header: /home/cvspublic/jakarta-slide/src/stores/org/apache/slide/store/impl/rdbms/SQLServerRDBMSAdapter.java,v 1.10 2004/12/15 16:50:26 ozeigermann Exp $
 * $Revision: 1.10 $
 * $Date: 2004/12/15 16:50:26 $
 *
 * ====================================================================
 *
 * Copyright 1999-2003 The Apache Software Foundation 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.slide.store.impl.rdbms;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import org.apache.slide.common.Service;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.Uri;
import org.apache.slide.content.NodeProperty;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.RevisionDescriptorNotFoundException;
import org.apache.slide.macro.ConflictException;
import org.apache.slide.store.ConcurrencyConflictError;
import org.apache.slide.util.logger.Logger;

/**
 * Adapter for MS SQLServer. Actually does not change a thing from StandardRDBMSAdapter.
 * 
 * @version $Revision: 1.10 $
 */

public class SQLServerRDBMSAdapter extends StandardRDBMSAdapter implements SequenceAdapter {

    protected static final String LOG_CHANNEL = SQLServerRDBMSAdapter.class.getName();

    protected static String normalizeSequenceName(String sequenceName) {
        return sequenceName.replace('-', '_').toUpperCase() + "_SEQ";
    }

    public SQLServerRDBMSAdapter(Service service, Logger logger) {
        super(service, logger);
    }

    protected ServiceAccessException createException(SQLException e, String uri) {

        switch (e.getErrorCode()) {
            case 1205 : // thread was deadlock victim
                getLogger().log(e.getErrorCode() + ": Deadlock resolved on " + uri, LOG_CHANNEL, Logger.WARNING);
//                return new ServiceAccessException(service, new ConflictException(uri));
                throw new ConcurrencyConflictError(e, uri);

            case 547 : // referential integraty constaint was violated (like in storeObject on table URI )
            case 2627 : // primary key constraint violation (like in storeContent on table VERSION_CONTENT)
                getLogger().log(e.getErrorCode() + ": Low isolation conflict for " + uri, LOG_CHANNEL, Logger.WARNING);
//                return new ServiceAccessException(service, new ConflictException(uri));
                throw new ConcurrencyConflictError(e, uri);

            default :
                return super.createException(e, uri);
        }

    }

    public boolean isSequenceSupported(Connection conn) {
        return true;
    }

    public boolean createSequence(Connection conn, String sequenceName) throws ServiceAccessException {

        // XXX DUMMY is a keyword in Sybase, so spell it wrong
        String query =
            "CREATE TABLE dbo."
                + normalizeSequenceName(sequenceName)
                + " (ID id_type IDENTITY UNIQUE NOT NULL, DUMY bit NOT NULL)";

        PreparedStatement statement = null;

        try {
            statement = conn.prepareStatement(query);
            statement.executeUpdate();
            return true;
        } catch (SQLException e) {
            throw new ServiceAccessException(service, e);
        } finally {
            close(statement);
        }

    }

    public long nextSequenceValue(Connection conn, String sequenceName) throws ServiceAccessException {
        String query = "INSERT INTO dbo." + normalizeSequenceName(sequenceName) + " (DUMY) VALUES(1)";

        String selectQuery = "SELECT @@identity";

        PreparedStatement statement = null;
        PreparedStatement selectStatement = null;
        ResultSet res = null;

        try {
            statement = conn.prepareStatement(query);
            statement.executeUpdate();

            selectStatement = conn.prepareStatement(selectQuery);
            res = selectStatement.executeQuery();
            if (!res.next()) {
                throw new ServiceAccessException(service, "Could not increment sequence " + sequenceName);
            }
            long value = res.getLong(1);
            return value;
        } catch (SQLException e) {
            throw new ServiceAccessException(service, e);
        } finally {
            close(statement);
            close(selectStatement, res);
        }
    }

    public void storeRevisionDescriptor(Connection connection, Uri uri, NodeRevisionDescriptor revisionDescriptor)
            throws ServiceAccessException, RevisionDescriptorNotFoundException {

        PreparedStatement statement = null;
        try {
            removeVersionLabels(connection, uri, revisionDescriptor.getRevisionNumber());
            createVersionLabels(connection, uri, revisionDescriptor);
            String revisionNumber = revisionDescriptor.getRevisionNumber().toString();
            for (Enumeration properties = revisionDescriptor.enumerateRemovedProperties(); properties.hasMoreElements();) {
                try {
                    NodeProperty property = (NodeProperty) properties.nextElement();
                    statement = connection
                            .prepareStatement("delete PROPERTIES from PROPERTIES p, VERSION_HISTORY vh, URI u where p.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID AND u.URI_STRING = ? AND p.PROPERTY_NAME = ? AND p.PROPERTY_NAMESPACE = ? and vh.REVISION_NO = ?");
                    statement.setString(1, uri.toString());
                    statement.setString(2, property.getName());
                    statement.setString(3, property.getNamespace());
                    statement.setString(4, revisionNumber);
                    statement.executeUpdate();
                } finally {
                    close(statement);
                }
            }

            for (Enumeration properties = revisionDescriptor.enumerateUpdatedProperties(); properties.hasMoreElements();) {
                NodeProperty property = (NodeProperty) properties.nextElement();
                int updated = 0;
                int protectedProperty = property.isProtected() ? 1 : 0;
                try {
                    statement = connection
                            .prepareStatement("update PROPERTIES set PROPERTY_VALUE = ?, PROPERTY_TYPE = ?, IS_PROTECTED = ? from PROPERTIES p, VERSION_HISTORY vh, URI u where p.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID AND u.URI_STRING = ? AND p.PROPERTY_NAME = ? AND p.PROPERTY_NAMESPACE = ? and vh.REVISION_NO = ?");
                    statement.setString(1, property.getValue().toString());
                    statement.setString(2, property.getType());
                    statement.setInt(3, protectedProperty);

                    statement.setString(4, uri.toString());
                    statement.setString(5, property.getName());
                    statement.setString(6, property.getNamespace());
                    statement.setString(7, revisionNumber);
                    updated = statement.executeUpdate();

                } finally {
                    close(statement);
                }

                // if it has not already been there we need to add it now
                if (updated == 0) {
                    try {
                        statement = connection
                                .prepareStatement("insert into PROPERTIES (VERSION_ID,PROPERTY_NAMESPACE,PROPERTY_NAME,PROPERTY_VALUE,PROPERTY_TYPE,IS_PROTECTED) select vh.VERSION_ID, ?, ?, ?, ?, ? from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
                        statement.setString(1, property.getNamespace());
                        statement.setString(2, property.getName());
                        statement.setString(3, property.getValue().toString());
                        statement.setString(4, property.getType());
                        statement.setInt(5, protectedProperty);
                        statement.setString(6, uri.toString());
                        statement.setString(7, revisionNumber);
                        statement.executeUpdate();
                    } finally {
                        close(statement);
                    }
                }
            }
        } catch (SQLException e) {
            throw createException(e, uri.toString());
        }
        revisionDescriptor.resetUpdatedProperties();
        revisionDescriptor.resetRemovedProperties();
    }

    public boolean sequenceExists(Connection conn, String sequenceName) throws ServiceAccessException {
        String selectQuery = getExistsQuery(sequenceName);

        PreparedStatement selectStatement = null;
        ResultSet res = null;

        try {
            selectStatement = conn.prepareStatement(selectQuery);
            res = selectStatement.executeQuery();
            return res.next();
        } catch (SQLException e) {
            throw new ServiceAccessException(service, e);
        } finally {
            close(selectStatement, res);
        }
    }

    protected String getExistsQuery(String sequenceName) {
        String selectQuery =
            "SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].["
                + normalizeSequenceName(sequenceName)
                + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
        return selectQuery;
    }

}
