Skip to content

Commit

Permalink
Add put/get for transactions.
Browse files Browse the repository at this point in the history
  • Loading branch information
io7m committed May 27, 2024
1 parent 97143fd commit e5ca75b
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@

package com.io7m.darco.api;

import com.io7m.jmulticlose.core.CloseableCollection;
import com.io7m.jmulticlose.core.CloseableCollectionType;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Context;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
Expand All @@ -48,6 +51,8 @@ public abstract class DDatabaseTransactionAbstract<
private final N connection;
private final Span transactionSpan;
private final Map<Class<?>, Q> queries;
private final CloseableCollectionType<DDatabaseException> resources;
private final HashMap<Class<?>, Object> values;

protected DDatabaseTransactionAbstract(
final C inConfiguration,
Expand All @@ -63,6 +68,42 @@ protected DDatabaseTransactionAbstract(
Objects.requireNonNull(inTransactionScope, "inMetricsScope");
this.queries =
Objects.requireNonNull(inQueries, "queries");
this.resources =
CloseableCollection.create(() -> {
return new DDatabaseException(
"One or more resources could not be closed.",
"error-resource-close",
Map.of(),
Optional.empty()
);
});

this.values =
new HashMap<>();
}

@Override
public final <V> void put(
final Class<? extends V> clazz,
final V value)
{
if (value instanceof final AutoCloseable closeable) {
this.resources.add(closeable);
}
this.values.put(clazz, value);
}

@Override
public final <V> V get(
final Class<V> clazz)
{
return Optional.ofNullable(this.values.get(clazz))
.map(clazz::cast)
.orElseThrow(() -> {
return new IllegalStateException(
"No object registered for class %s".formatted(clazz)
);
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,29 @@ void commit()

Span createSubSpan(
String name);

/**
* Register an object on the transaction.
*
* @param clazz The class reference used to retrieve the object
* @param value The object
* @param <V> The type of object
*/

<V> void put(
Class<? extends V> clazz,
V value);

/**
* Retrieve an object from the transaction.
*
* @param clazz The class reference used to retrieve the object
* @param <V> The type of object
*
* @return The object
*
* @see #put(Class, Object)
*/

<V> V get(Class<V> clazz);
}

0 comments on commit e5ca75b

Please sign in to comment.