/**********************************************************************
Copyright (c) 2006 Andy Jefferson and others. All rights reserved.
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.

Contributors:
2006 Thomas Mueller - updated the dialect for the H2 database engine
**********************************************************************/
package org.jpox.store.rdbms.adapter;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.sql.DataSource;

import org.jpox.store.DatastoreContainerObject;
import org.jpox.store.DatastoreIdentifier;
import org.jpox.store.Dictionary;
import org.jpox.store.expression.LogicSetExpression;
import org.jpox.store.expression.NumericExpression;
import org.jpox.store.expression.QueryExpression;
import org.jpox.store.expression.ScalarExpression;
import org.jpox.store.expression.TableExprAsJoins;
import org.jpox.store.rdbms.Column;
import org.jpox.store.rdbms.key.PrimaryKey;
import org.jpox.store.rdbms.table.Table;

/**
 * Provides methods for adapting SQL language elements to the H2 Database Engine.
 *
 * @version $Revision: 1.1 $
 */
class H2Adapter extends DatabaseAdapter
{
    private String schemaName;

    /**
     * Constructs a H2 adapter based on the given JDBC metadata.
     * @param dictionary The Dictionary to use
     * @param metadata the database metadata.
     */
    public H2Adapter(Dictionary dictionary, DatabaseMetaData metadata)
    {
        super(dictionary, metadata);

        // Set schema name
        try
        {
            ResultSet rs = metadata.getSchemas();
            while (rs.next())
            {
                if (rs.getBoolean("IS_DEFAULT"))
                {
                    schemaName = rs.getString("TABLE_SCHEM");
                }
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            // ignore
        }
    }

    /**
     * Getter for the vendor ID for this adapter.
     * @return The vendor ID
     */
    public String getVendorID()
    {
        return "h2";
    }

    /**
     * Accessor for a Connection to the datastore.
     * @param ds The data source. Possible to have more than one data source for fail over
     * @param userName The username for the datastore
     * @param password The password for the datastore
     * @param isolationLevel The level of transaction isolation
     * @return The Connection
     * @throws SQLException Thrown when an error occurs in the creation.
     **/
    public Connection getConnection(DataSource[] ds, String userName, String password, int isolationLevel)
    throws SQLException
    {
        return super.getConnection(ds,userName,password,Connection.TRANSACTION_SERIALIZABLE);
    }

    /**
     * Accessor for the maximum table name length permitted on this
     * datastore.
     * @return Max table name length
     **/
    public int getMaxTableNameLength()
    {
        return SQLConstants.MAX_IDENTIFIER_LENGTH;
    }

    /**
     * Accessor for the maximum constraint name length permitted on this
     * datastore.
     * @return Max constraint name length
     **/
    public int getMaxConstraintNameLength()
    {
        return SQLConstants.MAX_IDENTIFIER_LENGTH;
    }

    /**
     * Accessor for the maximum index name length permitted on this datastore.
     * @return Max index name length
     **/
    public int getMaxIndexNameLength()
    {
        return SQLConstants.MAX_IDENTIFIER_LENGTH;
    }

    /**
     * Accessor for the maximum column name length permitted on this datastore.
     * @return Max column name length
     **/
    public int getMaxColumnNameLength()
    {
        return SQLConstants.MAX_IDENTIFIER_LENGTH;
    }

    /**
     * Accessor for the SQL statement to add a column to a table.
     * @param table The table
     * @param col The column
     * @return The SQL necessary to add the column
     */
    public String getAddColumnStatement(DatastoreContainerObject table, Column col)
    {
        return "ALTER TABLE " + table.toString() + " ADD COLUMN " + col.getSQLDefinition();
    }

    /**
     * Method to return the SQL to append to the SELECT clause of a SELECT statement to handle
     * restriction of ranges using the LIMIT keyword.
     * @param offset The offset to return from
     * @param count The number of items to return
     * @return The SQL to append to allow for ranges using LIMIT.
     */
    public String getRangeByLimitSelectClause(long offset, long count)
    {
        if (offset >= 0 && count > 0)
        {
            return " LIMIT " + offset + " " + count + " ";
        }
        else if (offset <= 0 && count > 0)
        {
            return " LIMIT 0 " + count + " ";
        }
        else
        {
            return "";
        }
    }

    /**
     * Accessor for whether the adapter supports the transaction isolation level
     *
     * @param isolationLevel the isolation level
     * @return Whether the transaction isolation level setting is supported.
     */
    public boolean supportsTransactionIsolationLevel(int isolationLevel)
    {
        if (isolationLevel == Connection.TRANSACTION_READ_COMMITTED || isolationLevel == Connection.TRANSACTION_SERIALIZABLE)
        {
            return true;
        }
        return false;
    }

    /**
     * Whether the datastore supports specification of the primary key in CREATE
     * TABLE statements.
     * @return Whether it allows "PRIMARY KEY ..."
     */
    public boolean supportsPrimaryKeyInCreateStatements()
    {
        return true;
    }

    /**
     * Accessor for the Schema Name for this datastore.
     *
     * @param conn Connection to the datastore
     * @return The schema name
     **/
    public String getSchemaName(Connection conn)
    throws SQLException
    {
        return schemaName;
    }

    /**
     * @param pk An object describing the primary key.
     * @return The PK statement
     */
    public String getAddPrimaryKeyStatement(PrimaryKey pk)
    {
        // PK is created by the CREATE TABLE statement so we just return null
        return null;
    }


    /**
     * Returns the appropriate SQL to drop the given table.
     * It should return something like:
     * <p>
     * <blockquote><pre>
     * DROP TABLE FOO
     * </pre></blockquote>
     *
     * @param table     The table to drop.
     * @return  The text of the SQL statement.
     */
    public String getDropTableStatement(DatastoreContainerObject table)
    {
        return "DROP TABLE " + table.toString();
    }

    /**
     * Whether we support deferred constraints in keys.
     * @return whether we support deferred constraints in keys.
     **/
    public boolean supportsDeferredConstraints()
    {
        return false;
    }

    /**
     * Whether we support auto incrementing fields.
     * @return whether we support auto incrementing fields.
     **/
    public boolean supportsAutoIncrementFields()
    {
        return true;
    }

    /**
     * Accessor for the auto-increment sql statement for this datastore.
     * @param tableName Name of the table that the autoincrement is for
     * @param columnName Name of the column that the autoincrement is for
     * @return The statement for getting the latest auto-increment key
     **/
    public String getAutoIncrementStmt(String tableName, String columnName)
    {
        return "CALL IDENTITY()";
    }

    /**
     * Accessor for the auto-increment keyword for generating DDLs (CREATE TABLE...).
     * @return The keyword for a column using auto-increment
     **/
    public String getAutoIncrementKeyword()
    {
        return "IDENTITY";
    }

    /**
     * Method to return the INSERT statement to use when inserting into a table that has no
     * columns specified. This is the case when we have a single column in the table and that column
     * is autoincrement/identity (and so is assigned automatically in the datastore).
     * @param table The table
     * @return The INSERT statement
     */
    public String getInsertStatementForNoColumns(Table table)
    {
        return "INSERT INTO " + table.toString() + " VALUES(NULL)";
    }

    /**
     * Whether to allow Unique statements in the section of CREATE TABLE after the
     * column definitions.
     * @see org.jpox.store.rdbms.adapter.DatabaseAdapter#supportsUniqueConstraintsInEndCreateStatements()
     */
    public boolean supportsUniqueConstraintsInEndCreateStatements()
    {
        return true;
    }

    /**
     * Whether this datastore supports the use of CHECK after the column
     * definitions in CREATE TABLE statements (DDL).
     * e.g.
     * CREATE TABLE XYZ
     * (
     *   COL_A int,
     *   COL_B char(1),
     *   PRIMARY KEY (COL_A),
     *   CHECK (COL_B IN ('Y','N'))
     * )
     * @return whether we can use CHECK after the column definitions in CREATE TABLE.
     **/
    public boolean supportsCheckConstraintsInEndCreateStatements()
    {
        return true;
    }

    /**
     * Accessor for whether the specified type is allow to be part of a PK.
     * @param datatype The JDBC type
     * @return Whether it is permitted in the PK
     */
    public boolean isValidPrimaryKeyType(int datatype)
    {
        return true;
    }

    /**
     * Method to generate a modulus expression. The binary % operator is said to
     * yield the remainder of its operands from an implied division; the
     * left-hand operand is the dividend and the right-hand operand is the
     * divisor. This returns MOD(expr1, expr2).
     * @param operand1 the left expression
     * @param operand2 the right expression
     * @return The Expression for modulus
     */
    public NumericExpression modOperator(ScalarExpression operand1, ScalarExpression operand2)
    {
        ArrayList args = new ArrayList();
        args.add(operand1);
        args.add(operand2);
        return new NumericExpression("MOD", args);
    }
    /**
     * Return a new TableExpression.
     * @param qs The QueryStatement to add the expression to
     * @param table The table in the expression
     * @param rangeVar range variable to assign to the expression.
     * @return The expression.
     **/
    public LogicSetExpression newTableExpression(QueryExpression qs, DatastoreContainerObject table, DatastoreIdentifier rangeVar)
    {
        return new TableExprAsJoins(qs, table, rangeVar);
    }
}
