/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * 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 com.queplix.core.utils.sql.vendor.mssql;

import com.queplix.core.utils.sql.SqlWrapperFactory;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Helper class for working with MSSQL text
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:31:22 $
 */

public class MssqlText {

    // ========================================================== Public methods

    /**
     * Retrives the TEXT object from ResultSet object.
     *
     * @param rs         ResultSet object to retrieve the TEXT from
     * @param pos        substitution position in statement
     * @param tableName  the table name
     * @param columnName the column name
     * @param size       TEXT data size
     * @return TEXT data
     * @throws SQLException
     */
    public static char[] getObject(ResultSet rs,
                                   int pos,
                                   String tableName,
                                   String columnName,
                                   int size)
            throws SQLException {

        Statement __stat = null;
        try {
            String ptrval = rs.getString(pos);
            if(rs.wasNull()) {
                return null;
            }

            StringBuffer sql = new StringBuffer();
            sql.append("begin\n");
            sql.append("declare @ptrval varbinary(16)\n");
            sql.append("select @ptrval = CAST(0x").append(ptrval).append(
                    " AS varbinary(16))\n");
            sql.append("readtext ").append(tableName).append(".").append(
                    columnName).append(" @ptrval 0 ").append(size).append("\n");
            sql.append("end\n");

            __stat = rs.getStatement().getConnection().createStatement();
            ResultSet __rs = __stat.executeQuery(sql.toString());

            if(__rs.next()) {
                return SqlWrapperFactory.getSqlWrapper().getMemoParser()
                        .getValue(__rs, 1);
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;

        } finally {
            if(__stat != null) {
                try {
                    __stat.close();
                } catch (Exception ex) {
                }
            }
        }
        return null;
    }
}
