//***************************************************************************
// (c) Copyright IBM Corp. 2007 All rights reserved.
// 
// The following sample of source code ("Sample") is owned by International 
// Business Machines Corporation or one of its subsidiaries ("IBM") and is 
// copyrighted and licensed, not sold. You may use, copy, modify, and 
// distribute the Sample in any form without payment to IBM, for the purpose of 
// assisting you in the development of your applications.
// 
// The Sample code is provided to you on an "AS IS" basis, without warranty of 
// any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR 
// IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do 
// not allow for the exclusion or limitation of implied warranties, so the above 
// limitations or exclusions may not apply to you. IBM shall not be liable for 
// any damages you suffer as a result of using, copying, modifying or 
// distributing the Sample, even if IBM has been advised of the possibility of 
// such damages.
//***************************************************************************
//
// SOURCE FILE NAME: Batch1Demo.sqlj
//
// SAMPLE: SQLJ batching -- How SQLJ batching works
//
//         This sample program shows how batching works in SQLJ.
//         If setBatching() is true and any non-batchable statements (e.g.
//         SELECT) or batch incompatible statement (e.g. INSERT with 3 
//         parameters) is encountered, SQLJ will implicitly execute the
//         pending batch. 
//
//         This sample program uses the DataSource jdbc/DB2SimpleDataSource_ds1 
//         from JNDI. The DataSource is registered using createRegisterDS.java 
//         and DS1.prop. Refer to the README file for details on how to run
//         this sample. 
//
//
// SQL Statements USED:
//         SELECT
//
// Classes used from Util.sqlj are:
//         Data
//
//                           
// Output will vary depending on the JDBC driver connectivity used.
//***************************************************************************
//
// For more information on the sample programs, see the README file.
//
// For information on developing Java applications see the Developing Java Applications book.
//
// For information on using SQL statements, see the SQL Reference.
//
// For the latest information on programming, compiling, and running DB2
// applications, visit the DB2 Information Center at
//     http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp
//**************************************************************************/

import java.sql.*;
import sqlj.runtime.*;
import sqlj.runtime.ref.*;

#sql iterator bd1_simpleNameIter(int c1, String c2);
#sql context Batch1_Ctx with (dataSource="jdbc/DB2SimpleDataSource_ds1");

class Batch1Demo 
{

  static Batch1_Ctx ctx = null;

  public static void main(String argv[]) throws SQLException
  {
    System.out.println();
    System.out.println(
      "THIS SAMPLE SHOWS HOW BATCHING WORKS IN SQLJ. \n");
    
    // Obtain Connection Context from DataSource jdbc/DB2SimpleDataSource_ds1
    ctx = new Batch1_Ctx();
    
    try
    {
      // Shows how batching works in SQLJ
      batchingInSQLJ(ctx);
      cleanup();
    }
    catch(Exception ex)
    {
      if (ex instanceof java.sql.SQLException)
      {
        System.out.println("error code: " +
             ((java.sql.SQLException)(ex)).getErrorCode());
        System.out.println("error message: " + ex.getMessage());
       }
       ex.printStackTrace();
    }
  }

 
  static void batchingInSQLJ( Batch1_Ctx ctx2 )
  {
    try 
    {
      ExecutionContext exCtx2 = ctx2.getExecutionContext();
      System.out.println("  Execution Contexts exCtx2 is created.\n");

      exCtx2.setBatching(true);
      System.out.println("  SetBatching() is set to true for exCtx2.\n");

      exCtx2.setBatchLimit(2);
      System.out.println(
        " **************************************************\n" +
        " **  Batch Limit is set to '2' rows for exCtx2.  **\n" +
        " **************************************************\n");

      // Insert one row into the testing table Batch_Test1
      System.out.println("  Insert one row into the table Batch_test1: \n");
 
      int index=1;
      String col2 = "ACE";
      #sql [ctx2, exCtx2] { INSERT INTO Batch_Test1 VALUES(:index, :col2) };
      System.out.println(
        "    INSERT INTO Batch_Test1 VALUES(" + index + ", " + col2 + ")\n");       

      // Retrieve and display the data in the table Batch_Test1
      // NOTE: This will trigger implicit execute and updates will go through
      // without executeBatch()
      System.out.println(
        "  Display the content of the table Batch_Test1 by performing\n" +
        "  the following SQL statement in 'SQLJ':\n\n" +
        "    SELECT * from Batch_Test1\n");

      bd1_simpleNameIter nameIter1 = null;
      #sql [ctx2] nameIter1 =  { SELECT * FROM Batch_Test1 };

      System.out.println(
        "  Results:\n\n" +
        "    INDEX  VALUE \n" +
        "    ------ -------- ");

      while (nameIter1.next())
      {
        System.out.println("    "+Data.format(nameIter1.c1(),6)+
                           " "+Data.format(nameIter1.c2(),8));
        System.out.println("");
      }

      System.out.println("");
      System.out.println(
        "  Note: The data we inserted in the table is returned without\n" +
        "        waiting for the second insert or explicit batch execute.\n" +
        "        Although the INSERT statement is a batch compatible \n" +
        "        statement but because the SQLJ SELECT is not batchable, \n" +
	"        an implicit batch execute has been triggered. \n");
    }
    catch(Exception ex)
    {
      if (ex instanceof java.sql.SQLException)
      {
        System.out.println("error code: " +
             ((java.sql.SQLException)(ex)).getErrorCode());
        System.out.println("error message: " + ex.getMessage());
       }
       ex.printStackTrace();
    }
  }
  
  private static void  cleanup() throws SQLException
  {
    #sql [ctx] { DELETE FROM Batch_Test1 WHERE 1=1 };
  }
}