Is there any reason why multi-select queries return R2dbcTimeoutException? - spring-webflux

I implemented a service method by combining two queries that only perform read(SELECT) into a transaction, and when I run that method, the trailing query is throwing R2dbcTimeoutException, returning a null value, as shown in the image. What is the reason for this?
#Transactional(readOnly=true)
public Mono<PaginatedUserResponse> userList(int page, int pageSize) {
final var pageable = PageRequest.of(page - 1, pageSize);
return userRepository.findAllBy(pageable)
.collectList()
.zipWith(userRepository.count()
.switchIfEmpty(Mono.defer(() -> Mono.error(new IllegalStateException()))))
.map(this::mapToPaginatedUserResponse);
}

Related

is it possible to get the execute sql that contains parameter when debugging mybatis source

I am setting a breakpoint in mybatis source BaseExecutor's queryFromDatabase function in Intellij Idea, this code block look like this:
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
but the boundSql content shows sql like this:
select * from article where channel_id in (?)
is it possible to get the execute sql in the trace? because the channel_id has more than 100 and the sql also contains other filter condition.

Mono.zip with null

My code:
Mono.zip(
credentialService.getCredentials(connect.getACredentialsId()),
credentialService.getCredentials(connect.getBCredentialsId())
)
.flatMap(...
From the frontend we get connect object with 2 fields:
connect{
aCredentialsId : UUID //required
bCredentialsId : UUID //optional
}
So sometimes the second line credentialService.getCredentials(connect.getBCredentialsId())) can return Mono.empty
How to write code to be prepared for this empty Mono when my second field bCredentialsId is null?
What should I do? In case of empty values return Mono.just(new Object) and then check if obj.getValue != null??? I need to fetch data from DB for 2 different values
The strategy I prefer here is to declare an optional() utility method like so:
public class Utils {
public static <T> Mono<Optional<T>> optional(Mono<T> in) {
return in.map(Optional::of).switchIfEmpty(Mono.just(Optional.empty()));
}
}
...which then allows you to transform your second Mono to one that will always return an optional, and thus do something like:
Mono.zip(
credentialService.getCredentials(connect.getACredentialsId()),
credentialService.getCredentials(connect.getBCredentialsId()).transform(Utils::optional)
).map(e -> new Connect(e.getT1(), e.getT2()))
(...assuming you have a Connect object that takes an Optional as the second parameter of course.)
An easier way is using mono's defaultIfEmpty method.
Mono<String> m1 = credentialService.getCredentials(connect.getACredentialsId());
Mono<String> m2 = credentialService.getCredentials(connect.getBCredentialsId()).defaultIfEmpty("");
Mono.zip(m1, m2).map(t -> connectService.connect(t.getT1(), t.getT2()));
Explanation: if m2 is null then get empty string as a default value instead of null.
Instead of using .zip here, I would work with a nullable property of Connect and use .flatMap in combination with .switchIfEmpty for it.
Kotlin-Version:
val aCredentials = credentialService.getCredentials(connect.getACredentialsId())
credentialService.getCredentials(connect.getBCredentialsId())
.flatMap { bCredentials -> aCredentials
.map { Connect(it, bCredentials)}
.switchIfEmpty(Connect(null, bCredentials))
}
.switchIfEmpty { aCredentials.map { Connect(it, null) } }

how to return the sum of a value in a table with where clause in grails 2.5.0

