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 3 commits
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
Expand Up @@ -2,10 +2,13 @@

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 @@ -26,6 +29,8 @@
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Vector;
import java.util.function.Consumer;
import java.util.stream.Collector;

/**
* @author ctsims
Expand Down Expand Up @@ -54,7 +59,7 @@ public FormplayerCaseIndexTable(ConnectionHandler connectionHandler) {
}

public FormplayerCaseIndexTable(ConnectionHandler connectionHandler, String tableName, String caseTableName,
boolean createTable) {
boolean createTable) {
this.connectionHandler = connectionHandler;
this.tableName = tableName;
this.caseTableName = caseTableName;
Expand Down Expand Up @@ -284,51 +289,105 @@ public int loadIntoIndexTable(HashMap<String, Vector<Integer>> indexCache, Strin
* @return
*/
public DualTableSingleMatchModelQuerySet bulkReadIndexToCaseIdMatch(String indexName,
Collection<Integer> cuedCases) {
Collection<Integer> cuedCases) {
DualTableSingleMatchModelQuerySet set = new DualTableSingleMatchModelQuerySet();
String caseIdIndex = TableBuilder.scrubName(Case.INDEX_CASE_ID);
List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(cuedCases, "?");

for (Pair<String, String[]> querySet : whereParamList) {

String query = String.format(
"SELECT %s,%s " +
"FROM %s " +
"INNER JOIN %s " +
"ON %s = %s " +
"WHERE %s = '%s' " +
"AND " +
"%s IN %s",

COL_CASE_RECORD_ID, caseTableName + "." + DatabaseHelper.ID_COL,
getTableName(),
caseTableName,
COL_INDEX_TARGET, caseIdIndex,
COL_INDEX_NAME, indexName,
COL_CASE_RECORD_ID, querySet.first);

executeQueryCollectResults(query, querySet.second, resultSet -> {
try {
int caseId = resultSet.getInt(resultSet.findColumn(COL_CASE_RECORD_ID));
int targetCase = resultSet.getInt(resultSet.findColumn(DatabaseHelper.ID_COL));
set.loadResult(caseId, targetCase);
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
}
return set;
}

/**
* 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, "?");

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};");

executeQueryCollectResults(query, querySet.second, resultSet -> {
try {
int caseId = resultSet.getInt(resultSet.findColumn(DatabaseHelper.ID_COL));
int targetCase = resultSet.getInt(resultSet.findColumn(COL_CASE_RECORD_ID));
set.loadResult(caseId, targetCase);
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
}
return set;
}

private void executeQueryCollectResults(String query, String[] args, Consumer<ResultSet> collector) {
try {
for (Pair<String, String[]> querySet : whereParamList) {

String query = String.format(
"SELECT %s,%s " +
"FROM %s " +
"INNER JOIN %s " +
"ON %s = %s " +
"WHERE %s = '%s' " +
"AND " +
"%s IN %s",

COL_CASE_RECORD_ID, caseTableName + "." + DatabaseHelper.ID_COL,
getTableName(),
caseTableName,
COL_INDEX_TARGET, caseIdIndex,
COL_INDEX_NAME, indexName,
COL_CASE_RECORD_ID, querySet.first);

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

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

try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
int caseId = resultSet.getInt(resultSet.findColumn(COL_CASE_RECORD_ID));
int targetCase = resultSet.getInt(resultSet.findColumn(DatabaseHelper.ID_COL));
set.loadResult(caseId, targetCase);
}
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
collector.accept(resultSet);
}
}
}
return set;
} catch (SQLException e) {
throw new RuntimeException(e);
}
Expand Down
169 changes: 144 additions & 25 deletions src/test/java/org/commcare/formplayer/tests/CaseDbModelQueryTests.java
Original file line number Diff line number Diff line change
@@ -1,59 +1,178 @@
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;
import org.commcare.formplayer.junit.RestoreFactoryExtension;
import org.commcare.formplayer.junit.StorageFactoryExtension;
import org.commcare.formplayer.junit.request.SyncDbRequest;
import org.commcare.formplayer.sandbox.UserSqlSandbox;
import org.commcare.formplayer.services.RestoreFactory;
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;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
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;


/**
* @author wspride
*/
@WebMvcTest
public class CaseDbModelQueryTests extends BaseTestClass {
@Import({UtilController.class})
@ContextConfiguration(classes = {TestContext.class, CacheConfiguration.class})
@ExtendWith(InitializeStaticsExtension.class)
public class CaseDbModelQueryTests {

@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
configureRestoreFactory("synctestdomain", "synctestusername");
}
@Autowired
private MockMvc mockMvc;

@Autowired
private RestoreFactory restoreFactory;

@Override
protected String getMockRestoreFileName() {
return "restores/dbtests/case_db_model_query.xml";
@RegisterExtension
static RestoreFactoryExtension restoreFactoryExt = new RestoreFactoryExtension.builder()
.withUser("synctestusername").withDomain("synctestdomain")
.withRestorePath("restores/dbtests/case_db_model_query.xml")
.build();

@RegisterExtension
static StorageFactoryExtension storageExt = new StorageFactoryExtension.builder()
.withUser("back_nav").withDomain("back_nav").build();
private UserSqlSandbox sandbox;
private EvaluationContext evaluationContext;

@BeforeEach
public void setUp() {
new SyncDbRequest(mockMvc, restoreFactory).request();
sandbox = restoreFactory.getSqlSandbox();
evaluationContext = TestStorageUtils.getEvaluationContextWithoutSession(sandbox);
evaluationContext.setDebugModeOn();
}

/**
* Tests for basic common case database queries
*/
@Test
public void testDbModelQueryLookups() throws Exception {
syncDb();
UserSqlSandbox sandbox = getRestoreSandbox();
EvaluationContext ec = TestStorageUtils.getEvaluationContextWithoutSession(sandbox);
ec.setDebugModeOn();
public void testModelQueryLookupDerivations() throws Exception {
evaluate(
"join(',',instance('casedb')/casedb/case[@case_type='unit_test_child_child"
+ "'][@status='open'][true() and "
+
"instance('casedb')/casedb/case[@case_id = instance('casedb')"
+ "/casedb/case[@case_id=current()/index/parent]/index/parent]/test = "
+ "'true']/@case_id)",
"child_ptwo_one_one,child_one_one", ec);
"child_ptwo_one_one,child_one_one", evaluationContext);
}

@Test
public void testModelSelfReference() throws XPathSyntaxException {
evaluate(
"join(',',instance('casedb')/casedb/case[@case_type='unit_test_child'][@status"
+ "='open'][true() and "
+
"count(instance('casedb')/casedb/case[index/parent = instance('casedb')"
+ "/casedb/case[@case_id=current()/@case_id]/index/parent][false = "
+ "'true']) > 0]/@case_id)",
"", ec);
"", 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);
}
}
Loading