Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sk/reverse index query optimize #1379

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package org.commcare.formplayer.database.models;

import static org.commcare.formplayer.sandbox.SqlSandboxUtils.execSql;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.commcare.cases.model.Case;
import org.commcare.cases.model.CaseIndex;
import org.commcare.cases.query.queryset.DualTableMultiMatchModelQuerySet;
import org.commcare.cases.query.queryset.DualTableSingleMatchModelQuerySet;
import org.commcare.formplayer.sandbox.SqlHelper;
import org.commcare.formplayer.sandbox.SqlStorage;
Expand All @@ -21,11 +22,9 @@
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Vector;
import java.util.*;

import static org.commcare.formplayer.sandbox.SqlSandboxUtils.execSql;

/**
* @author ctsims
Expand Down Expand Up @@ -334,6 +333,63 @@ public DualTableSingleMatchModelQuerySet bulkReadIndexToCaseIdMatch(String index
}
}

/**
* Performs a reverse index match on for the provided index name and target (parent) cases.
*
* @param indexName The name of the index e.g. 'parent'
* @param cuedCases Row IDs for the parent cases.
* @return ModelQuerySet with the results
*/
public DualTableMultiMatchModelQuerySet bulkReadIndexToCaseIdMatchReverse(String indexName,
snopoke marked this conversation as resolved.
Show resolved Hide resolved
Collection<Integer> cuedCases) {
DualTableMultiMatchModelQuerySet set = new DualTableMultiMatchModelQuerySet();
String caseIdIndex = TableBuilder.scrubName(Case.INDEX_CASE_ID);
List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(cuedCases, "?");
try {
for (Pair<String, String[]> querySet : whereParamList) {

StrSubstitutor substitutor = new StrSubstitutor(ImmutableMap.of(
"caseId", caseTableName + "." + DatabaseHelper.ID_COL,
"childId", COL_CASE_RECORD_ID,
"caseTable", caseTableName,
"indexTable", getTableName(),
"targetCol", COL_INDEX_TARGET,
"caseIdCol", caseIdIndex,
"indexNameCol", COL_INDEX_NAME,
"indexName", indexName,
"parentCases", querySet.first
));
String query = substitutor.replace("SELECT ${caseId}, ${childId} " +
"FROM ${caseTable} JOIN ${indexTable} ON ${targetCol} = ${caseIdCol} " +
"WHERE ${indexNameCol} = '${indexName}' AND ${caseId} IN ${parentCases};");

try (PreparedStatement preparedStatement =
connectionHandler.getConnection().prepareStatement(query)) {
int argIndex = 1;
for (String arg : querySet.second) {
preparedStatement.setString(argIndex, arg);
argIndex++;
}

if (log.isTraceEnabled()) {
SqlHelper.explainSql(connectionHandler.getConnection(), query, querySet.second);
}

try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
int caseId = resultSet.getInt(resultSet.findColumn(DatabaseHelper.ID_COL));
int targetCase = resultSet.getInt(resultSet.findColumn(COL_CASE_RECORD_ID));
set.loadResult(caseId, targetCase);
}
}
}
}
return set;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

public static String getArgumentBasedVariableSet(int number) {
StringBuffer sb = new StringBuffer();
sb.append("(");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package org.commcare.formplayer.tests;

import static org.commcare.formplayer.utils.DbTestUtils.evaluate;

import com.google.common.collect.ImmutableMap;
import org.commcare.cases.query.QueryContext;
import org.commcare.cases.query.queryset.CurrentModelQuerySet;
import org.commcare.formplayer.application.UtilController;
import org.commcare.formplayer.configuration.CacheConfiguration;
import org.commcare.formplayer.junit.InitializeStaticsExtension;
Expand All @@ -13,7 +14,15 @@
import org.commcare.formplayer.utils.TestContext;
import org.commcare.formplayer.utils.TestStorageUtils;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.trace.AccumulatingReporter;
import org.javarosa.core.model.trace.EvaluationTraceReporter;
import org.javarosa.core.model.utils.InstrumentationUtils;
import org.javarosa.xpath.XPathLazyNodeset;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.FunctionUtils;
import org.javarosa.xpath.parser.XPathSyntaxException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -24,6 +33,10 @@
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import java.util.function.Predicate;

import static org.commcare.formplayer.utils.DbTestUtils.evaluate;


@WebMvcTest
@Import({UtilController.class})
Expand Down Expand Up @@ -81,4 +94,85 @@ public void testModelSelfReference() throws XPathSyntaxException {
"", evaluationContext);

}

