use of org.finos.legend.engine.plan.execution.result.object.StreamingObjectResult in project legend-engine by finos.
the class ExecutionNodeExecutor method visit.
@Override
public Result visit(PureExpressionPlatformExecutionNode pureExpressionPlatformExecutionNode) {
if (!(pureExpressionPlatformExecutionNode.implementation instanceof JavaPlatformImplementation)) {
throw new RuntimeException("Only Java implementations are currently supported, found: " + pureExpressionPlatformExecutionNode.implementation);
}
JavaPlatformImplementation javaPlatformImpl = (JavaPlatformImplementation) pureExpressionPlatformExecutionNode.implementation;
String executionClassName = JavaHelper.getExecutionClassFullName(javaPlatformImpl);
Class<?> clazz = ExecutionNodeJavaPlatformHelper.getClassToExecute(pureExpressionPlatformExecutionNode, executionClassName, this.executionState, this.profiles);
if (Arrays.asList(clazz.getInterfaces()).contains(IPlatformPureExpressionExecutionNodeSerializeSpecifics.class)) {
try {
org.finos.legend.engine.plan.dependencies.store.platform.IPlatformPureExpressionExecutionNodeSerializeSpecifics nodeSpecifics = (org.finos.legend.engine.plan.dependencies.store.platform.IPlatformPureExpressionExecutionNodeSerializeSpecifics) clazz.newInstance();
Result childResult = pureExpressionPlatformExecutionNode.executionNodes().getFirst().accept(new ExecutionNodeExecutor(profiles, executionState));
IExecutionNodeContext context = new DefaultExecutionNodeContext(this.executionState, childResult);
AppliedFunction f = (AppliedFunction) pureExpressionPlatformExecutionNode.pure;
SerializationConfig config = f.parameters.size() == 3 ? (SerializationConfig) f.parameters.get(2) : null;
return ExecutionNodeSerializerHelper.executeSerialize(nodeSpecifics, config, childResult, context);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
if (Arrays.asList(clazz.getInterfaces()).contains(IPlatformPureExpressionExecutionNodeGraphFetchUnionSpecifics.class)) {
StreamingObjectResult<?> streamResult1 = (StreamingObjectResult) pureExpressionPlatformExecutionNode.executionNodes.get(0).accept(new ExecutionNodeExecutor(this.profiles, this.executionState));
StreamingObjectResult<?> streamResult2 = (StreamingObjectResult) pureExpressionPlatformExecutionNode.executionNodes.get(1).accept(new ExecutionNodeExecutor(this.profiles, this.executionState));
Result childResult = new Result("success") {
@Override
public <T> T accept(ResultVisitor<T> resultVisitor) {
throw new RuntimeException("Not implemented");
}
@Override
public void close() {
streamResult1.close();
streamResult2.close();
}
};
return new StreamingObjectResult<>(Stream.concat(streamResult1.getObjectStream(), streamResult2.getObjectStream()), streamResult1.getResultBuilder(), childResult);
}
if (Arrays.asList(clazz.getInterfaces()).contains(IPlatformPureExpressionExecutionNodeGraphFetchMergeSpecifics.class)) {
StreamingObjectResult<?> streamResult = (StreamingObjectResult) pureExpressionPlatformExecutionNode.executionNodes.get(0).accept(new ExecutionNodeExecutor(this.profiles, this.executionState));
return streamResult;
} else {
return ExecutionNodeJavaPlatformHelper.executeJavaImplementation(pureExpressionPlatformExecutionNode, DefaultExecutionNodeContext.factory(), this.profiles, this.executionState);
}
}
use of org.finos.legend.engine.plan.execution.result.object.StreamingObjectResult in project legend-engine by finos.
the class ExecutionNodeExecutor method visit.
@Override
public Result visit(GlobalGraphFetchExecutionNode globalGraphFetchExecutionNode) {
final Span topSpan = GlobalTracer.get().activeSpan();
final boolean isGraphRoot = globalGraphFetchExecutionNode.parentIndex == null;
if (isGraphRoot) {
final boolean enableConstraints = globalGraphFetchExecutionNode.enableConstraints == null ? false : globalGraphFetchExecutionNode.enableConstraints;
final boolean checked = globalGraphFetchExecutionNode.checked == null ? false : globalGraphFetchExecutionNode.checked;
// Handle batching at root level
final AtomicLong rowCount = new AtomicLong(0L);
final AtomicLong objectCount = new AtomicLong(0L);
final DoubleSummaryStatistics memoryStatistics = new DoubleSummaryStatistics();
GraphFetchResult graphFetchResult = (GraphFetchResult) globalGraphFetchExecutionNode.localGraphFetchExecutionNode.accept(new ExecutionNodeExecutor(this.profiles, this.executionState));
Stream<?> objectStream = graphFetchResult.getGraphObjectsBatchStream().map(batch -> {
List<?> parentObjects = batch.getObjectsForNodeIndex(0);
boolean nonEmptyObjectList = !parentObjects.isEmpty();
ExecutionState newState = new ExecutionState(this.executionState).setGraphObjectsBatch(batch);
if (globalGraphFetchExecutionNode.children != null && !globalGraphFetchExecutionNode.children.isEmpty() && nonEmptyObjectList) {
globalGraphFetchExecutionNode.children.forEach(c -> c.accept(new ExecutionNodeExecutor(this.profiles, newState)));
}
rowCount.addAndGet(batch.getRowCount());
if (nonEmptyObjectList) {
long currentObjectCount = objectCount.addAndGet(parentObjects.size());
memoryStatistics.accept(batch.getTotalObjectMemoryUtilization() / (parentObjects.size() * 1.0));
if (graphFetchResult.getGraphFetchSpan() != null) {
Span graphFetchSpan = graphFetchResult.getGraphFetchSpan();
graphFetchSpan.setTag("batchCount", memoryStatistics.getCount());
graphFetchSpan.setTag("objectCount", currentObjectCount);
graphFetchSpan.setTag("avgMemoryUtilizationInBytesPerObject", memoryStatistics.getAverage());
}
}
if (!nonEmptyObjectList) {
if (topSpan != null && rowCount.get() > 0) {
topSpan.setTag("lastQueryRowCount", rowCount);
}
}
if (checked) {
return parentObjects.stream().map(x -> (IChecked<?>) x).map(x -> x.getValue() instanceof Constrained ? ((Constrained<?>) x.getValue()).toChecked(x.getSource(), enableConstraints) : x).collect(Collectors.toList());
}
if (enableConstraints) {
return parentObjects.stream().map(x -> x instanceof Constrained ? ((Constrained<?>) x).withConstraintsApplied() : x).collect(Collectors.toList());
}
return parentObjects;
}).flatMap(Collection::stream);
boolean realizeAsConstant = this.executionState.inAllocation && ExecutionNodeResultHelper.isResultSizeRangeSet(globalGraphFetchExecutionNode) && ExecutionNodeResultHelper.isSingleRecordResult(globalGraphFetchExecutionNode);
if (realizeAsConstant) {
return new ConstantResult(objectStream.findFirst().orElseThrow(() -> new RuntimeException("Constant value not found")));
}
return new StreamingObjectResult<>(objectStream, new PartialClassBuilder(globalGraphFetchExecutionNode), graphFetchResult);
} else {
GraphObjectsBatch graphObjectsBatch = this.executionState.graphObjectsBatch;
List<?> parentObjects = graphObjectsBatch.getObjectsForNodeIndex(globalGraphFetchExecutionNode.parentIndex);
if ((parentObjects != null) && !parentObjects.isEmpty()) {
if (globalGraphFetchExecutionNode.xStorePropertyFetchDetails != null && globalGraphFetchExecutionNode.xStorePropertyFetchDetails.supportsCaching && this.executionState.graphFetchCaches != null) {
graphObjectsBatch.setXStorePropertyCachesForNodeIndex(globalGraphFetchExecutionNode.localGraphFetchExecutionNode.nodeIndex, findGraphFetchCacheByTargetCrossKeys(globalGraphFetchExecutionNode));
}
globalGraphFetchExecutionNode.localGraphFetchExecutionNode.accept(new ExecutionNodeExecutor(this.profiles, this.executionState));
if (globalGraphFetchExecutionNode.children != null && !globalGraphFetchExecutionNode.children.isEmpty()) {
globalGraphFetchExecutionNode.children.forEach(c -> c.accept(new ExecutionNodeExecutor(this.profiles, this.executionState)));
}
}
return new ConstantResult(parentObjects);
}
}
use of org.finos.legend.engine.plan.execution.result.object.StreamingObjectResult in project legend-engine by finos.
the class RelationalExecutionNodeExecutor method getStreamingObjectResultFromRelationalResult.
private Result getStreamingObjectResultFromRelationalResult(ExecutionNode node, RelationalResult relationalResult, DatabaseConnection databaseConnection) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, JsonProcessingException {
Class<?> executeClass = this.getExecuteClass(node);
if (Arrays.asList(executeClass.getInterfaces()).contains(IRelationalClassInstantiationNodeExecutor.class)) {
IRelationalClassInstantiationNodeExecutor executor = (IRelationalClassInstantiationNodeExecutor) executeClass.getConstructor().newInstance();
final ResultSet resultSet = relationalResult.getResultSet();
final String databaseTimeZone = relationalResult.getRelationalDatabaseTimeZone();
final String databaseConnectionString = ObjectMapperFactory.getNewStandardObjectMapperWithPureProtocolExtensionSupports().writeValueAsString(databaseConnection);
Iterator<Object> objectIterator = new Iterator<Object>() {
private boolean cursorMove;
private boolean hasNext;
@Override
public boolean hasNext() {
if (!this.cursorMove) {
try {
this.hasNext = resultSet.next();
} catch (SQLException e) {
throw new RuntimeException(e);
}
this.cursorMove = true;
}
return this.hasNext;
}
@Override
public Object next() {
if (this.hasNext()) {
cursorMove = false;
try {
return executor.getObjectFromResultSet(resultSet, databaseTimeZone, databaseConnectionString);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
throw new NoSuchElementException("End of result set reached!");
}
};
Stream<Object> objectStream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(objectIterator, Spliterator.ORDERED), false);
ClassBuilder classBuilder = new ClassBuilder(node);
return new StreamingObjectResult<>(objectStream, classBuilder, relationalResult);
} else {
throw new RuntimeException("Unknown execute class " + executeClass.getCanonicalName());
}
}
use of org.finos.legend.engine.plan.execution.result.object.StreamingObjectResult in project legend-engine by finos.
the class RelationalExecutionNodeExecutor method visit.
@Override
public Result visit(ExecutionNode executionNode) {
if (executionNode instanceof RelationalBlockExecutionNode) {
RelationalBlockExecutionNode relationalBlockExecutionNode = (RelationalBlockExecutionNode) executionNode;
ExecutionState connectionAwareState = new ExecutionState(this.executionState);
((RelationalStoreExecutionState) connectionAwareState.getStoreExecutionState(StoreType.Relational)).setRetainConnection(true);
try {
Result res = new ExecutionNodeExecutor(this.profiles, connectionAwareState).visit((SequenceExecutionNode) relationalBlockExecutionNode);
((RelationalStoreExecutionState) connectionAwareState.getStoreExecutionState(StoreType.Relational)).getBlockConnectionContext().unlockAllBlockConnections();
return res;
} catch (Exception e) {
((RelationalStoreExecutionState) connectionAwareState.getStoreExecutionState(StoreType.Relational)).getBlockConnectionContext().unlockAllBlockConnections();
((RelationalStoreExecutionState) connectionAwareState.getStoreExecutionState(StoreType.Relational)).getBlockConnectionContext().closeAllBlockConnections();
throw e;
}
} else if (executionNode instanceof CreateAndPopulateTempTableExecutionNode) {
CreateAndPopulateTempTableExecutionNode createAndPopulateTempTableExecutionNode = (CreateAndPopulateTempTableExecutionNode) executionNode;
Stream<Result> results = createAndPopulateTempTableExecutionNode.inputVarNames.stream().map(this.executionState::getResult);
Stream<?> inputStream = results.flatMap(result -> {
if (result instanceof ConstantResult) {
Object value = ((ConstantResult) result).getValue();
if (value instanceof Map && ((Map<?, ?>) value).get("values") instanceof List) {
return ((List<?>) ((Map<?, ?>) value).get("values")).stream().map(val -> ((List<?>) ((Map<?, ?>) val).get("values")).get(0));
}
if (value instanceof List) {
return ((List<?>) value).stream();
}
if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || (value instanceof String)) {
return Stream.of(value);
}
if (value instanceof Stream) {
return (Stream<?>) value;
}
throw new IllegalArgumentException("Result passed into CreateAndPopulateTempTableExecutionNode should be a stream");
}
if (result instanceof StreamingObjectResult) {
return ((StreamingObjectResult<?>) result).getObjectStream();
}
throw new IllegalArgumentException("Unexpected Result Type : " + result.getClass().getName());
});
if (!(createAndPopulateTempTableExecutionNode.implementation instanceof JavaPlatformImplementation)) {
throw new RuntimeException("Only Java implementations are currently supported, found: " + createAndPopulateTempTableExecutionNode.implementation);
}
JavaPlatformImplementation javaPlatformImpl = (JavaPlatformImplementation) createAndPopulateTempTableExecutionNode.implementation;
String executionClassName = JavaHelper.getExecutionClassFullName(javaPlatformImpl);
Class<?> clazz = ExecutionNodeJavaPlatformHelper.getClassToExecute(createAndPopulateTempTableExecutionNode, executionClassName, this.executionState, this.profiles);
if (Arrays.asList(clazz.getInterfaces()).contains(IRelationalCreateAndPopulateTempTableExecutionNodeSpecifics.class)) {
try {
IRelationalCreateAndPopulateTempTableExecutionNodeSpecifics nodeSpecifics = (IRelationalCreateAndPopulateTempTableExecutionNodeSpecifics) clazz.newInstance();
createAndPopulateTempTableExecutionNode.tempTableColumnMetaData.forEach(t -> t.identifierForGetter = nodeSpecifics.getGetterNameForProperty(t.identifierForGetter));
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
// TODO Remove once platform version supports above and existing plans mitigated
String executionMethodName = JavaHelper.getExecutionMethodName(javaPlatformImpl);
createAndPopulateTempTableExecutionNode.tempTableColumnMetaData.forEach(t -> t.identifierForGetter = ExecutionNodeJavaPlatformHelper.executeStaticJavaMethod(createAndPopulateTempTableExecutionNode, executionClassName, executionMethodName, Collections.singletonList(Result.class), Collections.singletonList(new ConstantResult(t.identifierForGetter)), this.executionState, this.profiles));
}
RelationalDatabaseCommands databaseCommands = DatabaseManager.fromString(createAndPopulateTempTableExecutionNode.connection.type.name()).relationalDatabaseSupport();
try (Connection connectionManagerConnection = this.getConnection(createAndPopulateTempTableExecutionNode, databaseCommands, this.profiles, this.executionState)) {
TempTableStreamingResult tempTableStreamingResult = new TempTableStreamingResult(inputStream, createAndPopulateTempTableExecutionNode);
String databaseTimeZone = createAndPopulateTempTableExecutionNode.connection.timeZone == null ? RelationalExecutor.DEFAULT_DB_TIME_ZONE : createAndPopulateTempTableExecutionNode.connection.timeZone;
databaseCommands.accept(RelationalDatabaseCommandsVisitorBuilder.getStreamResultToTempTableVisitor(((RelationalStoreExecutionState) this.executionState.getStoreExecutionState(StoreType.Relational)).getRelationalExecutor().getRelationalExecutionConfiguration(), connectionManagerConnection, tempTableStreamingResult, createAndPopulateTempTableExecutionNode.tempTableName, databaseTimeZone));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return new ConstantResult("success");
} else if (executionNode instanceof RelationalExecutionNode) {
RelationalExecutionNode relationalExecutionNode = (RelationalExecutionNode) executionNode;
Span topSpan = GlobalTracer.get().activeSpan();
this.executionState.topSpan = topSpan;
try (Scope scope = GlobalTracer.get().buildSpan("Relational DB Execution").startActive(true)) {
scope.span().setTag("databaseType", relationalExecutionNode.getDatabaseTypeName());
scope.span().setTag("sql", relationalExecutionNode.sqlQuery());
Result result = ((RelationalStoreExecutionState) executionState.getStoreExecutionState(StoreType.Relational)).getRelationalExecutor().execute(relationalExecutionNode, this.profiles, this.executionState);
if (result instanceof RelationalResult) {
scope.span().setTag("executedSql", ((RelationalResult) result).executedSQl);
}
if (relationalExecutionNode.implementation != null && !(ExecutionNodeResultHelper.isResultSizeRangeSet(relationalExecutionNode) && ExecutionNodeResultHelper.isSingleRecordResult(relationalExecutionNode))) {
return executeImplementation(relationalExecutionNode, result, this.executionState, this.profiles);
}
return result;
}
} else if (executionNode instanceof SQLExecutionNode) {
SQLExecutionNode SQLExecutionNode = (SQLExecutionNode) executionNode;
this.executionState.topSpan = GlobalTracer.get().activeSpan();
try (Scope scope = GlobalTracer.get().buildSpan("Relational DB Execution").startActive(true)) {
scope.span().setTag("databaseType", SQLExecutionNode.getDatabaseTypeName());
scope.span().setTag("sql", SQLExecutionNode.sqlQuery());
Result result = ((RelationalStoreExecutionState) executionState.getStoreExecutionState(StoreType.Relational)).getRelationalExecutor().execute(SQLExecutionNode, profiles, executionState);
if (result instanceof SQLExecutionResult) {
scope.span().setTag("executedSql", ((SQLExecutionResult) result).getExecutedSql());
}
return result;
}
} else if (executionNode instanceof RelationalTdsInstantiationExecutionNode) {
RelationalTdsInstantiationExecutionNode relationalTdsInstantiationExecutionNode = (RelationalTdsInstantiationExecutionNode) executionNode;
SQLExecutionResult sqlExecutionResult = null;
try {
sqlExecutionResult = (SQLExecutionResult) this.visit((SQLExecutionNode) relationalTdsInstantiationExecutionNode.executionNodes.get(0));
RelationalResult relationalTdsResult = new RelationalResult(sqlExecutionResult, relationalTdsInstantiationExecutionNode);
if (this.executionState.inAllocation) {
if (!this.executionState.transformAllocation) {
return relationalTdsResult;
}
RealizedRelationalResult realizedRelationalResult = (RealizedRelationalResult) relationalTdsResult.realizeInMemory();
List<Map<String, Object>> rowValueMaps = realizedRelationalResult.getRowValueMaps(false);
Result res = RelationalExecutor.evaluateAdditionalExtractors(this.resultInterpreterExtensions, this.executionState, rowValueMaps);
if (res != null) {
return res;
} else {
return new ConstantResult(rowValueMaps);
}
}
return relationalTdsResult;
} catch (Exception e) {
if (sqlExecutionResult != null) {
sqlExecutionResult.close();
}
throw e;
}
} else if (executionNode instanceof RelationalClassInstantiationExecutionNode) {
RelationalClassInstantiationExecutionNode node = (RelationalClassInstantiationExecutionNode) executionNode;
SQLExecutionResult sqlExecutionResult = null;
try {
SQLExecutionNode innerNode = (SQLExecutionNode) node.executionNodes.get(0);
sqlExecutionResult = (SQLExecutionResult) this.visit(innerNode);
RelationalResult relationalResult = new RelationalResult(sqlExecutionResult, node);
boolean realizeAsConstant = this.executionState.inAllocation && ExecutionNodeResultHelper.isResultSizeRangeSet(node) && ExecutionNodeResultHelper.isSingleRecordResult(node);
if (realizeAsConstant) {
RealizedRelationalResult realizedRelationalResult = (RealizedRelationalResult) relationalResult.realizeInMemory();
List<Map<String, Object>> rowValueMaps = realizedRelationalResult.getRowValueMaps(false);
if (rowValueMaps.size() == 1) {
return new ConstantResult(rowValueMaps.get(0));
} else {
return new ConstantResult(rowValueMaps);
}
}
return this.getStreamingObjectResultFromRelationalResult(node, relationalResult, innerNode.connection);
} catch (Exception e) {
if (sqlExecutionResult != null) {
sqlExecutionResult.close();
}
throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
}
} else if (executionNode instanceof RelationalRelationDataInstantiationExecutionNode) {
RelationalRelationDataInstantiationExecutionNode node = (RelationalRelationDataInstantiationExecutionNode) executionNode;
SQLExecutionResult sqlExecutionResult = null;
try {
sqlExecutionResult = (SQLExecutionResult) this.visit((SQLExecutionNode) node.executionNodes.get(0));
return new RelationalResult(sqlExecutionResult, node);
} catch (Exception e) {
if (sqlExecutionResult != null) {
sqlExecutionResult.close();
}
throw e;
}
} else if (executionNode instanceof RelationalDataTypeInstantiationExecutionNode) {
RelationalDataTypeInstantiationExecutionNode node = (RelationalDataTypeInstantiationExecutionNode) executionNode;
SQLExecutionResult sqlExecutionResult = null;
try {
sqlExecutionResult = (SQLExecutionResult) this.visit((SQLExecutionNode) node.executionNodes.get(0));
RelationalResult relationalPrimitiveResult = new RelationalResult(sqlExecutionResult, node);
if (this.executionState.inAllocation) {
if ((ExecutionNodeResultHelper.isResultSizeRangeSet(node) && !ExecutionNodeResultHelper.isSingleRecordResult(node)) && !this.executionState.transformAllocation) {
return relationalPrimitiveResult;
}
if (relationalPrimitiveResult.getResultSet().next()) {
List<org.eclipse.collections.api.block.function.Function<Object, Object>> transformers = relationalPrimitiveResult.getTransformers();
Object convertedValue = transformers.get(0).valueOf(relationalPrimitiveResult.getResultSet().getObject(1));
return new ConstantResult(convertedValue);
} else {
throw new RuntimeException("Result set is empty for allocation node");
}
}
return relationalPrimitiveResult;
} catch (Exception e) {
if (sqlExecutionResult != null) {
sqlExecutionResult.close();
}
throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
}
} else if (executionNode instanceof RelationalRootQueryTempTableGraphFetchExecutionNode) {
return this.executeRelationalRootQueryTempTableGraphFetchExecutionNode((RelationalRootQueryTempTableGraphFetchExecutionNode) executionNode);
} else if (executionNode instanceof RelationalCrossRootQueryTempTableGraphFetchExecutionNode) {
return this.executeRelationalCrossRootQueryTempTableGraphFetchExecutionNode((RelationalCrossRootQueryTempTableGraphFetchExecutionNode) executionNode);
} else if (executionNode instanceof RelationalPrimitiveQueryGraphFetchExecutionNode) {
return this.executeRelationalPrimitiveQueryGraphFetchExecutionNode((RelationalPrimitiveQueryGraphFetchExecutionNode) executionNode);
} else if (executionNode instanceof RelationalClassQueryTempTableGraphFetchExecutionNode) {
return this.executeRelationalClassQueryTempTableGraphFetchExecutionNode((RelationalClassQueryTempTableGraphFetchExecutionNode) executionNode);
} else if (executionNode instanceof RelationalRootGraphFetchExecutionNode) {
RelationalRootGraphFetchExecutionNode node = (RelationalRootGraphFetchExecutionNode) executionNode;
/* Fetch info from execution state */
GraphExecutionState graphExecutionState = (GraphExecutionState) executionState;
int batchSize = graphExecutionState.getBatchSize();
SQLExecutionResult rootResult = (SQLExecutionResult) graphExecutionState.getRootResult();
ResultSet rootResultSet = rootResult.getResultSet();
/* Ensure all children run in the same connection */
RelationalStoreExecutionState relationalStoreExecutionState = (RelationalStoreExecutionState) graphExecutionState.getStoreExecutionState(StoreType.Relational);
BlockConnectionContext oldBlockConnectionContext = relationalStoreExecutionState.getBlockConnectionContext();
boolean oldRetainConnectionFlag = relationalStoreExecutionState.retainConnection();
relationalStoreExecutionState.setBlockConnectionContext(new BlockConnectionContext());
relationalStoreExecutionState.setRetainConnection(true);
try (Scope ignored1 = GlobalTracer.get().buildSpan("Graph Query Relational: Execute Relational Root").startActive(true)) {
String databaseTimeZone = rootResult.getDatabaseTimeZone();
String databaseConnectionString = ObjectMapperFactory.getNewStandardObjectMapperWithPureProtocolExtensionSupports().writeValueAsString(rootResult.getSQLExecutionNode().connection);
/* Get Java executor */
Class<?> executeClass = this.getExecuteClass(node);
if (Arrays.asList(executeClass.getInterfaces()).contains(IRelationalRootGraphNodeExecutor.class)) {
IRelationalRootGraphNodeExecutor executor = (IRelationalRootGraphNodeExecutor) executeClass.getConstructor().newInstance();
List<Method> primaryKeyGetters = executor.primaryKeyGetters();
int primaryKeyCount = primaryKeyGetters.size();
/* Check if caching is enabled and fetch the cache if required */
boolean cachingEnabledForNode = false;
ExecutionCache<GraphFetchCacheKey, Object> graphCache = null;
RelationalGraphFetchUtils.RelationalSQLResultGraphFetchCacheKey rootResultCacheKey = null;
if ((this.executionState.graphFetchCaches != null) && executor.supportsCaching()) {
GraphFetchCacheByEqualityKeys graphFetchCacheByEqualityKeys = RelationalGraphFetchUtils.findCacheByEqualityKeys(node.graphFetchTree, executor.getMappingId(rootResultSet, databaseTimeZone, databaseConnectionString), executor.getInstanceSetId(rootResultSet, databaseTimeZone, databaseConnectionString), this.executionState.graphFetchCaches);
if (graphFetchCacheByEqualityKeys != null) {
List<String> parentSQLKeyColumns = executor.primaryKeyColumns();
List<Integer> parentPrimaryKeyIndices = FastList.newList();
for (String pkCol : parentSQLKeyColumns) {
parentPrimaryKeyIndices.add(rootResultSet.findColumn(pkCol));
}
cachingEnabledForNode = true;
graphCache = graphFetchCacheByEqualityKeys.getExecutionCache();
rootResultCacheKey = new RelationalGraphFetchUtils.RelationalSQLResultGraphFetchCacheKey(rootResult, parentPrimaryKeyIndices);
}
}
/* Get the next batch of root records */
List<Object> resultObjectsBatch = new ArrayList<>();
List<org.finos.legend.engine.plan.dependencies.domain.graphFetch.IGraphInstance<?>> instancesToDeepFetch = new ArrayList<>();
int objectCount = 0;
try (Scope ignored2 = GlobalTracer.get().buildSpan("Graph Query Relational: Read Next Batch").startActive(true)) {
while (rootResultSet.next()) {
graphExecutionState.incrementRowCount();
boolean shouldDeepFetchOnThisInstance = true;
if (cachingEnabledForNode) {
Object cachedObject = graphCache.getIfPresent(rootResultCacheKey);
if (cachedObject != null) {
resultObjectsBatch.add(executor.deepCopy(cachedObject));
shouldDeepFetchOnThisInstance = false;
}
}
if (shouldDeepFetchOnThisInstance) {
org.finos.legend.engine.plan.dependencies.domain.graphFetch.IGraphInstance<?> wrappedObject = executor.getObjectFromResultSet(rootResultSet, databaseTimeZone, databaseConnectionString);
instancesToDeepFetch.add(wrappedObject);
resultObjectsBatch.add(wrappedObject.getValue());
}
objectCount += 1;
if (objectCount >= batchSize) {
break;
}
}
}
if (!instancesToDeepFetch.isEmpty()) {
boolean childrenExist = node.children != null && !node.children.isEmpty();
String tempTableName = node.tempTableName;
RealizedRelationalResult realizedRelationalResult = RealizedRelationalResult.emptyRealizedRelationalResult(node.columns);
/* Create and populate double strategy map with key being object with its PK getters */
DoubleStrategyHashMap<Object, Object, SQLExecutionResult> rootMap = new DoubleStrategyHashMap<>(RelationalGraphFetchUtils.objectSQLResultDoubleHashStrategyWithEmptySecondStrategy(primaryKeyGetters));
for (org.finos.legend.engine.plan.dependencies.domain.graphFetch.IGraphInstance<?> rootGraphInstance : instancesToDeepFetch) {
Object rootObject = rootGraphInstance.getValue();
rootMap.put(rootObject, rootObject);
graphExecutionState.addObjectMemoryUtilization(rootGraphInstance.instanceSize());
if (childrenExist) {
this.addKeyRowToRealizedRelationalResult(rootObject, primaryKeyGetters, realizedRelationalResult);
}
}
/* Execute store local children */
if (childrenExist) {
this.executeRelationalChildren(node, tempTableName, realizedRelationalResult, rootResult.getSQLExecutionNode().connection, rootResult.getDatabaseType(), databaseTimeZone, rootMap, primaryKeyGetters);
}
}
graphExecutionState.setObjectsForNodeIndex(node.nodeIndex, resultObjectsBatch);
if (cachingEnabledForNode) {
for (org.finos.legend.engine.plan.dependencies.domain.graphFetch.IGraphInstance<?> deepFetchedInstance : instancesToDeepFetch) {
Object objectClone = executor.deepCopy(deepFetchedInstance.getValue());
graphCache.put(new RelationalGraphFetchUtils.RelationalObjectGraphFetchCacheKey(objectClone, primaryKeyGetters), objectClone);
}
}
return new ConstantResult(resultObjectsBatch);
} else {
throw new RuntimeException("Unknown execute class " + executeClass.getCanonicalName());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
relationalStoreExecutionState.getBlockConnectionContext().unlockAllBlockConnections();
relationalStoreExecutionState.getBlockConnectionContext().closeAllBlockConnectionsAsync();
relationalStoreExecutionState.setBlockConnectionContext(oldBlockConnectionContext);
relationalStoreExecutionState.setRetainConnection(oldRetainConnectionFlag);
}
} else if (executionNode instanceof RelationalCrossRootGraphFetchExecutionNode) {
RelationalCrossRootGraphFetchExecutionNode node = (RelationalCrossRootGraphFetchExecutionNode) executionNode;
GraphExecutionState graphExecutionState = (GraphExecutionState) executionState;
List<?> parentObjects = graphExecutionState.getObjectsToGraphFetch();
List<Object> childObjects = FastList.newList();
graphExecutionState.setObjectsForNodeIndex(node.nodeIndex, childObjects);
RelationalStoreExecutionState relationalStoreExecutionState = (RelationalStoreExecutionState) graphExecutionState.getStoreExecutionState(StoreType.Relational);
BlockConnectionContext oldBlockConnectionContext = relationalStoreExecutionState.getBlockConnectionContext();
boolean oldRetainConnectionFlag = relationalStoreExecutionState.retainConnection();
relationalStoreExecutionState.setBlockConnectionContext(new BlockConnectionContext());
relationalStoreExecutionState.setRetainConnection(true);
SQLExecutionResult childResult = null;
try (Scope ignored1 = GlobalTracer.get().buildSpan("Graph Query Relational: Execute Relational Cross Root").startActive(true)) {
/* Get Java executor */
Class<?> executeClass = this.getExecuteClass(node);
if (Arrays.asList(executeClass.getInterfaces()).contains(IRelationalCrossRootGraphNodeExecutor.class)) {
IRelationalCrossRootGraphNodeExecutor executor = (IRelationalCrossRootGraphNodeExecutor) executeClass.getConstructor().newInstance();
if (!parentObjects.isEmpty()) {
String parentTempTableName = node.parentTempTableName;
RealizedRelationalResult parentRealizedRelationalResult = RealizedRelationalResult.emptyRealizedRelationalResult(node.parentTempTableColumns);
List<Method> crossKeyGetters = executor.parentCrossKeyGetters();
int parentKeyCount = crossKeyGetters.size();
for (Object parentObject : parentObjects) {
this.addKeyRowToRealizedRelationalResult(parentObject, crossKeyGetters, parentRealizedRelationalResult);
}
graphExecutionState.addResult(parentTempTableName, parentRealizedRelationalResult);
/* Execute relational node corresponding to the cross root */
childResult = (SQLExecutionResult) node.relationalNode.accept(new ExecutionNodeExecutor(this.profiles, graphExecutionState));
ResultSet childResultSet = childResult.getResultSet();
boolean childrenExist = node.children != null && !node.children.isEmpty();
String tempTableName = childrenExist ? node.tempTableName : null;
RealizedRelationalResult realizedRelationalResult = childrenExist ? RealizedRelationalResult.emptyRealizedRelationalResult(node.columns) : null;
DatabaseConnection databaseConnection = childResult.getSQLExecutionNode().connection;
String databaseType = childResult.getDatabaseType();
String databaseTimeZone = childResult.getDatabaseTimeZone();
List<String> parentSQLKeyColumns = executor.parentSQLColumnsInResultSet(childResult.getResultColumns().stream().map(ResultColumn::getNonQuotedLabel).collect(Collectors.toList()));
List<Integer> parentCrossKeyIndices = FastList.newList();
for (String pkCol : parentSQLKeyColumns) {
parentCrossKeyIndices.add(childResultSet.findColumn(pkCol));
}
DoubleStrategyHashMap<Object, List<Object>, SQLExecutionResult> parentMap = new DoubleStrategyHashMap<>(RelationalGraphFetchUtils.objectSQLResultDoubleHashStrategy(crossKeyGetters, parentCrossKeyIndices));
for (Object parentObject : parentObjects) {
List<Object> mapped = parentMap.get(parentObject);
if (mapped == null) {
parentMap.put(parentObject, FastList.newListWith(parentObject));
} else {
mapped.add(parentObject);
}
}
List<Method> primaryKeyGetters = executor.primaryKeyGetters();
final int primaryKeyCount = primaryKeyGetters.size();
DoubleStrategyHashMap<Object, Object, SQLExecutionResult> currentMap = new DoubleStrategyHashMap<>(RelationalGraphFetchUtils.objectSQLResultDoubleHashStrategyWithEmptySecondStrategy(primaryKeyGetters));
String databaseConnectionString = ObjectMapperFactory.getNewStandardObjectMapperWithPureProtocolExtensionSupports().writeValueAsString(childResult.getSQLExecutionNode().connection);
while (childResultSet.next()) {
graphExecutionState.incrementRowCount();
List<Object> parents = parentMap.getWithSecondKey(childResult);
if (parents == null) {
throw new RuntimeException("No parent");
}
org.finos.legend.engine.plan.dependencies.domain.graphFetch.IGraphInstance<?> childGraphInstance = executor.getObjectFromResultSet(childResultSet, childResult.getDatabaseTimeZone(), databaseConnectionString);
Object child = childGraphInstance.getValue();
Object mapObject = currentMap.putIfAbsent(child, child);
if (mapObject == null) {
mapObject = child;
childObjects.add(mapObject);
graphExecutionState.addObjectMemoryUtilization(childGraphInstance.instanceSize());
if (childrenExist) {
this.addKeyRowToRealizedRelationalResult(child, primaryKeyGetters, realizedRelationalResult);
}
}
for (Object parent : parents) {
executor.addChildToParent(parent, mapObject, DefaultExecutionNodeContext.factory().create(graphExecutionState, null));
}
}
childResult.close();
childResult = null;
if (childrenExist) {
this.executeRelationalChildren(node, tempTableName, realizedRelationalResult, databaseConnection, databaseType, databaseTimeZone, currentMap, primaryKeyGetters);
}
}
} else {
throw new RuntimeException("Unknown execute class " + executeClass.getCanonicalName());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (childResult != null) {
childResult.close();
}
relationalStoreExecutionState.getBlockConnectionContext().unlockAllBlockConnections();
relationalStoreExecutionState.getBlockConnectionContext().closeAllBlockConnectionsAsync();
relationalStoreExecutionState.setBlockConnectionContext(oldBlockConnectionContext);
relationalStoreExecutionState.setRetainConnection(oldRetainConnectionFlag);
}
return new ConstantResult(childObjects);
}
throw new RuntimeException("Not implemented!");
}
use of org.finos.legend.engine.plan.execution.result.object.StreamingObjectResult in project legend-engine by finos.
the class RelationalExecutionNodeExecutor method executeImplementation.
@JsonIgnore
private Result executeImplementation(RelationalExecutionNode relationalExecutionNode, Result result, ExecutionState executionState, MutableList<CommonProfile> profiles) {
if (!(result instanceof RelationalResult)) {
throw new RuntimeException("Unexpected result: " + result.getClass().getName());
}
RelationalResult relationalResult = (RelationalResult) result;
try {
if (!(relationalExecutionNode.implementation instanceof JavaPlatformImplementation)) {
throw new RuntimeException("Only Java implementations are currently supported, found: " + relationalExecutionNode.implementation);
}
JavaPlatformImplementation javaPlatformImpl = (JavaPlatformImplementation) relationalExecutionNode.implementation;
String executionClassName = JavaHelper.getExecutionClassFullName(javaPlatformImpl);
String executionMethodName = JavaHelper.getExecutionMethodName(javaPlatformImpl);
String databaseConnectionString = ObjectMapperFactory.getNewStandardObjectMapperWithPureProtocolExtensionSupports().writeValueAsString(relationalExecutionNode.connection);
List<Pair<List<Class<?>>, List<Object>>> parameterTypesAndParametersAlternatives = Arrays.asList(Tuples.pair(Arrays.asList(RelationalResult.class, DatabaseConnection.class), Arrays.asList(result, relationalExecutionNode.connection)), Tuples.pair(Arrays.asList(RelationalResult.class, String.class), Arrays.asList(result, databaseConnectionString)), Tuples.pair(Arrays.asList(IRelationalResult.class, String.class), Arrays.asList(result, databaseConnectionString)));
Stream<?> transformedResult = ExecutionNodeJavaPlatformHelper.executeStaticJavaMethod(relationalExecutionNode, executionClassName, executionMethodName, parameterTypesAndParametersAlternatives, executionState, profiles);
return new StreamingObjectResult<>(transformedResult, relationalResult.builder, relationalResult);
} catch (Exception e) {
try {
return this.getStreamingObjectResultFromRelationalResult(relationalExecutionNode, relationalResult, relationalExecutionNode.connection);
} catch (Exception other) {
result.close();
other.addSuppressed(e);
throw (other instanceof RuntimeException) ? (RuntimeException) other : new RuntimeException(other);
}
}
}
Aggregations