/****************************************************************************
** (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: xmlinsert.sqc
** SAMPLE: This sample demonstrates different ways of inserting a XML document
**         into a column of XML data type.
**
** SQL STATEMENTS USED:
**                      INSERT
**                      ROLLBACK
** SQL/XML FUNCTION USED:
**                      XMLPARSE
**                      XMLVALIDATE
**                      DOCUMENT 
**                      XMLCAST
**                           
*****************************************************************************
**
** For more information on the sample programs, see the README file.
**
** For information on developing embedded SQL applications see the Developing Embedded SQL Applications book.
**
** For information on using SQL statements, see the SQL Reference.
**
** For the latest information on programming, building, and running DB2
** applications, visit the DB2 Information Center:
**     http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp
****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlenv.h>
#include <sqlutil.h>
#include "utilemb.h"

EXEC SQL INCLUDE SQLCA;

EXEC SQL BEGIN DECLARE SECTION;
  char xmldata[2000];
  char invalidxmldata[2000];
  short nullind;
  static SQL TYPE IS XML AS CLOB(1k) xmlclob1=SQL_CLOB_INIT("<a> a </a>") ;
  static SQL TYPE IS BLOB(1k) hv_blob2 = SQL_BLOB_INIT("<init> a </init>");
  static SQL TYPE IS XML AS BLOB(1k) xmlblob3 = SQL_BLOB_INIT("<init> a</init>");
  static SQL TYPE IS XML AS CLOB(1k) invaliddata = SQL_BLOB_INIT("<init> a </init>");
EXEC SQL END DECLARE SECTION;

int createtables(void);
int droptables(void);

int main(int argc, char *argv[])
{
  int rc = 0;
  int charcount = 0;
  char prep_string[200];
  char stmt[600];
  char dbAlias[SQL_ALIAS_SZ + 1];
  char user[USERID_SZ + 1];
  char pswd[PSWD_SZ + 1];
  nullind = 0;
 

  /* Create a XML document that will be used to INSERT in the table */
   strcpy (xmldata, "<product pid=\"10\"><description>"
                    "<name> Plastic Casing </name>"
                    "<details> Blue Color </details>"
                    "<price> 2.89 </price>"
                    "<weight> 0.23 </weight>");

  /* invalid xml data will not have the closing tags for */
  /* description and product */
  strcpy(invalidxmldata, xmldata);
 
  strcat(xmldata, "</description></product>");
  strcpy(xmlclob1.data, xmldata);
  strcpy(hv_blob2.data, xmldata);
  strcpy(xmlblob3.data, xmldata);

  /* Set the length of the data */ 
  xmlclob1.length = strlen(xmldata) + 1;
  hv_blob2.length = xmlclob1.length;
  xmlblob3.length = xmlclob1.length;
  
  /* check the command line arguments */
  rc = CmdLineArgsCheck1(argc, argv, dbAlias, user, pswd);
  if (rc != 0)
  {
    return rc;
  }

  /* connect to database */
  rc = DbConn(dbAlias, user, pswd);
  if (rc != 0)
  {
    return rc;
  }
  
  /* call function to create needed tables */
  rc = createtables();
  
  /* inserting when source is from host variable of type XML AS CLOB */
  printf(" Inserting when source is from host variable of type XML AS CLOB\n");
  EXEC SQL INSERT INTO purchaseorder (poid, porder)   
             VALUES (1612, :xmlclob1:nullind);
  EMB_SQL_CHECK("INSERTING with host variable of type XML as CLOB"); 
 
  /* inserting when source is from host variable of type BLOB */
  printf(" Inserting when source is from host variable of type BLOB\n");
  EXEC SQL INSERT INTO purchaseorder (poid, porder)  
             VALUES (712, XMLPARSE(DOCUMENT :hv_blob2:nullind STRIP WHITESPACE));
  EMB_SQL_CHECK("INSERTING with host variable of type BLOB");

  /* inserting when source is from host variable of type BLOB */
  /* implicit parsing is done here */
  printf(" Inserting when source is from host variable of type BLOB with Implicit parsing\n");
  EXEC SQL INSERT INTO purchaseorder (poid, porder)  
             VALUES (1111, :hv_blob2:nullind);
  EMB_SQL_CHECK("INSERTING with host varible of type BLOB");

  printf(" This insert should fail as the XML doc is not well-formed\n");
  /* inserting when source is from hostvariable of type VARCHAR */
  /* and the data is not a well-formed XML document */
  EXEC SQL INSERT INTO purchaseorder (poid, porder)   
             VALUES (2181, XMLPARSE(DOCUMENT :invalidxmldata:nullind preserve whitespace));
  if (sqlca.sqlcode != 0)
    {
      printf("\n Insertion failed as the document is not a wellformed document\n");
      printf(" FAILED WITH SQLCODE = %d\n\n", sqlca.sqlcode);
    }
  
  /* insert a XML document when target is from another column of type XML */
  /* using Implicit parsing */
  /* add a number to POID to avoid unique constraint conflict */
  printf(" Insert a XML document when target is from another column of type XML\n");
  printf(" Using Implicit parsing\n");
  EXEC SQL INSERT INTO purchaseorder(poid, porder) 
    (SELECT POID+5, porder FROM purchaseorder WHERE poid = 1111);
  EMB_SQL_CHECK("Insert from another column of XML data type"); 

  /* insert when source is a XML document from a column */
  /* of type VARCHAR */
  printf(" Insert when source is a XML document from a column of type VARCHAR\n");
  strcpy(stmt, "INSERT INTO purchaseorder (poid, porder) "
               "(SELECT  id, XMLPARSE( DOCUMENT desc) FROM vartable where "
               "id = 11111)");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK(" Insert from another column of type VARCHAR");

  /* insert when source is a XML document from a column */
  /* of type VARCHAR, Using Implicit Parsing */
  printf(" Insert when source is a XML document from a column of type VARCHAR, Using Implicit Parsing\n");
  strcpy(stmt, "INSERT INTO purchaseorder (poid, porder) "
               "(SELECT id, desc FROM vartable WHERE "
               "id = 22222)");
   EXEC SQL EXECUTE IMMEDIATE :stmt;
   EMB_SQL_CHECK("Insert from another column of type VARCHAR using implicit Parsing");

  /* insert when source is a variable of a simple type */
  /* it is typecasted to XML using the XMLCAST function */
  printf(" Insert when source is a variable of a simple type\n");
  strcpy(prep_string, "INSERT INTO purchaseorder (poid, porder) ");
  strcat(prep_string, "VALUES ( 1092, XMLCAST( ? AS XML))");
  EXEC SQL PREPARE stmt FROM :prep_string;
  EMB_SQL_CHECK("Preparing the statement");
  EXEC SQL EXECUTE stmt using :xmldata;
  EMB_SQL_CHECK("Executing the Insert statement");

  /* use XML Functions to create a XML document */
  /* insert this document into the table */
  printf(" Use XML Functions to create a XML document\n");
  printf(" Insert this document into the table \n");
  strcpy(stmt, "INSERT INTO purchaseorder (poid, porder)"
               "(SELECT  id, XMLDOCUMENT( XMLELEMENT( NAME \"PORDER\","
               " XMLELEMENT( NAME \"ID\", XMLATTRIBUTES( v.id as PRODID)),"
               " XMLELEMENT( NAME \"DESC\", v.desc)))"
               " FROM vartable AS v WHERE ID = 33333)");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK("Use XML functions to create XML doc");

  printf(" This insert should fail as the XML doc is as per Schema\n");
 
  /* validate an invalid XML document before inserting into the table */
  printf(" Validate an invalid XML document before inserting into the table\n");
  EXEC SQL INSERT INTO purchaseorder(poid, porder)
             VALUES (2181, XMLVALIDATE(:invaliddata:nullind ACCORDING TO XMLSCHEMA ID PRODUCT));
  if (sqlca.sqlcode != 0)          
    {
      printf("\n Insertion failed as the document is not a VALID XML document\n");
      printf(" FAILED WITH SQLCODE = %d\n\n", sqlca.sqlcode);
    }
  
  /* validate an XML document when target is from another column */
  /* add a number to POID to avoid unique constraint conflict */
  printf(" Validate an XML document when target is from another column\n");
  EXEC SQL INSERT INTO purchaseorder(poid, porder) 
    (SELECT poid+15, XMLVALIDATE(porder ACCORDING TO XMLSCHEMA ID PRODUCT) FROM purchaseorder
    WHERE poid = 1111);
  EMB_SQL_CHECK("Insert from another column of XML data type"); 
  
  EXEC SQL ROLLBACK;
  EMB_SQL_CHECK("ROLLBACK"); 
  
  /* Call function for cleanup */
  rc = droptables();

  /* disconnect from the database */
  rc = DbDisconn(dbAlias);
  if (rc != 0)
  {
    return rc;
  }
 
  return 0;
} /* main */