@Test
public void testModelReverseIndexLookup() throws XPathSyntaxException {
XPathLazyNodeset nodeset = (XPathLazyNodeset) XPathParseTool.parseXPath(
"instance('casedb')/casedb/case[@case_type='unit_test_parent']").eval(evaluationContext);

ImmutableMap<String, String> expectedOutputs = ImmutableMap.of(
"test_case_parent", "child_one,child_two,child_three",
"parent_two", "child_ptwo_one"
);
Assertions.assertEquals(nodeset.getReferences().size(), expectedOutputs.size());

EvaluationTraceReporter reporter = new AccumulatingReporter();
evaluationContext.setDebugModeOn(reporter);
for (TreeReference current : nodeset.getReferences()) {
EvaluationContext subContext = new EvaluationContext(evaluationContext, current);
QueryContext newContext = subContext.getCurrentQueryContext()
.checkForDerivativeContextAndReturn(nodeset.getReferences().size());
newContext.setHackyOriginalContextBody(new CurrentModelQuerySet(nodeset.getReferences()));
subContext.setQueryContext(newContext);

String parentCaseId = FunctionUtils.toString(
XPathParseTool.parseXPath("./@case_id").eval(subContext)
);

evaluate(
"join(',',instance('casedb')/casedb/case[index/parent = current()/@case_id]/@case_id)",
expectedOutputs.get(parentCaseId),
subContext
);

}
Predicate<String> predicate = line -> line.contains("Load Query Set Transform[current]=>[current|reverse index|parent]: Loaded: 4");
int matchedReverseIndexLoad = InstrumentationUtils.countMatchedTraces(reporter, predicate);
Assertions.assertEquals(1, matchedReverseIndexLoad);

int matchedLookups = InstrumentationUtils.countMatchedTraces(reporter, line -> line.contains("QuerySetLookup|current|reverse index|parent: Results:"));
Assertions.assertEquals(2, matchedLookups);
}

@Test
public void testModelIndexLookup() throws XPathSyntaxException {
XPathLazyNodeset nodeset = (XPathLazyNodeset) XPathParseTool.parseXPath(
"instance('casedb')/casedb/case[@case_type='unit_test_child']").eval(evaluationContext);
EvaluationTraceReporter reporter = new AccumulatingReporter();
evaluationContext.setDebugModeOn(reporter);

ImmutableMap<String, String> expectedOutputs = ImmutableMap.of(
"child_one", "test_case_parent",
"child_two", "test_case_parent",
"child_three", "test_case_parent",
"child_ptwo_one", "parent_two"
);

Assertions.assertEquals(nodeset.getReferences().size(), expectedOutputs.size());

for (TreeReference current : nodeset.getReferences()) {
EvaluationContext subContext = new EvaluationContext(evaluationContext, current);
QueryContext newContext = subContext.getCurrentQueryContext()
.checkForDerivativeContextAndReturn(nodeset.getReferences().size());
newContext.setHackyOriginalContextBody(new CurrentModelQuerySet(nodeset.getReferences()));
subContext.setQueryContext(newContext);

String childCaseId = FunctionUtils.toString(
XPathParseTool.parseXPath("./@case_id").eval(subContext)
);

evaluate(
"join(',',instance('casedb')/casedb/case[@case_id = current()/index/parent]/@case_id)",
expectedOutputs.get(childCaseId),
subContext
);

}
Predicate<String> predicate = line -> line.contains("Load Query Set Transform[current]=>[current|index|parent]: Loaded: 2");
int matchedReverseIndexLoad = InstrumentationUtils.countMatchedTraces(reporter, predicate);
snopoke marked this conversation as resolved.
Show resolved Hide resolved
Assertions.assertEquals(1, matchedReverseIndexLoad);

int matchedLookups = InstrumentationUtils.countMatchedTraces(reporter, line -> line.contains("QuerySetLookup|current|index|parent: Results: 1"));
Assertions.assertEquals(4, matchedLookups);
}
}