You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by tl...@apache.org on 2021/09/06 14:20:33 UTC

[ignite] branch sql-calcite updated: IGNITE-15394 Calcite integration. Query contexts refactoring (#9369)

This is an automated email from the ASF dual-hosted git repository.

tledkov pushed a commit to branch sql-calcite
in repository https://gitbox.apache.org/repos/asf/ignite.git


The following commit(s) were added to refs/heads/sql-calcite by this push:
     new dbed713  IGNITE-15394  Calcite integration. Query contexts refactoring (#9369)
dbed713 is described below

commit dbed71387fc71618f8901fbaa51c81b777b58b91
Author: Taras Ledkov <tl...@gridgain.com>
AuthorDate: Mon Sep 6 17:20:05 2021 +0300

    IGNITE-15394  Calcite integration. Query contexts refactoring (#9369)
---
 .../query/calcite/exec/ExchangeServiceImpl.java    |  16 +-
 .../query/calcite/exec/ExecutionContext.java       |  80 ++++--
 .../query/calcite/exec/ExecutionServiceImpl.java   | 121 +++++----
 .../processors/query/calcite/exec/IndexScan.java   |   2 +-
 .../query/calcite/exec/LogicalRelImplementor.java  |   2 +-
 .../processors/query/calcite/exec/TableScan.java   |   2 +-
 .../calcite/exec/exp/agg/AccumulatorsFactory.java  |   4 +-
 .../query/calcite/exec/rel/AbstractNode.java       |   3 +-
 .../processors/query/calcite/exec/rel/Outbox.java  |   7 +-
 .../query/calcite/externalize/RelJson.java         |  10 +-
 .../query/calcite/externalize/RelJsonReader.java   |  25 +-
 .../query/calcite/externalize/RelJsonWriter.java   |   2 +-
 .../calcite/metadata/IgniteMdFragmentMapping.java  |  72 +++---
 .../query/calcite/metadata/IgniteMetadata.java     |   5 +-
 .../query/calcite/metadata/RelMetadataQueryEx.java |   5 +-
 .../calcite/prepare/AbstractMultiStepPlan.java     |   2 +-
 ...yPlanFactory.java => AbstractQueryContext.java} |  26 +-
 .../query/calcite/prepare/BaseQueryContext.java    | 275 +++++++++++++++++++++
 .../processors/query/calcite/prepare/Fragment.java |  24 +-
 .../query/calcite/prepare/FragmentPlan.java        |   3 +-
 .../query/calcite/prepare/IgnitePlanner.java       |   8 +-
 ...{FragmentPlan.java => MappingQueryContext.java} |  34 +--
 .../query/calcite/prepare/MultiStepPlan.java       |   2 +-
 .../query/calcite/prepare/PlanningContext.java     | 261 +++----------------
 .../query/calcite/prepare/QueryPlanCache.java      |   6 +-
 .../query/calcite/prepare/QueryPlanCacheImpl.java  |   7 +-
 .../query/calcite/prepare/QueryTemplate.java       |  15 +-
 .../query/calcite/rel/IgniteTableModify.java       |   3 +-
 .../query/calcite/schema/IgniteIndex.java          |   2 +-
 .../query/calcite/schema/IgniteTable.java          |   4 +-
 .../query/calcite/schema/IgniteTableImpl.java      |   7 +-
 .../query/calcite/schema/TableDescriptor.java      |   4 +-
 .../query/calcite/schema/TableDescriptorImpl.java  |   4 +-
 .../processors/query/calcite/util/Commons.java     |  37 ++-
 .../query/calcite/util/IgniteMethod.java           |   5 +-
 .../processors/query/calcite/util/PlanUtils.java   |   5 +-
 .../query/calcite/exec/RuntimeSortedIndexTest.java |   9 +-
 .../calcite/exec/rel/AbstractExecutionTest.java    |  19 +-
 .../integration/AbstractBasicIntegrationTest.java  |   5 +-
 .../integration/AggregatesIntegrationTest.java     |   3 +-
 .../ServerStatisticsIntegrationTest.java           |   2 +
 .../planner/AbstractAggregatePlannerTest.java      |   5 +-
 .../query/calcite/planner/AbstractPlannerTest.java |  64 ++---
 .../calcite/planner/HashAggregatePlannerTest.java  |   4 +-
 .../query/calcite/planner/PlannerTest.java         | 207 ++++++++--------
 .../calcite/planner/SortAggregatePlannerTest.java  |   5 +-
 .../query/calcite/planner/UnionPlannerTest.java    |   8 +-
 47 files changed, 786 insertions(+), 635 deletions(-)

diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExchangeServiceImpl.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExchangeServiceImpl.java
index a9c7618a..6c1fca4 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExchangeServiceImpl.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExchangeServiceImpl.java
@@ -21,7 +21,6 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Objects;
 import java.util.UUID;
-
 import com.google.common.collect.ImmutableMap;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
@@ -37,7 +36,7 @@ import org.apache.ignite.internal.processors.query.calcite.message.OutboxCloseMe
 import org.apache.ignite.internal.processors.query.calcite.message.QueryBatchAcknowledgeMessage;
 import org.apache.ignite.internal.processors.query.calcite.message.QueryBatchMessage;
 import org.apache.ignite.internal.processors.query.calcite.metadata.FragmentDescription;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.util.AbstractService;
 import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 import org.apache.ignite.internal.util.typedef.F;
@@ -47,6 +46,9 @@ import org.apache.ignite.internal.util.typedef.F;
  */
 public class ExchangeServiceImpl extends AbstractService implements ExchangeService {
     /** */
+    private final UUID locaNodeId;
+
+    /** */
     private QueryTaskExecutor taskExecutor;
 
     /** */
@@ -60,6 +62,8 @@ public class ExchangeServiceImpl extends AbstractService implements ExchangeServ
      */
     public ExchangeServiceImpl(GridKernalContext ctx) {
         super(ctx);
+
+        locaNodeId = ctx.localNodeId();
     }
 
     /**
@@ -255,12 +259,14 @@ public class ExchangeServiceImpl extends AbstractService implements ExchangeServ
      */
     private ExecutionContext<?> baseInboxContext(UUID nodeId, UUID qryId, long fragmentId) {
         return new ExecutionContext<>(
-            taskExecutor(),
-            PlanningContext.builder()
-                .originatingNodeId(nodeId)
+            BaseQueryContext.builder()
                 .logger(log)
                 .build(),
+            taskExecutor(),
             qryId,
+            locaNodeId,
+            nodeId,
+            null,
             new FragmentDescription(
                 fragmentId,
                 null,
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionContext.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionContext.java
index 47efdc2..45f6cea 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionContext.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionContext.java
@@ -29,13 +29,18 @@ import java.util.function.Consumer;
 import org.apache.calcite.DataContext;
 import org.apache.calcite.linq4j.QueryProvider;
 import org.apache.calcite.schema.SchemaPlus;
+import org.apache.calcite.tools.Frameworks;
 import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot;
+import org.apache.ignite.internal.processors.query.GridQueryCancel;
 import org.apache.ignite.internal.processors.query.calcite.exec.exp.ExpressionFactory;
 import org.apache.ignite.internal.processors.query.calcite.exec.exp.ExpressionFactoryImpl;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
 import org.apache.ignite.internal.processors.query.calcite.metadata.FragmentDescription;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.AbstractQueryContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
 import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 import org.apache.ignite.internal.processors.query.calcite.util.TypeUtils;
@@ -47,11 +52,14 @@ import static org.apache.ignite.internal.processors.query.calcite.util.Commons.c
 /**
  * Runtime context allowing access to the tables in a database.
  */
-public class ExecutionContext<Row> implements DataContext {
+public class ExecutionContext<Row> extends AbstractQueryContext implements DataContext {
     /** */
     private final TimeZone timeZone = TimeZone.getDefault(); // TODO DistributedSqlConfiguration#timeZone
 
     /** */
+    private static final SchemaPlus DFLT_SCHEMA = Frameworks.createRootSchema(false);
+
+    /** */
     // TODO https://issues.apache.org/jira/browse/IGNITE-15276 Support other locales.
     private static final Locale LOCALE = Locale.ENGLISH;
 
@@ -59,7 +67,13 @@ public class ExecutionContext<Row> implements DataContext {
     private final UUID qryId;
 
     /** */
-    private final PlanningContext ctx;
+    private final UUID locNodeId;
+
+    /** */
+    private final UUID originatingNodeId;
+
+    /** */
+    private final AffinityTopologyVersion topVer;
 
     /** */
     private final FragmentDescription fragmentDesc;
@@ -89,41 +103,45 @@ public class ExecutionContext<Row> implements DataContext {
     private Object[] correlations = new Object[16];
 
     /**
-     * @param ctx Parent context.
+     * @param qctx Parent base query context.
      * @param qryId Query ID.
      * @param fragmentDesc Partitions information.
      * @param params Parameters.
      */
     @SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
     public ExecutionContext(
+        BaseQueryContext qctx,
         QueryTaskExecutor executor,
-        PlanningContext ctx,
         UUID qryId,
+        UUID locNodeId,
+        UUID originatingNodeId,
+        AffinityTopologyVersion topVer,
         FragmentDescription fragmentDesc,
         RowHandler<Row> handler,
         Map<String, Object> params
     ) {
+        super(qctx);
+
         this.executor = executor;
-        this.ctx = ctx;
         this.qryId = qryId;
+        this.locNodeId = locNodeId;
+        this.originatingNodeId = originatingNodeId;
+        this.topVer = topVer;
         this.fragmentDesc = fragmentDesc;
         this.handler = handler;
         this.params = params;
 
-        expressionFactory = new ExpressionFactoryImpl<>(this, ctx.typeFactory(), ctx.conformance());
+        expressionFactory = new ExpressionFactoryImpl<>(
+            this,
+            qctx.typeFactory(),
+            qctx.config().getParserConfig().conformance()
+        );
 
         long ts = U.currentTimeMillis();
         startTs = ts + timeZone.getOffset(ts);
     }
 
     /**
-     * @return Parent context.
-     */
-    public PlanningContext planningContext() {
-        return ctx;
-    }
-
-    /**
      * @return Query ID.
      */
     public UUID queryId() {
@@ -183,20 +201,46 @@ public class ExecutionContext<Row> implements DataContext {
     }
 
     /**
-     * @return Originating node ID.
+     * @return Local node ID.
+     */
+    public UUID localNodeId() {
+        return locNodeId;
+    }
+
+    /**
+     * @return Originating node ID (the node, who started the execution).
      */
     public UUID originatingNodeId() {
-        return planningContext().originatingNodeId();
+        return originatingNodeId;
+    }
+
+    /**
+     * @return Topology version.
+     */
+    public AffinityTopologyVersion topologyVersion() {
+        return topVer;
+    }
+
+    /** */
+    public IgniteLogger logger() {
+        return unwrap(BaseQueryContext.class).logger();
     }
 
     /** {@inheritDoc} */
     @Override public SchemaPlus getRootSchema() {
-        return ctx.schema();
+        return DFLT_SCHEMA;
     }
 
     /** {@inheritDoc} */
     @Override public IgniteTypeFactory getTypeFactory() {
-        return ctx.typeFactory();
+        return unwrap(BaseQueryContext.class).typeFactory();
+    }
+
+    /**
+     * @return Query cancel.
+     */
+    public GridQueryCancel queryCancel() {
+        return unwrap(BaseQueryContext.class).queryCancel();
     }
 
     /** {@inheritDoc} */
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java
index 5ecb28f..ed3bce2 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java
@@ -27,6 +27,7 @@ import java.util.Objects;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
+
 import org.apache.calcite.plan.Context;
 import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.RelOptUtil;
@@ -75,6 +76,7 @@ import org.apache.ignite.internal.processors.query.calcite.metadata.FragmentDesc
 import org.apache.ignite.internal.processors.query.calcite.metadata.FragmentMapping;
 import org.apache.ignite.internal.processors.query.calcite.metadata.MappingService;
 import org.apache.ignite.internal.processors.query.calcite.metadata.RemoteException;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.CacheKey;
 import org.apache.ignite.internal.processors.query.calcite.prepare.DdlPlan;
 import org.apache.ignite.internal.processors.query.calcite.prepare.ExplainPlan;
@@ -83,6 +85,7 @@ import org.apache.ignite.internal.processors.query.calcite.prepare.FieldsMetadat
 import org.apache.ignite.internal.processors.query.calcite.prepare.Fragment;
 import org.apache.ignite.internal.processors.query.calcite.prepare.FragmentPlan;
 import org.apache.ignite.internal.processors.query.calcite.prepare.IgnitePlanner;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.MultiStepDmlPlan;
 import org.apache.ignite.internal.processors.query.calcite.prepare.MultiStepPlan;
 import org.apache.ignite.internal.processors.query.calcite.prepare.MultiStepQueryPlan;
@@ -388,12 +391,12 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
         List<FieldsQueryCursor<List<?>>> cursors = new ArrayList<>(qryList.size());
 
         for (final SqlNode qry0: qryList) {
-            PlanningContext pctx = createContext(ctx, schema, qry0.toString(), params);
+            final PlanningContext pctx = createContext(ctx, schema, qry0.toString(), params);
 
             if (qryList.size() == 1) {
                 plan = queryPlanCache().queryPlan(
-                    pctx, new CacheKey(pctx.schemaName(), pctx.query()),
-                    pctx0 -> prepareSingle(qry0, pctx0));
+                    new CacheKey(pctx.schemaName(), pctx.query()),
+                    () -> prepareSingle(qry0, pctx));
             }
             else
                 plan = prepareSingle(qry0, pctx);
@@ -462,23 +465,28 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
 
     /** */
     private PlanningContext createContext(QueryContext ctx, @Nullable String schema, String qry, Object[] params) {
-        return createContext(Commons.convert(ctx), topologyVersion(), localNodeId(), schema, qry, params);
+        return createContext(Commons.convert(ctx), schema, qry, params);
     }
 
     /** */
-    private PlanningContext createContext(Context parent, AffinityTopologyVersion topVer, UUID originator,
-        @Nullable String schema, String qry, Object[] params) {
-        return PlanningContext.builder()
-            .localNodeId(localNodeId())
-            .originatingNodeId(originator)
+    private BaseQueryContext createQueryContext(Context parent, @Nullable String schema) {
+        return BaseQueryContext.builder()
             .parentContext(parent)
-            .frameworkConfig(Frameworks.newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(getDefaultSchema(schema))
-                .build())
+            .frameworkConfig(
+                Frameworks.newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(getDefaultSchema(schema))
+                    .build()
+            )
+            .logger(log)
+            .build();
+    }
+
+    /** */
+    private PlanningContext createContext(Context parent, @Nullable String schema, String qry, Object[] params) {
+        return PlanningContext.builder()
+            .parentContext(createQueryContext(parent, schema))
             .query(qry)
             .parameters(params)
-            .topologyVersion(topVer)
-            .logger(log)
             .build();
     }
 
@@ -488,8 +496,8 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
     }
 
     /** */
-    private QueryPlan prepareFragment(PlanningContext ctx) {
-        return new FragmentPlan(fromJson(ctx, ctx.query()));
+    private QueryPlan prepareFragment(BaseQueryContext ctx, String jsonFragment) {
+        return new FragmentPlan(fromJson(ctx, jsonFragment));
     }
 
     /** */
@@ -611,13 +619,28 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
     ) {
         switch (plan.type()) {
             case DML:
-                ListFieldsQueryCursor<?> cur = executeQuery(qryId, (MultiStepPlan)plan, pctx);
+                ListFieldsQueryCursor<?> cur = mapAndExecutePlan(
+                    qryId,
+                    (MultiStepPlan)plan,
+                    pctx.unwrap(BaseQueryContext.class),
+                    pctx.parameters()
+                );
+
                 cur.iterator().hasNext();
+
                 return cur;
+
             case QUERY:
-                return executeQuery(qryId, (MultiStepPlan) plan, pctx);
+                return mapAndExecutePlan(
+                    qryId,
+                    (MultiStepPlan)plan,
+                    pctx.unwrap(BaseQueryContext.class),
+                    pctx.parameters()
+                );
+
             case EXPLAIN:
                 return executeExplain((ExplainPlan)plan, pctx);
+
             case DDL:
                 return executeDdl(qryId, (DdlPlan)plan, pctx);
 
@@ -640,8 +663,14 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
     }
 
     /** */
-    private ListFieldsQueryCursor<?> executeQuery(UUID qryId, MultiStepPlan plan, PlanningContext pctx) {
-        plan.init(pctx);
+    private ListFieldsQueryCursor<?> mapAndExecutePlan(
+        UUID qryId,
+        MultiStepPlan plan,
+        BaseQueryContext qctx,
+        Object[] params
+    ) {
+        MappingQueryContext mapCtx = Commons.mapContext(locNodeId, topologyVersion());
+        plan.init(mapCtx);
 
         List<Fragment> fragments = plan.fragments();
 
@@ -657,7 +686,7 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
 
             List<UUID> nodes = mapping.nodeIds();
 
-            assert nodes != null && nodes.size() == 1 && F.first(nodes).equals(pctx.localNodeId());
+            assert nodes != null && nodes.size() == 1 && F.first(nodes).equals(localNodeId());
         }
 
         FragmentDescription fragmentDesc = new FragmentDescription(
@@ -667,12 +696,15 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
             plan.remotes(fragment));
 
         ExecutionContext<Row> ectx = new ExecutionContext<>(
+            qctx,
             taskExecutor(),
-            pctx,
             qryId,
+            locNodeId,
+            locNodeId,
+            mapCtx.topologyVersion(),
             fragmentDesc,
             handler,
-            Commons.parametersMap(pctx.parameters()));
+            Commons.parametersMap(params));
 
         Node<Row> node = new LogicalRelImplementor<>(ectx, partitionService(), mailboxRegistry(),
             exchangeService(), failureProcessor()).go(fragment.root());
@@ -699,11 +731,11 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
                     try {
                         QueryStartRequest req = new QueryStartRequest(
                             qryId,
-                            pctx.schemaName(),
+                            qctx.schemaName(),
                             fragment.serialized(),
-                            pctx.topologyVersion(),
+                            ectx.topologyVersion(),
                             fragmentDesc,
-                            pctx.parameters());
+                            params);
 
                         messageService().send(nodeId, req);
                     }
@@ -726,12 +758,8 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
     }
 
     /** */
-    private void executeFragment(UUID qryId, FragmentPlan plan, PlanningContext pctx, FragmentDescription fragmentDesc) {
-        ExecutionContext<Row> ectx = new ExecutionContext<>(taskExecutor(), pctx, qryId,
-            fragmentDesc, handler, Commons.parametersMap(pctx.parameters()));
-
-        long frId = fragmentDesc.fragmentId();
-        UUID origNodeId = pctx.originatingNodeId();
+    private void executeFragment(UUID qryId, FragmentPlan plan, ExecutionContext<Row> ectx) {
+        UUID origNodeId = ectx.originatingNodeId();
 
         Outbox<Row> node = new LogicalRelImplementor<>(
                 ectx,
@@ -742,7 +770,7 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
                 .go(plan.root());
 
         try {
-            messageService().send(origNodeId, new QueryStartResponse(qryId, frId));
+            messageService().send(origNodeId, new QueryStartResponse(qryId, ectx.fragmentId()));
         }
         catch (IgniteCheckedException e) {
             IgniteException wrpEx = new IgniteException("Failed to send reply. [nodeId=" + origNodeId + ']', e);
@@ -756,11 +784,10 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
     /** */
     private void register(QueryInfo info) {
         UUID qryId = info.ctx.queryId();
-        PlanningContext pctx = info.ctx.planningContext();
 
         running.put(qryId, info);
 
-        GridQueryCancel qryCancel = pctx.queryCancel();
+        GridQueryCancel qryCancel = info.ctx.queryCancel();
 
         if (qryCancel == null)
             return;
@@ -789,22 +816,32 @@ public class ExecutionServiceImpl<Row> extends AbstractService implements Execut
     }
 
     /** */
-    private void onMessage(UUID nodeId, QueryStartRequest msg) {
+    private void onMessage(UUID nodeId, final QueryStartRequest msg) {
         assert nodeId != null && msg != null;
 
         try {
-            PlanningContext pctx = createContext(Contexts.empty(), msg.topologyVersion(), nodeId, msg.schema(),
-                msg.root(), msg.parameters());
+            final BaseQueryContext qctx = createQueryContext(Contexts.empty(), msg.schema());
 
             QueryPlan qryPlan = queryPlanCache().queryPlan(
-                pctx,
-                new CacheKey(pctx.schemaName(), pctx.query()),
-                this::prepareFragment
+                new CacheKey(msg.schema(), msg.root()),
+                () -> prepareFragment(qctx, msg.root())
             );
 
             assert qryPlan.type() == QueryPlan.Type.FRAGMENT;
 
-            executeFragment(msg.queryId(), (FragmentPlan)qryPlan, pctx, msg.fragmentDescription());
+            ExecutionContext<Row> ectx = new ExecutionContext<>(
+                qctx,
+                taskExecutor(),
+                msg.queryId(),
+                locNodeId,
+                nodeId,
+                msg.topologyVersion(),
+                msg.fragmentDescription(),
+                handler,
+                Commons.parametersMap(msg.parameters())
+            );
+
+            executeFragment(msg.queryId(), (FragmentPlan)qryPlan, ectx);
         }
         catch (Throwable ex) {
             U.error(log, "Failed to start query fragment ", ex);
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/IndexScan.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/IndexScan.java
index ea37f49..7ae84e7 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/IndexScan.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/IndexScan.java
@@ -129,7 +129,7 @@ public class IndexScan<Row> extends AbstractIndexScan<Row, IndexRow> {
         coCtx = cctx.cacheObjectContext();
 
         factory = ectx.rowHandler().factory(ectx.getTypeFactory(), rowType);
-        topVer = ectx.planningContext().topologyVersion();
+        topVer = ectx.topologyVersion();
         this.parts = parts;
         mvccSnapshot = ectx.mvccSnapshot();
         this.requiredColumns = requiredColumns;
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/LogicalRelImplementor.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/LogicalRelImplementor.java
index 269e446..d3f9a79 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/LogicalRelImplementor.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/LogicalRelImplementor.java
@@ -187,7 +187,7 @@ public class LogicalRelImplementor<Row> implements IgniteRelVisitor<Node<Row>> {
 
         IgniteDistribution distr = rel.distribution();
         Destination<Row> dest = distr.destination(ctx, affSrvc, ctx.group(rel.sourceId()));
-        UUID localNodeId = ctx.planningContext().localNodeId();
+        UUID localNodeId = ctx.localNodeId();
 
         FilterNode<Row> node = new FilterNode<>(ctx, rel.getRowType(), r -> Objects.equals(localNodeId, F.first(dest.targets(r))));
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/TableScan.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/TableScan.java
index f3a460e..1717776 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/TableScan.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/TableScan.java
@@ -100,7 +100,7 @@ public class TableScan<Row> implements Iterable<Row>, AutoCloseable {
         RelDataType rowType = desc.rowType(this.ectx.getTypeFactory(), requiredColunms);
 
         factory = this.ectx.rowHandler().factory(this.ectx.getTypeFactory(), rowType);
-        topVer = ectx.planningContext().topologyVersion();
+        topVer = ectx.topologyVersion();
         mvccSnapshot = ectx.mvccSnapshot();
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/agg/AccumulatorsFactory.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/agg/AccumulatorsFactory.java
index 4f4789c..3ae40c2 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/agg/AccumulatorsFactory.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/agg/AccumulatorsFactory.java
@@ -22,7 +22,6 @@ import java.util.List;
 import java.util.concurrent.ExecutionException;
 import java.util.function.Function;
 import java.util.function.Supplier;
-
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
@@ -50,7 +49,6 @@ import org.apache.calcite.util.Pair;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
 import org.apache.ignite.internal.processors.query.calcite.exec.RowHandler;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
 import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 import org.apache.ignite.internal.util.typedef.F;
@@ -89,7 +87,7 @@ public class AccumulatorsFactory<Row> implements Supplier<List<AccumulatorWrappe
 
     /** */
     private static Function<Object, Object> cast0(Pair<RelDataType, RelDataType> types) {
-        IgniteTypeFactory typeFactory = PlanningContext.empty().typeFactory();
+        IgniteTypeFactory typeFactory = Commons.typeFactory();
 
         RelDataType from = types.left;
         RelDataType to = types.right;
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractNode.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractNode.java
index 409d633..3f9fa5e 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractNode.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractNode.java
@@ -20,7 +20,6 @@ package org.apache.ignite.internal.processors.query.calcite.exec.rel;
 import java.util.Collection;
 import java.util.Comparator;
 import java.util.List;
-
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.ignite.IgniteSystemProperties;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
@@ -143,7 +142,7 @@ public abstract class AbstractNode<Row> implements Node<Row> {
      */
     public void onError(Throwable e) {
         if (e instanceof ExecutionCancelledException)
-            U.warn(context().planningContext().logger(), "Execution is cancelled.", e);
+            U.warn(context().logger(), "Execution is cancelled.", e);
         else
             onErrorInternal(e);
     }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/Outbox.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/Outbox.java
index 7b8c3da..b2f036a 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/Outbox.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/Outbox.java
@@ -26,7 +26,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 import java.util.stream.Collectors;
-
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExchangeService;
@@ -152,14 +151,14 @@ public class Outbox<Row> extends AbstractNode<Row> implements Mailbox<Row>, Sing
 
     /** {@inheritDoc} */
     @Override protected void onErrorInternal(Throwable e) {
-        U.error(context().planningContext().logger(),
+        U.error(context().logger(),
             "Error occurred during execution: " + X.getFullStackTrace(e));
 
         try {
             sendError(e);
         }
         catch (IgniteCheckedException ex) {
-            U.error(context().planningContext().logger(),
+            U.error(context().logger(),
                 "Error occurred during send error message: " + X.getFullStackTrace(e));
         }
         finally {
@@ -212,7 +211,7 @@ public class Outbox<Row> extends AbstractNode<Row> implements Mailbox<Row>, Sing
             exchange.closeInbox(nodeId, queryId(), targetFragmentId, exchangeId);
         }
         catch (IgniteCheckedException e) {
-            U.warn(context().planningContext().logger(), "Failed to send cancel message.", e);
+            U.warn(context().logger(), "Failed to send cancel message.", e);
         }
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJson.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJson.java
index cf024a7..0ecc98f 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJson.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJson.java
@@ -114,9 +114,6 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 @SuppressWarnings({"rawtypes", "unchecked"})
 class RelJson {
     /** */
-    private final RelOptCluster cluster;
-
-    /** */
     @SuppressWarnings("PublicInnerClass") @FunctionalInterface
     public static interface RelFactory extends Function<RelInput, RelNode> {
         /** {@inheritDoc} */
@@ -226,11 +223,6 @@ class RelJson {
             "org.apache.calcite.adapter.jdbc.JdbcRules$");
 
     /** */
-    RelJson(RelOptCluster cluster) {
-        this.cluster = cluster;
-    }
-
-    /** */
     Function<RelInput, RelNode> factory(String type) {
         return FACTORIES_CACHE.getUnchecked(type);
     }
@@ -728,7 +720,7 @@ class RelJson {
     /** */
     private Object toJson(RexNode node) {
         // removes calls to SEARCH and the included Sarg and converts them to comparisons
-        node = RexUtil.expandSearch(cluster.getRexBuilder(), null, node);
+        node = RexUtil.expandSearch(Commons.cluster().getRexBuilder(), null, node);
 
         Map<String, Object> map;
         switch (node.getKind()) {
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonReader.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonReader.java
index 10aea34f..573fdf3 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonReader.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonReader.java
@@ -24,7 +24,6 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.function.Function;
-
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -47,7 +46,7 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 import org.apache.ignite.IgniteException;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 
 /** */
@@ -61,9 +60,6 @@ public class RelJsonReader {
     private final ObjectMapper mapper = new ObjectMapper().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
 
     /** */
-    private final RelOptCluster cluster;
-
-    /** */
     private final RelOptSchema relOptSchema;
 
     /** */
@@ -76,18 +72,17 @@ public class RelJsonReader {
     private RelNode lastRel;
 
     /** */
-    public static <T extends RelNode> T fromJson(PlanningContext ctx, String json) {
-        RelJsonReader reader = new RelJsonReader(ctx.cluster(), ctx.catalogReader());
+    public static <T extends RelNode> T fromJson(BaseQueryContext ctx, String json) {
+        RelJsonReader reader = new RelJsonReader(ctx.catalogReader());
 
         return (T)reader.read(json);
     }
 
     /** */
-    public RelJsonReader(RelOptCluster cluster, RelOptSchema relOptSchema) {
-        this.cluster = cluster;
+    public RelJsonReader(RelOptSchema relOptSchema) {
         this.relOptSchema = relOptSchema;
 
-        relJson = new RelJson(cluster);
+        relJson = new RelJson();
     }
 
     /** */
@@ -132,12 +127,12 @@ public class RelJsonReader {
 
         /** {@inheritDoc} */
         @Override public RelOptCluster getCluster() {
-            return cluster;
+            return Commons.cluster();
         }
 
         /** {@inheritDoc} */
         @Override public RelTraitSet getTraitSet() {
-            return cluster.traitSet();
+            return Commons.cluster().traitSet();
         }
 
         /** {@inheritDoc} */
@@ -249,7 +244,7 @@ public class RelJsonReader {
         /** {@inheritDoc} */
         @Override public RelDataType getRowType(String tag) {
             Object o = jsonRel.get(tag);
-            return relJson.toType(Commons.typeFactory(cluster), o);
+            return relJson.toType(Commons.typeFactory(Commons.cluster()), o);
         }
 
         /** {@inheritDoc} */
@@ -257,7 +252,7 @@ public class RelJsonReader {
             List<RexNode> expressionList = getExpressionList(expressionsTag);
             List<String> names =
                 (List<String>)get(fieldsTag);
-            return Commons.typeFactory(cluster).createStructType(
+            return Commons.typeFactory(Commons.cluster()).createStructType(
                 new AbstractList<Map.Entry<String, RelDataType>>() {
                     @Override public Map.Entry<String, RelDataType> get(int index) {
                         return Pair.of(names.get(index),
@@ -320,7 +315,7 @@ public class RelJsonReader {
             Boolean distinct = (Boolean)jsonAggCall.get("distinct");
             List<Integer> operands = (List<Integer>)jsonAggCall.get("operands");
             Integer filterOperand = (Integer)jsonAggCall.get("filter");
-            RelDataType type = relJson.toType(Commons.typeFactory(cluster), jsonAggCall.get("type"));
+            RelDataType type = relJson.toType(Commons.typeFactory(Commons.cluster()), jsonAggCall.get("type"));
             String name = (String)jsonAggCall.get("name");
             return AggregateCall.create(aggregation, distinct, false, false, operands,
                 filterOperand == null ? -1 : filterOperand,
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonWriter.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonWriter.java
index eade491..8a178b4 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonWriter.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/externalize/RelJsonWriter.java
@@ -73,7 +73,7 @@ public class RelJsonWriter implements RelWriter {
     public RelJsonWriter(RelOptCluster cluster, boolean pretty) {
         this.pretty = pretty;
 
-        relJson = new RelJson(cluster);
+        relJson = new RelJson();
     }
 
     /** {@inheritDoc} */
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdFragmentMapping.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdFragmentMapping.java
index e16ce58..d46cdb6 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdFragmentMapping.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdFragmentMapping.java
@@ -30,6 +30,7 @@ import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.ignite.internal.processors.query.calcite.metadata.IgniteMetadata.FragmentMappingMetadata;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteExchange;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteFilter;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteIndexScan;
@@ -41,11 +42,10 @@ import org.apache.ignite.internal.processors.query.calcite.rel.IgniteValues;
 import org.apache.ignite.internal.processors.query.calcite.schema.IgniteTable;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions;
 import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
-import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 import org.apache.ignite.internal.processors.query.calcite.util.IgniteMethod;
 
 /**
- * Implementation class for {@link RelMetadataQueryEx#fragmentMapping(RelNode)} method call.
+ * Implementation class for {@link RelMetadataQueryEx#fragmentMapping(RelNode, MappingQueryContext)} method call.
  */
 public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingMetadata> {
     /**
@@ -67,26 +67,26 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
      * @param mq Metadata query instance. Used to request appropriate metadata from node children.
      * @return Nodes mapping, representing a list of nodes capable to execute a query over particular partitions.
      */
-    public FragmentMapping fragmentMapping(RelNode rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(RelNode rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         throw new AssertionError();
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(RelSubset rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(RelSubset rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         throw new AssertionError();
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(SingleRel rel, RelMetadataQuery mq) {
-        return _fragmentMapping(rel.getInput(), mq);
+    public FragmentMapping fragmentMapping(SingleRel rel, RelMetadataQuery mq, MappingQueryContext ctx) {
+        return _fragmentMapping(rel.getInput(), mq, ctx);
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      *
      * {@link ColocationMappingException} may be thrown on two children nodes locations merge. This means
      * that the fragment (which part the parent node is) cannot be executed on any node and additional exchange
@@ -94,12 +94,12 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
      * exchange. After the exchange is put into the fragment and the fragment is split into two ones, fragment meta
      * information will be recalculated for all fragments.
      */
-    public FragmentMapping fragmentMapping(BiRel rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(BiRel rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         RelNode left = rel.getLeft();
         RelNode right = rel.getRight();
 
-        FragmentMapping fLeft = _fragmentMapping(left, mq);
-        FragmentMapping fRight = _fragmentMapping(right, mq);
+        FragmentMapping fLeft = _fragmentMapping(left, mq, ctx);
+        FragmentMapping fRight = _fragmentMapping(right, mq, ctx);
 
         try {
             return fLeft.colocate(fRight);
@@ -122,7 +122,7 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      *
      * {@link ColocationMappingException} may be thrown on two children nodes locations merge. This means
      * that the fragment (which part the parent node is) cannot be executed on any node and additional exchange
@@ -130,17 +130,17 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
      * exchange. After the exchange is put into the fragment and the fragment is split into two ones, fragment meta
      * information will be recalculated for all fragments.
      */
-    public FragmentMapping fragmentMapping(SetOp rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(SetOp rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         FragmentMapping res = null;
 
         if (TraitUtils.distribution(rel) == IgniteDistributions.random()) {
             for (RelNode input : rel.getInputs())
-                res = res == null ? _fragmentMapping(input, mq) : res.combine(_fragmentMapping(input, mq));
+                res = res == null ? _fragmentMapping(input, mq, ctx) : res.combine(_fragmentMapping(input, mq, ctx));
         }
         else {
             for (RelNode input : rel.getInputs()) {
                 try {
-                    res = res == null ? _fragmentMapping(input, mq) : res.colocate(_fragmentMapping(input, mq));
+                    res = res == null ? _fragmentMapping(input, mq, ctx) : res.colocate(_fragmentMapping(input, mq, ctx));
                 }
                 catch (ColocationMappingException e) {
                     throw new NodeMappingException("Failed to calculate physical distribution", input, e);
@@ -152,23 +152,23 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      *
      * Prunes involved partitions (hence nodes, involved in query execution) if possible.
      */
-    public FragmentMapping fragmentMapping(IgniteFilter rel, RelMetadataQuery mq) {
-        return _fragmentMapping(rel.getInput(), mq).prune(rel);
+    public FragmentMapping fragmentMapping(IgniteFilter rel, RelMetadataQuery mq, MappingQueryContext ctx) {
+        return _fragmentMapping(rel.getInput(), mq, ctx).prune(rel);
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      *
      * Prunes involved partitions (hence nodes, involved in query execution) if possible.
      */
-    public FragmentMapping fragmentMapping(IgniteTrimExchange rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(IgniteTrimExchange rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         try {
             return FragmentMapping.create(rel.sourceId())
-                .colocate(_fragmentMapping(rel.getInput(), mq));
+                .colocate(_fragmentMapping(rel.getInput(), mq, ctx));
         }
         catch (ColocationMappingException e) {
             throw new AssertionError(e);
@@ -176,39 +176,39 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(IgniteReceiver rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(IgniteReceiver rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         return FragmentMapping.create(rel.exchangeId());
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(IgniteIndexScan rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(IgniteIndexScan rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         return FragmentMapping.create(rel.sourceId(),
-            rel.getTable().unwrap(IgniteTable.class).colocationGroup(Commons.context(rel)));
+            rel.getTable().unwrap(IgniteTable.class).colocationGroup(ctx));
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(IgniteTableScan rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(IgniteTableScan rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         return FragmentMapping.create(rel.sourceId(),
-            rel.getTable().unwrap(IgniteTable.class).colocationGroup(Commons.context(rel)));
+            rel.getTable().unwrap(IgniteTable.class).colocationGroup(ctx));
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(IgniteValues rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(IgniteValues rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         return FragmentMapping.create();
     }
 
     /**
-     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery)}
+     * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}
      */
-    public FragmentMapping fragmentMapping(IgniteTableFunctionScan rel, RelMetadataQuery mq) {
+    public FragmentMapping fragmentMapping(IgniteTableFunctionScan rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         return FragmentMapping.create();
     }
 
@@ -218,9 +218,9 @@ public class IgniteMdFragmentMapping implements MetadataHandler<FragmentMappingM
      * @param mq Metadata query instance.
      * @return Fragment meta information.
      */
-    public static FragmentMapping _fragmentMapping(RelNode rel, RelMetadataQuery mq) {
+    public static FragmentMapping _fragmentMapping(RelNode rel, RelMetadataQuery mq, MappingQueryContext ctx) {
         assert mq instanceof RelMetadataQueryEx;
 
-        return ((RelMetadataQueryEx) mq).fragmentMapping(rel);
+        return ((RelMetadataQueryEx)mq).fragmentMapping(rel, ctx);
     }
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java
index eff7bb7..321af9c 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java
@@ -26,6 +26,7 @@ import org.apache.calcite.rel.metadata.MetadataDef;
 import org.apache.calcite.rel.metadata.MetadataHandler;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.util.IgniteMethod;
 
 /**
@@ -59,11 +60,11 @@ public class IgniteMetadata {
             FragmentMappingMetadata.Handler.class, IgniteMethod.FRAGMENT_MAPPING.method());
 
         /** Determines how the rows are distributed. */
-        FragmentMapping fragmentMapping();
+        FragmentMapping fragmentMapping(MappingQueryContext ctx);
 
         /** Handler API. */
         interface Handler extends MetadataHandler<FragmentMappingMetadata> {
-            FragmentMapping fragmentMapping(RelNode r, RelMetadataQuery mq);
+            FragmentMapping fragmentMapping(RelNode r, RelMetadataQuery mq, MappingQueryContext ctx);
         }
     }
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/RelMetadataQueryEx.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/RelMetadataQueryEx.java
index 72f9601..ed6b7eb 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/RelMetadataQueryEx.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/RelMetadataQueryEx.java
@@ -24,6 +24,7 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.metadata.JaninoRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.reflections.Reflections;
@@ -91,10 +92,10 @@ public class RelMetadataQueryEx extends RelMetadataQuery {
      * @param rel Relational node.
      * @return Fragment meta information.
      */
-    public FragmentMapping fragmentMapping(RelNode rel) {
+    public FragmentMapping fragmentMapping(RelNode rel, MappingQueryContext ctx) {
         for (;;) {
             try {
-                return sourceDistributionHandler.fragmentMapping(rel, this);
+                return sourceDistributionHandler.fragmentMapping(rel, this, ctx);
             } catch (JaninoRelMetadataProvider.NoHandler e) {
                 sourceDistributionHandler = revise(e.relClass, IgniteMetadata.FragmentMappingMetadata.DEF);
             }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractMultiStepPlan.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractMultiStepPlan.java
index 9ad8222..7fb55d8 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractMultiStepPlan.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractMultiStepPlan.java
@@ -88,7 +88,7 @@ public abstract class AbstractMultiStepPlan implements MultiStepPlan {
     }
 
     /** {@inheritDoc} */
-    @Override public void init(PlanningContext ctx) {
+    @Override public void init(MappingQueryContext ctx) {
         executionPlan = queryTemplate.map(ctx);
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanFactory.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractQueryContext.java
similarity index 65%
rename from modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanFactory.java
rename to modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractQueryContext.java
index 91dc8c5..7fd4d73 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanFactory.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/AbstractQueryContext.java
@@ -17,13 +17,25 @@
 
 package org.apache.ignite.internal.processors.query.calcite.prepare;
 
+import org.apache.calcite.plan.Context;
+
 /**
- *
+ * Abstract query context.
  */
-public interface QueryPlanFactory {
-    /**
-     * @param ctx Planning context.
-     * @return Query plan.
-     */
-    QueryPlan create(PlanningContext ctx);
+public class AbstractQueryContext implements Context {
+    /** */
+    private final Context parentCtx;
+
+    /** */
+    public AbstractQueryContext(Context parentCtx) {
+        this.parentCtx = parentCtx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <C> C unwrap(Class<C> aCls) {
+        if (aCls == getClass())
+            return aCls.cast(this);
+
+        return parentCtx.unwrap(aCls);
+    }
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/BaseQueryContext.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/BaseQueryContext.java
new file mode 100644
index 0000000..490e555
--- /dev/null
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/BaseQueryContext.java
@@ -0,0 +1,275 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.prepare;
+
+import java.util.Properties;
+import org.apache.calcite.config.CalciteConnectionConfig;
+import org.apache.calcite.config.CalciteConnectionConfigImpl;
+import org.apache.calcite.config.CalciteConnectionProperty;
+import org.apache.calcite.jdbc.CalciteSchema;
+import org.apache.calcite.plan.Context;
+import org.apache.calcite.plan.Contexts;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.volcano.VolcanoPlanner;
+import org.apache.calcite.prepare.CalciteCatalogReader;
+import org.apache.calcite.rel.metadata.CachingRelMetadataProvider;
+import org.apache.calcite.rel.type.RelDataTypeSystem;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.schema.SchemaPlus;
+import org.apache.calcite.tools.FrameworkConfig;
+import org.apache.calcite.tools.Frameworks;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.internal.processors.query.GridQueryCancel;
+import org.apache.ignite.internal.processors.query.calcite.metadata.IgniteMetadata;
+import org.apache.ignite.internal.processors.query.calcite.metadata.RelMetadataQueryEx;
+import org.apache.ignite.internal.processors.query.calcite.metadata.cost.IgniteCostFactory;
+import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
+import org.apache.ignite.logger.NullLogger;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.calcite.tools.Frameworks.createRootSchema;
+import static org.apache.ignite.internal.processors.query.calcite.CalciteQueryProcessor.FRAMEWORK_CONFIG;
+
+/**
+ * Base query context.
+ */
+public final class BaseQueryContext extends AbstractQueryContext {
+    /** */
+    private static final IgniteCostFactory COST_FACTORY = new IgniteCostFactory();
+
+    /** */
+    public static final CalciteConnectionConfig CALCITE_CONNECTION_CONFIG;
+
+    /** */
+    private static final BaseQueryContext EMPTY_CONTEXT;
+
+    /** */
+    private static final VolcanoPlanner EMPTY_PLANNER;
+
+    /** */
+    private static final RexBuilder DFLT_REX_BUILDER;
+
+    /** */
+    public static final RelOptCluster CLUSTER;
+
+    /** */
+    public static final IgniteTypeFactory TYPE_FACTORY;
+
+    static {
+        Properties props = new Properties();
+
+        props.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(),
+            String.valueOf(FRAMEWORK_CONFIG.getParserConfig().caseSensitive()));
+        props.setProperty(CalciteConnectionProperty.CONFORMANCE.camelName(),
+            String.valueOf(FRAMEWORK_CONFIG.getParserConfig().conformance()));
+        props.setProperty(CalciteConnectionProperty.MATERIALIZATIONS_ENABLED.camelName(),
+            String.valueOf(true));
+
+        CALCITE_CONNECTION_CONFIG = new CalciteConnectionConfigImpl(props);
+
+        EMPTY_CONTEXT = builder().build();
+
+        EMPTY_PLANNER = new VolcanoPlanner(COST_FACTORY, EMPTY_CONTEXT);
+
+        RelDataTypeSystem typeSys = CALCITE_CONNECTION_CONFIG.typeSystem(RelDataTypeSystem.class, FRAMEWORK_CONFIG.getTypeSystem());
+        TYPE_FACTORY = new IgniteTypeFactory(typeSys);
+
+        DFLT_REX_BUILDER = new RexBuilder(TYPE_FACTORY);
+
+        CLUSTER = RelOptCluster.create(EMPTY_PLANNER, DFLT_REX_BUILDER);
+
+        CLUSTER.setMetadataProvider(new CachingRelMetadataProvider(IgniteMetadata.METADATA_PROVIDER, EMPTY_PLANNER));
+        CLUSTER.setMetadataQuerySupplier(RelMetadataQueryEx::create);
+    }
+
+    /** */
+    private final FrameworkConfig cfg;
+
+    /** */
+    private final IgniteLogger log;
+
+    /** */
+    private final IgniteTypeFactory typeFactory;
+
+    /** */
+    private final RexBuilder rexBuilder;
+
+    /** */
+    private CalciteCatalogReader catalogReader;
+
+    /** */
+    private final GridQueryCancel qryCancel;
+
+    /**
+     * Private constructor, used by a builder.
+     */
+    private BaseQueryContext(
+        FrameworkConfig cfg,
+        Context parentCtx,
+        IgniteLogger log
+    ) {
+        super(Contexts.chain(parentCtx, cfg.getContext()));
+
+        // link frameworkConfig#context() to this.
+        this.cfg = Frameworks.newConfigBuilder(cfg).context(this).build();
+
+        this.log = log;
+
+        RelDataTypeSystem typeSys = CALCITE_CONNECTION_CONFIG.typeSystem(RelDataTypeSystem.class, cfg.getTypeSystem());
+
+        typeFactory = new IgniteTypeFactory(typeSys);
+
+        qryCancel = unwrap(GridQueryCancel.class);
+
+        rexBuilder = new RexBuilder(typeFactory);
+    }
+
+    /**
+     * @return Framework config.
+     */
+    public FrameworkConfig config() {
+        return cfg;
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger logger() {
+        return log;
+    }
+
+    /**
+     * @return Schema name.
+     */
+    public String schemaName() {
+        return schema().getName();
+    }
+
+    /**
+     * @return Schema.
+     */
+    public SchemaPlus schema() {
+        return cfg.getDefaultSchema();
+    }
+
+    /**
+     * @return Type factory.
+     */
+    public IgniteTypeFactory typeFactory() {
+        return typeFactory;
+    }
+
+    /** */
+    public RexBuilder rexBuilder() {
+        return rexBuilder;
+    }
+
+    /**
+     * @return New catalog reader.
+     */
+    public CalciteCatalogReader catalogReader() {
+        if (catalogReader != null)
+            return catalogReader;
+
+        SchemaPlus dfltSchema = schema(), rootSchema = dfltSchema;
+
+        while (rootSchema.getParentSchema() != null)
+            rootSchema = rootSchema.getParentSchema();
+
+        return catalogReader = new CalciteCatalogReader(
+            CalciteSchema.from(rootSchema),
+            CalciteSchema.from(dfltSchema).path(null),
+            typeFactory(), CALCITE_CONNECTION_CONFIG);
+    }
+
+    /**
+     * @return Query cancel.
+     */
+    public GridQueryCancel queryCancel() {
+        return qryCancel;
+    }
+
+    /**
+     * @return Context builder.
+     */
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    /** */
+    public static BaseQueryContext empty() {
+        return EMPTY_CONTEXT;
+    }
+
+    /**
+     * Query context builder.
+     */
+    @SuppressWarnings("PublicInnerClass") 
+    public static class Builder {
+        /** */
+        private static final FrameworkConfig EMPTY_CONFIG =
+            Frameworks.newConfigBuilder(FRAMEWORK_CONFIG)
+                .defaultSchema(createRootSchema(false))
+                .build();
+
+        /** */
+        private FrameworkConfig frameworkCfg = EMPTY_CONFIG;
+
+        /** */
+        private Context parentCtx = Contexts.empty();
+
+        /** */
+        private IgniteLogger log = new NullLogger();
+
+        /**
+         * @param frameworkCfg Framework config.
+         * @return Builder for chaining.
+         */
+        public Builder frameworkConfig(@NotNull FrameworkConfig frameworkCfg) {
+            this.frameworkCfg = frameworkCfg;
+            return this;
+        }
+
+        /**
+         * @param parentCtx Parent context.
+         * @return Builder for chaining.
+         */
+        public Builder parentContext(@NotNull Context parentCtx) {
+            this.parentCtx = parentCtx;
+            return this;
+        }
+
+        /**
+         * @param log Logger.
+         * @return Builder for chaining.
+         */
+        public Builder logger(@NotNull IgniteLogger log) {
+            this.log = log;
+            return this;
+        }
+
+        /**
+         * Builds planner context.
+         *
+         * @return Planner context.
+         */
+        public BaseQueryContext build() {
+            return new BaseQueryContext(frameworkCfg, parentCtx, log);
+        }
+    }
+}
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/Fragment.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/Fragment.java
index 2634535..04f84f2 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/Fragment.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/Fragment.java
@@ -35,6 +35,7 @@ import org.apache.ignite.internal.processors.query.calcite.rel.IgniteReceiver;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteSender;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 import org.apache.ignite.internal.util.tostring.GridToStringExclude;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.jetbrains.annotations.NotNull;
@@ -121,17 +122,8 @@ public class Fragment {
     }
 
     /** */
-    public Fragment attach(PlanningContext ctx) {
-        RelOptCluster cluster = ctx.cluster();
-
-        return root.getCluster() == cluster ? this : new Cloner(cluster).go(this);
-    }
-
-    /** */
-    public Fragment detach() {
-        RelOptCluster cluster = PlanningContext.empty().cluster();
-
-        return root.getCluster() == cluster ? this : new Cloner(cluster).go(this);
+    public Fragment copy() {
+        return new Cloner(Commons.cluster()).go(this);
     }
 
     /**
@@ -139,9 +131,7 @@ public class Fragment {
      * @param ctx Planner context.
      * @param mq Metadata query.
      */
-    Fragment map(MappingService mappingSrvc, PlanningContext ctx, RelMetadataQuery mq) throws FragmentMappingException {
-        assert root.getCluster() == ctx.cluster() : "Fragment is detached [fragment=" + this + "]";
-
+    Fragment map(MappingService mappingSrvc, MappingQueryContext ctx, RelMetadataQuery mq) throws FragmentMappingException {
         if (mapping != null)
             return this;
 
@@ -149,9 +139,9 @@ public class Fragment {
     }
 
     /** */
-    private FragmentMapping mapping(PlanningContext ctx, RelMetadataQuery mq, Supplier<List<UUID>> nodesSource) {
+    private FragmentMapping mapping(MappingQueryContext ctx, RelMetadataQuery mq, Supplier<List<UUID>> nodesSource) {
         try {
-            FragmentMapping mapping = IgniteMdFragmentMapping._fragmentMapping(root, mq);
+            FragmentMapping mapping = IgniteMdFragmentMapping._fragmentMapping(root, mq, ctx);
 
             if (rootFragment())
                 mapping = FragmentMapping.create(ctx.localNodeId()).colocate(mapping);
@@ -175,7 +165,7 @@ public class Fragment {
     }
 
     /** */
-    @NotNull private Supplier<List<UUID>> nodesSource(MappingService mappingSrvc, PlanningContext ctx) {
+    @NotNull private Supplier<List<UUID>> nodesSource(MappingService mappingSrvc, MappingQueryContext ctx) {
         return () -> mappingSrvc.executionNodes(ctx.topologyVersion(), single(), null);
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java
index c4485f3..62284d2 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java
@@ -19,6 +19,7 @@ package org.apache.ignite.internal.processors.query.calcite.prepare;
 
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
 
 /** */
 public class FragmentPlan implements QueryPlan {
@@ -27,7 +28,7 @@ public class FragmentPlan implements QueryPlan {
 
     /** */
     public FragmentPlan(IgniteRel root) {
-        RelOptCluster cluster = PlanningContext.empty().cluster();
+        RelOptCluster cluster = Commons.cluster();
 
         this.root = new Cloner(cluster).visit(root);
     }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/IgnitePlanner.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/IgnitePlanner.java
index 1179634..0d444ab 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/IgnitePlanner.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/IgnitePlanner.java
@@ -43,7 +43,6 @@ import org.apache.calcite.rel.RelRoot;
 import org.apache.calcite.rel.metadata.CachingRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexExecutor;
 import org.apache.calcite.sql.SqlDataTypeSpec;
 import org.apache.calcite.sql.SqlKind;
@@ -101,9 +100,6 @@ public class IgnitePlanner implements Planner, RelOptTable.ViewExpander {
     private final SqlRexConvertletTable convertletTbl;
 
     /** */
-    private final RexBuilder rexBuilder;
-
-    /** */
     private final RexExecutor rexExecutor;
 
     /** */
@@ -139,8 +135,6 @@ public class IgnitePlanner implements Planner, RelOptTable.ViewExpander {
         convertletTbl = frameworkCfg.getConvertletTable();
         rexExecutor = frameworkCfg.getExecutor();
         traitDefs = frameworkCfg.getTraitDefs();
-
-        rexBuilder = new RexBuilder(typeFactory);
     }
 
     /** {@inheritDoc} */
@@ -304,7 +298,7 @@ public class IgnitePlanner implements Planner, RelOptTable.ViewExpander {
     /** Creates a cluster. */
     RelOptCluster cluster() {
         if (cluster == null) {
-            cluster = RelOptCluster.create(planner(), rexBuilder);
+            cluster = RelOptCluster.create(planner(), ctx.rexBuilder());
             cluster.setMetadataProvider(new CachingRelMetadataProvider(IgniteMetadata.METADATA_PROVIDER, planner()));
             cluster.setMetadataQuerySupplier(RelMetadataQueryEx::create);
         }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MappingQueryContext.java
similarity index 63%
copy from modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java
copy to modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MappingQueryContext.java
index c4485f3..612f080 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/FragmentPlan.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MappingQueryContext.java
@@ -17,33 +17,33 @@
 
 package org.apache.ignite.internal.processors.query.calcite.prepare;
 
+import java.util.UUID;
 import org.apache.calcite.plan.RelOptCluster;
-import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
+import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 
-/** */
-public class FragmentPlan implements QueryPlan {
+/**
+ * Query mapping context.
+ */
+public class MappingQueryContext {
     /** */
-    private final IgniteRel root;
+    private final UUID locNodeId;
 
     /** */
-    public FragmentPlan(IgniteRel root) {
-        RelOptCluster cluster = PlanningContext.empty().cluster();
-
-        this.root = new Cloner(cluster).visit(root);
-    }
+    private final AffinityTopologyVersion topVer;
 
     /** */
-    public IgniteRel root() {
-        return root;
+    public MappingQueryContext(UUID locNodeId, AffinityTopologyVersion topVer) {
+        this.locNodeId = locNodeId;
+        this.topVer = topVer;
     }
 
-    /** {@inheritDoc} */
-    @Override public Type type() {
-        return Type.FRAGMENT;
+    /** */
+    public UUID localNodeId() {
+        return locNodeId;
     }
 
-    /** {@inheritDoc} */
-    @Override public QueryPlan copy() {
-        return this;
+    /** */
+    public AffinityTopologyVersion topologyVersion() {
+        return topVer;
     }
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MultiStepPlan.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MultiStepPlan.java
index 12c2086..c370afe 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MultiStepPlan.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/MultiStepPlan.java
@@ -54,5 +54,5 @@ public interface MultiStepPlan extends QueryPlan {
      *
      * @param ctx Planner context.
      */
-    void init(PlanningContext ctx);
+    void init(MappingQueryContext ctx);
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlanningContext.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlanningContext.java
index 529080c..cde49b9 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlanningContext.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlanningContext.java
@@ -17,131 +17,51 @@
 
 package org.apache.ignite.internal.processors.query.calcite.prepare;
 
-import java.util.Properties;
-import java.util.UUID;
 import java.util.function.Function;
-import org.apache.calcite.config.CalciteConnectionConfig;
-import org.apache.calcite.config.CalciteConnectionConfigImpl;
-import org.apache.calcite.config.CalciteConnectionProperty;
-import org.apache.calcite.jdbc.CalciteSchema;
 import org.apache.calcite.plan.Context;
 import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.prepare.CalciteCatalogReader;
-import org.apache.calcite.rel.type.RelDataTypeSystem;
+import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.schema.SchemaPlus;
 import org.apache.calcite.sql.SqlOperatorTable;
 import org.apache.calcite.sql.validate.SqlConformance;
 import org.apache.calcite.tools.FrameworkConfig;
-import org.apache.calcite.tools.Frameworks;
 import org.apache.calcite.tools.RuleSet;
-import org.apache.ignite.IgniteLogger;
-import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
-import org.apache.ignite.internal.processors.query.GridQueryCancel;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
-import org.apache.ignite.logger.NullLogger;
 import org.jetbrains.annotations.NotNull;
 
-import static org.apache.calcite.tools.Frameworks.createRootSchema;
-import static org.apache.ignite.internal.processors.query.calcite.CalciteQueryProcessor.FRAMEWORK_CONFIG;
-
 /**
  * Planning context.
  */
 public final class PlanningContext implements Context {
     /** */
-    private static final PlanningContext EMPTY = builder().build();
-
-    /** */
-    private final FrameworkConfig cfg;
-
-    /** */
     private final Context parentCtx;
 
     /** */
-    private final UUID locNodeId;
-
-    /** */
-    private final UUID originatingNodeId;
-
-    /** */
     private final String qry;
 
     /** */
     private final Object[] parameters;
 
     /** */
-    private final AffinityTopologyVersion topVer;
-
-    /** */
-    private final GridQueryCancel qryCancel;
-
-    /** */
-    private final IgniteLogger log;
-
-    /** */
-    private final IgniteTypeFactory typeFactory;
-
-    /** */
     private Function<RuleSet, RuleSet> rulesFilter;
 
     /** */
     private IgnitePlanner planner;
 
-    /** */
-    private CalciteConnectionConfig connCfg;
-
-    /** */
-    private CalciteCatalogReader catalogReader;
-
     /**
      * Private constructor, used by a builder.
      */
     private PlanningContext(
-        FrameworkConfig cfg,
         Context parentCtx,
-        UUID locNodeId,
-        UUID originatingNodeId,
         String qry,
-        Object[] parameters,
-        AffinityTopologyVersion topVer,
-        IgniteLogger log) {
-        this.locNodeId = locNodeId;
-        this.originatingNodeId = originatingNodeId;
+        Object[] parameters
+    ) {
         this.qry = qry;
         this.parameters = parameters;
-        this.topVer = topVer;
-        this.log = log;
-
-        this.parentCtx = Contexts.chain(parentCtx, cfg.getContext());
-        // link frameworkConfig#context() to this.
-        this.cfg = Frameworks.newConfigBuilder(cfg).context(this).build();
 
-        qryCancel = unwrap(GridQueryCancel.class);
-
-        RelDataTypeSystem typeSys = connectionConfig().typeSystem(RelDataTypeSystem.class, cfg.getTypeSystem());
-        typeFactory = new IgniteTypeFactory(typeSys);
-    }
-
-    /**
-     * @return Local node ID.
-     */
-    public UUID localNodeId() {
-        return locNodeId;
-    }
-
-    /**
-     * @return Originating node ID (the node, who started the execution).
-     */
-    public UUID originatingNodeId() {
-        return originatingNodeId == null ? locNodeId : originatingNodeId;
-    }
-
-    /**
-     * @return Framework config.
-     */
-    public FrameworkConfig config() {
-        return cfg;
+        this.parentCtx = parentCtx;
     }
 
     /**
@@ -159,29 +79,7 @@ public final class PlanningContext implements Context {
         return parameters;
     }
 
-    /**
-     * @return Topology version.
-     */
-    public AffinityTopologyVersion topologyVersion() {
-        return topVer;
-    }
-
-    /**
-     * @return Query cancel.
-     */
-    public GridQueryCancel queryCancel() {
-        return qryCancel;
-    }
-
-    /**
-     * @return Logger.
-     */
-    public IgniteLogger logger() {
-        return log;
-    }
-
     // Helper methods
-
     /**
      * @return Sql operators table.
      */
@@ -193,17 +91,7 @@ public final class PlanningContext implements Context {
      * @return Sql conformance.
      */
     public SqlConformance conformance() {
-        return cfg.getParserConfig().conformance();
-    }
-
-    /**
-     * @return Planner.
-     */
-    public IgnitePlanner planner() {
-        if (planner == null)
-            planner = new IgnitePlanner(this);
-
-        return planner;
+        return config().getParserConfig().conformance();
     }
 
     /**
@@ -217,56 +105,31 @@ public final class PlanningContext implements Context {
      * @return Schema.
      */
     public SchemaPlus schema() {
-        return cfg.getDefaultSchema();
+        return config().getDefaultSchema();
     }
 
     /**
-     * @return Type factory.
+     * @return Planner.
      */
-    public IgniteTypeFactory typeFactory() {
-        return typeFactory;
+    public IgnitePlanner planner() {
+        if (planner == null)
+            planner = new IgnitePlanner(this);
+
+        return planner;
     }
 
     /**
-     * @return Connection config. Defines connected user parameters like TimeZone or Locale.
+     * @return Type factory.
      */
-    public CalciteConnectionConfig connectionConfig() {
-        if (connCfg != null)
-            return connCfg;
-
-        CalciteConnectionConfig connCfg = unwrap(CalciteConnectionConfig.class);
-
-        if (connCfg != null)
-            return this.connCfg = connCfg;
-
-        Properties props = new Properties();
-
-        props.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(),
-            String.valueOf(cfg.getParserConfig().caseSensitive()));
-        props.setProperty(CalciteConnectionProperty.CONFORMANCE.camelName(),
-            String.valueOf(cfg.getParserConfig().conformance()));
-        props.setProperty(CalciteConnectionProperty.MATERIALIZATIONS_ENABLED.camelName(),
-            String.valueOf(true));
-
-        return this.connCfg = new CalciteConnectionConfigImpl(props);
+    public IgniteTypeFactory typeFactory() {
+        return unwrap(BaseQueryContext.class).typeFactory();
     }
 
     /**
      * @return New catalog reader.
      */
     public CalciteCatalogReader catalogReader() {
-        if (catalogReader != null)
-            return catalogReader;
-
-        SchemaPlus dfltSchema = schema(), rootSchema = dfltSchema;
-
-        while (rootSchema.getParentSchema() != null)
-            rootSchema = rootSchema.getParentSchema();
-
-        return catalogReader = new CalciteCatalogReader(
-            CalciteSchema.from(rootSchema),
-            CalciteSchema.from(dfltSchema).path(null),
-            typeFactory(), connectionConfig());
+        return unwrap(BaseQueryContext.class).catalogReader();
     }
 
     /**
@@ -281,9 +144,6 @@ public final class PlanningContext implements Context {
         if (aCls == getClass())
             return aCls.cast(this);
 
-        if (aCls.isInstance(connCfg))
-            return aCls.cast(connCfg);
-
         return parentCtx.unwrap(aCls);
     }
 
@@ -294,13 +154,6 @@ public final class PlanningContext implements Context {
         return new Builder();
     }
 
-    /**
-     * @return Empty context.
-     */
-    public static PlanningContext empty() {
-        return EMPTY;
-    }
-
     /** */
     public RuleSet rules(RuleSet set) {
         return rulesFilter != null ? rulesFilter.apply(set) : set;
@@ -314,68 +167,31 @@ public final class PlanningContext implements Context {
     }
 
     /**
+     * @return Framework config.
+     */
+    public FrameworkConfig config() {
+        return unwrap(BaseQueryContext.class).config();
+    }
+
+    /** */
+    public RexBuilder rexBuilder() {
+        return unwrap(BaseQueryContext.class).rexBuilder();
+    }
+
+    /**
      * Planner context builder.
      */
     @SuppressWarnings("PublicInnerClass") 
     public static class Builder {
         /** */
-        private static final FrameworkConfig EMPTY_CONFIG =
-            Frameworks.newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(createRootSchema(false))
-                .traitDefs()
-                .build();
-
-        /** */
-        private FrameworkConfig frameworkCfg = EMPTY_CONFIG;
-
-        /** */
         private Context parentCtx = Contexts.empty();
 
         /** */
-        private UUID locNodeId;
-
-        /** */
-        private UUID originatingNodeId;
-
-        /** */
         private String qry;
 
         /** */
         private Object[] parameters;
 
-        /** */
-        private AffinityTopologyVersion topVer;
-
-        /** */
-        private IgniteLogger log = new NullLogger();
-
-        /**
-         * @param locNodeId Local node ID.
-         * @return Builder for chaining.
-         */
-        public Builder localNodeId(@NotNull UUID locNodeId) {
-            this.locNodeId = locNodeId;
-            return this;
-        }
-
-        /**
-         * @param originatingNodeId Originating node ID (the node, who started the execution).
-         * @return Builder for chaining.
-         */
-        public Builder originatingNodeId(@NotNull UUID originatingNodeId) {
-            this.originatingNodeId = originatingNodeId;
-            return this;
-        }
-
-        /**
-         * @param frameworkCfg Framework config.
-         * @return Builder for chaining.
-         */
-        public Builder frameworkConfig(@NotNull FrameworkConfig frameworkCfg) {
-            this.frameworkCfg = frameworkCfg;
-            return this;
-        }
-
         /**
          * @param parentCtx Parent context.
          * @return Builder for chaining.
@@ -405,31 +221,12 @@ public final class PlanningContext implements Context {
         }
 
         /**
-         * @param topVer Topology version.
-         * @return Builder for chaining.
-         */
-        public Builder topologyVersion(@NotNull AffinityTopologyVersion topVer) {
-            this.topVer = topVer;
-            return this;
-        }
-
-        /**
-         * @param log Logger.
-         * @return Builder for chaining.
-         */
-        public Builder logger(@NotNull IgniteLogger log) {
-            this.log = log;
-            return this;
-        }
-
-        /**
          * Builds planner context.
          *
          * @return Planner context.
          */
         public PlanningContext build() {
-            return new PlanningContext(frameworkCfg, parentCtx, locNodeId, originatingNodeId, qry,
-                parameters, topVer, log);
+            return new PlanningContext(parentCtx, qry, parameters);
         }
     }
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCache.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCache.java
index e249c3b..043f215 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCache.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCache.java
@@ -17,6 +17,7 @@
 
 package org.apache.ignite.internal.processors.query.calcite.prepare;
 
+import java.util.function.Supplier;
 import org.apache.ignite.internal.processors.query.calcite.util.Service;
 
 /**
@@ -24,12 +25,11 @@ import org.apache.ignite.internal.processors.query.calcite.util.Service;
  */
 public interface QueryPlanCache extends Service {
     /**
-     * @param ctx Context.
      * @param key Cache key.
-     * @param factory Factory method to generate a plan on cache miss.
+     * @param planSupplier Factory method to generate a plan on cache miss.
      * @return Query plan.
      */
-    QueryPlan queryPlan(PlanningContext ctx, CacheKey key, QueryPlanFactory factory);
+    QueryPlan queryPlan(CacheKey key, Supplier<QueryPlan> planSupplier);
 
     /**
      * @param key Cache key.
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCacheImpl.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCacheImpl.java
index 3d9a90e..2552898 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCacheImpl.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryPlanCacheImpl.java
@@ -18,6 +18,7 @@
 package org.apache.ignite.internal.processors.query.calcite.prepare;
 
 import java.util.Map;
+import java.util.function.Supplier;
 import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.cache.query.index.Index;
 import org.apache.ignite.internal.processors.cache.GridCacheContextInfo;
@@ -71,9 +72,11 @@ public class QueryPlanCacheImpl extends AbstractService implements QueryPlanCach
     }
 
     /** {@inheritDoc} */
-    @Override public QueryPlan queryPlan(PlanningContext ctx, CacheKey key, QueryPlanFactory factory) {
+    @Override public QueryPlan queryPlan(CacheKey key, Supplier<QueryPlan> planSupplier) {
         Map<CacheKey, QueryPlan> cache = this.cache;
-        QueryPlan plan = cache.computeIfAbsent(key, k -> factory.create(ctx));
+
+        QueryPlan plan = cache.computeIfAbsent(key, k -> planSupplier.get());
+
         return plan.copy();
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryTemplate.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryTemplate.java
index 5689994..12c00f8 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryTemplate.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/QueryTemplate.java
@@ -51,21 +51,23 @@ public class QueryTemplate {
 
         ImmutableList.Builder<Fragment> b = ImmutableList.builder();
         for (Fragment fragment : fragments)
-            b.add(fragment.detach());
+            b.add(fragment.copy());
 
         this.fragments = b.build();
     }
 
     /** */
-    public ExecutionPlan map(PlanningContext ctx) {
+    public ExecutionPlan map(MappingQueryContext ctx) {
         ExecutionPlan executionPlan = this.executionPlan.get();
+
         if (executionPlan != null && Objects.equals(executionPlan.topologyVersion(), ctx.topologyVersion()))
             return executionPlan;
 
-        List<Fragment> fragments = Commons.transform(this.fragments, f -> f.attach(ctx));
+        List<Fragment> fragments = Commons.transform(this.fragments, Fragment::copy);
 
         Exception ex = null;
         RelMetadataQuery mq = F.first(fragments).root().getCluster().getMetadataQuery();
+
         for (int i = 0; i < 3; i++) {
             try {
                 ExecutionPlan executionPlan0 = new ExecutionPlan(ctx.topologyVersion(), map(fragments, ctx, mq));
@@ -89,10 +91,11 @@ public class QueryTemplate {
     }
 
     /** */
-    @NotNull private List<Fragment> map(List<Fragment> fragments, PlanningContext ctx, RelMetadataQuery mq) {
+    @NotNull private List<Fragment> map(List<Fragment> fragments, MappingQueryContext ctx, RelMetadataQuery mq) {
         ImmutableList.Builder<Fragment> b = ImmutableList.builder();
+
         for (Fragment fragment : fragments)
-            b.add(fragment.map(mappingService, ctx, mq).detach());
+            b.add(fragment.map(mappingService, ctx, mq));
 
         return b.build();
     }
@@ -102,12 +105,14 @@ public class QueryTemplate {
         assert !F.isEmpty(replacement);
 
         Map<Long, Long> newTargets = new HashMap<>();
+
         for (Fragment fragment0 : replacement) {
             for (IgniteReceiver remote : fragment0.remotes())
                 newTargets.put(remote.exchangeId(), fragment0.fragmentId());
         }
 
         List<Fragment> fragments0 = new ArrayList<>(fragments.size() + replacement.size() - 1);
+
         for (Fragment fragment0 : fragments) {
             if (fragment0 == fragment)
                 fragment0 = F.first(replacement);
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableModify.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableModify.java
index 166c432..713ef0a 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableModify.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableModify.java
@@ -56,7 +56,8 @@ public class IgniteTableModify extends TableModify implements IgniteRel {
         List<RexNode> sourceExpressionList,
         boolean flattened
     ) {
-        super(cluster, traitSet, table, Commons.context(cluster).catalogReader(), input, operation, updateColumnList,
+        super(cluster, traitSet, table, Commons.context(cluster).catalogReader(),
+            input, operation, updateColumnList,
             sourceExpressionList, flattened);
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteIndex.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteIndex.java
index c5afdbb..24ffaa8 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteIndex.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteIndex.java
@@ -78,7 +78,7 @@ public class IgniteIndex {
         Supplier<Row> upperIdxConditions,
         Function<Row, Row> rowTransformer,
         @Nullable ImmutableBitSet requiredColumns) {
-        UUID localNodeId = execCtx.planningContext().localNodeId();
+        UUID localNodeId = execCtx.localNodeId();
         if (group.nodeIds().contains(localNodeId) && idx != null) {
             return new IndexScan<>(execCtx, table().descriptor(), idx.unwrap(InlineIndex.class), collation.getKeys(),
                 group.partitions(localNodeId), filters, lowerIdxConditions, upperIdxConditions, rowTransformer,
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTable.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTable.java
index 41452b1..69dce5c 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTable.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTable.java
@@ -31,7 +31,7 @@ import org.apache.calcite.schema.TranslatableTable;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalIndexScan;
 import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalTableScan;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
@@ -125,7 +125,7 @@ public interface IgniteTable extends TranslatableTable {
      * @param ctx Planning context.
      * @return Nodes mapping.
      */
-    ColocationGroup colocationGroup(PlanningContext ctx);
+    ColocationGroup colocationGroup(MappingQueryContext ctx);
 
     /**
      * @return Table distribution.
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTableImpl.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTableImpl.java
index 4343553..f41878a 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTableImpl.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/IgniteTableImpl.java
@@ -37,7 +37,7 @@ import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
 import org.apache.ignite.internal.processors.query.calcite.exec.TableScan;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalIndexScan;
 import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalTableScan;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
@@ -133,7 +133,8 @@ public class IgniteTableImpl extends AbstractTable implements IgniteTable {
         Predicate<Row> filter,
         Function<Row, Row> rowTransformer,
         @Nullable ImmutableBitSet usedColumns) {
-        UUID localNodeId = execCtx.planningContext().localNodeId();
+        UUID localNodeId = execCtx.localNodeId();
+
         if (group.nodeIds().contains(localNodeId))
             return new TableScan<>(execCtx, desc, group.partitions(localNodeId), filter, rowTransformer, usedColumns);
 
@@ -146,7 +147,7 @@ public class IgniteTableImpl extends AbstractTable implements IgniteTable {
     }
 
     /** {@inheritDoc} */
-    @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+    @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
         return desc.colocationGroup(ctx);
     }
 
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptor.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptor.java
index 74c9e51..a61c13d 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptor.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptor.java
@@ -32,7 +32,7 @@ import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
 import org.apache.ignite.internal.processors.query.calcite.exec.RowHandler;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
 import org.apache.ignite.lang.IgniteBiTuple;
@@ -65,7 +65,7 @@ public interface TableDescriptor extends RelProtoDataType, InitializerExpression
      * @param ctx Planning context.
      * @return Nodes mapping.
      */
-    ColocationGroup colocationGroup(PlanningContext ctx);
+    ColocationGroup colocationGroup(MappingQueryContext ctx);
 
     /** {@inheritDoc} */
     @Override default RelDataType apply(RelDataTypeFactory factory) {
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptorImpl.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptorImpl.java
index 01af95e..c9c36b2 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptorImpl.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/schema/TableDescriptorImpl.java
@@ -57,7 +57,7 @@ import org.apache.ignite.internal.processors.query.QueryUtils;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
 import org.apache.ignite.internal.processors.query.calcite.exec.RowHandler;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
@@ -517,7 +517,7 @@ public class TableDescriptorImpl extends NullInitializerExpressionFactory
     }
 
     /** {@inheritDoc} */
-    @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+    @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
         GridCacheContext<?, ?> cctx = cacheContext();
 
         if (!cctx.gate().enterIfNotStopped())
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/Commons.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/Commons.java
index 0b90f2d..2f0b3e1 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/Commons.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/Commons.java
@@ -29,6 +29,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.UUID;
 import java.util.function.Function;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
@@ -53,12 +54,14 @@ import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridComponent;
 import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode;
 import org.apache.ignite.internal.processors.query.IgniteSQLException;
 import org.apache.ignite.internal.processors.query.QueryContext;
 import org.apache.ignite.internal.processors.query.calcite.exec.RowHandler;
 import org.apache.ignite.internal.processors.query.calcite.exec.exp.ExpressionFactoryImpl;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.A;
@@ -174,24 +177,17 @@ public final class Commons {
     }
 
     /**
-     * Extracts planner context.
+     * Extracts query context.
      */
-    public static PlanningContext context(RelNode rel) {
+    public static BaseQueryContext context(RelNode rel) {
         return context(rel.getCluster());
     }
 
     /**
-     * Extracts planner context.
+     * Extracts query context.
      */
-    public static PlanningContext context(RelOptCluster cluster) {
-        return context(cluster.getPlanner().getContext());
-    }
-
-    /**
-     * Extracts planner context.
-     */
-    public static PlanningContext context(Context ctx) {
-        return Objects.requireNonNull(ctx.unwrap(PlanningContext.class));
+    public static BaseQueryContext context(RelOptCluster cluster) {
+        return Objects.requireNonNull(cluster.getPlanner().getContext().unwrap(BaseQueryContext.class));
     }
 
     /**
@@ -431,4 +427,19 @@ public final class Commons {
 
         return res;
     }
+
+    /** */
+    public static RelOptCluster cluster() {
+        return BaseQueryContext.CLUSTER;
+    }
+
+    /** */
+    public static IgniteTypeFactory typeFactory() {
+        return BaseQueryContext.TYPE_FACTORY;
+    }
+
+    /** */
+    public static MappingQueryContext mapContext(UUID locNodeId, AffinityTopologyVersion topVer) {
+        return new MappingQueryContext(locNodeId, topVer);
+    }
 }
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/IgniteMethod.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/IgniteMethod.java
index c14ba3d5..94a3592 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/IgniteMethod.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/IgniteMethod.java
@@ -24,6 +24,7 @@ import org.apache.ignite.internal.processors.query.calcite.exec.RowHandler;
 import org.apache.ignite.internal.processors.query.calcite.exec.exp.BiScalar;
 import org.apache.ignite.internal.processors.query.calcite.exec.exp.SingleScalar;
 import org.apache.ignite.internal.processors.query.calcite.metadata.IgniteMetadata.FragmentMappingMetadata;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 
 /**
  * Contains methods used in metadata definitions.
@@ -44,8 +45,8 @@ public enum IgniteMethod {
     SCALAR_EXECUTE(SingleScalar.class, "execute", ExecutionContext.class, Object.class, Object.class),
     /** See {@link BiScalar#execute(ExecutionContext, Object, Object, Object)} */
     BI_SCALAR_EXECUTE(BiScalar.class, "execute", ExecutionContext.class, Object.class, Object.class, Object.class),
-    /** See {@link FragmentMappingMetadata#fragmentMapping()} */
-    FRAGMENT_MAPPING(FragmentMappingMetadata.class, "fragmentMapping");
+    /** See {@link FragmentMappingMetadata#fragmentMapping(MappingQueryContext)} */
+    FRAGMENT_MAPPING(FragmentMappingMetadata.class, "fragmentMapping", MappingQueryContext.class);
 
     /** */
     private final Method method;
diff --git a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/PlanUtils.java b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/PlanUtils.java
index d444c9e..ab2eb74 100644
--- a/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/PlanUtils.java
+++ b/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/PlanUtils.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.processors.query.calcite.util;
 import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode;
 import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
 
 /** */
@@ -41,7 +42,7 @@ public class PlanUtils {
             schemaName = schemaId.getSimple();
         }
 
-        ensureSchemaExists(ctx, schemaName);
+        ensureSchemaExists(ctx.unwrap(BaseQueryContext.class), schemaName);
 
         return schemaName;
     }
@@ -63,7 +64,7 @@ public class PlanUtils {
     }
 
     /** */
-    private static void ensureSchemaExists(PlanningContext ctx, String schemaName) {
+    private static void ensureSchemaExists(BaseQueryContext ctx, String schemaName) {
         if (ctx.catalogReader().getRootSchema().getSubSchema(schemaName, true) == null)
             throw new IgniteSQLException("Schema with name " + schemaName + " not found",
                 IgniteQueryErrorCode.SCHEMA_NOT_FOUND);
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/RuntimeSortedIndexTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/RuntimeSortedIndexTest.java
index 62b62f1..0ffaae6 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/RuntimeSortedIndexTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/RuntimeSortedIndexTest.java
@@ -30,7 +30,7 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Pair;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
 import org.apache.ignite.internal.processors.query.calcite.util.TypeUtils;
 import org.apache.ignite.internal.util.lang.GridCursor;
@@ -104,12 +104,15 @@ public class RuntimeSortedIndexTest extends GridCommonAbstractTest {
     private RuntimeSortedIndex<Object[]> generate(RelDataType rowType, final List<Integer> idxCols, int notUnique) {
         RuntimeSortedIndex<Object[]> idx = new RuntimeSortedIndex<>(
             new ExecutionContext<>(
-                null,
-                PlanningContext.builder()
+                BaseQueryContext.builder()
                     .logger(log())
                     .build(),
                 null,
                 null,
+                null,
+                null,
+                null,
+                null,
                 ArrayRowHandler.INSTANCE,
                 null),
             RelCollations.of(ImmutableIntList.copyOf(idxCols)),
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractExecutionTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractExecutionTest.java
index d5d1b80..40a6a5f 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractExecutionTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/AbstractExecutionTest.java
@@ -38,6 +38,7 @@ import com.google.common.collect.ImmutableMap;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.query.calcite.exec.ArrayRowHandler;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExchangeService;
 import org.apache.ignite.internal.processors.query.calcite.exec.ExchangeServiceImpl;
@@ -50,7 +51,7 @@ import org.apache.ignite.internal.processors.query.calcite.message.CalciteMessag
 import org.apache.ignite.internal.processors.query.calcite.message.MessageServiceImpl;
 import org.apache.ignite.internal.processors.query.calcite.message.TestIoManager;
 import org.apache.ignite.internal.processors.query.calcite.metadata.FragmentDescription;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.util.typedef.T2;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.testframework.GridTestUtils;
@@ -277,12 +278,18 @@ public class AbstractExecutionTest extends GridCommonAbstractTest {
     protected ExecutionContext<Object[]> executionContext(UUID nodeId, UUID qryId, long fragmentId) {
         FragmentDescription fragmentDesc = new FragmentDescription(fragmentId, null, null, null);
         return new ExecutionContext<>(
-            taskExecutor(nodeId),
-            PlanningContext.builder()
-                .localNodeId(nodeId)
-                .logger(log())
+            BaseQueryContext.builder()
+                .logger(log)
                 .build(),
-            qryId, fragmentDesc, ArrayRowHandler.INSTANCE, ImmutableMap.of());
+            taskExecutor(nodeId),
+            qryId,
+            nodeId,
+            nodeId,
+            AffinityTopologyVersion.NONE,
+            fragmentDesc,
+            ArrayRowHandler.INSTANCE,
+            ImmutableMap.of()
+        );
     }
 
     /** */
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AbstractBasicIntegrationTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AbstractBasicIntegrationTest.java
index 950b74f..03394e6 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AbstractBasicIntegrationTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AbstractBasicIntegrationTest.java
@@ -48,12 +48,14 @@ public class AbstractBasicIntegrationTest extends GridCommonAbstractTest {
     }
 
     /** {@inheritDoc} */
-    @Override protected void afterTest() {
+    @Override protected void afterTest() throws Exception {
         for (Ignite ign : G.allGrids()) {
             for (String cacheName : ign.cacheNames())
                 ign.destroyCache(cacheName);
         }
 
+        awaitPartitionMapExchange();
+
         cleanQueryPlanCache();
     }
 
@@ -91,6 +93,7 @@ public class AbstractBasicIntegrationTest extends GridCommonAbstractTest {
         );
 
         int idx = 0;
+
         person.put(idx++, new Employer("Igor", 10d));
         person.put(idx++, new Employer(null, 15d));
         person.put(idx++, new Employer("Ilya", 15d));
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AggregatesIntegrationTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AggregatesIntegrationTest.java
index f4bd515..49fc2ee 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AggregatesIntegrationTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/AggregatesIntegrationTest.java
@@ -19,6 +19,7 @@ package org.apache.ignite.internal.processors.query.calcite.integration;
 
 import java.util.List;
 import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.internal.processors.query.QueryEngine;
 import org.apache.ignite.internal.processors.query.calcite.util.Commons;
@@ -107,7 +108,7 @@ public class AggregatesIntegrationTest extends AbstractBasicIntegrationTest {
     /** */
     @SuppressWarnings("ThrowableNotThrown")
     @Test
-    public void testMultipleRowsFromSingleAggr() throws Exception {
+    public void testMultipleRowsFromSingleAggr() throws IgniteCheckedException {
         createAndPopulateTable();
 
         GridTestUtils.assertThrowsWithCause(() -> assertQuery("SELECT (SELECT name FROM person)").check(),
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/ServerStatisticsIntegrationTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/ServerStatisticsIntegrationTest.java
index a7d2db4..e56e380 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/ServerStatisticsIntegrationTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/ServerStatisticsIntegrationTest.java
@@ -115,7 +115,9 @@ public class ServerStatisticsIntegrationTest extends AbstractBasicIntegrationTes
     @Test
     public void testQueryCostWithStatistics() throws IgniteCheckedException {
         String sql = "select name from person where salary is not null";
+
         createAndPopulateTable();
+
         StatisticsKey key = new StatisticsKey("PUBLIC", "PERSON");
         srv = ignite(0);
 
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractAggregatePlannerTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractAggregatePlannerTest.java
index ad98770..421b948 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractAggregatePlannerTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractAggregatePlannerTest.java
@@ -18,10 +18,9 @@
 package org.apache.ignite.internal.processors.query.calcite.planner;
 
 import java.util.Arrays;
-
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
 import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions;
 import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
@@ -70,7 +69,7 @@ public class AbstractAggregatePlannerTest extends AbstractPlannerTest {
                 .add("GRP1", f.createJavaType(Integer.class))
                 .build()) {
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractPlannerTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractPlannerTest.java
index a584d3a..f2a168d 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractPlannerTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/AbstractPlannerTest.java
@@ -31,7 +31,6 @@ import java.util.function.Supplier;
 import java.util.stream.Collectors;
 import com.google.common.collect.ImmutableSet;
 import org.apache.calcite.config.CalciteConnectionConfig;
-import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.plan.RelOptUtil;
@@ -77,9 +76,11 @@ import org.apache.ignite.internal.processors.query.calcite.message.CalciteMessag
 import org.apache.ignite.internal.processors.query.calcite.message.MessageServiceImpl;
 import org.apache.ignite.internal.processors.query.calcite.message.TestIoManager;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.Cloner;
 import org.apache.ignite.internal.processors.query.calcite.prepare.Fragment;
 import org.apache.ignite.internal.processors.query.calcite.prepare.IgnitePlanner;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.Splitter;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
@@ -228,15 +229,16 @@ public abstract class AbstractPlannerTest extends GridCommonAbstractTest {
             .add("PUBLIC", publicSchema);
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
-                .build())
-            .logger(log)
+            .parentContext(BaseQueryContext.builder()
+                .frameworkConfig(
+                    newConfigBuilder(FRAMEWORK_CONFIG)
+                        .defaultSchema(schema)
+                        .build()
+                )
+                .logger(log)
+                .build()
+            )
             .query(sql)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgnitePlanner planner = ctx.planner();
@@ -284,20 +286,7 @@ public abstract class AbstractPlannerTest extends GridCommonAbstractTest {
 
     /** */
     protected RelNode originalLogicalTree(String sql, IgniteSchema publicSchema, String... disabledRules) throws Exception {
-        SchemaPlus schema = createRootSchema(false)
-            .add("PUBLIC", publicSchema);
-
-        PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
-                .build())
-            .logger(log)
-            .query(sql)
-            .topologyVersion(AffinityTopologyVersion.NONE)
-            .build();
+        PlanningContext ctx = plannerCtx(sql, publicSchema);
 
         RelRoot relRoot;
 
@@ -342,24 +331,21 @@ public abstract class AbstractPlannerTest extends GridCommonAbstractTest {
 
         assertNotNull(serialized);
 
-        PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
-                .build())
+        BaseQueryContext ctx = BaseQueryContext.builder()
+            .frameworkConfig(
+                newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build()
+            )
             .logger(log)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         List<RelNode> deserializedNodes = new ArrayList<>();
 
-        try (IgnitePlanner ignored = ctx.planner()) {
-            for (String s : serialized) {
-                RelJsonReader reader = new RelJsonReader(ctx.cluster(), ctx.catalogReader());
-                deserializedNodes.add(reader.read(s));
-            }
+        for (String s : serialized) {
+            RelJsonReader reader = new RelJsonReader(ctx.catalogReader());
+
+            deserializedNodes.add(reader.read(s));
         }
 
         List<RelNode> expectedRels = fragments.stream()
@@ -429,7 +415,7 @@ public abstract class AbstractPlannerTest extends GridCommonAbstractTest {
     protected static void createTable(IgniteSchema schema, String name, RelDataType type, IgniteDistribution distr,
         List<List<UUID>> assignment) {
         TestTable table = new TestTable(type) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 if (F.isEmpty(assignment))
                     return super.colocationGroup(ctx);
                 else
@@ -745,7 +731,7 @@ public abstract class AbstractPlannerTest extends GridCommonAbstractTest {
         }
 
         /** {@inheritDoc} */
-        @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+        @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
             throw new AssertionError();
         }
 
@@ -825,7 +811,7 @@ public abstract class AbstractPlannerTest extends GridCommonAbstractTest {
         }
 
         /** {@inheritDoc} */
-        @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+        @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
             throw new AssertionError();
         }
 
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/HashAggregatePlannerTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/HashAggregatePlannerTest.java
index 6cdbe2f..716506f 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/HashAggregatePlannerTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/HashAggregatePlannerTest.java
@@ -26,7 +26,7 @@ import org.apache.calcite.sql.fun.SqlAvgAggFunction;
 import org.apache.calcite.sql.fun.SqlCountAggFunction;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
 import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteMapHashAggregate;
 import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteReduceHashAggregate;
@@ -59,7 +59,7 @@ public class HashAggregatePlannerTest extends AbstractAggregatePlannerTest {
                 .add("SALARY", f.createJavaType(Double.class))
                 .build()) {
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/PlannerTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/PlannerTest.java
index d1e40db..d01cf67 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/PlannerTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/PlannerTest.java
@@ -25,7 +25,6 @@ import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Function;
 import java.util.function.Predicate;
-import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.plan.RelTraitSet;
 import org.apache.calcite.rel.RelCollations;
@@ -52,8 +51,10 @@ import org.apache.ignite.internal.processors.query.calcite.message.TestIoManager
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
 import org.apache.ignite.internal.processors.query.calcite.metadata.FragmentDescription;
 import org.apache.ignite.internal.processors.query.calcite.metadata.cost.IgniteCostFactory;
+import org.apache.ignite.internal.processors.query.calcite.prepare.BaseQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.Fragment;
 import org.apache.ignite.internal.processors.query.calcite.prepare.IgnitePlanner;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.prepare.MultiStepPlan;
 import org.apache.ignite.internal.processors.query.calcite.prepare.MultiStepQueryPlan;
 import org.apache.ignite.internal.processors.query.calcite.prepare.PlannerPhase;
@@ -101,7 +102,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("PROJECTID", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
@@ -122,7 +123,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("VER", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
@@ -151,16 +152,14 @@ public class PlannerTest extends AbstractPlannerTest {
             "ON d.id = p.id0";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
+            .parentContext(BaseQueryContext.builder()
+                .logger(log)
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build())
                 .build())
-            .logger(log)
             .query(sql)
             .parameters(2)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         assertNotNull(ctx);
@@ -174,7 +173,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         assertNotNull(plan);
 
@@ -209,7 +208,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 );
             }
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 1));
             }
 
@@ -237,7 +236,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 );
             }
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 1));
             }
 
@@ -261,17 +260,17 @@ public class PlannerTest extends AbstractPlannerTest {
             "ON d.projectId = p.id0 " +
             "WHERE (d.projectId + 1) > ?";
 
-        PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
+        BaseQueryContext qctx = BaseQueryContext.builder()
+            .logger(log)
             .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
                 .defaultSchema(schema)
                 .build())
-            .logger(log)
+            .build();
+
+        PlanningContext ctx = PlanningContext.builder()
+            .parentContext(qctx)
             .query(sql)
             .parameters(-10)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -283,7 +282,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         List<Fragment> fragments = plan.fragments();
         assertEquals(2, fragments.size());
@@ -334,16 +333,21 @@ public class PlannerTest extends AbstractPlannerTest {
         exchangeSvc.mailboxRegistry(mailboxRegistry);
         exchangeSvc.init();
 
-        ectx = new ExecutionContext<>(taskExecutor,
-            ctx,
+        ectx = new ExecutionContext<>(
+            qctx,
+            taskExecutor,
             qryId,
+            F.first(nodes),
+            F.first(nodes),
+            AffinityTopologyVersion.NONE,
             new FragmentDescription(
                 fragment.fragmentId(),
                 fragment.mapping(),
                 plan.target(fragment),
                 plan.remotes(fragment)),
             ArrayRowHandler.INSTANCE,
-            Commons.parametersMap(ctx.parameters()));
+            Commons.parametersMap(ctx.parameters())
+        );
 
         exec = new LogicalRelImplementor<>(ectx, c1 -> r1 -> 0, mailboxRegistry, exchangeSvc,
             new TestFailureProcessor(kernal)).go(fragment.root());
@@ -387,17 +391,12 @@ public class PlannerTest extends AbstractPlannerTest {
         exchangeSvc.init();
 
         ectx = new ExecutionContext<>(
+            qctx,
             taskExecutor,
-            PlanningContext.builder()
-                .localNodeId(nodes.get(1))
-                .originatingNodeId(nodes.get(0))
-                .parentContext(Contexts.empty())
-                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                    .defaultSchema(schema)
-                    .build())
-                .logger(log)
-                .build(),
             qryId,
+            nodes.get(1),
+            F.first(nodes),
+            AffinityTopologyVersion.NONE,
             new FragmentDescription(
                 fragment.fragmentId(),
                 fragment.mapping(),
@@ -469,7 +468,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 return checkRes0;
             }
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 1));
             }
 
@@ -487,17 +486,17 @@ public class PlannerTest extends AbstractPlannerTest {
 
         String sql = "SELECT (ID0 + ID1) AS RES FROM PUBLIC.TEST_TABLE";
 
-        PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
+        BaseQueryContext qctx = BaseQueryContext.builder()
+            .logger(log)
             .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
                 .defaultSchema(schema)
                 .build())
-            .logger(log)
+            .build();
+
+        PlanningContext ctx = PlanningContext.builder()
+            .parentContext(qctx)
             .query(sql)
             .parameters(-10)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -509,7 +508,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         List<Fragment> fragments = plan.fragments();
         assertEquals(2, fragments.size());
@@ -560,9 +559,13 @@ public class PlannerTest extends AbstractPlannerTest {
         exchangeSvc.mailboxRegistry(mailboxRegistry);
         exchangeSvc.init();
 
-        ectx = new ExecutionContext<>(taskExecutor,
-            ctx,
+        ectx = new ExecutionContext<>(
+            qctx,
+            taskExecutor,
             qryId,
+            F.first(nodes),
+            F.first(nodes),
+            AffinityTopologyVersion.NONE,
             new FragmentDescription(
                 fragment.fragmentId(),
                 fragment.mapping(),
@@ -613,17 +616,12 @@ public class PlannerTest extends AbstractPlannerTest {
         exchangeSvc.init();
 
         ectx = new ExecutionContext<>(
+            qctx,
             taskExecutor,
-            PlanningContext.builder()
-                .localNodeId(nodes.get(1))
-                .originatingNodeId(nodes.get(0))
-                .parentContext(Contexts.empty())
-                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                    .defaultSchema(schema)
-                    .build())
-                .logger(log)
-                .build(),
             qryId,
+            nodes.get(1),
+            F.first(nodes),
+            AffinityTopologyVersion.NONE,
             new FragmentDescription(
                 fragment.fragmentId(),
                 fragment.mapping(),
@@ -669,7 +667,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("PROJECTID", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 0, 1, 2, 3));
             }
 
@@ -684,7 +682,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("VER", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 0, 1, 2, 3));
             }
 
@@ -709,16 +707,14 @@ public class PlannerTest extends AbstractPlannerTest {
             "WHERE (d.projectId + 1) > ?";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
+            .parentContext(BaseQueryContext.builder()
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build())
+                .logger(log)
                 .build())
-            .logger(log)
             .query(sql)
             .parameters(2)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -730,7 +726,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         assertNotNull(plan);
 
@@ -750,7 +746,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("PROJECTID", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 0));
             }
 
@@ -765,7 +761,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("VER", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 1, 2),
                     select(nodes, 2, 3),
@@ -795,16 +791,14 @@ public class PlannerTest extends AbstractPlannerTest {
             "WHERE (d.projectId + 1) > ?";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
+            .parentContext(BaseQueryContext.builder()
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build())
+                .logger(log)
                 .build())
-            .logger(log)
             .query(sql)
             .parameters(2)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -816,7 +810,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         assertEquals(3, plan.fragments().size());
     }
@@ -834,7 +828,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("PROJECTID", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 1, 2, 3));
             }
 
@@ -849,7 +843,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("VER", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0),
                     select(nodes, 1),
@@ -878,16 +872,14 @@ public class PlannerTest extends AbstractPlannerTest {
             "WHERE (d.projectId + 1) > ?";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
+            .parentContext(BaseQueryContext.builder()
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build())
+                .logger(log)
                 .build())
-            .logger(log)
             .query(sql)
             .parameters(2)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -899,7 +891,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         assertNotNull(plan);
 
@@ -919,7 +911,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("PROJECTID", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 0));
             }
 
@@ -934,7 +926,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("VER", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 1),
                     select(nodes, 2),
@@ -963,16 +955,14 @@ public class PlannerTest extends AbstractPlannerTest {
             "WHERE (d.projectId + 1) > ?";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
+            .parentContext(BaseQueryContext.builder()
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build())
+                .logger(log)
                 .build())
-            .logger(log)
             .query(sql)
             .parameters(2)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -984,7 +974,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         assertEquals(3, plan.fragments().size());
     }
@@ -1002,7 +992,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("PROJECTID", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 2));
             }
 
@@ -1017,7 +1007,7 @@ public class PlannerTest extends AbstractPlannerTest {
                 .add("NAME", f.createJavaType(String.class))
                 .add("VER", f.createJavaType(Integer.class))
                 .build()) {
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forNodes(select(nodes, 0, 1));
             }
 
@@ -1042,16 +1032,14 @@ public class PlannerTest extends AbstractPlannerTest {
             "WHERE (d.projectId + 1) > ?";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
+            .parentContext(BaseQueryContext.builder()
+                .logger(log)
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .build())
                 .build())
-            .logger(log)
             .query(sql)
             .parameters(2)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         IgniteRel phys = physicalPlan(sql, ctx);
@@ -1063,7 +1051,7 @@ public class PlannerTest extends AbstractPlannerTest {
 
         assertNotNull(plan);
 
-        plan.init(ctx);
+        plan.init(Commons.mapContext(F.first(nodes), AffinityTopologyVersion.NONE));
 
         assertNotNull(plan);
 
@@ -1168,16 +1156,15 @@ public class PlannerTest extends AbstractPlannerTest {
             "where d.deptno + e.deptno = 2";
 
         PlanningContext ctx = PlanningContext.builder()
-            .localNodeId(F.first(nodes))
-            .originatingNodeId(F.first(nodes))
-            .parentContext(Contexts.empty())
-            .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
-                .defaultSchema(schema)
-                .costFactory(new IgniteCostFactory(1, 100, 1, 1))
-                .build())
-            .logger(log)
+            .parentContext(BaseQueryContext.builder()
+                .frameworkConfig(newConfigBuilder(FRAMEWORK_CONFIG)
+                    .defaultSchema(schema)
+                    .costFactory(new IgniteCostFactory(1, 100, 1, 1))
+                    .build())
+                .logger(log)
+                .build()
+            )
             .query(sql)
-            .topologyVersion(AffinityTopologyVersion.NONE)
             .build();
 
         RelRoot relRoot;
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/SortAggregatePlannerTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/SortAggregatePlannerTest.java
index 88f9cdb..3a56796 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/SortAggregatePlannerTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/SortAggregatePlannerTest.java
@@ -18,14 +18,13 @@
 package org.apache.ignite.internal.processors.query.calcite.planner;
 
 import java.util.Arrays;
-
 import org.apache.calcite.plan.RelOptPlanner;
 import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.RelCollations;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteSort;
 import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteReduceSortAggregate;
@@ -127,7 +126,7 @@ public class SortAggregatePlannerTest extends AbstractAggregatePlannerTest {
                 .add("GRP1", f.createJavaType(Integer.class))
                 .build()) {
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/UnionPlannerTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/UnionPlannerTest.java
index 202a952..19eddfe 100644
--- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/UnionPlannerTest.java
+++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/planner/UnionPlannerTest.java
@@ -22,7 +22,7 @@ import java.util.Arrays;
 import org.apache.calcite.rel.core.Union;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
-import org.apache.ignite.internal.processors.query.calcite.prepare.PlanningContext;
+import org.apache.ignite.internal.processors.query.calcite.prepare.MappingQueryContext;
 import org.apache.ignite.internal.processors.query.calcite.rel.IgniteUnionAll;
 import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteReduceAggregateBase;
 import org.apache.ignite.internal.processors.query.calcite.schema.IgniteSchema;
@@ -93,7 +93,7 @@ public class UnionPlannerTest extends AbstractPlannerTest {
                 .add("SALARY", f.createJavaType(Double.class))
                 .build()) {
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
@@ -115,7 +115,7 @@ public class UnionPlannerTest extends AbstractPlannerTest {
                 .add("SALARY", f.createJavaType(Double.class))
                 .build()) {
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),
@@ -137,7 +137,7 @@ public class UnionPlannerTest extends AbstractPlannerTest {
                 .add("SALARY", f.createJavaType(Double.class))
                 .build()) {
 
-            @Override public ColocationGroup colocationGroup(PlanningContext ctx) {
+            @Override public ColocationGroup colocationGroup(MappingQueryContext ctx) {
                 return ColocationGroup.forAssignments(Arrays.asList(
                     select(nodes, 0, 1),
                     select(nodes, 1, 2),