package froop.db.jdbc;

import froop.domain.SampleData;

import java.sql.*;
import java.util.Optional;

/**
 * JDBCでデータベースに直接アクセスするサンプル.
 */
public class JdbcSample implements SampleData {
  private static final String DB_URL = "jdbc:derby:data/derby/sample";
  private static final String SQL_SELECT = "SELECT name FROM sample WHERE id=?";
  private static final String SQL_UPDATE = "UPDATE sample SET name=? WHERE id=?";

  @Override
  public Optional<String> queryNameById(long id) {
    return execute(conn -> {
      try (PreparedStatement stmt = conn.prepareStatement(SQL_SELECT)) {
        stmt.setLong(1, id);
        try (ResultSet rs = stmt.executeQuery()) {
          if (rs.next()) {
            return Optional.of(rs.getString("name"));
          } else {
            return Optional.empty();
          }
        }
      }
    });
  }

  @Override
  public void update(long id, String name) {
    executeUpdate(conn -> {
      try (PreparedStatement stmt = conn.prepareStatement(SQL_UPDATE)) {
        stmt.setString(1, name);
        stmt.setLong(2, id);
        stmt.execute();
      }
    });
  }

  private void executeUpdate(UpdateSqlExecutor executor) {
    execute(conn -> {
      executor.execute(conn);
      return null;
    });
  }

  @FunctionalInterface
  private static interface UpdateSqlExecutor {
    void execute(Connection conn) throws SQLException;
  }

  private <R> R execute(SqlExecutor<R> executor) {
    try (Connection conn = DriverManager.getConnection(DB_URL)) {
      return executor.execute(conn);
    } catch (SQLException e) {
      throw new IllegalStateException(e);
    }
  }

  @FunctionalInterface
  private static interface SqlExecutor<R> {
    R execute(Connection conn) throws SQLException;
  }
}

@@ -921,76 +921,8 @@
 ate(
-conn -%3E %7B%0A      try (PreparedStatement stmt = conn.prepareStatement(
 SQL_
@@ -927,18 +927,25 @@
 L_UPDATE
-))
+, stmt -%3E
  %7B%0A     
@@ -1005,40 +1005,8 @@
 d);%0A
-        stmt.execute();%0A      %7D%0A
     
@@ -1043,16 +1043,34 @@
 eUpdate(
+String sqlString, 
 UpdateSq
@@ -1070,23 +1070,23 @@
 pdateSql
-Executo
+Setuppe
 r execut
@@ -1119,24 +1119,139 @@
 %7B%0A      
-executor
+try (PreparedStatement statement = conn.prepareStatement(sqlString)) %7B%0A        executor.setup(statement);%0A        statement
 .execute
@@ -1247,28 +1247,24 @@
 ent.execute(
-conn
 );%0A      ret
@@ -1256,24 +1256,26 @@
 te();%0A      
+ 
+ 
 return null;
@@ -1275,16 +1275,24 @@
 n null;%0A
+      %7D%0A
     %7D);%0A
@@ -1355,23 +1355,23 @@
 pdateSql
-Executo
+Setuppe
 r %7B%0A    
@@ -1375,39 +1375,49 @@
    void 
-execute(Connection conn
+setup(PreparedStatement statement
 ) throws

modify UpdateSqlSetupper <- UpdateSqlExecutor