package org.arpit.projects.ignite_db_demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.ignite.Ignition;

public class SomeClass {

	public static void main(String [] args) throws SQLException
	{
		Ignition.start("F:\\apache-ignite-2.7.0-bin\\config\\default-config.xml");
		
		createIgniteDatabase();
		
		testTransaction();
		
		
	}
	static void testTransaction() throws SQLException
	{
		try
		{
			Connection conn=getConnection();
			PreparedStatement ps=conn.prepareStatement("INSERT INTO person (id, name) VALUES (?,?)");
			conn.setAutoCommit(false);
			for(int i=0;i<10;i++)
			{
				ps.setLong(1,i);
				ps.setString(2, "Person-"+i);
				ps.executeUpdate();
			}
			ps.close();
			conn.close();
			
			
			conn=getConnection();
			ps=null;
			ps=conn.prepareStatement("select * from person");
			ResultSet rs=ps.executeQuery();
			
			while(rs.next())
			{
				System.out.println("["+rs.getInt("id")+","+rs.getString("name")+"]");
			}
			rs.close();
			ps.close();
			conn.close();
		}
		catch(Exception e)
		{
			System.out.println("Caught Exception For Transction:"+e.getMessage());
		}
	}
	static void createIgniteDatabase() {
		try {
			
			Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
			Connection conn = getConnection();
			
			
			try (Statement stmt = conn.createStatement()) {

			    // Create table based on PARTITIONED template with one backup
			    stmt.executeUpdate("CREATE TABLE person (" +
			    " id INTEGER, name VARCHAR," +
			    " PRIMARY KEY (id)) " +
			    " WITH \"backups=1, affinityKey=id\"");
			}
			
			/*
			 * try (Statement stmt = conn.createStatement()) {
			 * 
			 * // Create an index on the Person table
			 * stmt.executeUpdate("CREATE INDEX idx_person_name ON Person (name)"); }
			 */
			
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unused")
	static Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/");
	}
}
