Skip to content

Commit

Permalink
Merge pull request #46 from ZorTik/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
ZorTik authored Feb 11, 2024
2 parents 6f28931 + 10c1363 commit cab6bd3
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.zort.sqllib;

import com.google.common.annotations.Beta;
import lombok.Getter;
import me.zort.sqllib.api.DefsVals;
import me.zort.sqllib.api.ObjectMapper;
Expand All @@ -25,6 +26,7 @@

import java.io.Closeable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -141,6 +143,10 @@ public SQLDatabaseConnection(final @NotNull SQLConnectionFactory connectionFacto

public abstract QueryRowsResult<Row> query(String query);

@Beta
@Nullable
public abstract ResultSet queryRaw(Query query) throws SQLException;

/**
* Executes given query and returns execution result.
* This result does not contain any rows. If you want to
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.zort.sqllib;

import com.google.common.annotations.Beta;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -32,6 +33,8 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.*;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -274,11 +277,14 @@ public QueryRowsResult<Row> query(final @NotNull String query) {
@NotNull
QueryRowsResult<Row> query(final @NotNull Query query, boolean isRetry) {
Objects.requireNonNull(query);
if (!handleAutoReconnect())
if (!handleAutoReconnect()) {
return new QueryRowsResult<>(false, "Cannot connect to database!");
}

QueryResult cachedResult = cacheManager.get(query, false);
if (cachedResult instanceof QueryRowsResult) return (QueryRowsResult<Row>) cachedResult;
if (cachedResult instanceof QueryRowsResult) {
return (QueryRowsResult<Row>) cachedResult;
}

try (PreparedStatement stmt = buildStatement(query);
ResultSet resultSet = stmt.executeQuery()) {
Expand Down Expand Up @@ -310,6 +316,31 @@ QueryRowsResult<Row> query(final @NotNull Query query, boolean isRetry) {
}
}

/**
* Executes given query and returns raw ResultSet.
* Please note that this function is not recommended to be frequently used and is provided
* as is as feature.
*
* @param query Query to use for building query string.
* @return ResultSet object or null if there was an error in connection.
* @throws SQLException If there was an error while executing query.
*/
@Beta
@Nullable
public ResultSet queryRaw(Query query) throws SQLException {
Objects.requireNonNull(query);
if (!handleAutoReconnect()) {
return null;
}
try (PreparedStatement stmt = buildStatement(query);
ResultSet resultSet = stmt.executeQuery()) {
// Create in-memory cached result set
CachedRowSet cachedResultSet = RowSetProvider.newFactory().createCachedRowSet();
cachedResultSet.populate(resultSet);
return cachedResultSet;
}
}

/**
* Executes given query and returns execution result.
* This result does not contain any rows. If you want to
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.zort.sqllib.internal.query;

import com.google.common.annotations.Beta;
import lombok.Getter;
import me.zort.sqllib.SQLDatabaseConnection;
import me.zort.sqllib.SQLDatabaseConnectionImpl;
Expand Down Expand Up @@ -48,6 +49,41 @@ public QueryNode(@Nullable P parent, List<QueryNode<?>> initial, int priority) {
this.details = new ConcurrentHashMap<>();
}

/**
* Creates a new QueryNode from a query string in PreparedStatement format and
* parameters to replace question marks in the query. This is useful if there is no
* other way to create a query than using raw SQL details.
* <p></p>
* Example:
* <pre>
* Query query = QueryNode.fromRawQuery("SELECT * FROM table WHERE id = ?", 1);
* </pre>
*
* @param query
* @param params
* @return
*/
@Beta
public static QueryNode<?> fromRawQuery(String query, Object... params) {
return new QueryNode<>(null, Collections.emptyList(), QueryPriority.GENERAL) {
@Override
public QueryDetails buildQueryDetails() {
Map<String, Object> values = new HashMap<>();
String preparedStr = query;
int index = 0;
while (true) {
final String before = preparedStr;
preparedStr = before.replaceFirst("\\?", String.format("<val_%d>", index));
if (preparedStr.equals(before)) {
break;
}
values.put("val_" + index, params[index]);
}
return new QueryDetails(preparedStr, values);
}
};
}

/**
* Builds the query string with placeholders containing values
* for passing into PreparedStatement.
Expand Down
29 changes: 28 additions & 1 deletion src/test/java/me/zort/sqllib/test/TestCase1.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.zort.sqllib.SQLConnectionBuilder;
import me.zort.sqllib.api.Query;
import me.zort.sqllib.internal.annotation.NullableField;
import me.zort.sqllib.internal.annotation.PrimaryKey;
import me.zort.sqllib.internal.query.QueryDetails;
import me.zort.sqllib.internal.query.QueryNode;
import me.zort.sqllib.pool.SQLConnectionPool;
import me.zort.sqllib.SQLDatabaseConnection;
import me.zort.sqllib.SQLDatabaseOptions;
Expand All @@ -14,12 +17,14 @@
import me.zort.sqllib.api.provider.Select;
import me.zort.sqllib.internal.impl.DefaultSQLEndpoint;
import me.zort.sqllib.transaction.TransactionFlow;
import me.zort.sqllib.util.Pair;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

Expand Down Expand Up @@ -196,7 +201,29 @@ public void test6_Transactions() {
}

@Test
public void test7_Close() {
public void test7_RawNode() {
String raw = "SELECT * FROM " + table + " WHERE nickname = ?";
QueryNode<?> query = QueryNode.fromRawQuery(raw, "User1");
Pair<String, Object[]> preparedQuery = query.toPreparedQuery();
assertEquals(raw, preparedQuery.getFirst());
assertArrayEquals(new Object[]{"User1"}, preparedQuery.getSecond());
}

@Test
public void test8_RawQuery() {
Query query = QueryNode.fromRawQuery("SELECT * FROM " + table + " WHERE nickname = ?", "User1");
try {
ResultSet result = connection.queryRaw(query);
assertNotNull(result);
assertTrue(result.next());
assertEquals("User1", result.getString("nickname"));
} catch (SQLException e) {
fail(e);
}
}

@Test
public void test9_Close() {
System.out.println("Closing connection...");
connection.disconnect();
System.out.println("Connection closed");
Expand Down

0 comments on commit cab6bd3

Please sign in to comment.