Skip to content

Commit

Permalink
Revert "完成#4"
Browse files Browse the repository at this point in the history
This reverts commit 090ac59.
  • Loading branch information
fantasy0v0 authored Nov 21, 2024
1 parent 090ac59 commit e35e93b
Show file tree
Hide file tree
Showing 11 changed files with 131 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

Expand All @@ -34,8 +36,8 @@ public <T> List<T> batch(List<List<Object>> batchParams, FetchMapper<T> keyMappe
}
}

private <T> T _fetchKey(FetchMapper<T> mapper,
List<Object> params) {
private <T> List<T> _fetchKey(FetchMapper<T> mapper,
List<Object> params, boolean firstOnly) {
try (ConnectionReference ref = ConnectionPoolUtil.getReference(dataSource)) {
Connection conn = ref.unwrap();
LogUtil.performance().info("fetchKey begin");
Expand All @@ -46,8 +48,7 @@ private <T> T _fetchKey(FetchMapper<T> mapper,
fillStatementParams(conn, statement, params, parameterHandler);
int updated = statement.executeUpdate();
LogUtil.sql().debug("executeUpdate: {}", updated);
List<T> list = fetchByResultSet(statement.getGeneratedKeys(), mapper, true);
return list.isEmpty() ? null : list.getFirst();
return fetchByResultSet(statement.getGeneratedKeys(), mapper, firstOnly);
} finally {
long cost = System.nanoTime() / 1000 - startTime;
NumberFormat format = NumberFormat.getNumberInstance();
Expand All @@ -58,27 +59,52 @@ private <T> T _fetchKey(FetchMapper<T> mapper,
}
}

public <T> T fetchKey(FetchMapper<T> mapper, List<Object> params) {
return _fetchKey(mapper, params);
public <T> List<T> fetchKey(FetchMapper<T> mapper, List<Object> params) {
return _fetchKey(mapper, params, false);
}

public <T> T fetchKey(FetchMapper<T> mapper, Object... params) {
public <T> List<T> fetchKey(FetchMapper<T> mapper, Object... params) {
return fetchKey(mapper, Arrays.stream(params).toList());
}

public <T> T fetchKey(FetchMapper<T> mapper) {
public <T> List<T> fetchKey(FetchMapper<T> mapper) {
return fetchKey(mapper, (List<Object>) null);
}

public Object[] fetchKey(List<Object> params) {
public List<Object[]> fetchKey(List<Object> params) {
return fetchKey(Utils::fetchByRow, params);
}

public Object[] fetchKey(Object... params) {
public List<Object[]> fetchKey(Object... params) {
return fetchKey(Arrays.stream(params).toList());
}

public Object[] fetchKey() {
public List<Object[]> fetchKey() {
return fetchKey(Utils::fetchByRow, (List<Object>) null);
}

public <T> T fetchKeyOne(FetchMapper<T> mapper, List<Object> params) {
List<T> list = _fetchKey(mapper, params, true);
return list.isEmpty() ? null : list.getFirst();
}

public <T> T fetchKeyOne(FetchMapper<T> mapper, Object... params) {
return fetchKeyOne(mapper, Arrays.stream(params).toList());
}

public <T> T fetchKeyOne(FetchMapper<T> mapper) {
return fetchKeyOne(mapper, (List<Object>) null);
}

public Object[] fetchKeyOne(List<Object> params) {
return fetchKeyOne(Utils::fetchByRow, params);
}

public Object[] fetchKeyOne(Object... params) {
return fetchKeyOne(Arrays.stream(params).toList());
}

public Object[] fetchKeyOne() {
return fetchKeyOne((List<Object>) null);
}
}
5 changes: 3 additions & 2 deletions jdbc/src/main/java/com/github/fantasy0v0/swift/jdbc/JDBC.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,9 @@ public static SelectBuilder select(String sql, Object... params) {
return select(sql, Arrays.stream(params).toList());
}

public static InsertBuilder insert(String sql) {
return new InsertBuilder(requireNonNull(dataSource), statementConfiguration, sql.trim());
@Deprecated
public static ModifyBuilder modify(String sql) {
return new ModifyBuilder(requireNonNull(dataSource), sql.trim());
}

public static UpdateBuilder update(String sql) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,7 @@ static <T> List<T> executeBatch(Connection conn, StatementConfiguration statemen
fillStatementParams(conn, statement, params, parameterHandler);
statement.addBatch();
}
int[] result = statement.executeBatch();
LogUtil.sql().debug("executeBatch: {}", result.length);
statement.executeBatch();
return fetchByResultSet(statement.getGeneratedKeys(), mapper, false);
} finally {
long cost = System.nanoTime() / 1000 - startTime;
Expand Down
61 changes: 10 additions & 51 deletions jdbc/src/test/java/test/InsertTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.container.ContainerUtil;
import test.container.JdbcContainer;
import test.container.SwiftJdbcExtension;
import test.exception.WorkException;

Expand All @@ -28,18 +30,18 @@ public class InsertTest {
void test() {
Assertions.assertThrowsExactly(WorkException.class, () -> {
transaction(() -> {
int executed = JDBC.insert("""
int executed = JDBC.modify("""
insert into student(id, name, status)
values(1000, '测试学生', 0)""").execute();
Assertions.assertEquals(1, executed);

executed = JDBC.insert("""
executed = JDBC.modify("""
insert into student(id, name, status)
values(?, ?, ?)""").execute(1001, "测试学生", 0);
Assertions.assertEquals(1, executed);

// test null
executed = JDBC.insert("""
executed = JDBC.modify("""
insert into student(id, name, status, ext)
values(?, ?, ?, ?)""").execute(1002, "测试学生", 0, null);
Assertions.assertEquals(1, executed);
Expand All @@ -63,35 +65,20 @@ void testBatch() {
batchParams.add(List.of(1004, "测试用户5", 4));
batchParams.add(List.of(1005, "测试用户6", 5));

int[] executed = JDBC.insert("""
int[] executed = JDBC.modify("""
insert into student(id, name, status)
values(?, ?, ?)""").batch(batchParams);
values(?, ?, ?)""").executeBatch(batchParams);
Assertions.assertEquals(6, executed.length);
for (int i : executed) {
Assertions.assertEquals(1, i);
}

batchParams = new ArrayList<>();
batchParams.add(List.of("测试用户1", 0));
batchParams.add(List.of("测试用户2", 1));
batchParams.add(List.of("测试用户3", 2));
batchParams.add(List.of("测试用户4", 3));
batchParams.add(List.of("测试用户5", 4));
batchParams.add(List.of("测试用户6", 5));
List<Long> keys = JDBC.insert("""
insert into swift_user(name, status) values(?, ?)
""").batch(batchParams, row -> row.getLong(1));
Assertions.assertEquals(6, executed.length);
for (long key : keys) {
Assertions.assertTrue(key > 0);
}
}

@TestTemplate
void fetch(DataSource dataSource) throws SQLException {
String driverClassName = dataSource.unwrap(HikariDataSource.class).getDriverClassName();
if (driverClassName.contains("postgresql")) {
List<Object[]> result = JDBC.insert("""
List<Object[]> result = JDBC.modify("""
insert into student(id, name, status)
values(?, ?, ?)
returning id""").fetch(1000L, "测试学生", 0);
Expand All @@ -106,45 +93,17 @@ void testDateTime(DataSource dataSource) throws SQLException {
if (driverClassName.contains("postgresql")) {
OffsetDateTime offsetDateTime = OffsetDateTime.of(1500, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
LocalDateTime localDateTime = LocalDateTime.of(1600, 1, 1, 0, 0, 0, 0);
List<Object[]> objects = JDBC.insert("""
List<Object[]> objects = JDBC.modify("""
insert into datetime_test(id, date)
values(?, ?) returning date
""").fetch(1, offsetDateTime);
log.debug("value: {}", objects.getFirst()[0]);

objects = JDBC.insert("""
objects = JDBC.modify("""
insert into datetime_test(id, date)
values(?, ?) returning date
""").fetch(1, localDateTime);
log.debug("value: {}", objects.getFirst()[0]);
}
}

@TestTemplate
void testFetchKey(DataSource dataSource) {
long key = JDBC.insert("""
insert into swift_user(name, status) values('测试学生', 0)
""").fetchKey(row -> row.getLong(1));
log.debug("key: {}", key);
Assertions.assertTrue(key > 0);

key = JDBC.insert("""
insert into swift_user(name, status) values(?, ?)
""").fetchKey(row -> row.getLong(1), "测试学生1", 1);
Assertions.assertTrue(key > 0);

Object[] row = JDBC.insert("""
insert into swift_user(name, status) values(?, ?)
""").fetchKey( "测试学生2", 2);
// pg会返回整行数据
Assertions.assertTrue(row.length > 0);
Assertions.assertTrue(((Number)row[0]).longValue() > 0);

row = JDBC.insert("""
insert into swift_user(name, status) values('测试学生3', 2)
""").fetchKey();
// pg会返回整行数据
Assertions.assertTrue(row.length > 0);
Assertions.assertTrue(((Number)row[0]).longValue() > 0);
}
}
2 changes: 2 additions & 0 deletions jdbc/src/test/java/test/SelectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.container.ContainerUtil;
import test.container.JdbcTest;
import test.container.SwiftJdbcExtension;
import test.vo.Student;

Expand Down
12 changes: 10 additions & 2 deletions jdbc/src/test/java/test/TransactionTest.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
package test;

import com.github.fantasy0v0.swift.jdbc.JDBC;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.container.ContainerUtil;
import test.container.JdbcContainer;
import test.container.SwiftJdbcExtension;

import javax.sql.DataSource;

import static com.github.fantasy0v0.swift.jdbc.JDBC.*;

@ExtendWith(SwiftJdbcExtension.class)
Expand All @@ -32,7 +40,7 @@ void test() {
transaction(() -> {
select("select * from student").fetch();
transaction(() -> {
update("update student set name = ? where id = ?")
modify("update student set name = ? where id = ?")
.execute("修改", 1L);
});
});
Expand All @@ -42,7 +50,7 @@ void test() {
@TestTemplate
void rollback() {
transaction(() -> {
update("update student set name = ? where id = ?")
modify("update student set name = ? where id = ?")
.execute("修改", 1L);
});
}
Expand Down
10 changes: 10 additions & 0 deletions jdbc/src/test/java/test/container/ContainerExecutable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package test.container;

import java.util.List;

@FunctionalInterface
public interface ContainerExecutable {

List<JdbcTest> execute();

}
32 changes: 32 additions & 0 deletions jdbc/src/test/java/test/container/ContainerUtil.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
package test.container;

import com.github.fantasy0v0.swift.jdbc.JDBC;
import org.junit.jupiter.api.DynamicTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.containers.PostgreSQLContainer;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.DynamicTest.dynamicTest;

public final class ContainerUtil {

private static final Logger log = LoggerFactory.getLogger(ContainerUtil.class);

public static final PostgreSQLContainer<?> PG = new PostgreSQLContainer<>("postgres:16-alpine");

public static final String PG_LOCATIONS = "classpath:db/pg";
Expand All @@ -20,4 +30,26 @@ public final class ContainerUtil {
JdbcContainer.create(MYSQL, MYSQL_LOCATIONS)
);

public static List<DynamicTest> testAllContainers(ContainerExecutable executable) {
List<DynamicTest> tests = new ArrayList<>();
for (JdbcContainer container : ContainerUtil.containers) {
String name = container.getDriverClassName();
tests.addAll(
executable.execute()
.stream()
.map(test -> dynamicTest(name + " " + test.name(), () -> {
DataSource dataSource = container.start();
JDBC.configuration(dataSource);
try {
test.executable().execute(dataSource);
} finally {
container.stop();
}
}))
.toList()
);
}
return tests;
}

}
11 changes: 11 additions & 0 deletions jdbc/src/test/java/test/container/JdbcExecutable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package test.container;

import javax.sql.DataSource;
import java.sql.SQLException;

@FunctionalInterface
public interface JdbcExecutable {

void execute(DataSource dataSource) throws SQLException;

}
10 changes: 10 additions & 0 deletions jdbc/src/test/java/test/container/JdbcTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package test.container;

public record JdbcTest(String name,
JdbcExecutable executable) {

public static JdbcTest of(String name, JdbcExecutable executable) {
return new JdbcTest(name, executable);
}

}
5 changes: 5 additions & 0 deletions jdbc/src/test/java/test/jdbc/TransactionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@
import com.github.fantasy0v0.swift.jdbc.exception.SwiftSQLException;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.container.ContainerUtil;
import test.container.JdbcTest;
import test.container.SwiftJdbcExtension;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import static com.github.fantasy0v0.swift.jdbc.JDBC.*;

Expand Down

0 comments on commit e35e93b

Please sign in to comment.