/* Create tables */
int createtables(void)
{
  int rc = 0;
  char stmt[800];
  
  strcpy(stmt, "CREATE TABLE vartable (id INT,"
               " desc VARCHAR(200), comment VARCHAR(25))");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK("Table--Creation");
  
  strcpy(stmt, "INSERT INTO vartable VALUES "
               "(11111, \'<NAME><FIRSTNAME> Neeraj </FIRSTNAME>"
               "<LASTNAME> Gaurav </LASTNAME></NAME>\', "
               "\'Final Year\')");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK("Table--Insert");
  
  strcpy(stmt, "INSERT INTO vartable VALUES "
               "(22222, '<product pid=\"80\">"
               "<description><name> Plastic Casing </name>"
               "<details> Green Color </details>"
               "<price> 7.89 </price>"
               "<weight> 6.23 </weight>"
               "</description></product>', "
               "'Last Product')");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK("Table--Insert");

  strcpy(stmt, "INSERT INTO vartable VALUES "
               "(33333, \'<NAME><FIRSTNAME> Neeraj </FIRSTNAME>"
               "<LASTNAME> Gaurav </LASTNAME></NAME>\', "
               "\'Final Year\')");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK("Table--Insert");

  EXEC SQL COMMIT;
  EMB_SQL_CHECK("COMMIT");
  
  return 0; 
}

int droptables(void)
{
  int rc = 0;
  char stmt[200];
  
  strcpy(stmt, "DROP TABLE VARTABLE");
  EXEC SQL EXECUTE IMMEDIATE :stmt;
  EMB_SQL_CHECK("Table--Drop");
  
  EXEC SQL COMMIT;
  EMB_SQL_CHECK("COMMIT");
  
  return 0;
}