Skip to content

Commit

Permalink
完成#4
Browse files Browse the repository at this point in the history
  • Loading branch information
fantasy0v0 committed Nov 21, 2024
1 parent 0d17890 commit 57d7198
Show file tree
Hide file tree
Showing 11 changed files with 68 additions and 131 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
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 @@ -36,8 +34,8 @@ public <T> List<T> batch(List<List<Object>> batchParams, FetchMapper<T> keyMappe
}
}

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

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

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

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

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

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

public List<Object[]> fetchKey() {
public 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: 2 additions & 3 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,9 +108,8 @@ public static SelectBuilder select(String sql, Object... params) {
return select(sql, Arrays.stream(params).toList());
}

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

public static UpdateBuilder update(String sql) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ static <T> List<T> executeBatch(Connection conn, StatementConfiguration statemen
fillStatementParams(conn, statement, params, parameterHandler);
statement.addBatch();
}
statement.executeBatch();
int[] result = statement.executeBatch();
LogUtil.sql().debug("executeBatch: {}", result.length);
return fetchByResultSet(statement.getGeneratedKeys(), mapper, false);
} finally {
long cost = System.nanoTime() / 1000 - startTime;
Expand Down
61 changes: 51 additions & 10 deletions jdbc/src/test/java/test/InsertTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
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 @@ -30,18 +28,18 @@ public class InsertTest {
void test() {
Assertions.assertThrowsExactly(WorkException.class, () -> {
transaction(() -> {
int executed = JDBC.modify("""
int executed = JDBC.insert("""
insert into student(id, name, status)
values(1000, '测试学生', 0)""").execute();
Assertions.assertEquals(1, executed);

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

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

int[] executed = JDBC.modify("""
int[] executed = JDBC.insert("""
insert into student(id, name, status)
values(?, ?, ?)""").executeBatch(batchParams);
values(?, ?, ?)""").batch(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.modify("""
List<Object[]> result = JDBC.insert("""
insert into student(id, name, status)
values(?, ?, ?)
returning id""").fetch(1000L, "测试学生", 0);
Expand All @@ -93,17 +106,45 @@ 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.modify("""
List<Object[]> objects = JDBC.insert("""
insert into datetime_test(id, date)
values(?, ?) returning date
""").fetch(1, offsetDateTime);
log.debug("value: {}", objects.getFirst()[0]);

objects = JDBC.modify("""
objects = JDBC.insert("""
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: 0 additions & 2 deletions jdbc/src/test/java/test/SelectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
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: 2 additions & 10 deletions jdbc/src/test/java/test/TransactionTest.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
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 @@ -40,7 +32,7 @@ void test() {
transaction(() -> {
select("select * from student").fetch();
transaction(() -> {
modify("update student set name = ? where id = ?")
update("update student set name = ? where id = ?")
.execute("修改", 1L);
});
});
Expand All @@ -50,7 +42,7 @@ void test() {
@TestTemplate
void rollback() {
transaction(() -> {
modify("update student set name = ? where id = ?")
update("update student set name = ? where id = ?")
.execute("修改", 1L);
});
}
Expand Down
10 changes: 0 additions & 10 deletions jdbc/src/test/java/test/container/ContainerExecutable.java

This file was deleted.

32 changes: 0 additions & 32 deletions jdbc/src/test/java/test/container/ContainerUtil.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
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 @@ -30,26 +20,4 @@ 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: 0 additions & 11 deletions jdbc/src/test/java/test/container/JdbcExecutable.java

This file was deleted.

10 changes: 0 additions & 10 deletions jdbc/src/test/java/test/container/JdbcTest.java

This file was deleted.

5 changes: 0 additions & 5 deletions jdbc/src/test/java/test/jdbc/TransactionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,15 @@
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 57d7198

Please sign in to comment.