import java.sql.*;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader;

/**
 * Inserts a CLOB of some size with logging of SQL statements turned on.
 * Derby used to print the contents of LOBs to derby.log in such a way
 * that an OutOfMemoryError was caused.
 * derby.jar and derbyTesting.jar must be in the classpath, and the
 * repro should be run with default VM settings.
 */
public class ReproDerby1693 {

    public static void main(String[] args)
            throws Exception {
        System.setProperty("derby.language.logStatementText", "true");
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        Connection con = DriverManager.getConnection(
                "jdbc:derby:ReproDerby1693DB;create=true");
        Statement stmt = con.createStatement();
        // Try to drop the table, then create.
        try {
            stmt.executeUpdate("drop table clobs");
        } catch (SQLException sqle) {
            if (!sqle.getSQLState().equals("42Y55")) {
                throw sqle;
            }
        }
        stmt.executeUpdate("create table clobs (clobData clob)");
        stmt.close();
        // Insert a Clob that is likely to cause out-of-memory error if
        // the bug reported by DERBY-1693 is not fixed.
        PreparedStatement pStmt = con.prepareStatement(
                "insert into clobs values (?)");
        int clobSize = 50*1024*1024; // 50 MB
        pStmt.setCharacterStream(1,
                                 new LoopingAlphabetReader(clobSize),
                                 clobSize);
        pStmt.executeUpdate();
        pStmt.close();
        con.close();
        System.out.println("Success!");
    }

} // End class ReproDerby1693
