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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Consumer;
import java.sql.Statement;

public class TestFunctional {
    private static Integer get(Connection con, String key) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("SELECT cvalue FROM functional_cache WHERE ckey = ?");
        pstmt.setString(1, key);
        ResultSet rs = pstmt.executeQuery();
        Integer res = null;
        if(rs.next()) {
            res = rs.getInt(1);
        }
        rs.close();
        pstmt.close();
        return res;
    }
    private static void put(Connection con, String key, Integer value) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("MERGE INTO functional_cache(ckey,cvalue) VALUES(?,?)");
        pstmt.setString(1, key);
        pstmt.setInt(2, value);
        pstmt.executeUpdate();
        pstmt.close();
    }
    private static void remove(Connection con, String key) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("DELETE FROM functional_cache WHERE ckey = ?");
        pstmt.setString(1, key);
        pstmt.executeUpdate();
        pstmt.close();
    }
    private static void listall(Connection con, Consumer<ResultSet> f) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("SELECT ckey,cvalue FROM functional_cache");
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()) {
            f.accept(rs);
        }
        rs.close();
        pstmt.close();
    }
    private static void test(Connection con) throws InterruptedException, SQLException {
        // basic put, get and remove
        put(con, "v", 123);
        System.out.println(get(con, "v"));
        remove(con, "v");
        System.out.println(get(con, "v"));
        put(con, "v", 123);
        System.out.println(get(con, "v"));
        // persistence
        Integer counter = get(con, "counter");
        if(counter == null) {
            counter = 0;
        }
        counter++;
        System.out.println(counter);
        put(con, "counter", counter);
        // list all
        listall(con, (ResultSet rs) -> { try { System.out.println(rs.getString(1) + " = " + rs.getInt(2)); } catch (SQLException e) { } } );
        // listener not supported using thin
    }
    public static void main(String[] args) throws Exception {
        Connection con = DriverManager.getConnection("jdbc:ignite:thin://localhost:10800");
        Statement stmt = con.createStatement();
        stmt.executeUpdate("CREATE TABLE IF NOT EXISTS functional_cache (ckey VARCHAR(16) NOT NULL, cvalue INTEGER NOT NULL, PRIMARY KEY(ckey))");
        stmt.close();
        test(con);
        con.close();
    }
}
