/*
 * $Header: /esup-portail/injac/applications/SlideServer/Packages/esup-serveur-WebDav-3/update/slide/add-ons/stores/uPortalStore/src/stores/org/apache/slide/store/impl/rdbms/MySqlRDBMSAdapter.java,v 1.1 2005/02/08 09:23:45 tbellemb Exp $
 * $Revision: 1.1 $
 * $Date: 2005/02/08 09:23:45 $
 *
 * ====================================================================
 *
 * 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 org.apache.slide.common.*;
import org.apache.slide.macro.ConflictException;
import org.apache.slide.util.logger.Logger;

/**
 * Adapter for MySQL 4.
 * 
 * @version $Revision: 1.1 $
 */

public class MySqlRDBMSAdapter extends StandardRDBMSAdapter implements SequenceAdapter {

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

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

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

    protected ServiceAccessException createException(SQLException e, String uri) {

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

            default :
                getLogger().log(
                    "SQL error " + e.getErrorCode() + " on " + uri + ": " + e.getMessage(),
                    LOG_CHANNEL,
                    Logger.ERROR);

                return new ServiceAccessException(service, e);
        }
    }

    protected String convertRevisionNumberToComparable(String revisioNumber) {

        return "convert(SUBSTRING_INDEX("
            + revisioNumber
            + ", '.', 1), unsigned), convert(SUBSTRING_INDEX("
            + revisioNumber
            + ", '.', -1), unsigned)";
    }

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

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

        String query = "CREATE TABLE " + normalizeSequenceName(sequenceName) + "(id INT auto_increment NOT NULL,PRIMARY KEY (id))";

        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 " + normalizeSequenceName(sequenceName) + " VALUES(0)";

        String selectQuery = "SELECT LAST_INSERT_ID()";

        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 boolean sequenceExists(Connection conn, String sequenceName) throws ServiceAccessException {

        PreparedStatement selectStatement = null;
        ResultSet res = null;

        try {
            selectStatement = conn.prepareStatement("SELECT * FROM " + normalizeSequenceName(sequenceName));
            res = selectStatement.executeQuery();
            return true;
        } catch (SQLException e) {
            return false;
        } finally {
            close(selectStatement, res);
        }
    }

}