// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package nosql.orientdb.relational;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class TestJDBC {
	private static void dump(Statement sel, String criteria) throws SQLException {
		System.out.println("dumping " + criteria);
		ResultSet rs = sel.executeQuery("SELECT orderId,customer,items.itemNo,items.itemName,items.itemPrice,items.quantity FROM Order " + criteria);
		while(rs.next()) {
			int orderId = rs.getInt(1);
			String customer = rs.getString(2);
			@SuppressWarnings("unchecked")
			List<Integer> itemNo = (List<Integer>)rs.getObject(3);
			@SuppressWarnings("unchecked")
			List<String> itemName = (List<String>)rs.getObject(4);
			@SuppressWarnings("unchecked")
			List<Double> price = (List<Double>)rs.getObject(5);
			@SuppressWarnings("unchecked")
			List<Integer> quantity = (List<Integer>)rs.getObject(6);
			System.out.printf("(%d,%s) ->\n", orderId, customer);
			for(int i = 0; i < itemNo.size(); i++) {
				System.out.printf("  (%d,%s,%.2f,%d)\n", itemNo.get(i), itemName.get(i), price.get(i), quantity.get(i));
			}
		}
		rs.close();
	}
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		Class.forName("com.orientechnologies.orient.jdbc.OrientJdbcDriver");
		Connection con = DriverManager.getConnection("jdbc:orient:remote:localhost/test4", "admin", "hemmeligt");
		Statement sel = con.createStatement();
        dump(sel, ""); // all
        dump(sel, "WHERE orderId = 2"); // where id=2
        dump(sel, "WHERE customer = 'A A'"); // where customer='A A'
        dump(sel, "WHERE customer LIKE 'A%'"); // where customer like 'A%'
        dump(sel, "WHERE items.itemName CONTAINS 'i5 CPU'"); // where items.name='i5 CPU'
        // **** I can't get it working ****  // where items.name like '%Java%'
        dump(sel, "WHERE orderId IN [1,2]"); // where id in (1,2)
        // **** I can't get it working ****  // where exists items.note
		sel.close();
		con.close();
	}
}
