Elffuss BraidHub

kikocis/EDC public

main · 4.4 KiBRenderedRawPermalink
1# Sql query streaming
2
3## Decision
4
5We decided to switch the current way we are using to retrieve objects from sql query - that fetches everything in memory
6and then creates a `Stream` out of the resulting `List` - to a version where a `Stream` is actually used to iterate
7over the `ResultSet`.
8
9## Rationale
10
11Now that the EDC is being used by teams that are pushing its limits with heavy workloads we noticed, especially on catalog request,
12that a lot of time is wasted fetching all the rows in memory and then opening a stream later on.
13A `Spliterator` could be used to create a stream that actually fetches items lazily.
14
15
16## Approach
17
18To obtain streaming we would add a method in the `SqlQueryExecutor` that creates a stream with a `Spliterator` that iterates on the `ResultSet`.
19
20Here are some code snippets starting from the bottom to the top:
21
22The `SqlQueryExecutor.executeQueryStream` method:
23(note: `Statement`/`ResultSet` needs to be closed when the stream has been closed through the `onClose` method, the `Connection` closure would be attached to this event if `closeConnection` is true)
24
25```java
26public final class SqlQueryExecutor {
27
28 ...
29
30 public static <T> Stream<T> executeQueryStream(Connection connection, boolean closeConnection, ResultSetMapper<T> resultSetMapper, String sql, Object... arguments) {
31 try {
32 var statement = connection.prepareStatement(sql);
33 statement.setFetchSize(5000);
34 setArguments(statement, arguments);
35 var resultSet = statement.executeQuery();
36 return StreamSupport.stream(new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) {
37 @Override
38 public boolean tryAdvance(Consumer<? super T> action) {
39 try {
40 if (!resultSet.next()) {
41 return false;
42 }
43 action.accept(resultSetMapper.mapResultSet(resultSet));
44 return true;
45 } catch (Exception ex) {
46 throw new EdcPersistenceException(ex);
47 }
48 }
49
50 }, false).onClose(() -> {
51 // close statement/resultSet
52 if (closeConnection) {
53 // close connection
54 }
55 });
56 } catch (SQLException sqlEx) {
57 // close statement/resultSet if opened
58 if (closeConnection) {
59 // close connection
60 }
61 throw new EdcPersistenceException(sqlEx);
62 }
63 }
64
65 ...
66}
67```
68
69A caller of the `executeQueryStream` method, please note that the `Connection` is not closed by the caller anymore.
70
71```java
72public class SqlContractDefinitionStore implements ContractDefinitionStore {
73
74 ...
75
76 @Override
77 public @NotNull Stream<ContractDefinition> findAll(QuerySpec spec) {
78 return transactionContext.execute(() -> {
79 // try (var connection = getConnection()) { // the connection will be closed by the stream itself
80 try {
81 var connection = getConnection();
82 var queryStmt = statements.createQuery(spec);
83 return executeQueryStream(connection, true, this::mapResultSet, queryStmt.getQueryAsString(), queryStmt.getParameters());
84 } catch (SQLException exception) {
85 throw new EdcPersistenceException(exception);
86 }
87 });
88 }
89
90 ...
91
92}
93```
94
95One big news is that at the top of the call, the stream needs to be closed explicitly to avoid connection leaks, as
96neither `collect` nor `forEach` do that:
97
98```java
99public class PolicyDefinitionServiceImpl implements PolicyDefinitionService {
100 ...
101
102 @Override
103 public @NotNull ServiceResult<PolicyDefinition> deleteById(String policyId) {
104
105 ...
106
107 try (var contractDefinitionOnPolicy = contractDefinitionStore.findAll(queryContractPolicyFilter)) { // this will close the stream after the use
108 if (contractDefinitionOnPolicy.findAny().isPresent()) {
109 return ServiceResult.conflict(format("PolicyDefinition %s cannot be deleted as it is referenced by at least one contract definition", policyId));
110 }
111 }
112
113 ...
114
115 }
116
117}
118```
119
120This `executeQueryStream` method will likely be used by all the `.findAll` methods of the stores.