Domain class:
class Transaction {
String roundId
BigDecimal amount
:
}
The SQL we wish to execute the following:
"select sum(t.amount) from transaction t where t.roundId = xxx"
We have been unable to find an example which does not return Transaction rows.
We assume there are two approaches:
Use projections and/or criteria etc? All the examples we have found only return lists of transaction rows, not the sum.
Use raw SQL. How do we call SQL, and get a handle on the BigDecimal it returns?
I tried this:
class bla{
def sessionFactory
def someMethod() {
def SQLsession = sessionFactory.getCurrentSession()
def results = SQLsession.createSQLQuery("select sum(t.credit) from transaction t where t.round_id = :roundId", [roundId: roundId])
But this fails with
groovy.lang.MissingMethodException: No signature of method: org.hibernate.internal.SessionImpl.createSQLQuery() is applicable for argument types: (java.lang.String, java.util.LinkedHashMap)
Also, I have no idea what the return type would be (cant find any documentation). I am guessing it will be a list of something: Arrays? Maps?
==== UPDATE ====
Found one way which works (not very elegant or grails like)
def SQLsession = sessionFactory.getCurrentSession()
final query = "select sum(t.credit) from transaction t where t.round_id = :roundId"
final sqlQuery = SQLsession.createSQLQuery(query)
final results = sqlQuery.with {
setString('roundId', roundId)
list() // what is this for? Is there a better return value?
}
This seems to return an array, not a list as expected, so I can do this:
if (results?.size == 1) {
println results[0] // outputs a big decimal
}
Strangely, results.length fails, but results.size works.
Using Criteria, you can do
Transaction.withCriteria {
eq 'roundId', yourRoundIdValueHere
projections {
sum 'amount'
}
}
https://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/classic/Session.html
Query createSQLQuery(String sql, String[] returnAliases, Class[] returnClasses)
Query createSQLQuery(String sql, String returnAlias, Class returnClass)
The second argument of createSQLQuery is one or more returnAliases and not meant for binding the statement to a value.
Instead of passing your values in the 2nd argument, use the setters of your Query object i.e. setString, setInteger, etc.
results.setInteger('roundId',roundId);

NHibernate HQL Generator Caching Expression

I have created the following NHibernate HQL generator:
public class ContainsGenerator : BaseHqlGeneratorForMethod {
public ContainsGenerator() {
SupportedMethods = new[] {
ReflectionHelper.GetMethodDefinition(() =>
MyExtensions.Contains(null, null))
};
}
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject,
ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder,
IHqlExpressionVisitor visitor) {
var exp = FormatExpression((string)((ConstantExpression)arguments[1]).Value);
return treeBuilder.BooleanMethodCall("CONTAINS", new[] {
visitor.Visit(arguments[0]).AsExpression(),
treeBuilder.Constant(exp)
});
}
private string FormatExpression(string exp) {
exp = exp.Replace("'", "''");
exp = exp.Replace("\"", "");
exp = (char)34 + Regex.Replace(exp,
"(AND NOT|AND|OR NOT|OR) ",
(char)34 + " $1 " + (char)34, RegexOptions.IgnoreCase)
+ (char)34;
return exp;
}
}
This is used to do Full-Text searching to speed up searching over large tables.
The only difference to this and previous generators I've built in the past is that I call FormatExpression to convert the search expression to the correct format that SQL Server understands. However this seems to be the problem because although it works the first time I fire the query, subsequent searches produces the same query and the second argument passed into CONTAINS never changes. For example If I say:
var products = session.Query<Product>().Where(p => p.Name.Contains("Test 1")).ToList();
It will produce the following query:
select product0_.Id as Id2_,
product0_.Name as Name2_, from [dbo].Products product0_ where CONTAINS(product0_.Name, '"Test 1"')
Now if I say:
var products = session.Query<Product>().Where(p => p.Name.Contains("Test 2")).ToList();
It produces exactly the same query.
I'd appreciate it if someone could show me the correct way to do this. Thanks
It is a known bug in NHibernate: see https://nhibernate.jira.com/browse/NH-2658.

Best way to get Count for paging in ravenDB

I need to find the number of documents that are in the raven database , so that I can properly page the documents out. I had the following implementation -
public int Getcount<T>()
{
IQueryable<T> queryable = from p in _session.Query<T>().Customize(x =>x.WaitForNonStaleResultsAsOfLastWrite())
select p;
return queryable.Count();
}
But if the count is too large then it times out.
I tried the method suggested in FAQs -
public int GetCount<T>()
{
//IQueryable<T> queryable = from p in _session.Query<T>().Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
// select p;
//return queryable.Count();
RavenQueryStatistics stats;
var results = _session.Query<T>()
.Statistics(out stats);
return stats.TotalResults;
}
This always returns 0.
What am I doing wrong?
stats.TotalResults is 0 because the query was never executed. Try this instead:
var results = _session
.Query<T>()
.Statistics(out stats)
.Take(0)
.ToArray();
The strange syntax to get the statistics tripped me up as well. I can see why the query needs to be run in order to populate the statistic object but the syntax is a bit verbose imo.
I have written the following extension method for use in my unit tests. It helps keep the code terse.
Extension Method
public static int QuickCount<T>(this IRavenQueryable<T> results)
{
RavenQueryStatistics stats;
results.Statistics(out stats).Take(0).ToArray();
return stats.TotalResults;
}
Unit Test
...
db.Query<T>().QuickCount().ShouldBeGreaterThan(128);
...