<commit_before>/*

   Derby - Class org.apache.derby.client.am.Sqlca

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.derby.client.am;

import java.sql.DataTruncation;
import java.sql.Types;
import java.util.Locale;
import org.apache.derby.client.net.Typdef;
import org.apache.derby.shared.common.error.ExceptionSeverity;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.shared.common.error.MessageUtils;

public abstract class Sqlca {

    // Indexes into sqlErrd_
    private  static  final   int HIGH_ORDER_ROW_COUNT = 0;
    private  static  final   int LOW_ORDER_ROW_COUNT = 1;
    private  static  final   int LOW_ORDER_UPDATE_COUNT = 2;
    private  static  final   int HIGH_ORDER_UPDATE_COUNT = 3;
    public  static  final   int SQL_ERR_LENGTH = 6;
    transient private ClientConnection connection_;
    SqlException exceptionThrownOnStoredProcInvocation_;
    boolean messageTextRetrievedContainsTokensOnly_ = true;

    // data corresponding to SQLCA fields
    protected int sqlCode_;        // SQLCODE
    /** A string representation of <code>sqlErrmcBytes_</code>. */
    private String sqlErrmc_;
    /** Array of errmc strings for each message in the chain. */
    private String[] sqlErrmcMessages_;
    /** SQL states for all the messages in the exception chain. */
    private String[] sqlStates_;
    // contain an error token
    private String sqlErrp_;        // function name issuing error
    protected int[] sqlErrd_;        // 6 diagnostic Information
    private String sqlWarn_;        // 11 warning Flags
    protected String sqlState_;       // SQLSTATE

    // raw sqlca data fields before unicode conversion
    protected byte[] sqlErrmcBytes_;
    protected byte[] sqlErrpBytes_;
    protected byte[] sqlWarnBytes_;
    
    private boolean containsSqlcax_ = true;
    private long rowsetRowCount_;

    /**
     * Character sequence that separates the different messages in the errmc.
     * @see org.apache.derby.shared.common.error.MessageUtils#SQLERRMC_MESSAGE_DELIMITER
     */
    private static final String sqlErrmcDelimiter__ = "\u0014\u0014\u0014";

    

    // JDK stack trace calls e.getMessage(), so we must set some state on the sqlca that says return tokens only.
    private boolean returnTokensOnlyInMessageText_ = false;

    transient private final Agent agent_;

    /** Cached error messages (to prevent multiple invocations of the stored
     * procedure to get the same message). */
    private String[] cachedMessages;

    protected Sqlca(ClientConnection connection) {
        connection_ = connection;
        agent_ = connection_ != null ? connection_.agent_ : null;
    }

    void returnTokensOnlyInMessageText(boolean returnTokensOnlyInMessageText) {
        returnTokensOnlyInMessageText_ = returnTokensOnlyInMessageText;
    }

    /**
     * Returns the number of messages this SQLCA contains.
     *
     * @return number of messages
     */
    synchronized int numberOfMessages() {
        initSqlErrmcMessages();
        if (sqlErrmcMessages_ != null) {
            return sqlErrmcMessages_.length;
        }
        // even if we don't have an array of errmc messages, we are able to get
        // one message out of this sqlca (although it's not very readable)
        return 1;
    }

    synchronized public int getSqlCode() {
        return sqlCode_;
    }

    /**
     * <p>
     * Get the error code based on the SQL code received from the server.
     * </p>
     *
     * <p>
     * The conversion from SQL code to error code happens like this:
     * </p>
     *
     * <ul>
     * <li>If the SQL code is 0, there is no error code because the Sqlca
     * doesn't represent an error. Return 0.</li>
     * <li>If the SQL code is positive, the Sqlca represents a warning, and
     * the SQL code represents the actual error code. Return the SQL code.</li>
     * <li>If the SQL code is negative, the Sqlca represents an error, and
     * the error code is {@code -(sqlCode+1)}.</li>
     * </ul>
     *
     * @see org.apache.derby.impl.drda.DRDAConnThread#getSqlCode(java.sql.SQLException)
     */
    public synchronized int getErrorCode() {
        // Warning or other non-error, return SQL code.
        if (sqlCode_ >= 0) return sqlCode_;

        // Negative SQL code means it is an error. Transform into a positive
        // error code.
        int errorCode = -(sqlCode_ + 1);

        // In auto-commit mode, the embedded driver promotes statement
        // severity to transaction severity. Do the same here to match.
        if (errorCode == ExceptionSeverity.STATEMENT_SEVERITY &&
                connection_ != null && connection_.autoCommit_) {
            errorCode = ExceptionSeverity.TRANSACTION_SEVERITY;
        }

        return errorCode;
    }

    synchronized public String getSqlErrmc() {
        if (sqlErrmc_ != null) {
            return sqlErrmc_;
        }

        // sqlErrmc string is dependent on sqlErrmcMessages_ array having
        // been built
        initSqlErrmcMessages();

        // sqlErrmc will be built only if sqlErrmcMessages_ has been built.
        // Otherwise, a null string will be returned.
        if (sqlErrmcMessages_ == null) {
            return null;
        }

        // create 0-length String if no tokens
        if (sqlErrmcMessages_.length == 0) {
            sqlErrmc_ = "";
            return sqlErrmc_;
        }

        // concatenate tokens with sqlErrmcDelimiter delimiters into one String
        StringBuffer buffer = new StringBuffer();
        int indx;
        for (indx = 0; indx < sqlErrmcMessages_.length - 1; indx++) {
            buffer.append(sqlErrmcMessages_[indx]);
            buffer.append(sqlErrmcDelimiter__);
            // all but the first message should be preceded by the SQL state
            // and a colon (see DRDAConnThread.buildTokenizedSqlerrmc() on the
            // server)
            buffer.append(sqlStates_[indx+1]);
            buffer.append(":");
        }
        // add the last token
        buffer.append(sqlErrmcMessages_[indx]);

        // save as a string
        sqlErrmc_ = buffer.toString();
        return sqlErrmc_;
    }

    /**
     * Initialize and build the arrays <code>sqlErrmcMessages_</code> and<commit_msg>DERBY-6803: Change Sqlca and SqlException to call MessageUtils<commit_after>/*

   Derby - Class org.apache.derby.client.am.Sqlca

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.derby.client.am;

import java.sql.DataTruncation;
import java.sql.Types;
import java.util.Locale;
import org.apache.derby.client.net.Typdef;
import org.apache.derby.shared.common.error.ExceptionSeverity;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.shared.common.error.MessageUtils;

public abstract class Sqlca {

    // Indexes into sqlErrd_
    private  static  final   int HIGH_ORDER_ROW_COUNT = 0;
    private  static  final   int LOW_ORDER_ROW_COUNT = 1;
    private  static  final   int LOW_ORDER_UPDATE_COUNT = 2;
    private  static  final   int HIGH_ORDER_UPDATE_COUNT = 3;
    public  static  final   int SQL_ERR_LENGTH = 6;
    transient private ClientConnection connection_;
    SqlException exceptionThrownOnStoredProcInvocation_;
    boolean messageTextRetrievedContainsTokensOnly_ = true;

    // data corresponding to SQLCA fields
    protected int sqlCode_;        // SQLCODE
    /** A string representation of <code>sqlErrmcBytes_</code>. */
    private String sqlErrmc_;
    /** Array of errmc strings for each message in the chain. */
    private String[] sqlErrmcMessages_;
    /** SQL states for all the messages in the exception chain. */
    private String[] sqlStates_;
    // contain an error token
    private String sqlErrp_;        // function name issuing error
    protected int[] sqlErrd_;        // 6 diagnostic Information
    private String sqlWarn_;        // 11 warning Flags
    protected String sqlState_;       // SQLSTATE

    // raw sqlca data fields before unicode conversion
    protected byte[] sqlErrmcBytes_;
    protected byte[] sqlErrpBytes_;
    protected byte[] sqlWarnBytes_;
    
    private boolean containsSqlcax_ = true;
    private long rowsetRowCount_;

    // JDK stack trace calls e.getMessage(), so we must set some state on the sqlca that says return tokens only.
    private boolean returnTokensOnlyInMessageText_ = false;

    transient private final Agent agent_;

    /** Cached error messages (to prevent multiple invocations of the stored
     * procedure to get the same message). */
    private String[] cachedMessages;

    protected Sqlca(ClientConnection connection) {
        connection_ = connection;
        agent_ = connection_ != null ? connection_.agent_ : null;
    }

    void returnTokensOnlyInMessageText(boolean returnTokensOnlyInMessageText) {
        returnTokensOnlyInMessageText_ = returnTokensOnlyInMessageText;
    }

    /**
     * Returns the number of messages this SQLCA contains.
     *
     * @return number of messages
     */
    synchronized int numberOfMessages() {
        initSqlErrmcMessages();
        if (sqlErrmcMessages_ != null) {
            return sqlErrmcMessages_.length;
        }
        // even if we don't have an array of errmc messages, we are able to get
        // one message out of this sqlca (although it's not very readable)
        return 1;
    }

    synchronized public int getSqlCode() {
        return sqlCode_;
    }

    /**
     * <p>
     * Get the error code based on the SQL code received from the server.
     * </p>
     *
     * <p>
     * The conversion from SQL code to error code happens like this:
     * </p>
     *
     * <ul>
     * <li>If the SQL code is 0, there is no error code because the Sqlca
     * doesn't represent an error. Return 0.</li>
     * <li>If the SQL code is positive, the Sqlca represents a warning, and
     * the SQL code represents the actual error code. Return the SQL code.</li>
     * <li>If the SQL code is negative, the Sqlca represents an error, and
     * the error code is {@code -(sqlCode+1)}.</li>
     * </ul>
     *
     * @see org.apache.derby.impl.drda.DRDAConnThread#getSqlCode(java.sql.SQLException)
     */
    public synchronized int getErrorCode() {
        // Warning or other non-error, return SQL code.
        if (sqlCode_ >= 0) return sqlCode_;

        // Negative SQL code means it is an error. Transform into a positive
        // error code.
        int errorCode = -(sqlCode_ + 1);

        // In auto-commit mode, the embedded driver promotes statement
        // severity to transaction severity. Do the same here to match.
        if (errorCode == ExceptionSeverity.STATEMENT_SEVERITY &&
                connection_ != null && connection_.autoCommit_) {
            errorCode = ExceptionSeverity.TRANSACTION_SEVERITY;
        }

        return errorCode;
    }

    synchronized public String getSqlErrmc() {
        if (sqlErrmc_ != null) {
            return sqlErrmc_;
        }

        // sqlErrmc string is dependent on sqlErrmcMessages_ array having
        // been built
        initSqlErrmcMessages();

        // sqlErrmc will be built only if sqlErrmcMessages_ has been built.
        // Otherwise, a null string will be returned.
        if (sqlErrmcMessages_ == null) {
            return null;
        }

        // create 0-length String if no tokens
        if (sqlErrmcMessages_.length == 0) {
            sqlErrmc_ = "";
            return sqlErrmc_;
        }

        // concatenate tokens with sqlErrmcDelimiter delimiters into one String
        StringBuffer buffer = new StringBuffer();
        int indx;
        for (indx = 0; indx < sqlErrmcMessages_.length - 1; indx++) {
            buffer.append(sqlErrmcMessages_[indx]);
            buffer.append(MessageUtils.SQLERRMC_MESSAGE_DELIMITER);
            // all but the first message should be preceded by the SQL state
            // and a colon (see DRDAConnThread.buildTokenizedSqlerrmc() on the
            // server)
            buffer.append(sqlStates_[indx+1]);
            buffer.append(":");
        }
        // add the last token
        buffer.append(sqlErrmcMessages_[indx]);

        // save as a string
        sqlErrmc_ = buffer.toString();
        return sqlErrmc_;
    }

    /**
     * Initialize and build the arrays <code>sqlErrmcMessages_</code> and
{'fraction_non_alphanumeric': 0.07503066156842941, 'fraction_numerical': 0.004472981747348676, 'mean_word_length': 2.537126818065833, 'pattern_counts': {'":': 2, '<': 37, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '248065', 'n_tokens_mistral': 3773, 'n_tokens_neox': 3731, 'n_words': 1350}