public static DB<Unit> insert(Iterable<Employee> xs) { return new BatchUpdateOp<>("INSERT INTO EMPLOYEES (ID, NAME, DEPARTMENT_ID) VALUES (?, ?, ?)", x -> ps -> { ps.setInt(1, x.id); ps.setString(2, x.name); ps.setInt(3, x.departmentId); }, xs) .map(ignore -> Unit.unit()); }
@Override public Option<Integer> run(Connection c) throws SQLException { if (Collections.isEmpty(as)) { return Option.none(); } if (!isInsert(sql)) { throwIfAutoCommit(c); } try (PreparedStatement preparedStatement = c.prepareStatement(sql)) { return binder.f(preparedStatement); } }
public static DB<Option<Integer>> insertMany(Iterable<String> descriptions) { return new BatchUpdateOp<>( //SQL "INSERT INTO STUFF(DESCRIPTION) VALUES(?)", //given the current element of the iterable, return a binder which sets the parameters for that element // if you extracted the binder from the previous operations in a field named SET_DESCRIPTION, code becomes // description -> SET_DESCRIPTION description -> ps -> ps.setString(1, description), //the iterables to insert descriptions ); }
@Test public void selectBy() { DB<Unit> insertIt = insertKeysOp(list("a")) .bind(ids -> insertDataOp(ids.zip(list("my_description"))).map(ignore -> Unit.unit())); DB.submit(insertIt); List<String> descriptions = DB.submit(selectByDescOp("my_description")); assertEquals(list("my_description"), descriptions); }
@Test public void chainedTransaction() { DB<List<String>> readInserted = insertKeysOp(asList("a", "b", "c")).bind(ids -> { List<P2<Integer, String>> data = ids.zip(list("Pesho", "Gosho", "Dragan")); return insertDataOp(data).bind(whatever -> SELECT_ALL_DATA_OP); }); List<String> result = DB.transact(readInserted); assertThat(result, is(list("Pesho", "Gosho", "Dragan"))); }
private static BatchUpdateOp<P2<Integer, String>> insertDataOp(Iterable<P2<Integer, String>> data) { return new BatchUpdateOp<>("INSERT INTO MySqlTest_DATA VALUES (?, ?)", x -> st -> { st.setInt(1, x._1()); st.setString(2, x._2()); }, data); }
@Test public void rollback2() { DB<Unit> failedInsert = insertKeysOp(list("ok")) .bind(ids -> insertDataOp(ids.zip(list("description"))).bind(insertCount -> { throw new RuntimeException("failed I have"); })); swallow(() -> DB.transact(failedInsert)); DB<P2<Long, Long>> tryCounts = COUNT_IDS.bind(idCount -> COUNT_DATA.map(dataCount -> p(idCount, dataCount))); P2<Long, Long> counts = DB.submit(tryCounts); assertEquals(0, (long) counts._1()); assertEquals(0, (long) counts._2()); }
DB.transact(new BatchUpdateOp<>( "whatevs", ps -> {
new BatchUpdateOp<>( "INSERT INTO FOO(WHATEVER) VALUES(?)", x -> preparedStatement -> preparedStatement.setString(1, x),