<commit_before>/*
 **** BEGIN LICENSE BLOCK *****
 * Copyright (c) 2006-2010 <NAME> <<EMAIL>>
 * Copyright (c) 2006-2007 <NAME> <<EMAIL>>
 * Copyright (c) 2008-2009 <NAME> <<EMAIL>>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 ***** END LICENSE BLOCK *****/
package arjdbc.oracle;

import arjdbc.jdbc.Callable;
import arjdbc.jdbc.RubyJdbcConnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

/**
 *
 * @author nicksieger
 */
public class OracleRubyJdbcConnection extends RubyJdbcConnection {

    protected OracleRubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
        super(runtime, metaClass);
    }

    public static RubyClass createOracleJdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
        final RubyClass clazz = RubyJdbcConnection.getConnectionAdapters(runtime).
            defineClassUnder("OracleJdbcConnection", jdbcConnection, ORACLE_JDBCCONNECTION_ALLOCATOR);
        clazz.defineAnnotatedMethods(OracleRubyJdbcConnection.class);
        return clazz;
    }

    private static ObjectAllocator ORACLE_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
        public IRubyObject allocate(Ruby runtime, RubyClass klass) {
            return new OracleRubyJdbcConnection(runtime, klass);
        }
    };

    @JRubyMethod(name = "next_sequence_value", required = 1)
    public IRubyObject next_sequence_value(final ThreadContext context,
        final IRubyObject sequence) throws SQLException {
        return withConnection(context, new Callable<IRubyObject>() {
            public IRubyObject call(final Connection connection) throws SQLException {
                Statement statement = null; ResultSet valSet = null;
                try {
                    statement = connection.createStatement();
                    valSet = statement.executeQuery("SELECT "+ sequence +".NEXTVAL id FROM dual");
                    if ( ! valSet.next() ) return context.getRuntime().getNil();
                    return context.getRuntime().newFixnum( valSet.getLong(1) );
                }
                catch (final SQLException e) {
                    debugMessage(context, "failed to get " + sequence + ".NEXTVAL : " + e.getMessage());
                    throw e;
                }
                finally { close(valSet); close(statement); }
            }
        });
    }

    @Override // NOTE: Invalid column type:
    // getLong not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    protected IRubyObject mapGeneratedKey(final Ruby runtime, final ResultSet genKeys)
        throws SQLException {
        // NOTE: it's likely a ROWID which we do not care about :
        final String value = genKeys.getString(1); // "AAAsOjAAFAAABUlAAA"
        if ( isPositiveInteger(value) ) {
            return runtime.newFixnum( Long.parseLong(value) );
        }
        else {
            return runtime.getNil();
        }
    }

    private static boolean isPositiveInteger(final String value) {
        for ( int i = 0; i < value.length(); i++ ) {
            if ( ! Character.isDigit(value.charAt(i)) ) return false;
        }
        return true;
    }

    @Override // resultSet.wasNull() might be falsy for '' treated as null
    protected IRubyObject stringToRuby(final ThreadContext context,
        final Ruby runtime, final ResultSet resultSet, final int column)
        throws SQLException {
        final String value = resultSet.getString(column);
        if ( value == null ) return runtime.getNil();
        return RubyString.newUnicodeString(runtime, value);
    }

    @Override // booleans are emulated can not setNull(index, Types.BOOLEAN)
    protected void setBooleanParameter(final ThreadContext context,
        final Connection connection, final PreparedStatement statement,
        final int index, final Object value,
        final IRubyObject column, final int type) throws SQLException {<commit_msg>[oracle] PS - null char stream (text) should map to an empty string<commit_after>/*
 **** BEGIN LICENSE BLOCK *****
 * Copyright (c) 2006-2010 <NAME> <<EMAIL>>
 * Copyright (c) 2006-2007 <NAME> <<EMAIL>>
 * Copyright (c) 2008-2009 <NAME> <<EMAIL>>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 ***** END LICENSE BLOCK *****/
package arjdbc.oracle;

import arjdbc.jdbc.Callable;
import arjdbc.jdbc.RubyJdbcConnection;
import java.io.IOException;
import java.io.Reader;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

/**
 *
 * @author nicksieger
 */
public class OracleRubyJdbcConnection extends RubyJdbcConnection {

    protected OracleRubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
        super(runtime, metaClass);
    }

    public static RubyClass createOracleJdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
        final RubyClass clazz = RubyJdbcConnection.getConnectionAdapters(runtime).
            defineClassUnder("OracleJdbcConnection", jdbcConnection, ORACLE_JDBCCONNECTION_ALLOCATOR);
        clazz.defineAnnotatedMethods(OracleRubyJdbcConnection.class);
        return clazz;
    }

    private static ObjectAllocator ORACLE_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
        public IRubyObject allocate(Ruby runtime, RubyClass klass) {
            return new OracleRubyJdbcConnection(runtime, klass);
        }
    };

    @JRubyMethod(name = "next_sequence_value", required = 1)
    public IRubyObject next_sequence_value(final ThreadContext context,
        final IRubyObject sequence) throws SQLException {
        return withConnection(context, new Callable<IRubyObject>() {
            public IRubyObject call(final Connection connection) throws SQLException {
                Statement statement = null; ResultSet valSet = null;
                try {
                    statement = connection.createStatement();
                    valSet = statement.executeQuery("SELECT "+ sequence +".NEXTVAL id FROM dual");
                    if ( ! valSet.next() ) return context.getRuntime().getNil();
                    return context.getRuntime().newFixnum( valSet.getLong(1) );
                }
                catch (final SQLException e) {
                    debugMessage(context, "failed to get " + sequence + ".NEXTVAL : " + e.getMessage());
                    throw e;
                }
                finally { close(valSet); close(statement); }
            }
        });
    }

    @Override // NOTE: Invalid column type:
    // getLong not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    protected IRubyObject mapGeneratedKey(final Ruby runtime, final ResultSet genKeys)
        throws SQLException {
        // NOTE: it's likely a ROWID which we do not care about :
        final String value = genKeys.getString(1); // "AAAsOjAAFAAABUlAAA"
        if ( isPositiveInteger(value) ) {
            return runtime.newFixnum( Long.parseLong(value) );
        }
        else {
            return runtime.getNil();
        }
    }

    private static boolean isPositiveInteger(final String value) {
        for ( int i = 0; i < value.length(); i++ ) {
            if ( ! Character.isDigit(value.charAt(i)) ) return false;
        }
        return true;
    }

    @Override // resultSet.wasNull() might be falsy for '' treated as null
    protected IRubyObject stringToRuby(final ThreadContext context,
        final Ruby runtime, final ResultSet resultSet, final int column)
        throws SQLException {
        final String value = resultSet.getString(column);
        if ( value == null ) return runtime.getNil();
        return RubyString.newUnicodeString(runtime, value);
    }

    @Override
    protected IRubyObject readerToRuby(final ThreadContext context,
        final Ruby runtime, final ResultSet resultSet, final int column)
        throws SQLException, IOException {
        final Reader reader = resultSet.getCharacterStream(column);
        try {
            if ( resultSet.wasNull() ) return RubyString.newEmptyString(runtime);

            final int bufSize = streamBufferSize;
            final StringBuilder string = new StringBuilder(bufSize);

            final char[] buf = new char[ bufSize / 2 ];
            for (int len = reader.read(buf); len != -1; len = reader.read(buf)) {
                string.append(buf, 0, len);
            }

            return RubyString.newUnicodeString(runtime, string.toString());
        }
        finally { if ( reader != null ) reader.close(); }
    }

    @Override // booleans are emulated can not setNull(index, Types.BOOLEAN)
    protected void setBooleanParameter(final ThreadContext context,
        final Connection connection, final PreparedStatement statement,
        final int index, final Object value,
        final IRubyObject column, final int type) throws SQLException {
{'fraction_non_alphanumeric': 0.08509549795361528, 'fraction_numerical': 0.0052012278308321966, 'mean_word_length': 3.0542689249913586, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3309693', 'n_tokens_mistral': 3237, 'n_tokens_neox': 3014, 'n_words': 1015}