You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by sb...@apache.org on 2017/05/24 13:36:06 UTC

[01/31] ignite git commit: IGNITE-4947 - Move to Ignite 2.0 test suites - Fixes #1986.

Repository: ignite
Updated Branches:
  refs/heads/ignite-5075 7fc01683a -> ca176a7d7


http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/marshaller/GridMarshallerPerformanceTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/marshaller/GridMarshallerPerformanceTest.java b/modules/core/src/test/java/org/apache/ignite/marshaller/GridMarshallerPerformanceTest.java
index 3b45977..c4e29c5 100644
--- a/modules/core/src/test/java/org/apache/ignite/marshaller/GridMarshallerPerformanceTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/marshaller/GridMarshallerPerformanceTest.java
@@ -35,6 +35,7 @@ import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Map;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.lang.GridTuple;
 import org.apache.ignite.internal.util.typedef.CI1;
 import org.apache.ignite.internal.util.typedef.CIX1;
@@ -43,7 +44,6 @@ import org.apache.ignite.internal.util.typedef.COX;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteOutClosure;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 
 /**
@@ -115,11 +115,7 @@ public class GridMarshallerPerformanceTest extends GridCommonAbstractTest {
     public void testGridMarshaller() throws Exception {
         final GridTuple<byte[]> tuple = new GridTuple<>();
 
-        // Test marshaller context.
-        final MarshallerContext marshCtx = new MarshallerContextTestImpl();
-
-        final OptimizedMarshaller marsh = new OptimizedMarshaller();
-        marsh.setContext(marshCtx);
+        final BinaryMarshaller marsh = createStandaloneBinaryMarshaller();
 
         IgniteInClosure<TestObject> writer = new CIX1<TestObject>() {
             @Override public void applyx(TestObject obj) throws IgniteCheckedException {

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/messaging/IgniteMessagingWithClientTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/messaging/IgniteMessagingWithClientTest.java b/modules/core/src/test/java/org/apache/ignite/messaging/IgniteMessagingWithClientTest.java
index 0df7933..b96728f 100644
--- a/modules/core/src/test/java/org/apache/ignite/messaging/IgniteMessagingWithClientTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/messaging/IgniteMessagingWithClientTest.java
@@ -27,9 +27,9 @@ import org.apache.ignite.IgniteMessaging;
 import org.apache.ignite.cluster.ClusterGroup;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiPredicate;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -54,7 +54,7 @@ public class IgniteMessagingWithClientTest extends GridCommonAbstractTest implem
     @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
         IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
 
-        cfg.setMarshaller(new OptimizedMarshaller(false));
+        cfg.setMarshaller(new BinaryMarshaller());
 
         if (igniteInstanceName.equals(getTestIgniteInstanceName(2))) {
             cfg.setClientMode(true);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoveryMarshallerCheckSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoveryMarshallerCheckSelfTest.java b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoveryMarshallerCheckSelfTest.java
index eb011b4..1a88b11 100644
--- a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoveryMarshallerCheckSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpClientDiscoveryMarshallerCheckSelfTest.java
@@ -19,8 +19,8 @@ package org.apache.ignite.spi.discovery.tcp;
 
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -42,7 +42,7 @@ public class TcpClientDiscoveryMarshallerCheckSelfTest extends GridCommonAbstrac
         else {
             cfg.setClientMode(true);
 
-            cfg.setMarshaller(new OptimizedMarshaller());
+            cfg.setMarshaller(new BinaryMarshaller());
         }
 
         cfg.setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(ipFinder));

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryMarshallerCheckSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryMarshallerCheckSelfTest.java b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryMarshallerCheckSelfTest.java
index dd43cbc..696225c 100644
--- a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryMarshallerCheckSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryMarshallerCheckSelfTest.java
@@ -19,8 +19,8 @@ package org.apache.ignite.spi.discovery.tcp;
 
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -54,7 +54,7 @@ public class TcpDiscoveryMarshallerCheckSelfTest extends GridCommonAbstractTest
         if (flag)
             cfg.setMarshaller(new JdkMarshaller());
         else
-            cfg.setMarshaller(sameMarsh ? new JdkMarshaller() : new OptimizedMarshaller());
+            cfg.setMarshaller(sameMarsh ? new JdkMarshaller() : new BinaryMarshaller());
 
         // Flip flag.
         flag = !flag;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testframework/config/GridTestProperties.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/config/GridTestProperties.java b/modules/core/src/test/java/org/apache/ignite/testframework/config/GridTestProperties.java
index d13f117..6d1c3e6 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/config/GridTestProperties.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/config/GridTestProperties.java
@@ -28,6 +28,7 @@ import java.util.Map.Entry;
 import java.util.Properties;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import org.apache.ignite.binary.BinaryBasicNameMapper;
 import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.log4j.xml.DOMConfigurator;
 import org.jetbrains.annotations.Nullable;
@@ -78,7 +79,7 @@ public final class GridTestProperties {
     /** Binary marshaller compact footers property. */
     public static final String BINARY_COMPACT_FOOTERS = "binary.marshaller.compact.footers";
 
-    /** */
+    /** Enables {@link BinaryBasicNameMapper} with usage of simple (w/o package) name of class. */
     public static final String BINARY_MARSHALLER_USE_SIMPLE_NAME_MAPPER = "binary.marshaller.use.simple.name.mapper";
 
     /** */

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariations.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariations.java b/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariations.java
index d38eb14..8e7e554 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariations.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/configvariations/ConfigVariations.java
@@ -84,7 +84,7 @@ public class ConfigVariations {
     /** */
     @SuppressWarnings("unchecked")
     private static final ConfigParameter<IgniteConfiguration>[][] BASIC_IGNITE_SET = new ConfigParameter[][] {
-        Parameters.objectParameters("setMarshaller", Parameters.factory(BinaryMarshaller.class), optimizedMarshallerFactory()),
+        Parameters.objectParameters("setMarshaller", Parameters.factory(BinaryMarshaller.class), binaryMarshallerFactory()),
         Parameters.booleanParameters("setPeerClassLoadingEnabled"),
     };
 
@@ -183,14 +183,10 @@ public class ConfigVariations {
     /**
      * @return Marshaller.
      */
-    public static Factory<OptimizedMarshaller> optimizedMarshallerFactory() {
-        return new Factory<OptimizedMarshaller>() {
-            @Override public OptimizedMarshaller create() {
-                OptimizedMarshaller marsh = new OptimizedMarshaller(true);
-
-                marsh.setRequireSerializable(false);
-
-                return marsh;
+    public static Factory<BinaryMarshaller> binaryMarshallerFactory() {
+        return new Factory<BinaryMarshaller>() {
+            @Override public BinaryMarshaller create() {
+                return new BinaryMarshaller();
             }
         };
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java
index 8603d77..29c6396 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java
@@ -63,6 +63,8 @@ import org.apache.ignite.internal.IgniteInternalFuture;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.IgniteKernal;
 import org.apache.ignite.internal.IgnitionEx;
+import org.apache.ignite.internal.binary.BinaryCachingMetadataHandler;
+import org.apache.ignite.internal.binary.BinaryContext;
 import org.apache.ignite.internal.binary.BinaryEnumCache;
 import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
@@ -70,6 +72,7 @@ import org.apache.ignite.internal.processors.resource.GridSpringResourceContext;
 import org.apache.ignite.internal.util.GridClassLoaderCache;
 import org.apache.ignite.internal.util.GridTestClockTimer;
 import org.apache.ignite.internal.util.GridUnsafe;
+import org.apache.ignite.internal.util.IgniteUtils;
 import org.apache.ignite.internal.util.lang.GridAbsPredicate;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.G;
@@ -78,7 +81,9 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.lang.IgniteCallable;
 import org.apache.ignite.lang.IgniteClosure;
+import org.apache.ignite.logger.NullLogger;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerContextTestImpl;
 import org.apache.ignite.marshaller.MarshallerExclusions;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
@@ -1376,6 +1381,34 @@ public abstract class GridAbstractTest extends TestCase {
     }
 
     /**
+     * Create instance of {@link BinaryMarshaller} suitable for use
+     * without starting a grid upon an empty {@link IgniteConfiguration}.
+     * @return Binary marshaller.
+     * @throws IgniteCheckedException if failed.
+     */
+    protected BinaryMarshaller createStandaloneBinaryMarshaller() throws IgniteCheckedException {
+        return createStandaloneBinaryMarshaller(new IgniteConfiguration());
+    }
+
+    /**
+     * Create instance of {@link BinaryMarshaller} suitable for use
+     * without starting a grid upon given {@link IgniteConfiguration}.
+     * @return Binary marshaller.
+     * @throws IgniteCheckedException if failed.
+     */
+    protected BinaryMarshaller createStandaloneBinaryMarshaller(IgniteConfiguration cfg) throws IgniteCheckedException {
+        BinaryMarshaller marsh = new BinaryMarshaller();
+
+        BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), cfg, new NullLogger());
+
+        marsh.setContext(new MarshallerContextTestImpl());
+
+        IgniteUtils.invoke(BinaryMarshaller.class, marsh, "setBinaryContext", ctx, cfg);
+
+        return marsh;
+    }
+
+    /**
      * @return Generated unique test Ignite instance name.
      */
     public String getTestIgniteInstanceName() {

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteTestResources.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteTestResources.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteTestResources.java
index f8494da..2c7d597 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteTestResources.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/IgniteTestResources.java
@@ -28,15 +28,14 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.binary.BinaryCachingMetadataHandler;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.binary.BinaryContext;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.resource.GridResourceProcessor;
 import org.apache.ignite.internal.util.IgniteUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.logger.NullLogger;
 import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.marshaller.MarshallerContextTestImpl;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.testframework.config.GridTestProperties;
@@ -244,7 +243,7 @@ public class IgniteTestResources {
         Marshaller marsh;
 
         if (marshallerName == null)
-            marsh = new OptimizedMarshaller();
+            marsh = new BinaryMarshaller();
         else {
             try {
                 Class<? extends Marshaller> cls = (Class<? extends Marshaller>)Class.forName(marshallerName);
@@ -257,9 +256,6 @@ public class IgniteTestResources {
             }
         }
 
-        if (marsh instanceof OptimizedMarshaller)
-            ((OptimizedMarshaller)marsh).setRequireSerializable(false);
-
         marsh.setContext(new MarshallerContextTestImpl());
 
         if (marsh instanceof BinaryMarshaller) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/BinaryObjectsTxDeadlockDetectionTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/BinaryObjectsTxDeadlockDetectionTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/BinaryObjectsTxDeadlockDetectionTestSuite.java
deleted file mode 100644
index 45afba2..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/BinaryObjectsTxDeadlockDetectionTestSuite.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- *
- */
-public class BinaryObjectsTxDeadlockDetectionTestSuite {
-    /**
-     * @return Test suite.
-     * @throws Exception If failed.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        return TxDeadlockDetectionTestSuite.suite();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
index 8badd86..837523d 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
@@ -25,6 +25,13 @@ import org.apache.ignite.internal.GridReleaseTypeSelfTest;
 import org.apache.ignite.internal.GridVersionSelfTest;
 import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.managers.deployment.GridDeploymentMessageCountSelfTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerEnumSelfTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerNodeFailoverTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerPooledSelfTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerSelfTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerSerialPersistentFieldsSelfTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerTest;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedObjectStreamSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheP2pUnmarshallingErrorTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheP2pUnmarshallingNearErrorTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheP2pUnmarshallingRebalanceErrorTest;
@@ -39,13 +46,6 @@ import org.apache.ignite.internal.util.nio.GridNioSelfTest;
 import org.apache.ignite.internal.util.nio.GridNioSslSelfTest;
 import org.apache.ignite.marshaller.DynamicProxySerializationMultiJvmSelfTest;
 import org.apache.ignite.marshaller.jdk.GridJdkMarshallerSelfTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerEnumSelfTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerNodeFailoverTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerPooledSelfTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerSelfTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerSerialPersistentFieldsSelfTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerTest;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedObjectStreamSelfTest;
 import org.apache.ignite.messaging.GridMessagingNoPeerClassLoadingSelfTest;
 import org.apache.ignite.messaging.GridMessagingSelfTest;
 import org.apache.ignite.testframework.config.GridTestProperties;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheFullApiTestSuite.java
deleted file mode 100644
index e891d35..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheFullApiTestSuite.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- * Cache full API suite with binary marshaller.
- */
-public class IgniteBinaryCacheFullApiTestSuite extends TestSuite {
-    /**
-     * @return Suite.
-     * @throws Exception In case of error.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        return IgniteCacheFullApiSelfTestSuite.suite();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
index f2d1556..170bb33 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheTestSuite.java
@@ -19,7 +19,6 @@ package org.apache.ignite.testsuites;
 
 import java.util.HashSet;
 import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.cache.GridCacheAffinityRoutingSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheEntryMemorySizeSelfTest;
 import org.apache.ignite.internal.processors.cache.GridCacheMvccSelfTest;
@@ -36,7 +35,6 @@ import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCa
 import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCacheBinariesNearPartitionedByteArrayValuesSelfTest;
 import org.apache.ignite.internal.processors.cache.binary.distributed.dht.GridCacheBinariesPartitionedOnlyByteArrayValuesSelfTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessorSelfTest;
-import org.apache.ignite.testframework.config.GridTestProperties;
 
 /**
  * Cache suite with binary marshaller.
@@ -47,8 +45,6 @@ public class IgniteBinaryCacheTestSuite extends TestSuite {
      * @throws Exception In case of error.
      */
     public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
         TestSuite suite = new TestSuite("Binary Cache Test Suite");
 
         HashSet<Class> ignoredTests = new HashSet<>();

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheDataStructuresSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheDataStructuresSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheDataStructuresSelfTestSuite.java
deleted file mode 100644
index f8769a0..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheDataStructuresSelfTestSuite.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.internal.processors.cache.datastructures.IgniteDataStructuresNoClassOnServerTest;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- *
- */
-public class IgniteBinaryObjectsCacheDataStructuresSelfTestSuite {
-    /**
-     * @return Test suite.
-     * @throws Exception If failed.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        TestSuite suite = IgniteCacheDataStructuresSelfTestSuite.suite();
-
-        suite.addTestSuite(IgniteDataStructuresNoClassOnServerTest.class);
-
-        return suite;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheExpiryPolicyTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheExpiryPolicyTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheExpiryPolicyTestSuite.java
deleted file mode 100644
index 7cb4051..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheExpiryPolicyTestSuite.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.internal.processors.cache.expiry.IgniteCacheExpiryPolicyTestSuite;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- *
- */
-public class IgniteBinaryObjectsCacheExpiryPolicyTestSuite {
-    /**
-     * @return Test suite.
-     * @throws Exception If failed.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        return IgniteCacheExpiryPolicyTestSuite.suite();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheRestartTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheRestartTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheRestartTestSuite.java
deleted file mode 100644
index e3c9f68..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheRestartTestSuite.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- *
- */
-public class IgniteBinaryObjectsCacheRestartTestSuite {
-    /**
-     * @return Test suite.
-     * @throws Exception If failed.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        return IgniteCacheRestartTestSuite.suite();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite2.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite2.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite2.java
deleted file mode 100644
index c13693b..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite2.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- *
- */
-public class IgniteBinaryObjectsCacheTestSuite2 {
-    /**
-     * @return Test suite.
-     * @throws Exception If failed.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        return IgniteCacheTestSuite2.suite();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite3.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite3.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite3.java
index d80478b..8d21580 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite3.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite3.java
@@ -18,7 +18,6 @@
 package org.apache.ignite.testsuites;
 
 import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryAtomicEntryProcessorDeploymentSelfTest;
 import org.apache.ignite.internal.processors.cache.binary.GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest;
 import org.apache.ignite.testframework.config.GridTestProperties;
@@ -32,7 +31,6 @@ public class IgniteBinaryObjectsCacheTestSuite3 {
      * @throws Exception If failed.
      */
     public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
         GridTestProperties.setProperty(GridTestProperties.ENTRY_PROCESSOR_CLASS_NAME,
             "org.apache.ignite.tests.p2p.CacheDeploymentBinaryEntryProcessor");
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite4.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite4.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite4.java
deleted file mode 100644
index 2292a93..0000000
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsCacheTestSuite4.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- *
- */
-public class IgniteBinaryObjectsCacheTestSuite4 {
-    /**
-     * @return Test suite.
-     * @throws Exception If failed.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        return IgniteCacheTestSuite4.suite();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsComputeGridTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsComputeGridTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsComputeGridTestSuite.java
index e659966..8798db9 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsComputeGridTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryObjectsComputeGridTestSuite.java
@@ -19,8 +19,6 @@ package org.apache.ignite.testsuites;
 
 import junit.framework.TestSuite;
 import org.apache.ignite.internal.GridComputationBinarylizableClosuresSelfTest;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
 
 /**
  *
@@ -31,8 +29,6 @@ public class IgniteBinaryObjectsComputeGridTestSuite {
      * @throws Exception If failed.
      */
     public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
         TestSuite suite = IgniteComputeGridTestSuite.suite();
 
         suite.addTestSuite(GridComputationBinarylizableClosuresSelfTest.class);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
index d544810..2ae9297 100755
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
@@ -28,8 +28,6 @@ import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreBinaryMarshallerStor
 import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreBinaryMarshallerStoreKeepBinaryWithSqlEscapeSelfTest;
 import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreBinaryMarshallerWithSqlEscapeSelfTest;
 import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreMultitreadedSelfTest;
-import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreOptimizedMarshallerSelfTest;
-import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest;
 import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStoreTest;
 import org.apache.ignite.cache.store.jdbc.GridCacheJdbcBlobStoreMultithreadedSelfTest;
 import org.apache.ignite.cache.store.jdbc.GridCacheJdbcBlobStoreSelfTest;
@@ -227,8 +225,6 @@ public class IgniteCacheTestSuite extends TestSuite {
         suite.addTestSuite(GridCacheJdbcBlobStoreMultithreadedSelfTest.class);
         suite.addTestSuite(JdbcTypesDefaultTransformerTest.class);
         suite.addTestSuite(CacheJdbcPojoStoreTest.class);
-        suite.addTestSuite(CacheJdbcPojoStoreOptimizedMarshallerSelfTest.class);
-        suite.addTestSuite(CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest.class);
         suite.addTestSuite(CacheJdbcPojoStoreBinaryMarshallerSelfTest.class);
         suite.addTestSuite(CacheJdbcPojoStoreBinaryMarshallerStoreKeepBinarySelfTest.class);
         suite.addTestSuite(CacheJdbcPojoStoreBinaryMarshallerWithSqlEscapeSelfTest.class);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteComputeBasicConfigVariationsFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteComputeBasicConfigVariationsFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteComputeBasicConfigVariationsFullApiTestSuite.java
index 1be932a..41cc8a1 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteComputeBasicConfigVariationsFullApiTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteComputeBasicConfigVariationsFullApiTestSuite.java
@@ -37,7 +37,7 @@ public class IgniteComputeBasicConfigVariationsFullApiTestSuite extends TestSuit
         Parameters.objectParameters("setMarshaller",
             Parameters.factory(JdkMarshaller.class),
             Parameters.factory(BinaryMarshaller.class),
-            ConfigVariations.optimizedMarshallerFactory()
+            ConfigVariations.binaryMarshallerFactory()
         ),
         Parameters.booleanParameters("setPeerClassLoadingEnabled"),
         Parameters.booleanParameters("setMarshalLocalJobs"),

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
index a2519fb..908390f 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteIgfsTestSuite.java
@@ -45,7 +45,6 @@ import org.apache.ignite.internal.processors.igfs.IgfsModeResolverSelfTest;
 import org.apache.ignite.internal.processors.igfs.IgfsModesSelfTest;
 import org.apache.ignite.internal.processors.igfs.IgfsPrimaryMultiNodeSelfTest;
 import org.apache.ignite.internal.processors.igfs.IgfsOneClientNodeTest;
-import org.apache.ignite.internal.processors.igfs.IgfsPrimaryOptimziedMarshallerSelfTest;
 import org.apache.ignite.internal.processors.igfs.IgfsPrimaryRelaxedConsistencyClientSelfTest;
 import org.apache.ignite.internal.processors.igfs.IgfsPrimaryRelaxedConsistencyMultiNodeSelfTest;
 import org.apache.ignite.internal.processors.igfs.IgfsPrimaryRelaxedConsistencySelfTest;
@@ -88,8 +87,6 @@ public class IgniteIgfsTestSuite extends TestSuite {
         suite.addTest(new TestSuite(IgfsPrimaryRelaxedConsistencySelfTest.class));
         suite.addTest(new TestSuite(IgfsPrimaryRelaxedConsistencyMultiNodeSelfTest.class));
 
-        suite.addTest(new TestSuite(IgfsPrimaryOptimziedMarshallerSelfTest.class));
-
         suite.addTest(new TestSuite(IgfsDualSyncSelfTest.class));
         suite.addTest(new TestSuite(IgfsDualAsyncSelfTest.class));
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
index 04be453..38b9d0a 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java
@@ -61,10 +61,8 @@ import org.apache.ignite.internal.processors.service.GridServiceReassignmentSelf
 import org.apache.ignite.internal.processors.service.GridServiceSerializationSelfTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersJdkMarshallerTest;
-import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingDefaultMarshallerTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingJdkMarshallerTest;
-import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceDynamicCachesSelfTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceProxyTimeoutInitializedTest;
 import org.apache.ignite.internal.processors.service.IgniteServiceReassignmentTest;
@@ -146,10 +144,8 @@ public class IgniteKernalSelfTestSuite extends TestSuite {
         suite.addTestSuite(ServiceThreadPoolSelfTest.class);
 
         suite.addTestSuite(IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.class);
-        suite.addTestSuite(IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.class);
         suite.addTestSuite(IgniteServiceDeploymentClassLoadingJdkMarshallerTest.class);
         suite.addTestSuite(IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.class);
-        suite.addTestSuite(IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.class);
         suite.addTestSuite(IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.class);
 
         return suite;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
index 4c5cb98..98a6bde 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
@@ -20,10 +20,6 @@ package org.apache.ignite.testsuites;
 import java.util.Set;
 import junit.framework.TestSuite;
 import org.apache.ignite.internal.direct.stream.v2.DirectByteBufferStreamImplV2ByteOrderSelfTest;
-import org.apache.ignite.internal.util.GridHandleTableSelfTest;
-import org.apache.ignite.internal.util.io.GridUnsafeDataInputOutputByteOrderSelfTest;
-import org.apache.ignite.internal.util.io.GridUnsafeDataOutputArraySizingSelfTest;
-import org.apache.ignite.marshaller.jdk.GridJdkMarshallerSelfTest;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerEnumSelfTest;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerNodeFailoverTest;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerPooledSelfTest;
@@ -31,6 +27,10 @@ import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerSelfTe
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerSerialPersistentFieldsSelfTest;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerTest;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedObjectStreamSelfTest;
+import org.apache.ignite.internal.util.GridHandleTableSelfTest;
+import org.apache.ignite.internal.util.io.GridUnsafeDataInputOutputByteOrderSelfTest;
+import org.apache.ignite.internal.util.io.GridUnsafeDataOutputArraySizingSelfTest;
+import org.apache.ignite.marshaller.jdk.GridJdkMarshallerSelfTest;
 import org.apache.ignite.testframework.GridTestUtils;
 
 /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMessagingConfigVariationFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMessagingConfigVariationFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMessagingConfigVariationFullApiTestSuite.java
index bfb9cd1..0490a92 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMessagingConfigVariationFullApiTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMessagingConfigVariationFullApiTestSuite.java
@@ -37,7 +37,7 @@ public class IgniteMessagingConfigVariationFullApiTestSuite extends TestSuite {
         Parameters.objectParameters("setMarshaller",
             Parameters.factory(JdkMarshaller.class),
             Parameters.factory(BinaryMarshaller.class),
-            ConfigVariations.optimizedMarshallerFactory()
+            ConfigVariations.binaryMarshallerFactory()
         ),
         Parameters.booleanParameters("setPeerClassLoadingEnabled")
     };

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteServiceConfigVariationsFullApiTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteServiceConfigVariationsFullApiTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteServiceConfigVariationsFullApiTestSuite.java
index 328ae8d..84af386 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteServiceConfigVariationsFullApiTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteServiceConfigVariationsFullApiTestSuite.java
@@ -37,7 +37,7 @@ public class IgniteServiceConfigVariationsFullApiTestSuite extends TestSuite {
         Parameters.objectParameters("setMarshaller",
             Parameters.factory(JdkMarshaller.class),
             Parameters.factory(BinaryMarshaller.class),
-            ConfigVariations.optimizedMarshallerFactory()
+            ConfigVariations.binaryMarshallerFactory()
         ),
 
         Parameters.booleanParameters("setPeerClassLoadingEnabled")

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/webapp/META-INF/ignite-webapp-config.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/webapp/META-INF/ignite-webapp-config.xml b/modules/core/src/test/webapp/META-INF/ignite-webapp-config.xml
index ac3a8da..66db1ed 100644
--- a/modules/core/src/test/webapp/META-INF/ignite-webapp-config.xml
+++ b/modules/core/src/test/webapp/META-INF/ignite-webapp-config.xml
@@ -48,21 +48,10 @@
         <property name="peerClassLoadingEnabled" value="true"/>
 
         <!--
-            Configure optimized marshaller.
+            Configure binary marshaller.
         -->
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <!--
-                    For better performance set this property to true in case
-                    all marshalled classes implement java.io.Serializable.
-                    Default value is true.
-
-                    Note, that it is recommended to implement java.io.Externalizable
-                    instead of java.io.Serializable for smaller network footprint
-                    and even better performance.
-                -->
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!-- Set to local host address just for examples. -->

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-0.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-0.xml b/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-0.xml
index 03cf945..291433c 100644
--- a/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-0.xml
+++ b/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-0.xml
@@ -54,8 +54,7 @@
         <property name="gridName" value="IGFS-cli-0"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-1.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-1.xml b/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-1.xml
index a6022fa..e20bc38 100644
--- a/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-1.xml
+++ b/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-1.xml
@@ -54,8 +54,7 @@
         <property name="gridName" value="IGFS-cli-1"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-2.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-2.xml b/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-2.xml
index 6cfcf57..ad56227 100644
--- a/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-2.xml
+++ b/modules/hadoop/src/test/config/hadoop-fs-open-test/grid-2.xml
@@ -54,8 +54,7 @@
         <property name="gridName" value="IGFS-cli-2"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/igfs-cli-config-dual-async.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/igfs-cli-config-dual-async.xml b/modules/hadoop/src/test/config/igfs-cli-config-dual-async.xml
index 488d8d9..5cefc3d 100644
--- a/modules/hadoop/src/test/config/igfs-cli-config-dual-async.xml
+++ b/modules/hadoop/src/test/config/igfs-cli-config-dual-async.xml
@@ -55,8 +55,7 @@
         <property name="gridName" value="test-IGFS-cli"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/igfs-cli-config-dual-sync.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/igfs-cli-config-dual-sync.xml b/modules/hadoop/src/test/config/igfs-cli-config-dual-sync.xml
index f6d5bab..243de7e 100644
--- a/modules/hadoop/src/test/config/igfs-cli-config-dual-sync.xml
+++ b/modules/hadoop/src/test/config/igfs-cli-config-dual-sync.xml
@@ -53,8 +53,7 @@
     <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
         <property name="clientMode" value="true"/>
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/igfs-cli-config-primary.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/igfs-cli-config-primary.xml b/modules/hadoop/src/test/config/igfs-cli-config-primary.xml
index c1c41b4..46914b2 100644
--- a/modules/hadoop/src/test/config/igfs-cli-config-primary.xml
+++ b/modules/hadoop/src/test/config/igfs-cli-config-primary.xml
@@ -55,8 +55,7 @@
         <property name="gridName" value="test-IGFS-cli"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/config/igfs-cli-config-proxy.xml
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/config/igfs-cli-config-proxy.xml b/modules/hadoop/src/test/config/igfs-cli-config-proxy.xml
index bd4b215..d7c7f00 100644
--- a/modules/hadoop/src/test/config/igfs-cli-config-proxy.xml
+++ b/modules/hadoop/src/test/config/igfs-cli-config-proxy.xml
@@ -53,8 +53,7 @@
     <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
         <property name="clientMode" value="true"/>
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemAbstractSelfTest.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemAbstractSelfTest.java
index 5ae2c3e..6434182 100644
--- a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemAbstractSelfTest.java
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemAbstractSelfTest.java
@@ -70,6 +70,7 @@ import org.apache.ignite.igfs.IgfsIpcEndpointConfiguration;
 import org.apache.ignite.igfs.IgfsIpcEndpointType;
 import org.apache.ignite.igfs.IgfsMode;
 import org.apache.ignite.igfs.IgfsPath;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.igfs.IgfsCommonAbstractTest;
 import org.apache.ignite.internal.processors.igfs.IgfsModeResolver;
 import org.apache.ignite.internal.util.GridConcurrentHashSet;
@@ -78,7 +79,6 @@ import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.G;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiTuple;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -359,7 +359,7 @@ public abstract class IgniteHadoopFileSystemAbstractSelfTest extends IgfsCommonA
         discoSpi.setIpFinder(IP_FINDER);
 
         cfg.setIgniteInstanceName(igniteInstanceName);
-        cfg.setMarshaller(new OptimizedMarshaller());
+        cfg.setMarshaller(new BinaryMarshaller());
         cfg.setDiscoverySpi(discoSpi);
         cfg.setFileSystemConfiguration(igfsConfiguration(igniteInstanceName));
         cfg.setIncludeEventTypes(EVT_TASK_FAILED, EVT_TASK_FINISHED, EVT_JOB_MAPPED);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
index 4fa73b5..e0148b3 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
@@ -27,7 +27,7 @@ import org.apache.ignite.cache.QueryIndex;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.NearCacheConfiguration;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -70,7 +70,7 @@ public class IgniteCacheNoClassQuerySelfTest extends GridCommonAbstractTest {
 
         CacheConfiguration cc = defaultCacheConfiguration();
 
-        c.setMarshaller(new OptimizedMarshaller());
+        c.setMarshaller(new BinaryMarshaller());
 
         cc.setName("cache");
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/AbstractH2CompareQueryTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/AbstractH2CompareQueryTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/AbstractH2CompareQueryTest.java
index ec83687..5475311 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/AbstractH2CompareQueryTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/AbstractH2CompareQueryTest.java
@@ -37,8 +37,8 @@ import org.apache.ignite.cache.CacheWriteSynchronizationMode;
 import org.apache.ignite.cache.query.SqlFieldsQuery;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -73,7 +73,7 @@ public abstract class AbstractH2CompareQueryTest extends GridCommonAbstractTest
 
         c.setDiscoverySpi(disco);
 
-        c.setMarshaller(new OptimizedMarshaller(true));
+        c.setMarshaller(new BinaryMarshaller());
 
         return c;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/loadtests/h2indexing/FetchingQueryCursorStressTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/loadtests/h2indexing/FetchingQueryCursorStressTest.java b/modules/indexing/src/test/java/org/apache/ignite/loadtests/h2indexing/FetchingQueryCursorStressTest.java
index bbc9762..8a73a8e 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/loadtests/h2indexing/FetchingQueryCursorStressTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/loadtests/h2indexing/FetchingQueryCursorStressTest.java
@@ -34,7 +34,7 @@ import org.apache.ignite.cache.query.SqlFieldsQuery;
 import org.apache.ignite.cache.query.annotations.QuerySqlField;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 
 /**
  * SQL query stress test.
@@ -158,7 +158,7 @@ public class FetchingQueryCursorStressTest {
 
         ccfg.setName(CACHE_NAME);
         ccfg.setIndexedTypes(Integer.class, Person.class);
-        cfg.setMarshaller(new OptimizedMarshaller());
+        cfg.setMarshaller(new BinaryMarshaller());
 
         cfg.setCacheConfiguration(ccfg);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite.java
index 5826b72..1cfb345 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite.java
@@ -18,11 +18,9 @@
 package org.apache.ignite.testsuites;
 
 import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.cache.BinarySerializationQuerySelfTest;
 import org.apache.ignite.internal.processors.cache.BinarySerializationQueryWithReflectiveSerializerSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheBinaryObjectsScanSelfTest;
-import org.apache.ignite.testframework.config.GridTestProperties;
 
 /**
  * Cache query suite with binary marshaller.
@@ -33,8 +31,6 @@ public class IgniteBinaryCacheQueryTestSuite extends TestSuite {
      * @throws Exception In case of error.
      */
     public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
         TestSuite suite = IgniteCacheQuerySelfTestSuite.suite();
 
         // Serialization.

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite2.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite2.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite2.java
index 359c7fd..ce2a666 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite2.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite2.java
@@ -18,9 +18,7 @@
 package org.apache.ignite.testsuites;
 
 import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.cache.IgniteCacheQueriesLoadTest1;
-import org.apache.ignite.testframework.config.GridTestProperties;
 
 /**
  * Cache query suite with binary marshaller.
@@ -31,8 +29,6 @@ public class IgniteBinaryCacheQueryTestSuite2 extends TestSuite {
      * @throws Exception In case of error.
      */
     public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
         TestSuite suite = IgniteCacheQuerySelfTestSuite2.suite();
 
         suite.addTestSuite(IgniteCacheQueriesLoadTest1.class);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite3.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite3.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite3.java
deleted file mode 100644
index f9e9af2..0000000
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite3.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- * Cache query suite with binary marshaller.
- */
-public class IgniteBinaryCacheQueryTestSuite3 extends TestSuite {
-    /**
-     * @return Suite.
-     * @throws Exception In case of error.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        TestSuite suite = IgniteCacheQuerySelfTestSuite3.suite();
-
-        return suite;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite4.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite4.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite4.java
deleted file mode 100644
index 32a693f..0000000
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteBinaryCacheQueryTestSuite4.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.testsuites;
-
-import junit.framework.TestSuite;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.testframework.config.GridTestProperties;
-
-/**
- * Cache query suite with binary marshaller.
- */
-public class IgniteBinaryCacheQueryTestSuite4 extends TestSuite {
-    /**
-     * @return Suite.
-     * @throws Exception In case of error.
-     */
-    public static TestSuite suite() throws Exception {
-        GridTestProperties.setProperty(GridTestProperties.MARSH_CLASS_NAME, BinaryMarshaller.class.getName());
-
-        TestSuite suite = IgniteCacheQuerySelfTestSuite4.suite();
-
-        return suite;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/platforms/dotnet/Apache.Ignite.Core.Tests/MarshallerTest.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/MarshallerTest.cs b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/MarshallerTest.cs
index 030916b..2ec9c6f 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/MarshallerTest.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/MarshallerTest.cs
@@ -68,7 +68,7 @@ namespace Apache.Ignite.Core.Tests
             var ex = Assert.Throws<IgniteException>(() => StartIgnite("config\\marshaller-invalid.xml"));
             Assert.AreEqual("Unsupported marshaller (only org.apache.ignite.internal.binary.BinaryMarshaller " +
                             "can be used when running Apache Ignite.NET): org.apache.ignite.internal." +
-                            "marshaller.optimized.OptimizedMarshaller", ex.Message);
+                            "marshaller.optimized.OptimizedMarshaller", ex.Message, ex.ToString());
         }
 
         /// <summary>

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java b/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java
index 4c0613f..6f7d27a 100644
--- a/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java
+++ b/modules/spring/src/test/java/org/apache/ignite/internal/GridSpringBeanSerializationSelfTest.java
@@ -18,11 +18,10 @@
 package org.apache.ignite.internal;
 
 import org.apache.ignite.IgniteSpringBean;
+import org.apache.ignite.configuration.BinaryConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.marshaller.Marshaller;
-import org.apache.ignite.marshaller.MarshallerContextTestImpl;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -36,7 +35,7 @@ public class GridSpringBeanSerializationSelfTest extends GridCommonAbstractTest
     private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
 
     /** Marshaller. */
-    private static final Marshaller MARSHALLER = new OptimizedMarshaller();
+    private Marshaller marsh;
 
     /** Attribute key. */
     private static final String ATTR_KEY = "checkAttr";
@@ -46,11 +45,13 @@ public class GridSpringBeanSerializationSelfTest extends GridCommonAbstractTest
 
     /** {@inheritDoc} */
     @Override protected void beforeTestsStarted() throws Exception {
-        MARSHALLER.setContext(new MarshallerContextTestImpl());
+        IgniteConfiguration cfg = config();
+
+        marsh = createStandaloneBinaryMarshaller(cfg);
 
         bean = new IgniteSpringBean();
 
-        bean.setConfiguration(config());
+        bean.setConfiguration(cfg);
 
         bean.afterPropertiesSet();
     }
@@ -73,6 +74,8 @@ public class GridSpringBeanSerializationSelfTest extends GridCommonAbstractTest
 
         cfg.setIgniteInstanceName(getTestIgniteInstanceName());
 
+        cfg.setBinaryConfiguration(new BinaryConfiguration());
+
         return cfg;
     }
 
@@ -87,7 +90,7 @@ public class GridSpringBeanSerializationSelfTest extends GridCommonAbstractTest
     public void testSerialization() throws Exception {
         assert bean != null;
 
-        IgniteSpringBean bean0 = MARSHALLER.unmarshal(MARSHALLER.marshal(bean), null);
+        IgniteSpringBean bean0 = marsh.unmarshal(marsh.marshal(bean), null);
 
         assert bean0 != null;
         assert bean0.log() != null;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/web/src/test/webapp2/META-INF/ignite-webapp-config.xml
----------------------------------------------------------------------
diff --git a/modules/web/src/test/webapp2/META-INF/ignite-webapp-config.xml b/modules/web/src/test/webapp2/META-INF/ignite-webapp-config.xml
index 09a7848..7224796 100644
--- a/modules/web/src/test/webapp2/META-INF/ignite-webapp-config.xml
+++ b/modules/web/src/test/webapp2/META-INF/ignite-webapp-config.xml
@@ -39,21 +39,10 @@
         <property name="peerClassLoadingEnabled" value="true"/>
 
         <!--
-            Configure optimized marshaller.
+            Configure binary marshaller.
         -->
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <!--
-                    For better performance set this property to true in case
-                    all marshalled classes implement java.io.Serializable.
-                    Default value is true.
-
-                    Note, that it is recommended to implement java.io.Externalizable
-                    instead of java.io.Serializable for smaller network footprint
-                    and even better performance.
-                -->
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!-- Set to local host address just for examples. -->

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/yardstick/config/ignite-int-max-values-onheap-config.xml
----------------------------------------------------------------------
diff --git a/modules/yardstick/config/ignite-int-max-values-onheap-config.xml b/modules/yardstick/config/ignite-int-max-values-onheap-config.xml
index 242ae7d..9ad5fcd 100644
--- a/modules/yardstick/config/ignite-int-max-values-onheap-config.xml
+++ b/modules/yardstick/config/ignite-int-max-values-onheap-config.xml
@@ -29,9 +29,7 @@
         <property name="peerClassLoadingEnabled" value="true"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
 <!--

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/yardstick/config/ignite-jdbc-config.xml
----------------------------------------------------------------------
diff --git a/modules/yardstick/config/ignite-jdbc-config.xml b/modules/yardstick/config/ignite-jdbc-config.xml
index b944a6b..a279d46 100644
--- a/modules/yardstick/config/ignite-jdbc-config.xml
+++ b/modules/yardstick/config/ignite-jdbc-config.xml
@@ -33,9 +33,7 @@
         <property name="localHost" value="127.0.0.1"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <property name="discoverySpi">


[03/31] ignite git commit: IGNITE-5175: Performance degradation using evictions in near-enabled caches - Fixes #1931.

Posted by sb...@apache.org.
IGNITE-5175: Performance degradation using evictions in near-enabled caches - Fixes #1931.

Signed-off-by: Alexey Goncharuk <al...@gmail.com>


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/21109947
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/21109947
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/21109947

Branch: refs/heads/ignite-5075
Commit: 2110994715e646b3b2c6cb5f1c30d85ca967d090
Parents: 98a1758
Author: Ivan Rakov <iv...@gmail.com>
Authored: Tue May 23 10:34:55 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue May 23 10:34:55 2017 +0300

----------------------------------------------------------------------
 .../paged/PageEvictionMultinodeTest.java        | 22 ++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/21109947/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/eviction/paged/PageEvictionMultinodeTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/eviction/paged/PageEvictionMultinodeTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/eviction/paged/PageEvictionMultinodeTest.java
index 7a58dd4..c2c0775 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/eviction/paged/PageEvictionMultinodeTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/eviction/paged/PageEvictionMultinodeTest.java
@@ -17,12 +17,14 @@
 package org.apache.ignite.internal.processors.cache.eviction.paged;
 
 import java.util.concurrent.ThreadLocalRandom;
+import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCache;
 import org.apache.ignite.cache.CacheAtomicityMode;
 import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.cache.CachePeekMode;
 import org.apache.ignite.cache.CacheWriteSynchronizationMode;
 import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
 
 /**
  *
@@ -39,9 +41,25 @@ public abstract class PageEvictionMultinodeTest extends PageEvictionAbstractTest
     private static final CacheWriteSynchronizationMode[] WRITE_MODES = {CacheWriteSynchronizationMode.PRIMARY_SYNC,
         CacheWriteSynchronizationMode.FULL_SYNC, CacheWriteSynchronizationMode.FULL_ASYNC};
 
+    /** Client grid. */
+    private Ignite clientGrid;
+
     /** {@inheritDoc} */
     @Override protected void beforeTestsStarted() throws Exception {
         startGridsMultiThreaded(4, false);
+
+        clientGrid = startGrid("client");
+    }
+
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration configuration = super.getConfiguration(gridName);
+
+        if (gridName.startsWith("client"))
+            configuration.setClientMode(true);
+
+        return configuration;
     }
 
     /** {@inheritDoc} */
@@ -77,7 +95,7 @@ public abstract class PageEvictionMultinodeTest extends PageEvictionAbstractTest
      * @throws Exception If failed.
      */
     private void createCacheAndTestEvcition(CacheConfiguration<Object, Object> cfg) throws Exception {
-        IgniteCache<Object, Object> cache = ignite(0).getOrCreateCache(cfg);
+        IgniteCache<Object, Object> cache = clientGrid.getOrCreateCache(cfg);
 
         for (int i = 1; i <= ENTRIES; i++) {
             ThreadLocalRandom r = ThreadLocalRandom.current();
@@ -105,6 +123,6 @@ public abstract class PageEvictionMultinodeTest extends PageEvictionAbstractTest
         // Eviction started, no OutOfMemory occurred, success.
         assertTrue(resultingSize < ENTRIES);
 
-        ignite(0).destroyCache(cfg.getName());
+        clientGrid.destroyCache(cfg.getName());
     }
 }


[31/31] ignite git commit: Merge remote-tracking branch 'remotes/origin/master' into ignite-5075

Posted by sb...@apache.org.
Merge remote-tracking branch 'remotes/origin/master' into ignite-5075

# Conflicts:
#	modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
#	modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/ca176a7d
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/ca176a7d
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/ca176a7d

Branch: refs/heads/ignite-5075
Commit: ca176a7d76548c41eb6cf22a5a6ad26b33edc56c
Parents: 7fc0168 8c75e4d
Author: sboikov <sb...@gridgain.com>
Authored: Wed May 24 16:35:54 2017 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed May 24 16:35:54 2017 +0300

----------------------------------------------------------------------
 examples/config/filesystem/example-igfs.xml     |    4 +
 .../examples/datagrid/CacheQueryExample.java    |    2 +-
 modules/clients/src/test/config/jdbc-config.xml |    6 -
 .../internal/jdbc2/JdbcMetadataSelfTest.java    |    5 +-
 .../internal/jdbc2/JdbcResultSetSelfTest.java   |   24 +-
 .../ignite/jdbc/JdbcMetadataSelfTest.java       |    4 +-
 .../ignite/jdbc/JdbcResultSetSelfTest.java      |  121 +-
 .../jdbc/suite/IgniteJdbcDriverTestSuite.java   |    3 +
 .../jdbc/thin/JdbcConnectionSelfTest.java       |  195 ++
 .../java/org/apache/ignite/IgniteCache.java     |   13 +
 .../org/apache/ignite/IgniteJdbcThinDriver.java |  312 +++
 .../apache/ignite/IgniteSystemProperties.java   |    2 +-
 .../ignite/binary/BinaryBasicNameMapper.java    |    2 +-
 .../ignite/cache/query/FieldsQueryCursor.java   |   39 +
 .../configuration/AtomicConfiguration.java      |   25 +
 .../configuration/MemoryConfiguration.java      |    3 +-
 .../MemoryPolicyConfiguration.java              |    4 +-
 .../ignite/internal/GridKernalContext.java      |    8 +-
 .../ignite/internal/GridKernalContextImpl.java  |   12 +-
 .../apache/ignite/internal/IgniteKernal.java    |    6 +-
 .../org/apache/ignite/internal/IgnitionEx.java  |    1 +
 .../internal/binary/BinaryClassDescriptor.java  |    1 +
 .../ignite/internal/binary/BinaryContext.java   |   58 +-
 .../internal/binary/BinaryWriterExImpl.java     |   16 +-
 .../GridClientOptimizedMarshaller.java          |    2 +-
 .../GridClientZipOptimizedMarshaller.java       |    2 +-
 .../internal/jdbc/thin/JdbcConnection.java      |  529 +++++
 .../ignite/internal/jdbc/thin/JdbcTcpIo.java    |  207 ++
 .../ignite/internal/jdbc2/JdbcConnection.java   |    3 +-
 .../managers/communication/GridIoManager.java   |  380 +++-
 .../communication/IgniteIoTestMessage.java      |  362 ++-
 .../managers/indexing/GridIndexingManager.java  |   19 +-
 .../optimized/OptimizedClassDescriptor.java     |    2 +-
 .../optimized/OptimizedMarshaller.java          |    2 +-
 .../marshaller/optimized/package-info.java      |   22 +
 .../mem/unsafe/UnsafeMemoryProvider.java        |   18 +-
 .../pagemem/impl/PageMemoryNoStoreImpl.java     |   22 +-
 .../processors/cache/GridCacheMapEntry.java     |    4 +-
 .../processors/cache/IgniteCacheProxy.java      |   24 +-
 .../processors/cache/QueryCursorImpl.java       |   19 +-
 .../IgniteCacheDatabaseSharedManager.java       |   51 +-
 .../cache/database/tree/BPlusTree.java          |   64 +-
 .../cache/query/GridCacheQueryManager.java      |   32 +-
 .../processors/odbc/OdbcNioListener.java        |  242 --
 .../internal/processors/odbc/OdbcProcessor.java |  199 --
 .../odbc/SqlListenerAbstractMessageParser.java  |  265 +++
 .../odbc/SqlListenerAbstractObjectReader.java   |  137 ++
 .../odbc/SqlListenerAbstractObjectWriter.java   |  111 +
 .../processors/odbc/SqlListenerNioListener.java |  263 +++
 .../processors/odbc/SqlListenerProcessor.java   |  191 ++
 .../odbc/SqlListenerRequestHandlerImpl.java     |  494 ++++
 .../processors/odbc/jdbc/JdbcMessageParser.java |   50 +
 .../processors/odbc/jdbc/JdbcObjectReader.java  |   33 +
 .../processors/odbc/jdbc/JdbcObjectWriter.java  |   33 +
 .../processors/odbc/odbc/OdbcMessageParser.java |  249 +-
 .../processors/odbc/odbc/OdbcObjectReader.java  |   33 +
 .../processors/odbc/odbc/OdbcObjectWriter.java  |   32 +
 .../odbc/odbc/OdbcRequestHandler.java           |  513 -----
 .../processors/query/GridQueryIndexing.java     |  101 +-
 .../processors/query/GridQueryProcessor.java    |  312 +--
 .../processors/query/QueryIndexKey.java         |   20 +-
 .../query/QueryTypeDescriptorImpl.java          |   16 +-
 .../processors/query/QueryTypeIdKey.java        |   26 +-
 .../processors/query/QueryTypeNameKey.java      |   12 +-
 .../internal/processors/query/QueryUtils.java   |   14 +-
 .../schema/SchemaIndexCacheVisitorImpl.java     |   12 +-
 .../processors/query/schema/SchemaKey.java      |   59 -
 .../message/SchemaProposeDiscoveryMessage.java  |    7 +-
 .../operation/SchemaAbstractOperation.java      |   27 +-
 .../operation/SchemaIndexAbstractOperation.java |    7 +-
 .../operation/SchemaIndexCreateOperation.java   |    8 +-
 .../operation/SchemaIndexDropOperation.java     |    7 +-
 .../handlers/GridRestCommandHandlerAdapter.java |    3 +
 .../handlers/cache/GridCacheCommandHandler.java |    2 +-
 .../handlers/query/QueryCommandHandler.java     |   13 +-
 .../ignite/internal/util/IgniteUtils.java       |   17 +
 .../apache/ignite/marshaller/Marshaller.java    |    3 -
 .../ignite/marshaller/jdk/JdkMarshaller.java    |    5 +-
 .../spi/indexing/IndexingQueryFilter.java       |    8 +-
 .../apache/ignite/spi/indexing/IndexingSpi.java |   17 +-
 .../spi/indexing/noop/NoopIndexingSpi.java      |    6 +-
 modules/core/src/test/config/example-cache.xml  |    5 +-
 .../src/test/config/spring-start-nodes-attr.xml |    4 +-
 .../core/src/test/config/spring-start-nodes.xml |    4 +-
 .../config/websession/example-cache-base.xml    |    5 +-
 .../IgniteExternalizableAbstractTest.java       |   15 +-
 ...dbcPojoStoreOptimizedMarshallerSelfTest.java |   31 -
 ...ptimizedMarshallerWithSqlEscapeSelfTest.java |   28 -
 .../apache/ignite/igfs/IgfsPathSelfTest.java    |    7 +-
 .../internal/GridLifecycleAwareSelfTest.java    |    3 +-
 .../BinarySimpleNameTestPropertySelfTest.java   |   17 +
 .../managers/GridManagerStopSelfTest.java       |    3 +-
 .../GridDiscoveryManagerAttributesSelfTest.java |    2 +-
 .../optimized/OptimizedMarshallerTest.java      |    8 +
 .../marshaller/optimized/package-info.java      |   22 +
 .../pagemem/impl/PageMemoryNoLoadSelfTest.java  |   31 +-
 .../AtomicCacheAffinityConfigurationTest.java   |  175 ++
 .../CacheStartupInDeploymentModesTest.java      |   37 -
 .../cache/GridCacheEntryMemorySizeSelfTest.java |    2 +-
 ...ridCacheStoreManagerDeserializationTest.java |    4 +-
 .../cache/GridCacheVersionSelfTest.java         |    7 +-
 .../IgniteTxExceptionAbstractSelfTest.java      |    6 +-
 .../distributed/CacheAffinityEarlyTest.java     |    7 +-
 .../CacheGetFutureHangsSelfTest.java            |    6 +-
 .../IgniteCacheCreatePutMultiNodeSelfTest.java  |    7 +-
 .../distributed/IgniteCacheCreatePutTest.java   |    7 +-
 .../IgniteCachePartitionLossPolicySelfTest.java |    1 +
 .../paged/PageEvictionMultinodeTest.java        |   22 +-
 .../cache/query/IndexingSpiQuerySelfTest.java   |   14 +-
 .../cache/query/IndexingSpiQueryTxSelfTest.java |    6 +-
 .../CacheEntryProcessorNonSerializableTest.java |    5 +-
 .../igfs/IgfsAbstractBaseSelfTest.java          |   10 -
 .../processors/igfs/IgfsFileInfoSelfTest.java   |   16 +-
 .../IgfsPrimaryOptimziedMarshallerSelfTest.java |   28 -
 .../odbc/OdbcProcessorValidationSelfTest.java   |  182 --
 .../SqlListenerProcessorValidationSelfTest.java |  184 ++
 .../service/ClosureServiceClientsNodesTest.java |    4 +-
 ...namicProxySerializationMultiJvmSelfTest.java |   13 -
 .../GridMarshallerPerformanceTest.java          |    8 +-
 .../IgniteMessagingWithClientTest.java          |    4 +-
 ...pClientDiscoveryMarshallerCheckSelfTest.java |    4 +-
 .../TcpDiscoveryMarshallerCheckSelfTest.java    |    4 +-
 .../ignite/testframework/GridTestUtils.java     |    2 +-
 .../config/GridTestProperties.java              |    3 +-
 .../configvariations/ConfigVariations.java      |   14 +-
 .../testframework/junits/GridAbstractTest.java  |   33 +
 .../junits/IgniteTestResources.java             |    8 +-
 .../multijvm/IgniteCacheProcessProxy.java       |    8 +
 ...naryObjectsTxDeadlockDetectionTestSuite.java |   37 -
 .../ignite/testsuites/IgniteBasicTestSuite.java |    4 +-
 .../testsuites/IgniteBinaryBasicTestSuite.java  |   14 +-
 .../IgniteBinaryCacheFullApiTestSuite.java      |   37 -
 .../testsuites/IgniteBinaryCacheTestSuite.java  |    4 -
 ...ObjectsCacheDataStructuresSelfTestSuite.java |   42 -
 ...BinaryObjectsCacheExpiryPolicyTestSuite.java |   38 -
 ...gniteBinaryObjectsCacheRestartTestSuite.java |   37 -
 .../IgniteBinaryObjectsCacheTestSuite2.java     |   37 -
 .../IgniteBinaryObjectsCacheTestSuite3.java     |    2 -
 .../IgniteBinaryObjectsCacheTestSuite4.java     |   37 -
 ...IgniteBinaryObjectsComputeGridTestSuite.java |    4 -
 .../IgniteCacheDataStructuresSelfTestSuite.java |    3 +
 .../ignite/testsuites/IgniteCacheTestSuite.java |    4 -
 ...teBasicConfigVariationsFullApiTestSuite.java |    2 +-
 .../ignite/testsuites/IgniteIgfsTestSuite.java  |    3 -
 .../testsuites/IgniteKernalSelfTestSuite.java   |    4 -
 .../IgniteMarshallerSelfTestSuite.java          |    8 +-
 ...essagingConfigVariationFullApiTestSuite.java |    2 +-
 ...ServiceConfigVariationsFullApiTestSuite.java |    2 +-
 .../webapp/META-INF/ignite-webapp-config.xml    |   15 +-
 .../test/config/hadoop-fs-open-test/grid-0.xml  |    3 +-
 .../test/config/hadoop-fs-open-test/grid-1.xml  |    3 +-
 .../test/config/hadoop-fs-open-test/grid-2.xml  |    3 +-
 .../test/config/igfs-cli-config-dual-async.xml  |    3 +-
 .../test/config/igfs-cli-config-dual-sync.xml   |    3 +-
 .../src/test/config/igfs-cli-config-primary.xml |    3 +-
 .../src/test/config/igfs-cli-config-proxy.xml   |    3 +-
 .../IgniteHadoopFileSystemAbstractSelfTest.java |    4 +-
 .../query/h2/DmlStatementsProcessor.java        |   71 +-
 .../query/h2/GridH2ResultSetIterator.java       |  191 --
 .../query/h2/H2ConnectionWrapper.java           |   67 +
 .../processors/query/h2/H2DatabaseType.java     |  161 ++
 .../processors/query/h2/H2FieldsIterator.java   |   50 +
 .../processors/query/h2/H2KeyValueIterator.java |   48 +
 .../query/h2/H2ResultSetIterator.java           |  191 ++
 .../processors/query/h2/H2RowDescriptor.java    |  479 ++++
 .../internal/processors/query/h2/H2Schema.java  |  135 ++
 .../processors/query/h2/H2SqlFieldMetadata.java |  111 +
 .../processors/query/h2/H2StatementCache.java   |   73 +
 .../processors/query/h2/H2TableDescriptor.java  |  345 +++
 .../processors/query/h2/H2TableEngine.java      |   89 +
 .../query/h2/H2TwoStepCachedQuery.java          |   49 +
 .../query/h2/H2TwoStepCachedQueryKey.java       |  107 +
 .../internal/processors/query/h2/H2Utils.java   |  299 +++
 .../processors/query/h2/IgniteH2Indexing.java   | 2146 +++---------------
 .../query/h2/database/H2PkHashIndex.java        |    4 +-
 .../query/h2/database/H2TreeIndex.java          |    4 +-
 .../query/h2/ddl/DdlStatementsProcessor.java    |   25 +-
 .../query/h2/opt/GridH2CollocationModel.java    |    6 +-
 .../query/h2/opt/GridH2IndexBase.java           |   12 +-
 .../processors/query/h2/opt/GridH2Table.java    |  149 +-
 .../query/h2/opt/GridH2TreeIndex.java           |    2 +-
 .../query/h2/opt/GridLuceneIndex.java           |   15 +-
 .../query/h2/sql/GridSqlDropIndex.java          |   14 +-
 .../query/h2/sql/GridSqlQueryParser.java        |    2 +-
 .../query/h2/sql/GridSqlQuerySplitter.java      |    4 +-
 .../query/h2/twostep/GridMapQueryExecutor.java  |   10 +-
 .../h2/twostep/GridReduceQueryExecutor.java     |   31 +-
 .../cache/GridCacheCrossCacheQuerySelfTest.java |   12 +-
 .../cache/IgniteCacheNoClassQuerySelfTest.java  |    4 +-
 .../cache/SqlFieldsQuerySelfTest.java           |   12 +-
 .../DynamicIndexAbstractBasicSelfTest.java      |   26 +-
 .../DynamicIndexAbstractConcurrentSelfTest.java |   74 +-
 .../cache/index/SchemaExchangeSelfTest.java     |    2 +-
 .../query/IgniteQueryDedicatedPoolTest.java     |    6 +-
 .../query/IgniteSqlSegmentedIndexSelfTest.java  |   25 +
 .../h2/GridIndexingSpiAbstractSelfTest.java     |  140 +-
 .../h2/sql/AbstractH2CompareQueryTest.java      |    4 +-
 .../query/h2/sql/GridQueryParsingTest.java      |    6 +-
 .../FetchingQueryCursorStressTest.java          |    4 +-
 .../IgniteBinaryCacheQueryTestSuite.java        |    4 -
 .../IgniteBinaryCacheQueryTestSuite2.java       |    4 -
 .../IgniteBinaryCacheQueryTestSuite3.java       |   39 -
 .../IgniteBinaryCacheQueryTestSuite4.java       |   39 -
 .../cpp/odbc/include/ignite/odbc/message.h      |   10 +
 .../Apache.Ignite.Core.Tests/MarshallerTest.cs  |    2 +-
 .../GridSpringBeanSerializationSelfTest.java    |   15 +-
 .../webapp2/META-INF/ignite-webapp-config.xml   |   15 +-
 .../ignite-int-max-values-onheap-config.xml     |    4 +-
 modules/yardstick/config/ignite-jdbc-config.xml |    4 +-
 209 files changed, 7872 insertions(+), 5023 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCachePartitionLossPolicySelfTest.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/core/src/test/java/org/apache/ignite/testframework/junits/GridAbstractTest.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
----------------------------------------------------------------------
diff --cc modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
index bba5fca,a31263f..2ed5200
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
@@@ -1049,12 -1052,12 +1052,12 @@@ public class GridReduceQueryExecutor 
      private Set<ClusterNode> replicatedUnstableDataNodes(GridCacheContext<?,?> cctx) {
          assert cctx.isReplicated() : cctx.name() + " must be replicated";
  
-         String space = cctx.name();
+         String cacheName = cctx.name();
  
 -        Set<ClusterNode> dataNodes = new HashSet<>(dataNodes(cacheName, NONE));
 +        Set<ClusterNode> dataNodes = new HashSet<>(dataNodes(cctx.groupId(), NONE));
  
          if (dataNodes.isEmpty())
-             throw new CacheException("Failed to find data nodes for cache: " + space);
+             throw new CacheException("Failed to find data nodes for cache: " + cacheName);
  
          // Find all the nodes owning all the partitions for replicated cache.
          for (int p = 0, parts = cctx.affinity().partitions(); p < parts; p++) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/ca176a7d/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
----------------------------------------------------------------------
diff --cc modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
index d50cb4c,e0148b3..770770e
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheNoClassQuerySelfTest.java
@@@ -24,7 -26,8 +24,7 @@@ import org.apache.ignite.cache.QueryEnt
  import org.apache.ignite.cache.QueryIndex;
  import org.apache.ignite.configuration.CacheConfiguration;
  import org.apache.ignite.configuration.IgniteConfiguration;
- import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 -import org.apache.ignite.configuration.NearCacheConfiguration;
+ import org.apache.ignite.internal.binary.BinaryMarshaller;
  import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
  import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
  import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;


[04/31] ignite git commit: IGNITE-5248 - Detect a 32-bit JVM using too large init page size. Closes #1976

Posted by sb...@apache.org.
IGNITE-5248 - Detect a 32-bit JVM using too large init page size. Closes #1976


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/c5a04da7
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/c5a04da7
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/c5a04da7

Branch: refs/heads/ignite-5075
Commit: c5a04da7103701d4ee95910d90ba786a6ea5750b
Parents: 2110994
Author: Wuwei Lin <vi...@gmail.com>
Authored: Tue May 23 11:35:24 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue May 23 11:35:24 2017 +0300

----------------------------------------------------------------------
 .../mem/unsafe/UnsafeMemoryProvider.java        | 18 +++++++++++++-
 .../IgniteCacheDatabaseSharedManager.java       | 25 ++++++++++++++++++--
 .../ignite/internal/util/IgniteUtils.java       | 17 +++++++++++++
 3 files changed, 57 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/c5a04da7/modules/core/src/main/java/org/apache/ignite/internal/mem/unsafe/UnsafeMemoryProvider.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/mem/unsafe/UnsafeMemoryProvider.java b/modules/core/src/main/java/org/apache/ignite/internal/mem/unsafe/UnsafeMemoryProvider.java
index ef101d0..bf6e807 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/mem/unsafe/UnsafeMemoryProvider.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/mem/unsafe/UnsafeMemoryProvider.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.mem.unsafe;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.mem.DirectMemoryProvider;
 import org.apache.ignite.internal.mem.DirectMemoryRegion;
@@ -73,7 +74,22 @@ public class UnsafeMemoryProvider implements DirectMemoryProvider {
 
         long chunkSize = sizes[regions.size()];
 
-        long ptr = GridUnsafe.allocateMemory(chunkSize);
+        long ptr;
+
+        try {
+            ptr = GridUnsafe.allocateMemory(chunkSize);
+        }
+        catch (IllegalArgumentException e) {
+            String msg = "Failed to allocate next memory chunk: " + U.readableSize(chunkSize, true) +
+                ". Check if chunkSize is too large and 32-bit JVM is used.";
+
+            if (regions.size() == 0)
+                throw new IgniteException(msg, e);
+
+            U.error(log, msg);
+
+            return null;
+        }
 
         if (ptr <= 0) {
             U.error(log, "Failed to allocate next memory chunk: " + U.readableSize(chunkSize, true));

http://git-wip-us.apache.org/repos/asf/ignite/blob/c5a04da7/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
index 7151b2f..fbb3b0f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
@@ -72,6 +72,9 @@ public class IgniteCacheDatabaseSharedManager extends GridCacheSharedManagerAdap
     /** Minimum size of memory chunk */
     private static final long MIN_PAGE_MEMORY_SIZE = 10 * 1024 * 1024;
 
+    /** Maximum initial size on 32-bit JVM */
+    private static final long MAX_PAGE_MEMORY_INIT_SIZE_32_BIT = 2L * 1024 * 1024 * 1024;
+
     /** */
     protected Map<String, MemoryPolicy> memPlcMap;
 
@@ -354,8 +357,14 @@ public class IgniteCacheDatabaseSharedManager extends GridCacheSharedManagerAdap
     private void checkSystemMemoryPolicySizeConfiguration(long sysCacheInitSize, long sysCacheMaxSize) throws IgniteCheckedException {
         if (sysCacheInitSize < MIN_PAGE_MEMORY_SIZE)
             throw new IgniteCheckedException("Initial size for system cache must have size more than 10MB (use " +
-                "MemoryConfiguration.systemCacheInitialSize property to set correct size in bytes); " +
-                "size: " + U.readableSize(sysCacheInitSize, true)
+                "MemoryConfiguration.systemCacheInitialSize property to set correct size in bytes) " +
+                "[size=" + U.readableSize(sysCacheInitSize, true) + ']'
+            );
+
+        if (U.jvm32Bit() && sysCacheInitSize > MAX_PAGE_MEMORY_INIT_SIZE_32_BIT)
+            throw new IgniteCheckedException("Initial size for system cache exceeds 2GB on 32-bit JVM (use " +
+                "MemoryPolicyConfiguration.systemCacheInitialSize property to set correct size in bytes " +
+                "or use 64-bit JVM) [size=" + U.readableSize(sysCacheInitSize, true) + ']'
             );
 
         if (sysCacheMaxSize < sysCacheInitSize)
@@ -388,6 +397,12 @@ public class IgniteCacheDatabaseSharedManager extends GridCacheSharedManagerAdap
             if (dfltPlcSize < MIN_PAGE_MEMORY_SIZE)
                 throw new IgniteCheckedException("User-defined default MemoryPolicy size is less than 1MB. " +
                         "Use MemoryConfiguration.defaultMemoryPolicySize property to set correct size.");
+
+            if (U.jvm32Bit() && dfltPlcSize > MAX_PAGE_MEMORY_INIT_SIZE_32_BIT)
+                throw new IgniteCheckedException("User-defined default MemoryPolicy size exceeds 2GB on 32-bit JVM " +
+                    "(use MemoryConfiguration.defaultMemoryPolicySize property to set correct size in bytes " +
+                    "or use 64-bit JVM) [size=" + U.readableSize(dfltPlcSize, true) + ']'
+                );
         }
 
         if (!DFLT_MEM_PLC_DEFAULT_NAME.equals(dfltPlcName)) {
@@ -416,6 +431,12 @@ public class IgniteCacheDatabaseSharedManager extends GridCacheSharedManagerAdap
                 "initialSize [name=" + plcCfg.getName() +
                 ", initSize=" + U.readableSize(plcCfg.getInitialSize(), true) +
                 ", maxSize=" + U.readableSize(plcCfg.getMaxSize(), true) + ']');
+
+        if (U.jvm32Bit() && plcCfg.getInitialSize() > MAX_PAGE_MEMORY_INIT_SIZE_32_BIT)
+            throw new IgniteCheckedException("MemoryPolicy initialSize exceeds 2GB on 32-bit JVM (use " +
+                "MemoryPolicyConfiguration.initialSize property to set correct size in bytes or use 64-bit JVM) " +
+                "[name=" + plcCfg.getName() +
+                ", size=" + U.readableSize(plcCfg.getInitialSize(), true) + "]");
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/c5a04da7/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
index 0668708..4e9d0c7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
@@ -416,6 +416,9 @@ public abstract class IgniteUtils {
     /** Name of the JVM implementation. */
     private static String jvmImplName;
 
+    /** Will be set to {@code true} if detected a 32-bit JVM. */
+    private static boolean jvm32Bit;
+
     /** JMX domain as 'xxx.apache.ignite'. */
     public static final String JMX_DOMAIN = IgniteUtils.class.getName().substring(0, IgniteUtils.class.getName().
         indexOf('.', IgniteUtils.class.getName().indexOf('.') + 1));
@@ -607,6 +610,9 @@ public abstract class IgniteUtils {
         String jvmImplVendor = System.getProperty("java.vm.vendor");
         String jvmImplName = System.getProperty("java.vm.name");
 
+        // Best effort to detect a 32-bit JVM.
+        String jvmArchDataModel = System.getProperty("sun.arch.data.model");
+
         String jdkStr = javaRtName + ' ' + javaRtVer + ' ' + jvmImplVendor + ' ' + jvmImplName + ' ' +
             jvmImplVer;
 
@@ -628,6 +634,8 @@ public abstract class IgniteUtils {
         IgniteUtils.javaRtName = javaRtName;
         IgniteUtils.javaRtVer = javaRtVer;
 
+        jvm32Bit = "32".equals(jvmArchDataModel);
+
         primitiveMap.put("byte", byte.class);
         primitiveMap.put("short", short.class);
         primitiveMap.put("int", int.class);
@@ -6509,6 +6517,15 @@ public abstract class IgniteUtils {
     }
 
     /**
+     * Does a best effort to detect if we a running on a 32-bit JVM.
+     *
+     * @return {@code true} if detected that we are running on a 32-bit JVM.
+     */
+    public static boolean jvm32Bit() {
+        return jvm32Bit;
+    }
+
+    /**
      * Compare java implementation version
      *
      * @param v1 - java implementation version


[29/31] ignite git commit: IGNITE-5284: Splitted IgniteH2Indexing into several classes. This closes #1999.

Posted by sb...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java
new file mode 100644
index 0000000..75d739d
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java
@@ -0,0 +1,299 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2IndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.util.GridStringBuilder;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.SB;
+import org.h2.engine.Session;
+import org.h2.jdbc.JdbcConnection;
+import org.h2.result.SortOrder;
+import org.h2.table.IndexColumn;
+
+import java.lang.reflect.Constructor;
+import java.sql.Connection;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * H2 utility methods.
+ */
+public class H2Utils {
+    /** Spatial index class name. */
+    private static final String SPATIAL_IDX_CLS =
+        "org.apache.ignite.internal.processors.query.h2.opt.GridH2SpatialIndex";
+
+    /** */
+    public static final char ESC_CH = '\"';
+
+    /** */
+    private static final String ESC_STR = ESC_CH + "" + ESC_CH;
+
+    /**
+     * @param c1 First column.
+     * @param c2 Second column.
+     * @return {@code true} If they are the same.
+     */
+    public static boolean equals(IndexColumn c1, IndexColumn c2) {
+        return c1.column.getColumnId() == c2.column.getColumnId();
+    }
+
+    /**
+     * @param cols Columns list.
+     * @param col Column to find.
+     * @return {@code true} If found.
+     */
+    public static boolean containsColumn(List<IndexColumn> cols, IndexColumn col) {
+        for (int i = cols.size() - 1; i >= 0; i--) {
+            if (equals(cols.get(i), col))
+                return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Check whether columns list contains key or key alias column.
+     *
+     * @param desc Row descriptor.
+     * @param cols Columns list.
+     * @return Result.
+     */
+    public static boolean containsKeyColumn(GridH2RowDescriptor desc, List<IndexColumn> cols) {
+        for (int i = cols.size() - 1; i >= 0; i--) {
+            if (desc.isKeyColumn(cols.get(i).column.getColumnId()))
+                return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Generate {@code CREATE INDEX} SQL statement for given params.
+     * @param fullTblName Fully qualified table name.
+     * @param h2Idx H2 index.
+     * @param ifNotExists Quietly skip index creation if it exists.
+     * @return Statement string.
+     */
+    public static String indexCreateSql(String fullTblName, GridH2IndexBase h2Idx, boolean ifNotExists,
+        boolean escapeAll) {
+        boolean spatial = F.eq(SPATIAL_IDX_CLS, h2Idx.getClass().getName());
+
+        GridStringBuilder sb = new SB("CREATE ")
+            .a(spatial ? "SPATIAL " : "")
+            .a("INDEX ")
+            .a(ifNotExists ? "IF NOT EXISTS " : "")
+            .a(escapeName(h2Idx.getName(), escapeAll))
+            .a(" ON ")
+            .a(fullTblName)
+            .a(" (");
+
+        boolean first = true;
+
+        for (IndexColumn col : h2Idx.getIndexColumns()) {
+            if (first)
+                first = false;
+            else
+                sb.a(", ");
+
+            sb.a("\"" + col.columnName + "\"").a(" ").a(col.sortType == SortOrder.ASCENDING ? "ASC" : "DESC");
+        }
+
+        sb.a(')');
+
+        return sb.toString();
+    }
+
+    /**
+     * Generate {@code CREATE INDEX} SQL statement for given params.
+     * @param schemaName <b>Quoted</b> schema name.
+     * @param idxName Index name.
+     * @param ifExists Quietly skip index drop if it exists.
+     * @param escapeAll Escape flag.
+     * @return Statement string.
+     */
+    public static String indexDropSql(String schemaName, String idxName, boolean ifExists, boolean escapeAll) {
+        return "DROP INDEX " + (ifExists ? "IF EXISTS " : "") + schemaName + '.' + escapeName(idxName, escapeAll);
+    }
+
+    /**
+     * Escapes name to be valid SQL identifier. Currently just replaces '.' and '$' sign with '_'.
+     *
+     * @param name Name.
+     * @param escapeAll Escape flag.
+     * @return Escaped name.
+     */
+    public static String escapeName(String name, boolean escapeAll) {
+        if (name == null) // It is possible only for a cache name.
+            return ESC_STR;
+
+        if (escapeAll)
+            return ESC_CH + name + ESC_CH;
+
+        SB sb = null;
+
+        for (int i = 0; i < name.length(); i++) {
+            char ch = name.charAt(i);
+
+            if (!Character.isLetter(ch) && !Character.isDigit(ch) && ch != '_' &&
+                !(ch == '"' && (i == 0 || i == name.length() - 1)) && ch != '-') {
+                // Class name can also contain '$' or '.' - these should be escaped.
+                assert ch == '$' || ch == '.';
+
+                if (sb == null)
+                    sb = new SB();
+
+                sb.a(name.substring(sb.length(), i));
+
+                // Replace illegal chars with '_'.
+                sb.a('_');
+            }
+        }
+
+        if (sb == null)
+            return name;
+
+        sb.a(name.substring(sb.length(), name.length()));
+
+        return sb.toString();
+    }
+
+    /**
+     * @param desc Row descriptor.
+     * @param cols Columns list.
+     * @param keyCol Primary key column.
+     * @param affCol Affinity key column.
+     * @return The same list back.
+     */
+    public static List<IndexColumn> treeIndexColumns(GridH2RowDescriptor desc, List<IndexColumn> cols,
+        IndexColumn keyCol, IndexColumn affCol) {
+        assert keyCol != null;
+
+        if (!containsKeyColumn(desc, cols))
+            cols.add(keyCol);
+
+        if (affCol != null && !containsColumn(cols, affCol))
+            cols.add(affCol);
+
+        return cols;
+    }
+
+    /**
+     * Create spatial index.
+     *
+     * @param tbl Table.
+     * @param idxName Index name.
+     * @param cols Columns.
+     */
+    public static GridH2IndexBase createSpatialIndex(GridH2Table tbl, String idxName, IndexColumn[] cols) {
+        try {
+            Class<?> cls = Class.forName(SPATIAL_IDX_CLS);
+
+            Constructor<?> ctor = cls.getConstructor(
+                GridH2Table.class,
+                String.class,
+                Integer.TYPE,
+                IndexColumn[].class);
+
+            if (!ctor.isAccessible())
+                ctor.setAccessible(true);
+
+            final int segments = tbl.rowDescriptor().configuration().getQueryParallelism();
+
+            return (GridH2IndexBase)ctor.newInstance(tbl, idxName, segments, cols);
+        }
+        catch (Exception e) {
+            throw new IgniteException("Failed to instantiate: " + SPATIAL_IDX_CLS, e);
+        }
+    }
+
+    /**
+     * Stores rule for constructing schemaName according to cache configuration.
+     *
+     * @param ccfg Cache configuration.
+     * @return Proper schema name according to ANSI-99 standard.
+     */
+    public static String schemaNameFromCacheConfiguration(CacheConfiguration<?, ?> ccfg) {
+        if (ccfg.getSqlSchema() == null)
+            return escapeName(ccfg.getName(), true);
+
+        if (ccfg.getSqlSchema().charAt(0) == ESC_CH)
+            return ccfg.getSqlSchema();
+
+        return ccfg.isSqlEscapeAll() ?
+            escapeName(ccfg.getSqlSchema(), true) : ccfg.getSqlSchema().toUpperCase();
+    }
+
+    /**
+     * @param rsMeta Metadata.
+     * @return List of fields metadata.
+     * @throws SQLException If failed.
+     */
+    public static List<GridQueryFieldMetadata> meta(ResultSetMetaData rsMeta) throws SQLException {
+        List<GridQueryFieldMetadata> meta = new ArrayList<>(rsMeta.getColumnCount());
+
+        for (int i = 1; i <= rsMeta.getColumnCount(); i++) {
+            String schemaName = rsMeta.getSchemaName(i);
+            String typeName = rsMeta.getTableName(i);
+            String name = rsMeta.getColumnLabel(i);
+            String type = rsMeta.getColumnClassName(i);
+
+            if (type == null) // Expression always returns NULL.
+                type = Void.class.getName();
+
+            meta.add(new H2SqlFieldMetadata(schemaName, typeName, name, type));
+        }
+
+        return meta;
+    }
+
+    /**
+     * @param c Connection.
+     * @return Session.
+     */
+    public static Session session(Connection c) {
+        return (Session)((JdbcConnection)c).getSession();
+    }
+
+    /**
+     * @param conn Connection to use.
+     * @param distributedJoins If distributed joins are enabled.
+     * @param enforceJoinOrder Enforce join order of tables.
+     */
+    public static void setupConnection(Connection conn, boolean distributedJoins, boolean enforceJoinOrder) {
+        Session s = session(conn);
+
+        s.setForceJoinOrder(enforceJoinOrder);
+        s.setJoinBatchEnabled(distributedJoins);
+    }
+
+    /**
+     * Private constructor.
+     */
+    private H2Utils() {
+        // No-op.
+    }
+}


[10/31] ignite git commit: Fixed segmented indices snapshots. - Fixes #1936.

Posted by sb...@apache.org.
Fixed segmented indices snapshots. - Fixes #1936.

Signed-off-by: Sergi Vladykin <se...@gmail.com>


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/1554a160
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/1554a160
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/1554a160

Branch: refs/heads/ignite-5075
Commit: 1554a1606244b46f042ecbf6aeb7eb09c3a2abb8
Parents: 647fd19
Author: Andrey V. Mashenkov <an...@gmail.com>
Authored: Tue May 23 15:26:00 2017 +0300
Committer: Sergi Vladykin <se...@gmail.com>
Committed: Tue May 23 15:26:00 2017 +0300

----------------------------------------------------------------------
 .../processors/query/h2/opt/GridH2Table.java    | 107 ++++++++++++-------
 .../query/h2/twostep/GridMapQueryExecutor.java  |   2 +-
 .../query/IgniteSqlSegmentedIndexSelfTest.java  |  25 +++++
 3 files changed, 93 insertions(+), 41 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/1554a160/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
index 41cf68b..ec728de 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
@@ -23,7 +23,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicReferenceArray;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -74,6 +74,9 @@ public class GridH2Table extends TableBase {
     private volatile ArrayList<Index> idxs;
 
     /** */
+    private final int pkIndexPos;
+
+    /** */
     private final Map<String, GridH2IndexBase> tmpIdxs = new HashMap<>();
 
     /** */
@@ -86,7 +89,7 @@ public class GridH2Table extends TableBase {
     private final ConcurrentMap<Session, Boolean> sessions = new ConcurrentHashMap8<>();
 
     /** */
-    private final AtomicReference<Object[]> actualSnapshot = new AtomicReference<>();
+    private final AtomicReferenceArray<Object[]> actualSnapshot;
 
     /** */
     private IndexColumn affKeyCol;
@@ -164,21 +167,31 @@ public class GridH2Table extends TableBase {
         assert idxs != null;
 
         List<Index> clones = new ArrayList<>(idxs.size());
-        for (Index index: idxs) {
+        for (Index index : idxs) {
             Index clone = createDuplicateIndexIfNeeded(index);
             if (clone != null)
-               clones.add(clone);
+                clones.add(clone);
         }
         idxs.addAll(clones);
 
+        boolean hasHashIndex = idxs.size() >= 2 && index(0).getIndexType().isHash();
+
         // Add scan index at 0 which is required by H2.
-        if (idxs.size() >= 2 && index(0).getIndexType().isHash())
+        if (hasHashIndex)
             idxs.add(0, new GridH2PrimaryScanIndex(this, index(1), index(0)));
         else
             idxs.add(0, new GridH2PrimaryScanIndex(this, index(0), null));
 
         snapshotEnabled = desc == null || desc.snapshotableIndex();
 
+        pkIndexPos = hasHashIndex ? 2 : 1;
+
+        final int segments = desc != null ? desc.configuration().getQueryParallelism() :
+            // Get index segments count from PK index. Null desc can be passed from tests.
+            index(pkIndexPos).segmentsCount();
+
+        actualSnapshot = snapshotEnabled ? new AtomicReferenceArray<Object[]>(Math.max(segments, 1)) : null;
+
         lock = new ReentrantReadWriteLock();
     }
 
@@ -233,8 +246,13 @@ public class GridH2Table extends TableBase {
             throw new IllegalStateException("Table " + identifierString() + " already destroyed.");
         }
 
-        if (snapshotInLock())
-            snapshotIndexes(null);
+        if (snapshotInLock()) {
+            final GridH2QueryContext qctx = GridH2QueryContext.get();
+
+            assert qctx != null;
+
+            snapshotIndexes(null, qctx.segment());
+        }
 
         return false;
     }
@@ -255,21 +273,22 @@ public class GridH2Table extends TableBase {
 
     /**
      * @param qctx Query context.
+     * @param segment id of index segment to be snapshoted.
      */
-    public void snapshotIndexes(GridH2QueryContext qctx) {
+    public void snapshotIndexes(GridH2QueryContext qctx, int segment) {
         if (!snapshotEnabled)
             return;
 
-        Object[] snapshots;
+        Object[] segmentSnapshot;
 
         // Try to reuse existing snapshots outside of the lock.
-        for (long waitTime = 200;; waitTime *= 2) { // Increase wait time to avoid starvation.
-            snapshots = actualSnapshot.get();
+        for (long waitTime = 200; ; waitTime *= 2) { // Increase wait time to avoid starvation.
+            segmentSnapshot = actualSnapshot.get(segment);
 
-            if (snapshots != null) { // Reuse existing snapshot without locking.
-                snapshots = doSnapshotIndexes(snapshots, qctx);
+            if (segmentSnapshot != null) { // Reuse existing snapshot without locking.
+                segmentSnapshot = doSnapshotIndexes(segment, segmentSnapshot, qctx);
 
-                if (snapshots != null)
+                if (segmentSnapshot != null)
                     return; // Reused successfully.
             }
 
@@ -281,17 +300,17 @@ public class GridH2Table extends TableBase {
             ensureNotDestroyed();
 
             // Try again inside of the lock.
-            snapshots = actualSnapshot.get();
+            segmentSnapshot = actualSnapshot.get(segment);
 
-            if (snapshots != null) // Try reusing.
-                snapshots = doSnapshotIndexes(snapshots, qctx);
+            if (segmentSnapshot != null) // Try reusing.
+                segmentSnapshot = doSnapshotIndexes(segment, segmentSnapshot, qctx);
 
-            if (snapshots == null) { // Reuse failed, produce new snapshots.
-                snapshots = doSnapshotIndexes(null, qctx);
+            if (segmentSnapshot == null) { // Reuse failed, produce new snapshots.
+                segmentSnapshot = doSnapshotIndexes(segment,null, qctx);
 
-                assert snapshots != null;
+                assert segmentSnapshot != null;
 
-                actualSnapshot.set(snapshots);
+                actualSnapshot.set(segment, segmentSnapshot);
             }
         }
         finally {
@@ -375,19 +394,22 @@ public class GridH2Table extends TableBase {
      * Must be called inside of write lock because when using multiple indexes we have to ensure that all of them have
      * the same contents at snapshot taking time.
      *
+     * @param segment id of index segment snapshot.
+     * @param segmentSnapshot snapshot to be reused.
      * @param qctx Query context.
      * @return New indexes data snapshot.
      */
     @SuppressWarnings("unchecked")
-    private Object[] doSnapshotIndexes(Object[] snapshots, GridH2QueryContext qctx) {
+    private Object[] doSnapshotIndexes(int segment, Object[] segmentSnapshot, GridH2QueryContext qctx) {
         assert snapshotEnabled;
 
-        if (snapshots == null) // Nothing to reuse, create new snapshots.
-            snapshots = new Object[idxs.size() - 2];
+        //TODO: make HashIndex snapshotable or remove it at all?
+        if (segmentSnapshot == null) // Nothing to reuse, create new snapshots.
+            segmentSnapshot = new Object[idxs.size() - pkIndexPos];
 
-        // Take snapshots on all except first which is scan and second which is hash.
-        for (int i = 2, len = idxs.size(); i < len; i++) {
-            Object s = snapshots[i - 2];
+        // Take snapshots on all except first which is scan.
+        for (int i = pkIndexPos, len = idxs.size(); i < len; i++) {
+            Object s = segmentSnapshot[i - pkIndexPos];
 
             boolean reuseExisting = s != null;
 
@@ -401,20 +423,20 @@ public class GridH2Table extends TableBase {
                 if (qctx != null)
                     qctx.clearSnapshots();
 
-                for (int j = 2; j < i; j++)
+                for (int j = pkIndexPos; j < i; j++)
                     if ((idxs.get(j) instanceof GridH2IndexBase))
                         index(j).releaseSnapshot();
 
                 // Drop invalidated snapshot.
-                actualSnapshot.compareAndSet(snapshots, null);
+                actualSnapshot.compareAndSet(segment, segmentSnapshot, null);
 
                 return null;
             }
 
-            snapshots[i - 2] = s;
+            segmentSnapshot[i - pkIndexPos] = s;
         }
 
-        return snapshots;
+        return segmentSnapshot;
     }
 
     /** {@inheritDoc} */
@@ -587,7 +609,7 @@ public class GridH2Table extends TableBase {
 
                 int len = idxs.size();
 
-                int i = 2;
+                int i = pkIndexPos;
 
                 // Put row if absent to all indexes sequentially.
                 // Start from 3 because 0 - Scan (don't need to update), 1 - PK hash (already updated), 2 - PK (already updated).
@@ -609,7 +631,7 @@ public class GridH2Table extends TableBase {
                 if (old != null) {
                     // Remove row from all indexes.
                     // Start from 3 because 0 - Scan (don't need to update), 1 - PK hash (already updated), 2 - PK (already updated).
-                    for (int i = 3, len = idxs.size(); i < len; i++) {
+                    for (int i = pkIndexPos + 1, len = idxs.size(); i < len; i++) {
                         if (!(idxs.get(i) instanceof GridH2IndexBase))
                             continue;
                         Row res = index(i).remove(old);
@@ -627,7 +649,8 @@ public class GridH2Table extends TableBase {
             }
 
             // The snapshot is not actual after update.
-            actualSnapshot.set(null);
+            if (actualSnapshot != null)
+                actualSnapshot.set(pk.segmentForRow(row), null);
 
             return true;
         }
@@ -684,9 +707,10 @@ public class GridH2Table extends TableBase {
     ArrayList<GridH2IndexBase> indexes() {
         ArrayList<GridH2IndexBase> res = new ArrayList<>(idxs.size() - 2);
 
-        for (int i = 2, len = idxs.size(); i < len; i++)
+        for (int i = pkIndexPos, len = idxs.size(); i < len; i++) {
             if (idxs.get(i) instanceof GridH2IndexBase)
                 res.add(index(i));
+        }
 
         return res;
     }
@@ -695,6 +719,8 @@ public class GridH2Table extends TableBase {
      *
      */
     public void markRebuildFromHashInProgress(boolean value) {
+        assert !value || (idxs.size() >= 2 && index(1).getIndexType().isHash()) : "Table has no hash index.";
+
         rebuildFromHashInProgress = value;
     }
 
@@ -759,7 +785,8 @@ public class GridH2Table extends TableBase {
 
             Index cloneIdx = createDuplicateIndexIfNeeded(idx);
 
-            ArrayList<Index> newIdxs = new ArrayList<>(idxs.size() + ((cloneIdx == null) ? 1 : 2));
+            ArrayList<Index> newIdxs = new ArrayList<>(
+                    idxs.size() + ((cloneIdx == null) ? 1 : 2));
 
             newIdxs.addAll(idxs);
 
@@ -837,14 +864,14 @@ public class GridH2Table extends TableBase {
         try {
             ArrayList<Index> idxs = new ArrayList<>(this.idxs);
 
-            Index targetIdx = (h2Idx instanceof GridH2ProxyIndex)?
-                    ((GridH2ProxyIndex)h2Idx).underlyingIndex(): h2Idx;
+            Index targetIdx = (h2Idx instanceof GridH2ProxyIndex) ?
+                ((GridH2ProxyIndex)h2Idx).underlyingIndex() : h2Idx;
 
-            for (int i = 2; i < idxs.size();) {
+            for (int i = pkIndexPos; i < idxs.size();) {
                 Index idx = idxs.get(i);
 
                 if (idx == targetIdx || (idx instanceof GridH2ProxyIndex &&
-                   ((GridH2ProxyIndex)idx).underlyingIndex() == targetIdx)) {
+                    ((GridH2ProxyIndex)idx).underlyingIndex() == targetIdx)) {
 
                     idxs.remove(i);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/1554a160/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
index 43cc230..6d76eea 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
@@ -573,7 +573,7 @@ public class GridMapQueryExecutor {
 
                     Objects.requireNonNull(h2Tbl, tbl.toString());
 
-                    h2Tbl.snapshotIndexes(qctx);
+                    h2Tbl.snapshotIndexes(qctx, segmentId);
 
                     snapshotedTbls.add(h2Tbl);
                 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/1554a160/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteSqlSegmentedIndexSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteSqlSegmentedIndexSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteSqlSegmentedIndexSelfTest.java
index 586b81e..03c3f1e 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteSqlSegmentedIndexSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteSqlSegmentedIndexSelfTest.java
@@ -135,6 +135,31 @@ public class IgniteSqlSegmentedIndexSelfTest extends GridCommonAbstractTest {
     }
 
     /**
+     * Check correct index snapshots with segmented indices.
+     * @throws Exception If failed.
+     */
+    public void testSegmentedIndexReproducableResults() throws Exception {
+        ignite(0).createCache(cacheConfig(ORG_CACHE_NAME, true, Integer.class, Organization.class));
+
+        IgniteCache<Object, Object> cache = ignite(0).cache(ORG_CACHE_NAME);
+
+        // Unequal entries distribution among partitions.
+        int expectedSize = nodesCount() * QRY_PARALLELISM_LVL *  3 / 2;
+
+        for (int i = 0; i < expectedSize; i++)
+            cache.put(i, new Organization("org-" + i));
+
+        String select0 = "select * from \"org\".Organization o";
+
+        // Check for stable results.
+        for(int i = 0; i < 10; i++) {
+            List<List<?>> result = cache.query(new SqlFieldsQuery(select0)).getAll();
+
+            assertEquals(expectedSize, result.size());
+        }
+    }
+
+    /**
      * Run tests on single-node grid
      *
      * @throws Exception If failed.


[25/31] ignite git commit: Typo

Posted by sb...@apache.org.
Typo


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/8c9b1bde
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/8c9b1bde
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/8c9b1bde

Branch: refs/heads/ignite-5075
Commit: 8c9b1bde2884e05e4f0cc4349606250a5bc37aa1
Parents: b131ff0
Author: Yakov Zhdanov <yz...@gridgain.com>
Authored: Wed May 24 11:01:26 2017 +0300
Committer: Yakov Zhdanov <yz...@gridgain.com>
Committed: Wed May 24 11:01:26 2017 +0300

----------------------------------------------------------------------
 .../ignite/internal/managers/communication/GridIoManager.java      | 2 +-
 .../internal/managers/communication/IgniteIoTestMessage.java       | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8c9b1bde/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
index 68bfd07..698baf8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
@@ -3067,7 +3067,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                 maxReqWireTimeTs = now;
             }
 
-            long resWireTimeMillis = msg.responseRecievedTsMillis() - msg.requestSendTsMillis();
+            long resWireTimeMillis = msg.responseReceivedTsMillis() - msg.requestSendTsMillis();
 
             if (maxResWireTimeMillis < resWireTimeMillis) {
                 maxResWireTimeMillis = resWireTimeMillis;

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c9b1bde/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
index 3e0fa76..0a8b2b7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
@@ -240,7 +240,7 @@ public class IgniteIoTestMessage implements Message {
     /**
      * @return Response received timestamp (millis).
      */
-    public long responseRecievedTsMillis() {
+    public long responseReceivedTsMillis() {
         return resRcvTsMillis;
     }
 


[14/31] ignite git commit: IGNITE-5163: Implemented infrastructure for the new JDBC driver. This closes #1912.

Posted by sb...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectWriter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectWriter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectWriter.java
new file mode 100644
index 0000000..f5e9924
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectWriter.java
@@ -0,0 +1,111 @@
+/*
+ * 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.odbc;
+
+import java.math.BigDecimal;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.UUID;
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Binary writer with marshaling non-primitive and non-embedded objects with JDK marshaller..
+ */
+public abstract class SqlListenerAbstractObjectWriter {
+    /**
+     * @param writer Writer.
+     * @param obj Object to write.
+     * @throws BinaryObjectException On error.
+     */
+    public void writeObject(BinaryWriterExImpl writer, @Nullable Object obj) throws BinaryObjectException {
+        if (obj == null) {
+            writer.writeByte(GridBinaryMarshaller.NULL);
+
+            return;
+        }
+
+        Class<?> cls = obj.getClass();
+
+        if (cls == Boolean.class)
+            writer.writeBooleanFieldPrimitive((Boolean)obj);
+        else if (cls == Byte.class)
+            writer.writeByteFieldPrimitive((Byte)obj);
+        else if (cls == Character.class)
+            writer.writeCharFieldPrimitive((Character)obj);
+        else if (cls == Short.class)
+            writer.writeShortFieldPrimitive((Short)obj);
+        else if (cls == Integer.class)
+            writer.writeIntFieldPrimitive((Integer)obj);
+        else if (cls == Long.class)
+            writer.writeLongFieldPrimitive((Long)obj);
+        else if (cls == Float.class)
+            writer.writeFloatFieldPrimitive((Float)obj);
+        else if (cls == Double.class)
+            writer.writeDoubleFieldPrimitive((Double)obj);
+        else if (cls == String.class)
+            writer.doWriteString((String)obj);
+        else if (cls == BigDecimal.class)
+            writer.doWriteDecimal((BigDecimal)obj);
+        else if (cls == UUID.class)
+            writer.writeUuid((UUID)obj);
+        else if (cls == Time.class)
+            writer.writeTime((Time)obj);
+        else if (cls == Timestamp.class)
+            writer.writeTimestamp((Timestamp)obj);
+        else if (cls == java.sql.Date.class || cls == java.util.Date.class)
+            writer.writeDate((java.util.Date)obj);
+        else if (cls == boolean[].class)
+            writer.writeBooleanArray((boolean[])obj);
+        else if (cls == byte[].class)
+            writer.writeByteArray((byte[])obj);
+        else if (cls == char[].class)
+            writer.writeCharArray((char[])obj);
+        else if (cls == short[].class)
+            writer.writeShortArray((short[])obj);
+        else if (cls == int[].class)
+            writer.writeIntArray((int[])obj);
+        else if (cls == float[].class)
+            writer.writeFloatArray((float[])obj);
+        else if (cls == double[].class)
+            writer.writeDoubleArray((double[])obj);
+        else if (cls == String[].class)
+            writer.writeStringArray((String[])obj);
+        else if (cls == BigDecimal[].class)
+            writer.writeDecimalArray((BigDecimal[])obj);
+        else if (cls == UUID[].class)
+            writer.writeUuidArray((UUID[])obj);
+        else if (cls == Time[].class)
+            writer.writeTimeArray((Time[])obj);
+        else if (cls == Timestamp[].class)
+            writer.writeTimestampArray((Timestamp[])obj);
+        else if (cls == java.util.Date[].class || cls == java.sql.Date[].class)
+            writer.writeDateArray((java.util.Date[])obj);
+        else
+            writeCustomObject(writer, obj);
+    }
+
+    /**
+     * @param writer Writer.
+     * @param obj Object to marshal with marshaller and write to binary stream.
+     * @throws BinaryObjectException On error.
+     */
+    protected abstract void writeCustomObject(BinaryWriterExImpl writer, Object obj) throws BinaryObjectException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerNioListener.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerNioListener.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerNioListener.java
new file mode 100644
index 0000000..9eaec04
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerNioListener.java
@@ -0,0 +1,263 @@
+/*
+ * 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.odbc;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+import org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.processors.odbc.jdbc.JdbcMessageParser;
+import org.apache.ignite.internal.processors.odbc.odbc.OdbcMessageParser;
+import org.apache.ignite.internal.util.GridSpinBusyLock;
+import org.apache.ignite.internal.util.nio.GridNioServerListenerAdapter;
+import org.apache.ignite.internal.util.nio.GridNioSession;
+import org.apache.ignite.internal.util.nio.GridNioSessionMetaKey;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * ODBC message listener.
+ */
+public class SqlListenerNioListener extends GridNioServerListenerAdapter<byte[]> {
+    /** The value corresponds to ODBC driver of the parser field of the handshake request. */
+    public static final byte ODBC_CLIENT = 0;
+
+    /** The value corresponds to JDBC driver of the parser field of the handshake request. */
+    public static final byte JDBC_CLIENT = 1;
+
+    /** Current version. */
+    private static final SqlListenerProtocolVersion CURRENT_VER = SqlListenerProtocolVersion.create(2, 1, 0);
+
+    /** Supported versions. */
+    private static final Set<SqlListenerProtocolVersion> SUPPORTED_VERS = new HashSet<>();
+
+    /** Connection-related metadata key. */
+    private static final int CONN_CTX_META_KEY = GridNioSessionMetaKey.nextUniqueKey();
+
+    /** Request ID generator. */
+    private static final AtomicLong REQ_ID_GEN = new AtomicLong();
+
+    /** Busy lock. */
+    private final GridSpinBusyLock busyLock;
+
+    /** Kernal context. */
+    private final GridKernalContext ctx;
+
+    /** Maximum allowed cursors. */
+    private final int maxCursors;
+
+    /** Logger. */
+    private final IgniteLogger log;
+
+    static {
+        SUPPORTED_VERS.add(CURRENT_VER);
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param ctx Context.
+     * @param busyLock Shutdown busy lock.
+     * @param maxCursors Maximum allowed cursors.
+     */
+    public SqlListenerNioListener(GridKernalContext ctx, GridSpinBusyLock busyLock, int maxCursors) {
+        this.ctx = ctx;
+        this.busyLock = busyLock;
+        this.maxCursors = maxCursors;
+
+        log = ctx.log(getClass());
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onConnected(GridNioSession ses) {
+        if (log.isDebugEnabled())
+            log.debug("SQL client connected: " + ses.remoteAddress());
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onDisconnected(GridNioSession ses, @Nullable Exception e) {
+        if (log.isDebugEnabled()) {
+            if (e == null)
+                log.debug("SQL client disconnected: " + ses.remoteAddress());
+            else
+                log.debug("SQL client disconnected due to an error [addr=" + ses.remoteAddress() + ", err=" + e + ']');
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onMessage(GridNioSession ses, byte[] msg) {
+        assert msg != null;
+
+        SqlListenerConnectionContext connCtx = ses.meta(CONN_CTX_META_KEY);
+
+        if (connCtx == null) {
+            onHandshake(ses, msg);
+
+            return;
+        }
+
+        SqlListenerMessageParser parser = connCtx.parser();
+
+        SqlListenerRequest req;
+
+        try {
+            req = parser.decode(msg);
+        }
+        catch (Exception e) {
+            log.error("Failed to parse SQL client request [err=" + e + ']');
+
+            ses.close();
+
+            return;
+        }
+
+        assert req != null;
+
+        req.requestId(REQ_ID_GEN.incrementAndGet());
+
+        try {
+            long startTime = 0;
+
+            if (log.isDebugEnabled()) {
+                startTime = System.nanoTime();
+
+                log.debug("SQL client request received [reqId=" + req.requestId() + ", addr=" + ses.remoteAddress() +
+                    ", req=" + req + ']');
+            }
+
+            SqlListenerRequestHandler handler = connCtx.handler();
+
+            SqlListenerResponse resp = handler.handle(req);
+
+            if (log.isDebugEnabled()) {
+                long dur = (System.nanoTime() - startTime) / 1000;
+
+                log.debug("SQL client request processed [reqId=" + req.requestId() + ", dur(mcs)=" + dur  +
+                    ", resp=" + resp.status() + ']');
+            }
+
+            byte[] outMsg = parser.encode(resp);
+
+            ses.send(outMsg);
+        }
+        catch (Exception e) {
+            log.error("Failed to process SQL client request [reqId=" + req.requestId() + ", err=" + e + ']');
+
+            ses.send(parser.encode(new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString())));
+        }
+    }
+
+    /**
+     * Perform handshake.
+     *
+     * @param ses Session.
+     * @param msg Message bytes.
+     */
+    private void onHandshake(GridNioSession ses, byte[] msg) {
+        BinaryInputStream stream = new BinaryHeapInputStream(msg);
+
+        BinaryReaderExImpl reader = new BinaryReaderExImpl(null, stream, null, true);
+
+        byte cmd = reader.readByte();
+
+        if (cmd != SqlListenerRequest.HANDSHAKE) {
+            log.error("Unexpected SQL client request (will close session): " + ses.remoteAddress());
+
+            ses.close();
+
+            return;
+        }
+
+        short verMajor = reader.readShort();
+        short verMinor = reader.readShort();
+        short verMaintenance = reader.readShort();
+
+        SqlListenerProtocolVersion ver = SqlListenerProtocolVersion.create(verMajor, verMinor, verMaintenance);
+
+        String errMsg = null;
+
+        if (SUPPORTED_VERS.contains(ver)) {
+            // Prepare context.
+            SqlListenerConnectionContext connCtx = prepareContext(ver, reader);
+
+            ses.addMeta(CONN_CTX_META_KEY, connCtx);
+        }
+        else {
+            log.warning("Unsupported version: " + ver.toString());
+
+            errMsg = "Unsupported version.";
+        }
+
+        // Send response.
+        BinaryWriterExImpl writer = new BinaryWriterExImpl(null, new BinaryHeapOutputStream(8), null, null);
+
+        if (errMsg == null)
+            writer.writeBoolean(true);
+        else {
+            writer.writeBoolean(false);
+            writer.writeShort(CURRENT_VER.major());
+            writer.writeShort(CURRENT_VER.minor());
+            writer.writeShort(CURRENT_VER.maintenance());
+            writer.doWriteString(errMsg);
+        }
+
+        ses.send(writer.array());
+    }
+
+    /**
+     * Prepare context.
+     *
+     * @param ver Version.
+     * @param reader Reader.
+     * @return Context.
+     */
+    private SqlListenerConnectionContext prepareContext(SqlListenerProtocolVersion ver, BinaryReaderExImpl reader) {
+        byte clientType = reader.readByte();
+
+        boolean distributedJoins = reader.readBoolean();
+        boolean enforceJoinOrder = reader.readBoolean();
+
+        SqlListenerRequestHandlerImpl handler = new SqlListenerRequestHandlerImpl(ctx, busyLock, maxCursors,
+            distributedJoins, enforceJoinOrder);
+
+        SqlListenerMessageParser parser = null;
+
+        switch (clientType) {
+            case ODBC_CLIENT:
+                parser = new OdbcMessageParser(ctx);
+
+                break;
+
+            case JDBC_CLIENT:
+                parser = new JdbcMessageParser(ctx);
+
+                break;
+        }
+
+        if (parser == null)
+            throw new IgniteException("Unknown client type: " + clientType);
+
+        return new SqlListenerConnectionContext(handler, parser);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessor.java
new file mode 100644
index 0000000..cbe54df
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessor.java
@@ -0,0 +1,191 @@
+/*
+ * 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.odbc;
+
+import java.net.InetAddress;
+import java.nio.ByteOrder;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.OdbcConfiguration;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.processors.GridProcessorAdapter;
+import org.apache.ignite.internal.util.GridSpinBusyLock;
+import org.apache.ignite.internal.util.HostAndPortRange;
+import org.apache.ignite.internal.util.nio.GridNioAsyncNotifyFilter;
+import org.apache.ignite.internal.util.nio.GridNioCodecFilter;
+import org.apache.ignite.internal.util.nio.GridNioFilter;
+import org.apache.ignite.internal.util.nio.GridNioServer;
+import org.apache.ignite.internal.util.nio.GridNioSession;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.spi.IgnitePortProtocol;
+import org.apache.ignite.thread.IgniteThreadPoolExecutor;
+
+/**
+ * ODBC processor.
+ */
+public class SqlListenerProcessor extends GridProcessorAdapter {
+    /** Default number of selectors. */
+    private static final int DFLT_SELECTOR_CNT = Math.min(4, Runtime.getRuntime().availableProcessors());
+
+    /** Default TCP_NODELAY flag. */
+    private static final boolean DFLT_TCP_NODELAY = true;
+
+    /** Default TCP direct buffer flag. */
+    private static final boolean DFLT_TCP_DIRECT_BUF = false;
+
+    /** Busy lock. */
+    private final GridSpinBusyLock busyLock = new GridSpinBusyLock();
+
+    /** ODBC TCP Server. */
+    private GridNioServer<byte[]> srv;
+
+    /** ODBC executor service. */
+    private ExecutorService odbcExecSvc;
+
+    /**
+     * @param ctx Kernal context.
+     */
+    public SqlListenerProcessor(GridKernalContext ctx) {
+        super(ctx);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void start(boolean activeOnStart) throws IgniteCheckedException {
+        IgniteConfiguration cfg = ctx.config();
+
+        OdbcConfiguration odbcCfg = cfg.getOdbcConfiguration();
+
+        if (odbcCfg != null) {
+            try {
+                HostAndPortRange hostPort;
+
+                if (F.isEmpty(odbcCfg.getEndpointAddress())) {
+                    hostPort = new HostAndPortRange(OdbcConfiguration.DFLT_TCP_HOST,
+                        OdbcConfiguration.DFLT_TCP_PORT_FROM,
+                        OdbcConfiguration.DFLT_TCP_PORT_TO
+                    );
+                }
+                else {
+                    hostPort = HostAndPortRange.parse(odbcCfg.getEndpointAddress(),
+                        OdbcConfiguration.DFLT_TCP_PORT_FROM,
+                        OdbcConfiguration.DFLT_TCP_PORT_TO,
+                        "Failed to parse ODBC endpoint address"
+                    );
+                }
+
+                assertParameter(odbcCfg.getThreadPoolSize() > 0, "threadPoolSize > 0");
+
+                odbcExecSvc = new IgniteThreadPoolExecutor(
+                    "odbc",
+                    cfg.getIgniteInstanceName(),
+                    odbcCfg.getThreadPoolSize(),
+                    odbcCfg.getThreadPoolSize(),
+                    0,
+                    new LinkedBlockingQueue<Runnable>());
+
+                InetAddress host;
+
+                try {
+                    host = InetAddress.getByName(hostPort.host());
+                }
+                catch (Exception e) {
+                    throw new IgniteCheckedException("Failed to resolve ODBC host: " + hostPort.host(), e);
+                }
+
+                Exception lastErr = null;
+
+                for (int port = hostPort.portFrom(); port <= hostPort.portTo(); port++) {
+                    try {
+                        GridNioFilter[] filters = new GridNioFilter[] {
+                            new GridNioAsyncNotifyFilter(ctx.igniteInstanceName(), odbcExecSvc, log) {
+                                @Override public void onSessionOpened(GridNioSession ses) throws IgniteCheckedException {
+                                    proceedSessionOpened(ses);
+                                }
+                            },
+                            new GridNioCodecFilter(new SqlListenerBufferedParser(), log, false)
+                        };
+
+                        GridNioServer<byte[]> srv0 = GridNioServer.<byte[]>builder()
+                            .address(host)
+                            .port(port)
+                            .listener(new SqlListenerNioListener(ctx, busyLock, odbcCfg.getMaxOpenCursors()))
+                            .logger(log)
+                            .selectorCount(DFLT_SELECTOR_CNT)
+                            .igniteInstanceName(ctx.igniteInstanceName())
+                            .serverName("odbc")
+                            .tcpNoDelay(DFLT_TCP_NODELAY)
+                            .directBuffer(DFLT_TCP_DIRECT_BUF)
+                            .byteOrder(ByteOrder.nativeOrder())
+                            .socketSendBufferSize(odbcCfg.getSocketSendBufferSize())
+                            .socketReceiveBufferSize(odbcCfg.getSocketReceiveBufferSize())
+                            .filters(filters)
+                            .directMode(false)
+                            .build();
+
+                        srv0.start();
+
+                        srv = srv0;
+
+                        ctx.ports().registerPort(port, IgnitePortProtocol.TCP, getClass());
+
+                        log.info("ODBC processor has started on TCP port " + port);
+
+                        lastErr = null;
+
+                        break;
+                    }
+                    catch (Exception e) {
+                        lastErr = e;
+                    }
+                }
+
+                assert (srv != null && lastErr == null) || (srv == null && lastErr != null);
+
+                if (lastErr != null)
+                    throw new IgniteCheckedException("Failed to bind to any [host:port] from the range [" +
+                        "address=" + hostPort + ", lastErr=" + lastErr + ']');
+            }
+            catch (Exception e) {
+                throw new IgniteCheckedException("Failed to start ODBC processor.", e);
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onKernalStop(boolean cancel) {
+        if (srv != null) {
+            busyLock.block();
+
+            srv.stop();
+
+            ctx.ports().deregisterPorts(getClass());
+
+            if (odbcExecSvc != null) {
+                U.shutdownNow(getClass(), odbcExecSvc, log);
+
+                odbcExecSvc = null;
+            }
+
+            if (log.isDebugEnabled())
+                log.debug("ODBC processor stopped.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerRequestHandlerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerRequestHandlerImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerRequestHandlerImpl.java
new file mode 100644
index 0000000..1230bb4
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerRequestHandlerImpl.java
@@ -0,0 +1,494 @@
+/*
+ * 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.odbc;
+
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.cache.query.QueryCursor;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.apache.ignite.internal.processors.cache.QueryCursorImpl;
+import org.apache.ignite.internal.processors.odbc.odbc.escape.OdbcEscapeUtils;
+import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.util.GridSpinBusyLock;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteBiTuple;
+
+import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.META_COLS;
+import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.META_PARAMS;
+import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.META_TBLS;
+import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.QRY_CLOSE;
+import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.QRY_EXEC;
+import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.QRY_FETCH;
+
+/**
+ * SQL query handler.
+ */
+public class SqlListenerRequestHandlerImpl implements SqlListenerRequestHandler {
+    /** Query ID sequence. */
+    private static final AtomicLong QRY_ID_GEN = new AtomicLong();
+
+    /** Kernel context. */
+    private final GridKernalContext ctx;
+
+    /** Logger. */
+    private final IgniteLogger log;
+
+    /** Busy lock. */
+    private final GridSpinBusyLock busyLock;
+
+    /** Maximum allowed cursors. */
+    private final int maxCursors;
+
+    /** Current queries cursors. */
+    private final ConcurrentHashMap<Long, IgniteBiTuple<QueryCursor, Iterator>> qryCursors = new ConcurrentHashMap<>();
+
+    /** Distributed joins flag. */
+    private final boolean distributedJoins;
+
+    /** Enforce join order flag. */
+    private final boolean enforceJoinOrder;
+
+    /**
+     * Constructor.
+     *
+     * @param ctx Context.
+     * @param busyLock Shutdown latch.
+     * @param maxCursors Maximum allowed cursors.
+     * @param distributedJoins Distributed joins flag.
+     * @param enforceJoinOrder Enforce join order flag.
+     */
+    public SqlListenerRequestHandlerImpl(GridKernalContext ctx, GridSpinBusyLock busyLock, int maxCursors,
+        boolean distributedJoins, boolean enforceJoinOrder) {
+        this.ctx = ctx;
+        this.busyLock = busyLock;
+        this.maxCursors = maxCursors;
+        this.distributedJoins = distributedJoins;
+        this.enforceJoinOrder = enforceJoinOrder;
+
+        log = ctx.log(getClass());
+    }
+
+    /** {@inheritDoc} */
+    @Override public SqlListenerResponse handle(SqlListenerRequest req) {
+        assert req != null;
+
+        if (!busyLock.enterBusy())
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
+                    "Failed to handle ODBC request because node is stopping: " + req);
+
+        try {
+            switch (req.command()) {
+                case QRY_EXEC:
+                    return executeQuery((SqlListenerQueryExecuteRequest)req);
+
+                case QRY_FETCH:
+                    return fetchQuery((SqlListenerQueryFetchRequest)req);
+
+                case QRY_CLOSE:
+                    return closeQuery((SqlListenerQueryCloseRequest)req);
+
+                case META_COLS:
+                    return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req);
+
+                case META_TBLS:
+                    return getTablesMeta((OdbcQueryGetTablesMetaRequest)req);
+
+                case META_PARAMS:
+                    return getParamsMeta((OdbcQueryGetParamsMetaRequest)req);
+            }
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, "Unsupported ODBC request: " + req);
+        }
+        finally {
+            busyLock.leaveBusy();
+        }
+    }
+
+    /**
+     * {@link SqlListenerQueryExecuteRequest} command handler.
+     *
+     * @param req Execute query request.
+     * @return Response.
+     */
+    private SqlListenerResponse executeQuery(SqlListenerQueryExecuteRequest req) {
+        int cursorCnt = qryCursors.size();
+
+        if (maxCursors > 0 && cursorCnt >= maxCursors)
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, "Too many opened cursors (either close other " +
+                "opened cursors or increase the limit through OdbcConfiguration.setMaxOpenCursors()) " +
+                "[maximum=" + maxCursors + ", current=" + cursorCnt + ']');
+
+        long qryId = QRY_ID_GEN.getAndIncrement();
+
+        try {
+            String sql = OdbcEscapeUtils.parse(req.sqlQuery());
+
+            if (log.isDebugEnabled())
+                log.debug("ODBC query parsed [reqId=" + req.requestId() + ", original=" + req.sqlQuery() +
+                    ", parsed=" + sql + ']');
+
+            SqlFieldsQuery qry = new SqlFieldsQuery(sql);
+
+            qry.setArgs(req.arguments());
+
+            qry.setDistributedJoins(distributedJoins);
+            qry.setEnforceJoinOrder(enforceJoinOrder);
+
+            IgniteCache<Object, Object> cache0 = ctx.grid().cache(req.cacheName());
+
+            if (cache0 == null)
+                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
+                    "Cache doesn't exist (did you configure it?): " + req.cacheName());
+
+            IgniteCache<Object, Object> cache = cache0.withKeepBinary();
+
+            if (cache == null)
+                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
+                    "Can not get cache with keep binary: " + req.cacheName());
+
+            QueryCursor qryCur = cache.query(qry);
+
+            qryCursors.put(qryId, new IgniteBiTuple<QueryCursor, Iterator>(qryCur, null));
+
+            List<?> fieldsMeta = ((QueryCursorImpl) qryCur).fieldsMeta();
+
+            SqlListenerQueryExecuteResult res = new SqlListenerQueryExecuteResult(qryId, convertMetadata(fieldsMeta));
+
+            return new SqlListenerResponse(res);
+        }
+        catch (Exception e) {
+            qryCursors.remove(qryId);
+
+            U.error(log, "Failed to execute SQL query [reqId=" + req.requestId() + ", req=" + req + ']', e);
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
+        }
+    }
+
+    /**
+     * {@link SqlListenerQueryCloseRequest} command handler.
+     *
+     * @param req Execute query request.
+     * @return Response.
+     */
+    private SqlListenerResponse closeQuery(SqlListenerQueryCloseRequest req) {
+        try {
+            IgniteBiTuple<QueryCursor, Iterator> tuple = qryCursors.get(req.queryId());
+
+            if (tuple == null)
+                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
+                    "Failed to find query with ID: " + req.queryId());
+
+            QueryCursor cur = tuple.get1();
+
+            assert(cur != null);
+
+            cur.close();
+
+            qryCursors.remove(req.queryId());
+
+            SqlListenerQueryCloseResult res = new SqlListenerQueryCloseResult(req.queryId());
+
+            return new SqlListenerResponse(res);
+        }
+        catch (Exception e) {
+            qryCursors.remove(req.queryId());
+
+            U.error(log, "Failed to close SQL query [reqId=" + req.requestId() + ", req=" + req.queryId() + ']', e);
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
+        }
+    }
+
+    /**
+     * {@link SqlListenerQueryFetchRequest} command handler.
+     *
+     * @param req Execute query request.
+     * @return Response.
+     */
+    private SqlListenerResponse fetchQuery(SqlListenerQueryFetchRequest req) {
+        try {
+            IgniteBiTuple<QueryCursor, Iterator> tuple = qryCursors.get(req.queryId());
+
+            if (tuple == null)
+                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
+                    "Failed to find query with ID: " + req.queryId());
+
+            Iterator iter = tuple.get2();
+
+            if (iter == null) {
+                QueryCursor cur = tuple.get1();
+
+                iter = cur.iterator();
+
+                tuple.put(cur, iter);
+            }
+
+            List<Object> items = new ArrayList<>();
+
+            for (int i = 0; i < req.pageSize() && iter.hasNext(); ++i)
+                items.add(iter.next());
+
+            SqlListenerQueryFetchResult res = new SqlListenerQueryFetchResult(req.queryId(), items, !iter.hasNext());
+
+            return new SqlListenerResponse(res);
+        }
+        catch (Exception e) {
+            U.error(log, "Failed to fetch SQL query result [reqId=" + req.requestId() + ", req=" + req + ']', e);
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
+        }
+    }
+
+    /**
+     * {@link OdbcQueryGetColumnsMetaRequest} command handler.
+     *
+     * @param req Get columns metadata request.
+     * @return Response.
+     */
+    private SqlListenerResponse getColumnsMeta(OdbcQueryGetColumnsMetaRequest req) {
+        try {
+            List<SqlListenerColumnMeta> meta = new ArrayList<>();
+
+            String cacheName;
+            String tableName;
+
+            if (req.tableName().contains(".")) {
+                // Parsing two-part table name.
+                String[] parts = req.tableName().split("\\.");
+
+                cacheName = OdbcUtils.removeQuotationMarksIfNeeded(parts[0]);
+
+                tableName = parts[1];
+            }
+            else {
+                cacheName = OdbcUtils.removeQuotationMarksIfNeeded(req.cacheName());
+
+                tableName = req.tableName();
+            }
+
+            Collection<GridQueryTypeDescriptor> tablesMeta = ctx.query().types(cacheName);
+
+            for (GridQueryTypeDescriptor table : tablesMeta) {
+                if (!matches(table.name(), tableName))
+                    continue;
+
+                for (Map.Entry<String, Class<?>> field : table.fields().entrySet()) {
+                    if (!matches(field.getKey(), req.columnName()))
+                        continue;
+
+                    SqlListenerColumnMeta columnMeta = new SqlListenerColumnMeta(req.cacheName(), table.name(),
+                        field.getKey(), field.getValue());
+
+                    if (!meta.contains(columnMeta))
+                        meta.add(columnMeta);
+                }
+            }
+
+            OdbcQueryGetColumnsMetaResult res = new OdbcQueryGetColumnsMetaResult(meta);
+
+            return new SqlListenerResponse(res);
+        }
+        catch (Exception e) {
+            U.error(log, "Failed to get columns metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
+        }
+    }
+
+    /**
+     * {@link OdbcQueryGetTablesMetaRequest} command handler.
+     *
+     * @param req Get tables metadata request.
+     * @return Response.
+     */
+    private SqlListenerResponse getTablesMeta(OdbcQueryGetTablesMetaRequest req) {
+        try {
+            List<OdbcTableMeta> meta = new ArrayList<>();
+
+            String realSchema = OdbcUtils.removeQuotationMarksIfNeeded(req.schema());
+
+            for (String cacheName : ctx.cache().cacheNames())
+            {
+                if (!matches(cacheName, realSchema))
+                    continue;
+
+                Collection<GridQueryTypeDescriptor> tablesMeta = ctx.query().types(cacheName);
+
+                for (GridQueryTypeDescriptor table : tablesMeta) {
+                    if (!matches(table.name(), req.table()))
+                        continue;
+
+                    if (!matches("TABLE", req.tableType()))
+                        continue;
+
+                    OdbcTableMeta tableMeta = new OdbcTableMeta(null, cacheName, table.name(), "TABLE");
+
+                    if (!meta.contains(tableMeta))
+                        meta.add(tableMeta);
+                }
+            }
+
+            OdbcQueryGetTablesMetaResult res = new OdbcQueryGetTablesMetaResult(meta);
+
+            return new SqlListenerResponse(res);
+        }
+        catch (Exception e) {
+            U.error(log, "Failed to get tables metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
+        }
+    }
+
+    /**
+     * {@link OdbcQueryGetParamsMetaRequest} command handler.
+     *
+     * @param req Get params metadata request.
+     * @return Response.
+     */
+    private SqlListenerResponse getParamsMeta(OdbcQueryGetParamsMetaRequest req) {
+        try {
+            PreparedStatement stmt = ctx.query().prepareNativeStatement(req.cacheName(), req.query());
+
+            ParameterMetaData pmd = stmt.getParameterMetaData();
+
+            byte[] typeIds = new byte[pmd.getParameterCount()];
+
+            for (int i = 1; i <= pmd.getParameterCount(); ++i) {
+                int sqlType = pmd.getParameterType(i);
+
+                typeIds[i - 1] = sqlTypeToBinary(sqlType);
+            }
+
+            OdbcQueryGetParamsMetaResult res = new OdbcQueryGetParamsMetaResult(typeIds);
+
+            return new SqlListenerResponse(res);
+        }
+        catch (Exception e) {
+            U.error(log, "Failed to get params metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
+
+            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
+        }
+    }
+
+    /**
+     * Convert {@link java.sql.Types} to binary type constant (See {@link GridBinaryMarshaller} constants).
+     *
+     * @param sqlType SQL type.
+     * @return Binary type.
+     */
+    private static byte sqlTypeToBinary(int sqlType) {
+        switch (sqlType) {
+            case Types.BIGINT:
+                return GridBinaryMarshaller.LONG;
+
+            case Types.BOOLEAN:
+                return GridBinaryMarshaller.BOOLEAN;
+
+            case Types.DATE:
+                return GridBinaryMarshaller.DATE;
+
+            case Types.DOUBLE:
+                return GridBinaryMarshaller.DOUBLE;
+
+            case Types.FLOAT:
+            case Types.REAL:
+                return GridBinaryMarshaller.FLOAT;
+
+            case Types.NUMERIC:
+            case Types.DECIMAL:
+                return GridBinaryMarshaller.DECIMAL;
+
+            case Types.INTEGER:
+                return GridBinaryMarshaller.INT;
+
+            case Types.SMALLINT:
+                return GridBinaryMarshaller.SHORT;
+
+            case Types.TIME:
+                return GridBinaryMarshaller.TIME;
+
+            case Types.TIMESTAMP:
+                return GridBinaryMarshaller.TIMESTAMP;
+
+            case Types.TINYINT:
+                return GridBinaryMarshaller.BYTE;
+
+            case Types.CHAR:
+            case Types.VARCHAR:
+            case Types.LONGNVARCHAR:
+                return GridBinaryMarshaller.STRING;
+
+            case Types.NULL:
+                return GridBinaryMarshaller.NULL;
+
+            case Types.BINARY:
+            case Types.VARBINARY:
+            case Types.LONGVARBINARY:
+            default:
+                return GridBinaryMarshaller.BYTE_ARR;
+        }
+    }
+
+    /**
+     * Convert metadata in collection from {@link GridQueryFieldMetadata} to
+     * {@link SqlListenerColumnMeta}.
+     *
+     * @param meta Internal query field metadata.
+     * @return Odbc query field metadata.
+     */
+    private static Collection<SqlListenerColumnMeta> convertMetadata(Collection<?> meta) {
+        List<SqlListenerColumnMeta> res = new ArrayList<>();
+
+        if (meta != null) {
+            for (Object info : meta) {
+                assert info instanceof GridQueryFieldMetadata;
+
+                res.add(new SqlListenerColumnMeta((GridQueryFieldMetadata)info));
+            }
+        }
+
+        return res;
+    }
+
+    /**
+     * Checks whether string matches SQL pattern.
+     *
+     * @param str String.
+     * @param ptrn Pattern.
+     * @return Whether string matches pattern.
+     */
+    private static boolean matches(String str, String ptrn) {
+        return str != null && (F.isEmpty(ptrn) ||
+            str.toUpperCase().matches(ptrn.toUpperCase().replace("%", ".*").replace("_", ".")));
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcMessageParser.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcMessageParser.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcMessageParser.java
new file mode 100644
index 0000000..cf87712
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcMessageParser.java
@@ -0,0 +1,50 @@
+/*
+ * 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.odbc.jdbc;
+
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+import org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream;
+import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.processors.odbc.SqlListenerAbstractMessageParser;
+
+/**
+ * JDBC message parser.
+ */
+public class JdbcMessageParser extends SqlListenerAbstractMessageParser {
+    /**
+     * @param ctx Context.
+     */
+    public JdbcMessageParser(GridKernalContext ctx) {
+        super(ctx, new JdbcObjectReader(), new JdbcObjectWriter());
+    }
+
+    /** {@inheritDoc} */
+    @Override protected BinaryReaderExImpl createReader(byte[] msg) {
+        BinaryInputStream stream = new BinaryHeapInputStream(msg);
+
+        return new BinaryReaderExImpl(null, stream, ctx.config().getClassLoader(), true);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected BinaryWriterExImpl createWriter(int cap) {
+        return new BinaryWriterExImpl(null, new BinaryHeapOutputStream(cap), null, null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectReader.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectReader.java
new file mode 100644
index 0000000..81c8c10
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectReader.java
@@ -0,0 +1,33 @@
+/*
+ * 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.odbc.jdbc;
+
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.processors.odbc.SqlListenerAbstractObjectReader;
+
+/**
+ * Binary reader with marshaling non-primitive and non-embedded objects with JDK marshaller.
+ */
+@SuppressWarnings("unchecked")
+public class JdbcObjectReader extends SqlListenerAbstractObjectReader {
+    /** {@inheritDoc} */
+    @Override protected Object readCustomObject(BinaryReaderExImpl reader) throws BinaryObjectException {
+        throw new BinaryObjectException("JDBC doesn't support custom objects.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectWriter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectWriter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectWriter.java
new file mode 100644
index 0000000..e87ef50
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcObjectWriter.java
@@ -0,0 +1,33 @@
+/*
+ * 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.odbc.jdbc;
+
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+import org.apache.ignite.internal.processors.odbc.SqlListenerAbstractObjectWriter;
+
+/**
+ * Binary writer with marshaling non-primitive and non-embedded objects with JDK marshaller..
+ */
+public class JdbcObjectWriter extends SqlListenerAbstractObjectWriter {
+    /** {@inheritDoc} */
+    @Override protected void writeCustomObject(BinaryWriterExImpl writer, Object obj)
+        throws BinaryObjectException {
+        throw new BinaryObjectException("JDBC doesn't support custom objects.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcMessageParser.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcMessageParser.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcMessageParser.java
index af595b9..300385f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcMessageParser.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcMessageParser.java
@@ -18,262 +18,51 @@
 package org.apache.ignite.internal.processors.odbc.odbc;
 
 import org.apache.ignite.IgniteException;
-import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryThreadLocalContext;
 import org.apache.ignite.internal.binary.BinaryWriterExImpl;
 import org.apache.ignite.internal.binary.GridBinaryMarshaller;
 import org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;
 import org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream;
 import org.apache.ignite.internal.binary.streams.BinaryInputStream;
 import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetColumnsMetaRequest;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetColumnsMetaResult;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetParamsMetaRequest;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetParamsMetaResult;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetTablesMetaRequest;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetTablesMetaResult;
-import org.apache.ignite.internal.processors.odbc.OdbcTableMeta;
-import org.apache.ignite.internal.processors.odbc.SqlListenerColumnMeta;
-import org.apache.ignite.internal.processors.odbc.SqlListenerMessageParser;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryCloseRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryCloseResult;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryExecuteRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryExecuteResult;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryFetchRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryFetchResult;
-import org.apache.ignite.internal.processors.odbc.SqlListenerRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerResponse;
-
-import java.util.Collection;
+import org.apache.ignite.internal.processors.odbc.SqlListenerAbstractMessageParser;
 
 /**
- * ODBC message parser.
+ * JDBC message parser.
  */
-public class OdbcMessageParser implements SqlListenerMessageParser {
-    /** Initial output stream capacity. */
-    private static final int INIT_CAP = 1024;
-
+public class OdbcMessageParser extends SqlListenerAbstractMessageParser {
     /** Marshaller. */
     private final GridBinaryMarshaller marsh;
 
-    /** Logger. */
-    private final IgniteLogger log;
-
     /**
      * @param ctx Context.
      */
-    public OdbcMessageParser(final GridKernalContext ctx) {
-        CacheObjectBinaryProcessorImpl cacheObjProc = (CacheObjectBinaryProcessorImpl)ctx.cacheObjects();
+    public OdbcMessageParser(GridKernalContext ctx) {
+        super(ctx, new OdbcObjectReader(), new OdbcObjectWriter());
 
-        this.marsh = cacheObjProc.marshaller();
+        if (ctx.cacheObjects() instanceof CacheObjectBinaryProcessorImpl) {
+            CacheObjectBinaryProcessorImpl cacheObjProc = (CacheObjectBinaryProcessorImpl)ctx.cacheObjects();
 
-        this.log = ctx.log(getClass());
+            marsh = cacheObjProc.marshaller();
+        }
+        else {
+            throw new IgniteException("ODBC can only be used with BinaryMarshaller (please set it " +
+                "through IgniteConfiguration.setMarshaller())");
+        }
     }
 
     /** {@inheritDoc} */
-    @Override public SqlListenerRequest decode(byte[] msg) {
-        assert msg != null;
-
+    @Override protected BinaryReaderExImpl createReader(byte[] msg) {
         BinaryInputStream stream = new BinaryHeapInputStream(msg);
 
-        BinaryReaderExImpl reader = new BinaryReaderExImpl(null, stream, null, true);
-
-        byte cmd = reader.readByte();
-
-        SqlListenerRequest res;
-
-        switch (cmd) {
-            case SqlListenerRequest.QRY_EXEC: {
-                String cache = reader.readString();
-                String sql = reader.readString();
-                int argsNum = reader.readInt();
-
-                Object[] params = new Object[argsNum];
-
-                for (int i = 0; i < argsNum; ++i)
-                    params[i] = reader.readObjectDetached();
-
-                res = new SqlListenerQueryExecuteRequest(cache, sql, params);
-
-                break;
-            }
-
-            case SqlListenerRequest.QRY_FETCH: {
-                long queryId = reader.readLong();
-                int pageSize = reader.readInt();
-
-                res = new SqlListenerQueryFetchRequest(queryId, pageSize);
-
-                break;
-            }
-
-            case SqlListenerRequest.QRY_CLOSE: {
-                long queryId = reader.readLong();
-
-                res = new SqlListenerQueryCloseRequest(queryId);
-
-                break;
-            }
-
-            case SqlListenerRequest.META_COLS: {
-                String cache = reader.readString();
-                String table = reader.readString();
-                String column = reader.readString();
-
-                res = new OdbcQueryGetColumnsMetaRequest(cache, table, column);
-
-                break;
-            }
-
-            case SqlListenerRequest.META_TBLS: {
-                String catalog = reader.readString();
-                String schema = reader.readString();
-                String table = reader.readString();
-                String tableType = reader.readString();
-
-                res = new OdbcQueryGetTablesMetaRequest(catalog, schema, table, tableType);
-
-                break;
-            }
-
-            case SqlListenerRequest.META_PARAMS: {
-                String cacheName = reader.readString();
-                String sqlQuery = reader.readString();
-
-                res = new OdbcQueryGetParamsMetaRequest(cacheName, sqlQuery);
-
-                break;
-            }
-
-            default:
-                throw new IgniteException("Unknown ODBC command: [cmd=" + cmd + ']');
-        }
-
-        return res;
+        return new BinaryReaderExImpl(marsh.context(), stream, ctx.config().getClassLoader(), true);
     }
 
     /** {@inheritDoc} */
-    @Override public byte[] encode(SqlListenerResponse msg) {
-        assert msg != null;
-
-        // Creating new binary writer
-        BinaryWriterExImpl writer = marsh.writer(new BinaryHeapOutputStream(INIT_CAP));
-
-        // Writing status.
-        writer.writeByte((byte) msg.status());
-
-        if (msg.status() != SqlListenerResponse.STATUS_SUCCESS) {
-            writer.writeString(msg.error());
-
-            return writer.array();
-        }
-
-        Object res0 = msg.response();
-
-        if (res0 == null)
-            return writer.array();
-        else if (res0 instanceof SqlListenerQueryExecuteResult) {
-            SqlListenerQueryExecuteResult res = (SqlListenerQueryExecuteResult) res0;
-
-            if (log.isDebugEnabled())
-                log.debug("Resulting query ID: " + res.getQueryId());
-
-            writer.writeLong(res.getQueryId());
-
-            Collection<SqlListenerColumnMeta> metas = res.getColumnsMetadata();
-
-            assert metas != null;
-
-            writer.writeInt(metas.size());
-
-            for (SqlListenerColumnMeta meta : metas)
-                meta.write(writer);
-        }
-        else if (res0 instanceof SqlListenerQueryFetchResult) {
-            SqlListenerQueryFetchResult res = (SqlListenerQueryFetchResult) res0;
-
-            if (log.isDebugEnabled())
-                log.debug("Resulting query ID: " + res.queryId());
-
-            writer.writeLong(res.queryId());
-
-            Collection<?> items0 = res.items();
-
-            assert items0 != null;
-
-            writer.writeBoolean(res.last());
-
-            writer.writeInt(items0.size());
-
-            for (Object row0 : items0) {
-                if (row0 != null) {
-                    Collection<?> row = (Collection<?>)row0;
-
-                    writer.writeInt(row.size());
-
-                    for (Object obj : row) {
-                        if (obj == null) {
-                            writer.writeObjectDetached(null);
-                            continue;
-                        }
-
-                        Class<?> cls = obj.getClass();
-
-                        if (cls == java.sql.Time.class)
-                            writer.writeTime((java.sql.Time)obj);
-                        else if (cls == java.sql.Timestamp.class)
-                            writer.writeTimestamp((java.sql.Timestamp)obj);
-                        else if (cls == java.sql.Date.class)
-                            writer.writeDate((java.util.Date)obj);
-                        else
-                            writer.writeObjectDetached(obj);
-                    }
-                }
-            }
-        }
-        else if (res0 instanceof SqlListenerQueryCloseResult) {
-            SqlListenerQueryCloseResult res = (SqlListenerQueryCloseResult) res0;
-
-            if (log.isDebugEnabled())
-                log.debug("Resulting query ID: " + res.getQueryId());
-
-            writer.writeLong(res.getQueryId());
-        }
-        else if (res0 instanceof OdbcQueryGetColumnsMetaResult) {
-            OdbcQueryGetColumnsMetaResult res = (OdbcQueryGetColumnsMetaResult) res0;
-
-            Collection<SqlListenerColumnMeta> columnsMeta = res.meta();
-
-            assert columnsMeta != null;
-
-            writer.writeInt(columnsMeta.size());
-
-            for (SqlListenerColumnMeta columnMeta : columnsMeta)
-                columnMeta.write(writer);
-        }
-        else if (res0 instanceof OdbcQueryGetTablesMetaResult) {
-            OdbcQueryGetTablesMetaResult res = (OdbcQueryGetTablesMetaResult) res0;
-
-            Collection<OdbcTableMeta> tablesMeta = res.meta();
-
-            assert tablesMeta != null;
-
-            writer.writeInt(tablesMeta.size());
-
-            for (OdbcTableMeta tableMeta : tablesMeta)
-                tableMeta.writeBinary(writer);
-        }
-        else if (res0 instanceof OdbcQueryGetParamsMetaResult) {
-            OdbcQueryGetParamsMetaResult res = (OdbcQueryGetParamsMetaResult) res0;
-
-            byte[] typeIds = res.typeIds();
-
-            writer.writeObjectDetached(typeIds);
-        }
-        else
-            assert false : "Should not reach here.";
-
-        return writer.array();
+    @Override protected BinaryWriterExImpl createWriter(int cap) {
+        return new BinaryWriterExImpl(marsh.context(), new BinaryHeapOutputStream(cap),
+            BinaryThreadLocalContext.get().schemaHolder(), null);
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectReader.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectReader.java
new file mode 100644
index 0000000..586fbc5
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectReader.java
@@ -0,0 +1,33 @@
+/*
+ * 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.odbc.odbc;
+
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.processors.odbc.SqlListenerAbstractObjectReader;
+
+/**
+ * Binary reader with marshaling non-primitive and non-embedded objects with JDK marshaller.
+ */
+@SuppressWarnings("unchecked")
+public class OdbcObjectReader extends SqlListenerAbstractObjectReader {
+    /** {@inheritDoc} */
+    @Override protected Object readCustomObject(BinaryReaderExImpl reader) throws BinaryObjectException {
+        return reader.readObjectDetached();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectWriter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectWriter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectWriter.java
new file mode 100644
index 0000000..c2f3aba
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcObjectWriter.java
@@ -0,0 +1,32 @@
+/*
+ * 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.odbc.odbc;
+
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+import org.apache.ignite.internal.processors.odbc.SqlListenerAbstractObjectWriter;
+
+/**
+ * Binary writer with marshaling non-primitive and non-embedded objects with JDK marshaller..
+ */
+public class OdbcObjectWriter extends SqlListenerAbstractObjectWriter {
+    /** {@inheritDoc} */
+    @Override protected void writeCustomObject(BinaryWriterExImpl writer, Object obj) throws BinaryObjectException {
+        writer.writeObjectDetached(obj);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java
deleted file mode 100644
index eabc486..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java
+++ /dev/null
@@ -1,513 +0,0 @@
-/*
- * 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.odbc.odbc;
-
-import org.apache.ignite.IgniteCache;
-import org.apache.ignite.IgniteLogger;
-import org.apache.ignite.cache.query.QueryCursor;
-import org.apache.ignite.cache.query.SqlFieldsQuery;
-import org.apache.ignite.internal.GridKernalContext;
-import org.apache.ignite.internal.binary.GridBinaryMarshaller;
-import org.apache.ignite.internal.processors.cache.QueryCursorImpl;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetColumnsMetaRequest;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetColumnsMetaResult;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetParamsMetaRequest;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetParamsMetaResult;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetTablesMetaRequest;
-import org.apache.ignite.internal.processors.odbc.OdbcQueryGetTablesMetaResult;
-import org.apache.ignite.internal.processors.odbc.OdbcTableMeta;
-import org.apache.ignite.internal.processors.odbc.OdbcUtils;
-import org.apache.ignite.internal.processors.odbc.SqlListenerColumnMeta;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryCloseRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryCloseResult;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryExecuteRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryExecuteResult;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryFetchRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerQueryFetchResult;
-import org.apache.ignite.internal.processors.odbc.SqlListenerRequest;
-import org.apache.ignite.internal.processors.odbc.SqlListenerRequestHandler;
-import org.apache.ignite.internal.processors.odbc.SqlListenerResponse;
-import org.apache.ignite.internal.processors.odbc.odbc.escape.OdbcEscapeUtils;
-import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
-import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
-import org.apache.ignite.internal.util.GridSpinBusyLock;
-import org.apache.ignite.internal.util.typedef.F;
-import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.lang.IgniteBiTuple;
-
-import java.sql.ParameterMetaData;
-import java.sql.PreparedStatement;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
-
-import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.META_COLS;
-import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.META_PARAMS;
-import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.META_TBLS;
-import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.QRY_CLOSE;
-import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.QRY_EXEC;
-import static org.apache.ignite.internal.processors.odbc.SqlListenerRequest.QRY_FETCH;
-
-/**
- * SQL query handler.
- */
-public class OdbcRequestHandler implements SqlListenerRequestHandler {
-    /** Query ID sequence. */
-    private static final AtomicLong QRY_ID_GEN = new AtomicLong();
-
-    /** Kernel context. */
-    private final GridKernalContext ctx;
-
-    /** Logger. */
-    private final IgniteLogger log;
-
-    /** Busy lock. */
-    private final GridSpinBusyLock busyLock;
-
-    /** Maximum allowed cursors. */
-    private final int maxCursors;
-
-    /** Current queries cursors. */
-    private final ConcurrentHashMap<Long, IgniteBiTuple<QueryCursor, Iterator>> qryCursors = new ConcurrentHashMap<>();
-
-    /** Distributed joins flag. */
-    private final boolean distributedJoins;
-
-    /** Enforce join order flag. */
-    private final boolean enforceJoinOrder;
-
-    /**
-     * Constructor.
-     *
-     * @param ctx Context.
-     * @param busyLock Shutdown latch.
-     * @param maxCursors Maximum allowed cursors.
-     * @param distributedJoins Distributed joins flag.
-     * @param enforceJoinOrder Enforce join order flag.
-     */
-    public OdbcRequestHandler(GridKernalContext ctx, GridSpinBusyLock busyLock, int maxCursors,
-        boolean distributedJoins, boolean enforceJoinOrder) {
-        this.ctx = ctx;
-        this.busyLock = busyLock;
-        this.maxCursors = maxCursors;
-        this.distributedJoins = distributedJoins;
-        this.enforceJoinOrder = enforceJoinOrder;
-
-        log = ctx.log(getClass());
-    }
-
-    /** {@inheritDoc} */
-    @Override public SqlListenerResponse handle(SqlListenerRequest req) {
-        assert req != null;
-
-        if (!busyLock.enterBusy())
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
-                    "Failed to handle ODBC request because node is stopping: " + req);
-
-        try {
-            switch (req.command()) {
-                case QRY_EXEC:
-                    return executeQuery((SqlListenerQueryExecuteRequest)req);
-
-                case QRY_FETCH:
-                    return fetchQuery((SqlListenerQueryFetchRequest)req);
-
-                case QRY_CLOSE:
-                    return closeQuery((SqlListenerQueryCloseRequest)req);
-
-                case META_COLS:
-                    return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req);
-
-                case META_TBLS:
-                    return getTablesMeta((OdbcQueryGetTablesMetaRequest)req);
-
-                case META_PARAMS:
-                    return getParamsMeta((OdbcQueryGetParamsMetaRequest)req);
-            }
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, "Unsupported ODBC request: " + req);
-        }
-        finally {
-            busyLock.leaveBusy();
-        }
-    }
-
-    /**
-     * {@link SqlListenerQueryExecuteRequest} command handler.
-     *
-     * @param req Execute query request.
-     * @return Response.
-     */
-    private SqlListenerResponse executeQuery(SqlListenerQueryExecuteRequest req) {
-        int cursorCnt = qryCursors.size();
-
-        if (maxCursors > 0 && cursorCnt >= maxCursors)
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, "Too many opened cursors (either close other " +
-                "opened cursors or increase the limit through OdbcConfiguration.setMaxOpenCursors()) " +
-                "[maximum=" + maxCursors + ", current=" + cursorCnt + ']');
-
-        long qryId = QRY_ID_GEN.getAndIncrement();
-
-        try {
-            String sql = OdbcEscapeUtils.parse(req.sqlQuery());
-
-            if (log.isDebugEnabled())
-                log.debug("ODBC query parsed [reqId=" + req.requestId() + ", original=" + req.sqlQuery() +
-                    ", parsed=" + sql + ']');
-
-            SqlFieldsQuery qry = new SqlFieldsQuery(sql);
-
-            qry.setArgs(req.arguments());
-
-            qry.setDistributedJoins(distributedJoins);
-            qry.setEnforceJoinOrder(enforceJoinOrder);
-
-            IgniteCache<Object, Object> cache0 = ctx.grid().cache(req.cacheName());
-
-            if (cache0 == null)
-                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
-                    "Cache doesn't exist (did you configure it?): " + req.cacheName());
-
-            IgniteCache<Object, Object> cache = cache0.withKeepBinary();
-
-            if (cache == null)
-                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
-                    "Can not get cache with keep binary: " + req.cacheName());
-
-            QueryCursor qryCur = cache.query(qry);
-
-            qryCursors.put(qryId, new IgniteBiTuple<QueryCursor, Iterator>(qryCur, null));
-
-            List<?> fieldsMeta = ((QueryCursorImpl) qryCur).fieldsMeta();
-
-            SqlListenerQueryExecuteResult res = new SqlListenerQueryExecuteResult(qryId, convertMetadata(fieldsMeta));
-
-            return new SqlListenerResponse(res);
-        }
-        catch (Exception e) {
-            qryCursors.remove(qryId);
-
-            U.error(log, "Failed to execute SQL query [reqId=" + req.requestId() + ", req=" + req + ']', e);
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
-        }
-    }
-
-    /**
-     * {@link SqlListenerQueryCloseRequest} command handler.
-     *
-     * @param req Execute query request.
-     * @return Response.
-     */
-    private SqlListenerResponse closeQuery(SqlListenerQueryCloseRequest req) {
-        try {
-            IgniteBiTuple<QueryCursor, Iterator> tuple = qryCursors.get(req.queryId());
-
-            if (tuple == null)
-                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
-                    "Failed to find query with ID: " + req.queryId());
-
-            QueryCursor cur = tuple.get1();
-
-            assert(cur != null);
-
-            cur.close();
-
-            qryCursors.remove(req.queryId());
-
-            SqlListenerQueryCloseResult res = new SqlListenerQueryCloseResult(req.queryId());
-
-            return new SqlListenerResponse(res);
-        }
-        catch (Exception e) {
-            qryCursors.remove(req.queryId());
-
-            U.error(log, "Failed to close SQL query [reqId=" + req.requestId() + ", req=" + req.queryId() + ']', e);
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
-        }
-    }
-
-    /**
-     * {@link SqlListenerQueryFetchRequest} command handler.
-     *
-     * @param req Execute query request.
-     * @return Response.
-     */
-    private SqlListenerResponse fetchQuery(SqlListenerQueryFetchRequest req) {
-        try {
-            IgniteBiTuple<QueryCursor, Iterator> tuple = qryCursors.get(req.queryId());
-
-            if (tuple == null)
-                return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED,
-                    "Failed to find query with ID: " + req.queryId());
-
-            Iterator iter = tuple.get2();
-
-            if (iter == null) {
-                QueryCursor cur = tuple.get1();
-
-                iter = cur.iterator();
-
-                tuple.put(cur, iter);
-            }
-
-            List<Object> items = new ArrayList<>();
-
-            for (int i = 0; i < req.pageSize() && iter.hasNext(); ++i)
-                items.add(iter.next());
-
-            SqlListenerQueryFetchResult res = new SqlListenerQueryFetchResult(req.queryId(), items, !iter.hasNext());
-
-            return new SqlListenerResponse(res);
-        }
-        catch (Exception e) {
-            U.error(log, "Failed to fetch SQL query result [reqId=" + req.requestId() + ", req=" + req + ']', e);
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
-        }
-    }
-
-    /**
-     * {@link OdbcQueryGetColumnsMetaRequest} command handler.
-     *
-     * @param req Get columns metadata request.
-     * @return Response.
-     */
-    private SqlListenerResponse getColumnsMeta(OdbcQueryGetColumnsMetaRequest req) {
-        try {
-            List<SqlListenerColumnMeta> meta = new ArrayList<>();
-
-            String cacheName;
-            String tableName;
-
-            if (req.tableName().contains(".")) {
-                // Parsing two-part table name.
-                String[] parts = req.tableName().split("\\.");
-
-                cacheName = OdbcUtils.removeQuotationMarksIfNeeded(parts[0]);
-
-                tableName = parts[1];
-            }
-            else {
-                cacheName = OdbcUtils.removeQuotationMarksIfNeeded(req.cacheName());
-
-                tableName = req.tableName();
-            }
-
-            Collection<GridQueryTypeDescriptor> tablesMeta = ctx.query().types(cacheName);
-
-            for (GridQueryTypeDescriptor table : tablesMeta) {
-                if (!matches(table.name(), tableName))
-                    continue;
-
-                for (Map.Entry<String, Class<?>> field : table.fields().entrySet()) {
-                    if (!matches(field.getKey(), req.columnName()))
-                        continue;
-
-                    SqlListenerColumnMeta columnMeta = new SqlListenerColumnMeta(req.cacheName(), table.name(),
-                        field.getKey(), field.getValue());
-
-                    if (!meta.contains(columnMeta))
-                        meta.add(columnMeta);
-                }
-            }
-
-            OdbcQueryGetColumnsMetaResult res = new OdbcQueryGetColumnsMetaResult(meta);
-
-            return new SqlListenerResponse(res);
-        }
-        catch (Exception e) {
-            U.error(log, "Failed to get columns metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
-        }
-    }
-
-    /**
-     * {@link OdbcQueryGetTablesMetaRequest} command handler.
-     *
-     * @param req Get tables metadata request.
-     * @return Response.
-     */
-    private SqlListenerResponse getTablesMeta(OdbcQueryGetTablesMetaRequest req) {
-        try {
-            List<OdbcTableMeta> meta = new ArrayList<>();
-
-            String realSchema = OdbcUtils.removeQuotationMarksIfNeeded(req.schema());
-
-            for (String cacheName : ctx.cache().cacheNames())
-            {
-                if (!matches(cacheName, realSchema))
-                    continue;
-
-                Collection<GridQueryTypeDescriptor> tablesMeta = ctx.query().types(cacheName);
-
-                for (GridQueryTypeDescriptor table : tablesMeta) {
-                    if (!matches(table.name(), req.table()))
-                        continue;
-
-                    if (!matches("TABLE", req.tableType()))
-                        continue;
-
-                    OdbcTableMeta tableMeta = new OdbcTableMeta(null, cacheName, table.name(), "TABLE");
-
-                    if (!meta.contains(tableMeta))
-                        meta.add(tableMeta);
-                }
-            }
-
-            OdbcQueryGetTablesMetaResult res = new OdbcQueryGetTablesMetaResult(meta);
-
-            return new SqlListenerResponse(res);
-        }
-        catch (Exception e) {
-            U.error(log, "Failed to get tables metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
-        }
-    }
-
-    /**
-     * {@link OdbcQueryGetParamsMetaRequest} command handler.
-     *
-     * @param req Get params metadata request.
-     * @return Response.
-     */
-    private SqlListenerResponse getParamsMeta(OdbcQueryGetParamsMetaRequest req) {
-        try {
-            PreparedStatement stmt = ctx.query().prepareNativeStatement(req.cacheName(), req.query());
-
-            ParameterMetaData pmd = stmt.getParameterMetaData();
-
-            byte[] typeIds = new byte[pmd.getParameterCount()];
-
-            for (int i = 1; i <= pmd.getParameterCount(); ++i) {
-                int sqlType = pmd.getParameterType(i);
-
-                typeIds[i - 1] = sqlTypeToBinary(sqlType);
-            }
-
-            OdbcQueryGetParamsMetaResult res = new OdbcQueryGetParamsMetaResult(typeIds);
-
-            return new SqlListenerResponse(res);
-        }
-        catch (Exception e) {
-            U.error(log, "Failed to get params metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
-
-            return new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString());
-        }
-    }
-
-    /**
-     * Convert {@link java.sql.Types} to binary type constant (See {@link GridBinaryMarshaller} constants).
-     *
-     * @param sqlType SQL type.
-     * @return Binary type.
-     */
-    private static byte sqlTypeToBinary(int sqlType) {
-        switch (sqlType) {
-            case Types.BIGINT:
-                return GridBinaryMarshaller.LONG;
-
-            case Types.BOOLEAN:
-                return GridBinaryMarshaller.BOOLEAN;
-
-            case Types.DATE:
-                return GridBinaryMarshaller.DATE;
-
-            case Types.DOUBLE:
-                return GridBinaryMarshaller.DOUBLE;
-
-            case Types.FLOAT:
-            case Types.REAL:
-                return GridBinaryMarshaller.FLOAT;
-
-            case Types.NUMERIC:
-            case Types.DECIMAL:
-                return GridBinaryMarshaller.DECIMAL;
-
-            case Types.INTEGER:
-                return GridBinaryMarshaller.INT;
-
-            case Types.SMALLINT:
-                return GridBinaryMarshaller.SHORT;
-
-            case Types.TIME:
-                return GridBinaryMarshaller.TIME;
-
-            case Types.TIMESTAMP:
-                return GridBinaryMarshaller.TIMESTAMP;
-
-            case Types.TINYINT:
-                return GridBinaryMarshaller.BYTE;
-
-            case Types.CHAR:
-            case Types.VARCHAR:
-            case Types.LONGNVARCHAR:
-                return GridBinaryMarshaller.STRING;
-
-            case Types.NULL:
-                return GridBinaryMarshaller.NULL;
-
-            case Types.BINARY:
-            case Types.VARBINARY:
-            case Types.LONGVARBINARY:
-            default:
-                return GridBinaryMarshaller.BYTE_ARR;
-        }
-    }
-
-    /**
-     * Convert metadata in collection from {@link GridQueryFieldMetadata} to
-     * {@link SqlListenerColumnMeta}.
-     *
-     * @param meta Internal query field metadata.
-     * @return Odbc query field metadata.
-     */
-    private static Collection<SqlListenerColumnMeta> convertMetadata(Collection<?> meta) {
-        List<SqlListenerColumnMeta> res = new ArrayList<>();
-
-        if (meta != null) {
-            for (Object info : meta) {
-                assert info instanceof GridQueryFieldMetadata;
-
-                res.add(new SqlListenerColumnMeta((GridQueryFieldMetadata)info));
-            }
-        }
-
-        return res;
-    }
-
-    /**
-     * Checks whether string matches SQL pattern.
-     *
-     * @param str String.
-     * @param ptrn Pattern.
-     * @return Whether string matches pattern.
-     */
-    private static boolean matches(String str, String ptrn) {
-        return str != null && (F.isEmpty(ptrn) ||
-            str.toUpperCase().matches(ptrn.toUpperCase().replace("%", ".*").replace("_", ".")));
-    }
-}


[18/31] ignite git commit: IGNITE-5281: Indexing: changed "space" to "cacheName". No more "spaces". This closes #1992.

Posted by sb...@apache.org.
IGNITE-5281: Indexing: changed "space" to "cacheName". No more "spaces". This closes #1992.

:quit
:quit
mdules/web-console/frontend/app/modules/states/configuration/summary/summary-zipper.service.js~HEAD


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/cbf0b2a5
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/cbf0b2a5
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/cbf0b2a5

Branch: refs/heads/ignite-5075
Commit: cbf0b2a5873395b127e05b411136f2d30f449573
Parents: 018b25b
Author: devozerov <vo...@gridgain.com>
Authored: Tue May 23 20:37:55 2017 +0300
Committer: devozerov <vo...@gridgain.com>
Committed: Tue May 23 20:38:49 2017 +0300

----------------------------------------------------------------------
 .../ignite/internal/jdbc2/JdbcConnection.java   |   3 +-
 .../managers/indexing/GridIndexingManager.java  |  19 +-
 .../cache/query/GridCacheQueryManager.java      |  32 +--
 .../processors/query/GridQueryIndexing.java     |  85 +++---
 .../processors/query/GridQueryProcessor.java    | 153 +++++------
 .../processors/query/QueryIndexKey.java         |  20 +-
 .../query/QueryTypeDescriptorImpl.java          |  16 +-
 .../processors/query/QueryTypeIdKey.java        |  26 +-
 .../processors/query/QueryTypeNameKey.java      |  12 +-
 .../internal/processors/query/QueryUtils.java   |  14 +-
 .../schema/SchemaIndexCacheVisitorImpl.java     |  12 +-
 .../operation/SchemaAbstractOperation.java      |   2 +-
 .../spi/indexing/IndexingQueryFilter.java       |   8 +-
 .../apache/ignite/spi/indexing/IndexingSpi.java |  17 +-
 .../spi/indexing/noop/NoopIndexingSpi.java      |   6 +-
 .../IgniteTxExceptionAbstractSelfTest.java      |   6 +-
 .../cache/query/IndexingSpiQuerySelfTest.java   |  14 +-
 .../cache/query/IndexingSpiQueryTxSelfTest.java |   6 +-
 .../query/h2/DmlStatementsProcessor.java        |  51 ++--
 .../processors/query/h2/IgniteH2Indexing.java   | 258 +++++++++----------
 .../query/h2/database/H2PkHashIndex.java        |   4 +-
 .../query/h2/database/H2TreeIndex.java          |   4 +-
 .../query/h2/opt/GridH2IndexBase.java           |  10 +-
 .../processors/query/h2/opt/GridH2Table.java    |   2 +-
 .../query/h2/opt/GridH2TreeIndex.java           |   2 +-
 .../query/h2/opt/GridLuceneIndex.java           |  15 +-
 .../query/h2/twostep/GridMapQueryExecutor.java  |   2 +-
 .../h2/twostep/GridReduceQueryExecutor.java     |  30 +--
 .../DynamicIndexAbstractBasicSelfTest.java      |  18 +-
 .../DynamicIndexAbstractConcurrentSelfTest.java |   8 +-
 .../query/IgniteQueryDedicatedPoolTest.java     |   6 +-
 .../h2/GridIndexingSpiAbstractSelfTest.java     | 136 +++++-----
 .../query/h2/sql/GridQueryParsingTest.java      |   2 +-
 33 files changed, 491 insertions(+), 508 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcConnection.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcConnection.java b/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcConnection.java
index 8da385a..f6f79fb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcConnection.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcConnection.java
@@ -47,7 +47,6 @@ import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteClientDisconnectedException;
-import org.apache.ignite.IgniteCompute;
 import org.apache.ignite.IgniteDataStreamer;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteJdbcDriver;
@@ -708,7 +707,7 @@ public class JdbcConnection implements Connection {
     @Override public void setSchema(String schema) throws SQLException {
         assert ignite instanceof IgniteEx;
 
-        cacheName = ((IgniteEx)ignite).context().query().space(schema);
+        cacheName = ((IgniteEx)ignite).context().query().cacheName(schema);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/managers/indexing/GridIndexingManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/indexing/GridIndexingManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/indexing/GridIndexingManager.java
index a60cdbd..6d29604 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/indexing/GridIndexingManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/indexing/GridIndexingManager.java
@@ -79,14 +79,15 @@ public class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
     /**
      * Writes key-value pair to index.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param key Key.
      * @param val Value.
      * @param expirationTime Expiration time or 0 if never expires.
      * @throws IgniteCheckedException In case of error.
      */
     @SuppressWarnings("unchecked")
-    public <K, V> void store(final String space, final K key, final V val, long expirationTime) throws IgniteCheckedException {
+    public <K, V> void store(final String cacheName, final K key, final V val, long expirationTime)
+        throws IgniteCheckedException {
         assert key != null;
         assert val != null;
         assert enabled();
@@ -98,7 +99,7 @@ public class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
             if (log.isDebugEnabled())
                 log.debug("Storing key to cache query index [key=" + key + ", value=" + val + "]");
 
-            getSpi().store(space, key, val, expirationTime);
+            getSpi().store(cacheName, key, val, expirationTime);
         }
         finally {
             busyLock.leaveBusy();
@@ -106,12 +107,12 @@ public class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param key Key.
      * @throws IgniteCheckedException Thrown in case of any errors.
      */
     @SuppressWarnings("unchecked")
-    public void remove(String space, Object key) throws IgniteCheckedException {
+    public void remove(String cacheName, Object key) throws IgniteCheckedException {
         assert key != null;
         assert enabled();
 
@@ -119,7 +120,7 @@ public class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
             throw new IllegalStateException("Failed to remove from index (grid is stopping).");
 
         try {
-            getSpi().remove(space, key);
+            getSpi().remove(cacheName, key);
         }
         finally {
             busyLock.leaveBusy();
@@ -127,14 +128,14 @@ public class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param params Parameters collection.
      * @param filters Filters.
      * @return Query result.
      * @throws IgniteCheckedException If failed.
      */
     @SuppressWarnings("unchecked")
-    public IgniteSpiCloseableIterator<?> query(String space, Collection<Object> params, IndexingQueryFilter filters)
+    public IgniteSpiCloseableIterator<?> query(String cacheName, Collection<Object> params, IndexingQueryFilter filters)
         throws IgniteCheckedException {
         if (!enabled())
             throw new IgniteCheckedException("Indexing SPI is not configured.");
@@ -143,7 +144,7 @@ public class GridIndexingManager extends GridManagerAdapter<IndexingSpi> {
             throw new IllegalStateException("Failed to execute query (grid is stopping).");
 
         try {
-            final Iterator<?> res = getSpi().query(space, params, filters);
+            final Iterator<?> res = getSpi().query(cacheName, params, filters);
 
             if (res == null)
                 return new GridEmptyCloseableIterator<>();

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java
index 0a789ae..07545a5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryManager.java
@@ -173,7 +173,7 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
     private GridQueryProcessor qryProc;
 
     /** */
-    private String space;
+    private String cacheName;
 
     /** */
     private int maxIterCnt;
@@ -221,9 +221,9 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
 
         qryProc = cctx.kernalContext().query();
 
-        space = cctx.name();
+        cacheName = cctx.name();
 
-        enabled = qryProcEnabled || (isIndexingSpiEnabled() && !CU.isSystemCache(space));
+        enabled = qryProcEnabled || (isIndexingSpiEnabled() && !CU.isSystemCache(cacheName));
 
         maxIterCnt = ccfg.getMaxQueryIteratorsCount();
 
@@ -409,11 +409,11 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
 
                 Object val0 = unwrapIfNeeded(val, coctx);
 
-                cctx.kernalContext().indexing().store(space, key0, val0, expirationTime);
+                cctx.kernalContext().indexing().store(cacheName, key0, val0, expirationTime);
             }
 
             if(qryProcEnabled)
-                qryProc.store(space, key, partId, prevVal, prevVer, val, ver, expirationTime, link);
+                qryProc.store(cacheName, key, partId, prevVal, prevVer, val, ver, expirationTime, link);
         }
         finally {
             invalidateResultCache();
@@ -443,12 +443,12 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
             if (isIndexingSpiEnabled()) {
                 Object key0 = unwrapIfNeeded(key, cctx.cacheObjectContext());
 
-                cctx.kernalContext().indexing().remove(space, key0);
+                cctx.kernalContext().indexing().remove(cacheName, key0);
             }
 
             // val may be null if we have no previous value. We should not call processor in this case.
             if(qryProcEnabled && val != null)
-                qryProc.remove(space, key, partId, val, ver);
+                qryProc.remove(cacheName, key, partId, val, ver);
         }
         finally {
             invalidateResultCache();
@@ -628,7 +628,7 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
                             taskName));
                     }
 
-                    iter = qryProc.queryText(space, qry.clause(), qry.queryClassName(), filter(qry));
+                    iter = qryProc.queryText(cacheName, qry.clause(), qry.queryClassName(), filter(qry));
 
                     break;
 
@@ -739,7 +739,7 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
 
         try {
             if (qry.type() == SPI) {
-                IgniteSpiCloseableIterator<?> iter = cctx.kernalContext().indexing().query(space, F.asList(args),
+                IgniteSpiCloseableIterator<?> iter = cctx.kernalContext().indexing().query(cacheName, F.asList(args),
                     filter(qry));
 
                 res.onDone(iter);
@@ -1907,7 +1907,7 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
             // Remote nodes that have current cache.
             Collection<ClusterNode> nodes = F.view(cctx.discovery().remoteNodes(), new P1<ClusterNode>() {
                 @Override public boolean apply(ClusterNode n) {
-                    return cctx.kernalContext().discovery().cacheAffinityNode(n, space);
+                    return cctx.kernalContext().discovery().cacheAffinityNode(n, cacheName);
                 }
             });
 
@@ -1945,7 +1945,7 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
             Collection<GridCacheSqlMetadata> col = new ArrayList<>(map.size());
 
             // Metadata for current cache must be first in list.
-            col.add(new CacheSqlMetadata(map.remove(space)));
+            col.add(new CacheSqlMetadata(map.remove(cacheName)));
 
             for (Collection<CacheSqlMetadata> metas : map.values())
                 col.add(new CacheSqlMetadata(metas));
@@ -1969,10 +1969,10 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
             return null;
 
         return new IndexingQueryFilter() {
-            @Nullable @Override public IgniteBiPredicate<K, V> forSpace(final String spaceName) {
+            @Nullable @Override public IgniteBiPredicate<K, V> forCache(final String cacheName) {
                 final GridKernalContext ctx = cctx.kernalContext();
 
-                final GridCacheAdapter<Object, Object> cache = ctx.cache().internalCache(spaceName);
+                final GridCacheAdapter<Object, Object> cache = ctx.cache().internalCache(cacheName);
 
                 if (cache.context().isReplicated() || cache.configuration().getBackups() == 0)
                     return null;
@@ -2016,10 +2016,10 @@ public abstract class GridCacheQueryManager<K, V> extends GridCacheManagerAdapte
     /**
      * FOR TESTING ONLY
      *
-     * @return Indexing space for this query manager.
+     * @return Cache name for this query manager.
      */
-    public String space() {
-        return space;
+    public String cacheName() {
+        return cacheName;
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
index bfa223e..1f5e701 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
@@ -89,14 +89,14 @@ public interface GridQueryIndexing {
     /**
      * Perform a MERGE statement using data streamer as receiver.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param qry Query.
      * @param params Query parameters.
      * @param streamer Data streamer to feed data to.
      * @return Query result.
      * @throws IgniteCheckedException If failed.
      */
-    public long streamUpdateQuery(final String spaceName, final String qry, @Nullable final Object[] params,
+    public long streamUpdateQuery(String cacheName, String qry, @Nullable Object[] params,
         IgniteDataStreamer<?, ?> streamer) throws IgniteCheckedException;
 
     /**
@@ -104,7 +104,7 @@ public interface GridQueryIndexing {
      *
      * @param cctx Cache context.
      * @param qry Query.
-     * @param filter Space name and key filter.
+     * @param filter Cache name and key filter.
      * @param keepBinary Keep binary flag.
      * @return Cursor.
      */
@@ -116,7 +116,7 @@ public interface GridQueryIndexing {
      *
      * @param cctx Cache context.
      * @param qry Query.
-     * @param filter Space name and key filter.
+     * @param filter Cache name and key filter.
      * @param cancel Query cancel.
      * @return Cursor.
      */
@@ -126,84 +126,84 @@ public interface GridQueryIndexing {
     /**
      * Executes text query.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param qry Text query.
      * @param typeName Type name.
-     * @param filter Space name and key filter.
+     * @param filter Cache name and key filter.
      * @return Queried rows.
      * @throws IgniteCheckedException If failed.
      */
-    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalText(String spaceName, String qry,
+    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalText(String cacheName, String qry,
         String typeName, IndexingQueryFilter filter) throws IgniteCheckedException;
 
     /**
      * Create new index locally.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param tblName Table name.
      * @param idxDesc Index descriptor.
      * @param ifNotExists Ignore operation if index exists (instead of throwing an error).
      * @param cacheVisitor Cache visitor
      * @throws IgniteCheckedException if failed.
      */
-    public void dynamicIndexCreate(String spaceName, String tblName, QueryIndexDescriptorImpl idxDesc,
+    public void dynamicIndexCreate(String cacheName, String tblName, QueryIndexDescriptorImpl idxDesc,
         boolean ifNotExists, SchemaIndexCacheVisitor cacheVisitor) throws IgniteCheckedException;
 
     /**
-     * Remove index from the space.
+     * Remove index from the cache.
      *
-     * @param spaceName Space name.
+     * @param cacheName cache name.
      * @param idxName Index name.
      * @param ifExists Ignore operation if index does not exist (instead of throwing an error).
      * @throws IgniteCheckedException If failed.
      */
     @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
-    public void dynamicIndexDrop(String spaceName, String idxName, boolean ifExists)
+    public void dynamicIndexDrop(String cacheName, String idxName, boolean ifExists)
         throws IgniteCheckedException;
 
     /**
      * Registers cache.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param cctx Cache context.
      * @param ccfg Cache configuration.
      * @throws IgniteCheckedException If failed.
      */
-    public void registerCache(String spaceName, GridCacheContext<?,?> cctx, CacheConfiguration<?,?> ccfg)
+    public void registerCache(String cacheName, GridCacheContext<?,?> cctx, CacheConfiguration<?,?> ccfg)
         throws IgniteCheckedException;
 
     /**
      * Unregisters cache.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @throws IgniteCheckedException If failed to drop cache schema.
      */
-    public void unregisterCache(String spaceName) throws IgniteCheckedException;
+    public void unregisterCache(String cacheName) throws IgniteCheckedException;
 
     /**
      * Registers type if it was not known before or updates it otherwise.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param desc Type descriptor.
      * @throws IgniteCheckedException If failed.
      * @return {@code True} if type was registered, {@code false} if for some reason it was rejected.
      */
-    public boolean registerType(String spaceName, GridQueryTypeDescriptor desc) throws IgniteCheckedException;
+    public boolean registerType(String cacheName, GridQueryTypeDescriptor desc) throws IgniteCheckedException;
 
     /**
      * Unregisters type and removes all corresponding data.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param typeName Type name.
      * @throws IgniteCheckedException If failed.
      */
-    public void unregisterType(String spaceName, String typeName) throws IgniteCheckedException;
+    public void unregisterType(String cacheName, String typeName) throws IgniteCheckedException;
 
     /**
-     * Updates index. Note that key is unique for space, so if space contains multiple indexes
+     * Updates index. Note that key is unique for cache, so if cache contains multiple indexes
      * the key should be removed from indexes other than one being updated.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param typeName Type name.
      * @param key Key.
      * @param val Value.
@@ -211,47 +211,36 @@ public interface GridQueryIndexing {
      * @param expirationTime Expiration time or 0 if never expires.
      * @throws IgniteCheckedException If failed.
      */
-    public void store(String spaceName,
-        String typeName,
-        KeyCacheObject key,
-        int partId,
-        CacheObject val,
-        GridCacheVersion ver,
-        long expirationTime,
-        long link) throws IgniteCheckedException;
+    public void store(String cacheName, String typeName, KeyCacheObject key, int partId, CacheObject val,
+        GridCacheVersion ver, long expirationTime, long link) throws IgniteCheckedException;
 
     /**
      * Removes index entry by key.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param key Key.
      * @param val Value.
      * @throws IgniteCheckedException If failed.
      */
-    public void remove(String spaceName,
-        GridQueryTypeDescriptor type,
-        KeyCacheObject key,
-        int partId,
-        CacheObject val,
+    public void remove(String cacheName, GridQueryTypeDescriptor type, KeyCacheObject key, int partId, CacheObject val,
         GridCacheVersion ver) throws IgniteCheckedException;
 
     /**
      * Rebuilds all indexes of given type from hash index.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param type Type descriptor.
      * @throws IgniteCheckedException If failed.
      */
-    public void rebuildIndexesFromHash(String spaceName,
-        GridQueryTypeDescriptor type) throws IgniteCheckedException;
+    public void rebuildIndexesFromHash(String cacheName, GridQueryTypeDescriptor type) throws IgniteCheckedException;
 
     /**
      * Marks all indexes of given type for rebuild from hash index, making them unusable until rebuild finishes.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param type Type descriptor.
      */
-    public void markForRebuildFromHash(String spaceName, GridQueryTypeDescriptor type);
+    public void markForRebuildFromHash(String cacheName, GridQueryTypeDescriptor type);
 
     /**
      * Returns backup filter.
@@ -272,19 +261,19 @@ public interface GridQueryIndexing {
     /**
      * Prepare native statement to retrieve JDBC metadata from.
      *
-     * @param space Schema.
+     * @param cacheName Cache name.
      * @param sql Query.
      * @return {@link PreparedStatement} from underlying engine to supply metadata to Prepared - most likely H2.
      */
-    public PreparedStatement prepareNativeStatement(String space, String sql) throws SQLException;
+    public PreparedStatement prepareNativeStatement(String cacheName, String sql) throws SQLException;
 
     /**
-     * Gets space name from database schema.
+     * Gets cache name from database schema.
      *
      * @param schemaName Schema name. Could not be null. Could be empty.
-     * @return Space name. Could be null.
+     * @return Cache name. Could be null.
      */
-    public String space(String schemaName);
+    public String cacheName(String schemaName);
 
     /**
      * Collect queries that already running more than specified duration.
@@ -307,7 +296,7 @@ public interface GridQueryIndexing {
     public void cancelAllQueries();
 
     /**
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param nativeStmt Native statement.
      * @param autoFlushFreq Automatic data flushing frequency, disabled if {@code 0}.
      * @param nodeBufSize Per node buffer size - see {@link IgniteDataStreamer#perNodeBufferSize(int)}
@@ -316,6 +305,6 @@ public interface GridQueryIndexing {
      * @return {@link IgniteDataStreamer} tailored to specific needs of given native statement based on its metadata;
      * {@code null} if given statement is a query.
      */
-    public IgniteDataStreamer<?,?> createStreamer(String spaceName, PreparedStatement nativeStmt, long autoFlushFreq,
+    public IgniteDataStreamer<?,?> createStreamer(String cacheName, PreparedStatement nativeStmt, long autoFlushFreq,
         int nodeBufSize, int nodeParOps, boolean allowOverwrite);
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
index 0df0f52..ced78cf 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
@@ -166,7 +166,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     /** Coordinator node (initialized lazily). */
     private ClusterNode crd;
 
-    /** Registered spaces. */
+    /** Registered cache names. */
     private final Collection<String> cacheNames = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
 
     /** ID history for index create/drop discovery messages. */
@@ -668,7 +668,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
         try {
             synchronized (stateMux) {
-                String space = cctx.name();
+                String cacheName = cctx.name();
 
                 // Prepare candidates.
                 List<Class<?>> mustDeserializeClss = new ArrayList<>();
@@ -679,7 +679,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
                 if (!F.isEmpty(qryEntities)) {
                     for (QueryEntity qryEntity : qryEntities) {
-                        QueryTypeCandidate cand = QueryUtils.typeForQueryEntity(space, cctx, qryEntity,
+                        QueryTypeCandidate cand = QueryUtils.typeForQueryEntity(cacheName, cctx, qryEntity,
                             mustDeserializeClss);
 
                         cands.add(cand);
@@ -696,14 +696,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                     QueryTypeDescriptorImpl oldDesc = tblTypMap.put(desc.tableName(), desc);
 
                     if (oldDesc != null)
-                        throw new IgniteException("Duplicate table name [cache=" + space +
+                        throw new IgniteException("Duplicate table name [cache=" + cacheName +
                             ", tblName=" + desc.tableName() + ", type1=" + desc.name() + ", type2=" + oldDesc.name() + ']');
 
                     for (String idxName : desc.indexes().keySet()) {
                         oldDesc = idxTypMap.put(idxName, desc);
 
                         if (oldDesc != null)
-                            throw new IgniteException("Duplicate index name [cache=" + space +
+                            throw new IgniteException("Duplicate index name [cache=" + cacheName +
                                 ", idxName=" + idxName + ", type1=" + desc.name() + ", type2=" + oldDesc.name() + ']');
                     }
                 }
@@ -755,7 +755,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 }
 
                 // Ready to register at this point.
-                registerCache0(space, cctx, cands);
+                registerCache0(cacheName, cctx, cands);
 
                 // Warn about possible implicit deserialization.
                 if (!mustDeserializeClss.isEmpty()) {
@@ -1268,7 +1268,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     /**
      * Register cache in indexing SPI.
      *
-     * @param cacheName Space.
+     * @param cacheName Cache name.
      * @param cctx Cache context.
      * @param cands Candidates.
      * @throws IgniteCheckedException If failed.
@@ -1324,7 +1324,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * Unregister cache.<p>
      * Use with {@link #busyLock} where appropriate.
      *
-     * @param cacheName Space.
+     * @param cacheName Cache name.
      */
     public void onCacheStop0(String cacheName) {
         if (idx == null)
@@ -1337,7 +1337,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             while (it.hasNext()) {
                 Map.Entry<QueryTypeIdKey, QueryTypeDescriptorImpl> entry = it.next();
 
-                if (F.eq(cacheName, entry.getKey().space())) {
+                if (F.eq(cacheName, entry.getKey().cacheName())) {
                     it.remove();
 
                     typesByName.remove(new QueryTypeNameKey(cacheName, entry.getValue().name()));
@@ -1354,7 +1354,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
                 QueryIndexKey idxKey = idxEntry.getKey();
 
-                if (F.eq(cacheName, idxKey.space()))
+                if (F.eq(cacheName, idxKey.cacheName()))
                     idxIt.remove();
             }
 
@@ -1377,21 +1377,21 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * Check whether provided key and value belongs to expected space and table.
+     * Check whether provided key and value belongs to expected cache and table.
      *
      * @param cctx Target cache context.
-     * @param expSpace Expected space.
+     * @param expCacheName Expected cache name.
      * @param expTblName Expected table name.
      * @param key Key.
      * @param val Value.
-     * @return {@code True} if this key-value pair belongs to expected space/table, {@code false} otherwise or
-     *     if space or table doesn't exist.
+     * @return {@code True} if this key-value pair belongs to expected cache/table, {@code false} otherwise or
+     *     if cache or table doesn't exist.
      * @throws IgniteCheckedException If failed.
      */
     @SuppressWarnings("ConstantConditions")
-    public boolean belongsToTable(GridCacheContext cctx, String expSpace, String expTblName, KeyCacheObject key,
+    public boolean belongsToTable(GridCacheContext cctx, String expCacheName, String expTblName, KeyCacheObject key,
         CacheObject val) throws IgniteCheckedException {
-        QueryTypeDescriptorImpl desc = type(expSpace, val);
+        QueryTypeDescriptorImpl desc = type(expCacheName, val);
 
         if (desc == null)
             return false;
@@ -1424,14 +1424,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      */
     public IgniteInternalFuture<?> rebuildIndexesFromHash(Collection<Integer> cacheIds) {
         if (!busyLock.enterBusy())
-            throw new IllegalStateException("Failed to get space size (grid is stopping).");
+            throw new IllegalStateException("Failed to rebuild indexes from hash (grid is stopping).");
 
         try {
             GridCompoundFuture<Object, ?> fut = new GridCompoundFuture<Object, Object>();
 
             for (Map.Entry<QueryTypeIdKey, QueryTypeDescriptorImpl> e : types.entrySet()) {
-                if (cacheIds.contains(CU.cacheId(e.getKey().space())))
-                    fut.add(rebuildIndexesFromHash(e.getKey().space(), e.getValue()));
+                if (cacheIds.contains(CU.cacheId(e.getKey().cacheName())))
+                    fut.add(rebuildIndexesFromHash(e.getKey().cacheName(), e.getValue()));
             }
 
             fut.markInitialized();
@@ -1444,12 +1444,12 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param desc Type descriptor.
      * @return Future that will be completed when rebuilding of all indexes is finished.
      */
     private IgniteInternalFuture<Object> rebuildIndexesFromHash(
-        @Nullable final String space,
+        @Nullable final String cacheName,
         @Nullable final QueryTypeDescriptorImpl desc
     ) {
         if (idx == null)
@@ -1460,12 +1460,12 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
         final GridWorkerFuture<Object> fut = new GridWorkerFuture<>();
 
-        idx.markForRebuildFromHash(space, desc);
+        idx.markForRebuildFromHash(cacheName, desc);
 
         GridWorker w = new GridWorker(ctx.igniteInstanceName(), "index-rebuild-worker", log) {
             @Override protected void body() {
                 try {
-                    idx.rebuildIndexesFromHash(space, desc);
+                    idx.rebuildIndexesFromHash(cacheName, desc);
 
                     fut.onDone();
                 }
@@ -1490,17 +1490,17 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @return Cache object context.
      */
-    private CacheObjectContext cacheObjectContext(String space) {
-        return ctx.cache().internalCache(space).context().cacheObjectContext();
+    private CacheObjectContext cacheObjectContext(String cacheName) {
+        return ctx.cache().internalCache(cacheName).context().cacheObjectContext();
     }
 
     /**
      * Writes key-value pair to index.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param key Key.
      * @param val Value.
      * @param ver Cache entry version.
@@ -1508,7 +1508,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * @throws IgniteCheckedException In case of error.
      */
     @SuppressWarnings({"unchecked", "ConstantConditions"})
-    public void store(final String space,
+    public void store(final String cacheName,
         final KeyCacheObject key,
         int partId,
         @Nullable CacheObject prevVal,
@@ -1521,7 +1521,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
         assert val != null;
 
         if (log.isDebugEnabled())
-            log.debug("Store [space=" + space + ", key=" + key + ", val=" + val + "]");
+            log.debug("Store [cache=" + cacheName + ", key=" + key + ", val=" + val + "]");
 
         if (idx == null)
             return;
@@ -1530,7 +1530,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             throw new NodeStoppingException("Operation has been cancelled (node is stopping).");
 
         try {
-            CacheObjectContext coctx = cacheObjectContext(space);
+            CacheObjectContext coctx = cacheObjectContext(cacheName);
 
             QueryTypeDescriptorImpl desc = typeByValue(coctx, key, val, true);
 
@@ -1538,13 +1538,13 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 QueryTypeDescriptorImpl prevValDesc = typeByValue(coctx, key, prevVal, false);
 
                 if (prevValDesc != null && prevValDesc != desc)
-                    idx.remove(space, prevValDesc, key, partId, prevVal, prevVer);
+                    idx.remove(cacheName, prevValDesc, key, partId, prevVal, prevVer);
             }
 
             if (desc == null)
                 return;
 
-            idx.store(space, desc.name(), key, partId, val, ver, expirationTime, link);
+            idx.store(cacheName, desc.name(), key, partId, val, ver, expirationTime, link);
         }
         finally {
             busyLock.leaveBusy();
@@ -1606,25 +1606,25 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * Gets type descriptor for space by given object's type.
+     * Gets type descriptor for cache by given object's type.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param val Object to determine type for.
      * @return Type descriptor.
      * @throws IgniteCheckedException If failed.
      */
     @SuppressWarnings("ConstantConditions")
-    private QueryTypeDescriptorImpl type(@Nullable String space, CacheObject val) throws IgniteCheckedException {
-        CacheObjectContext coctx = cacheObjectContext(space);
+    private QueryTypeDescriptorImpl type(@Nullable String cacheName, CacheObject val) throws IgniteCheckedException {
+        CacheObjectContext coctx = cacheObjectContext(cacheName);
 
         QueryTypeIdKey id;
 
         boolean binaryVal = ctx.cacheObjects().isBinaryObject(val);
 
         if (binaryVal)
-            id = new QueryTypeIdKey(space, ctx.cacheObjects().typeId(val));
+            id = new QueryTypeIdKey(cacheName, ctx.cacheObjects().typeId(val));
         else
-            id = new QueryTypeIdKey(space, val.value(coctx, false).getClass());
+            id = new QueryTypeIdKey(cacheName, val.value(coctx, false).getClass());
 
         return types.get(id);
     }
@@ -1718,12 +1718,12 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * @param spaceName Cache name.
+     * @param cacheName Cache name.
      * @param streamer Data streamer.
      * @param qry Query.
      * @return Iterator.
      */
-    public long streamUpdateQuery(@Nullable final String spaceName,
+    public long streamUpdateQuery(@Nullable final String cacheName,
         final IgniteDataStreamer<?, ?> streamer, final String qry, final Object[] args) {
         assert streamer != null;
 
@@ -1731,11 +1731,11 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             throw new IllegalStateException("Failed to execute query (grid is stopping).");
 
         try {
-            GridCacheContext cctx = ctx.cache().cache(spaceName).context();
+            GridCacheContext cctx = ctx.cache().cache(cacheName).context();
 
             return executeQuery(GridCacheQueryType.SQL_FIELDS, qry, cctx, new IgniteOutClosureX<Long>() {
                 @Override public Long applyx() throws IgniteCheckedException {
-                    return idx.streamUpdateQuery(spaceName, qry, args, streamer);
+                    return idx.streamUpdateQuery(cacheName, qry, args, streamer);
                 }
             }, true);
         }
@@ -1966,28 +1966,28 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
     /**
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param sql Query.
      * @return {@link PreparedStatement} from underlying engine to supply metadata to Prepared - most likely H2.
      */
-    public PreparedStatement prepareNativeStatement(String space, String sql) throws SQLException {
+    public PreparedStatement prepareNativeStatement(String cacheName, String sql) throws SQLException {
         checkxEnabled();
 
-        return idx.prepareNativeStatement(space, sql);
+        return idx.prepareNativeStatement(cacheName, sql);
     }
 
     /**
      * @param schema Schema name.
-     * @return space (cache) name from schema name.
+     * @return Cache name from schema name.
      */
-    public String space(String schema) throws SQLException {
+    public String cacheName(String schema) throws SQLException {
         checkxEnabled();
 
-        return idx.space(schema);
+        return idx.cacheName(schema);
     }
 
     /**
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param nativeStmt Native statement.
      * @param autoFlushFreq Automatic data flushing frequency, disabled if {@code 0}.
      * @param nodeBufSize Per node buffer size - see {@link IgniteDataStreamer#perNodeBufferSize(int)}
@@ -1996,21 +1996,22 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * @see IgniteDataStreamer#allowOverwrite
      * @return {@link IgniteDataStreamer} tailored to specific needs of given native statement based on its metadata.
      */
-    public IgniteDataStreamer<?, ?> createStreamer(String spaceName, PreparedStatement nativeStmt, long autoFlushFreq,
+    public IgniteDataStreamer<?, ?> createStreamer(String cacheName, PreparedStatement nativeStmt, long autoFlushFreq,
         int nodeBufSize, int nodeParOps, boolean allowOverwrite) {
-        return idx.createStreamer(spaceName, nativeStmt, autoFlushFreq, nodeBufSize, nodeParOps, allowOverwrite);
+        return idx.createStreamer(cacheName, nativeStmt, autoFlushFreq, nodeBufSize, nodeParOps, allowOverwrite);
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param key Key.
      * @throws IgniteCheckedException Thrown in case of any errors.
      */
-    public void remove(String space, KeyCacheObject key, int partId, CacheObject val, GridCacheVersion ver) throws IgniteCheckedException {
+    public void remove(String cacheName, KeyCacheObject key, int partId, CacheObject val, GridCacheVersion ver)
+        throws IgniteCheckedException {
         assert key != null;
 
         if (log.isDebugEnabled())
-            log.debug("Remove [space=" + space + ", key=" + key + ", val=" + val + "]");
+            log.debug("Remove [cacheName=" + cacheName + ", key=" + key + ", val=" + val + "]");
 
         if (idx == null)
             return;
@@ -2019,14 +2020,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             throw new IllegalStateException("Failed to remove from index (grid is stopping).");
 
         try {
-            CacheObjectContext coctx = cacheObjectContext(space);
+            CacheObjectContext coctx = cacheObjectContext(cacheName);
 
             QueryTypeDescriptorImpl desc = typeByValue(coctx, key, val, false);
 
             if (desc == null)
                 return;
 
-            idx.remove(space, desc, key, partId, val, ver);
+            idx.remove(cacheName, desc, key, partId, val, ver);
         }
         finally {
             busyLock.leaveBusy();
@@ -2034,7 +2035,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param clause Clause.
      * @param resType Result type.
      * @param filters Key and value filters.
@@ -2044,7 +2045,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * @throws IgniteCheckedException If failed.
      */
     @SuppressWarnings("unchecked")
-    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryText(final String space, final String clause,
+    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryText(final String cacheName, final String clause,
         final String resType, final IndexingQueryFilter filters) throws IgniteCheckedException {
         checkEnabled();
 
@@ -2052,14 +2053,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             throw new IllegalStateException("Failed to execute query (grid is stopping).");
 
         try {
-            final GridCacheContext<?, ?> cctx = ctx.cache().internalCache(space).context();
+            final GridCacheContext<?, ?> cctx = ctx.cache().internalCache(cacheName).context();
 
             return executeQuery(GridCacheQueryType.TEXT, clause, cctx,
                 new IgniteOutClosureX<GridCloseableIterator<IgniteBiTuple<K, V>>>() {
                     @Override public GridCloseableIterator<IgniteBiTuple<K, V>> applyx() throws IgniteCheckedException {
-                        String typeName = typeName(space, resType);
+                        String typeName = typeName(cacheName, resType);
 
-                        return idx.queryLocalText(space, clause, typeName, filters);
+                        return idx.queryLocalText(cacheName, clause, typeName, filters);
                     }
                 }, true);
         }
@@ -2069,33 +2070,33 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * Gets types for space.
+     * Gets types for cache.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @return Descriptors.
      */
-    public Collection<GridQueryTypeDescriptor> types(@Nullable String space) {
-        Collection<GridQueryTypeDescriptor> spaceTypes = new ArrayList<>();
+    public Collection<GridQueryTypeDescriptor> types(@Nullable String cacheName) {
+        Collection<GridQueryTypeDescriptor> cacheTypes = new ArrayList<>();
 
         for (Map.Entry<QueryTypeIdKey, QueryTypeDescriptorImpl> e : types.entrySet()) {
             QueryTypeDescriptorImpl desc = e.getValue();
 
-            if (F.eq(e.getKey().space(), space))
-                spaceTypes.add(desc);
+            if (F.eq(e.getKey().cacheName(), cacheName))
+                cacheTypes.add(desc);
         }
 
-        return spaceTypes;
+        return cacheTypes;
     }
 
     /**
-     * Get type descriptor for the given space and table name.
-     * @param space Space.
+     * Get type descriptor for the given cache and table name.
+     * @param cacheName Cache name.
      * @param tblName Table name.
      * @return Type (if any).
      */
-    @Nullable private QueryTypeDescriptorImpl type(@Nullable String space, String tblName) {
+    @Nullable private QueryTypeDescriptorImpl type(@Nullable String cacheName, String tblName) {
         for (QueryTypeDescriptorImpl type : types.values()) {
-            if (F.eq(space, type.space()) && F.eq(tblName, type.tableName()))
+            if (F.eq(cacheName, type.cacheName()) && F.eq(tblName, type.tableName()))
                 return type;
         }
 
@@ -2103,15 +2104,15 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     }
 
     /**
-     * Gets type name for provided space and type name if type is still valid.
+     * Gets type name for provided cache name and type name if type is still valid.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param typeName Type name.
      * @return Type descriptor.
      * @throws IgniteCheckedException If failed.
      */
-    private String typeName(@Nullable String space, String typeName) throws IgniteCheckedException {
-        QueryTypeDescriptorImpl type = typesByName.get(new QueryTypeNameKey(space, typeName));
+    private String typeName(@Nullable String cacheName, String typeName) throws IgniteCheckedException {
+        QueryTypeDescriptorImpl type = typesByName.get(new QueryTypeNameKey(cacheName, typeName));
 
         if (type == null)
             throw new IgniteCheckedException("Failed to find SQL table for type: " + typeName);

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryIndexKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryIndexKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryIndexKey.java
index f580111..7fdb805 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryIndexKey.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryIndexKey.java
@@ -29,8 +29,8 @@ public class QueryIndexKey implements Serializable {
     /** */
     private static final long serialVersionUID = 0L;
 
-    /** Space. */
-    private final String space;
+    /** Cache name. */
+    private final String cacheName;
 
     /** Name. */
     private final String name;
@@ -38,19 +38,19 @@ public class QueryIndexKey implements Serializable {
     /**
      * Constructor.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param name Name.
      */
-    public QueryIndexKey(String space, String name) {
-        this.space = space;
+    public QueryIndexKey(String cacheName, String name) {
+        this.cacheName = cacheName;
         this.name = name;
     }
 
     /**
-     * @return Space.
+     * @return Cache name.
      */
-    public String space() {
-        return space;
+    public String cacheName() {
+        return cacheName;
     }
 
     /**
@@ -62,7 +62,7 @@ public class QueryIndexKey implements Serializable {
 
     /** {@inheritDoc} */
     @Override public int hashCode() {
-        return 31 * (space != null ? space.hashCode() : 0) + (name != null ? name.hashCode() : 0);
+        return 31 * (cacheName != null ? cacheName.hashCode() : 0) + (name != null ? name.hashCode() : 0);
     }
 
     /** {@inheritDoc} */
@@ -75,7 +75,7 @@ public class QueryIndexKey implements Serializable {
 
         QueryIndexKey other = (QueryIndexKey)o;
 
-        return F.eq(name, other.name) && F.eq(space, other.space);
+        return F.eq(name, other.name) && F.eq(cacheName, other.cacheName);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java
index 56c6aa5..4848b0a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java
@@ -36,8 +36,8 @@ import java.util.Map;
  * Descriptor of type.
  */
 public class QueryTypeDescriptorImpl implements GridQueryTypeDescriptor {
-    /** Space. */
-    private final String space;
+    /** Cache name. */
+    private final String cacheName;
 
     /** */
     private String name;
@@ -102,17 +102,17 @@ public class QueryTypeDescriptorImpl implements GridQueryTypeDescriptor {
     /**
      * Constructor.
      *
-     * @param space Cache name.
+     * @param cacheName Cache name.
      */
-    public QueryTypeDescriptorImpl(String space) {
-        this.space = space;
+    public QueryTypeDescriptorImpl(String cacheName) {
+        this.cacheName = cacheName;
     }
 
     /**
-     * @return Space.
+     * @return Cache name.
      */
-    public String space() {
-        return space;
+    public String cacheName() {
+        return cacheName;
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeIdKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeIdKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeIdKey.java
index 4d486f9..fe7c487 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeIdKey.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeIdKey.java
@@ -20,11 +20,11 @@ package org.apache.ignite.internal.processors.query;
 import org.apache.ignite.internal.util.typedef.internal.S;
 
 /**
- * Identifying TypeDescriptor by space and value class.
+ * Identifying TypeDescriptor by cache name and value class.
  */
 public class QueryTypeIdKey {
     /** */
-    private final String space;
+    private final String cacheName;
 
     /** Value type. */
     private final Class<?> valType;
@@ -35,13 +35,13 @@ public class QueryTypeIdKey {
     /**
      * Constructor.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param valType Value type.
      */
-    public  QueryTypeIdKey(String space, Class<?> valType) {
+    public  QueryTypeIdKey(String cacheName, Class<?> valType) {
         assert valType != null;
 
-        this.space = space;
+        this.cacheName = cacheName;
         this.valType = valType;
 
         valTypeId = 0;
@@ -50,21 +50,21 @@ public class QueryTypeIdKey {
     /**
      * Constructor.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param valTypeId Value type ID.
      */
-    public QueryTypeIdKey(String space, int valTypeId) {
-        this.space = space;
+    public QueryTypeIdKey(String cacheName, int valTypeId) {
+        this.cacheName = cacheName;
         this.valTypeId = valTypeId;
 
         valType = null;
     }
 
     /**
-     * @return Space.
+     * @return Cache name.
      */
-    public String space() {
-        return space;
+    public String cacheName() {
+        return cacheName;
     }
 
     /** {@inheritDoc} */
@@ -79,12 +79,12 @@ public class QueryTypeIdKey {
 
         return (valTypeId == typeId.valTypeId) &&
             (valType != null ? valType == typeId.valType : typeId.valType == null) &&
-            (space != null ? space.equals(typeId.space) : typeId.space == null);
+            (cacheName != null ? cacheName.equals(typeId.cacheName) : typeId.cacheName == null);
     }
 
     /** {@inheritDoc} */
     @Override public int hashCode() {
-        return 31 * (space != null ? space.hashCode() : 0) + (valType != null ? valType.hashCode() : valTypeId);
+        return 31 * (cacheName != null ? cacheName.hashCode() : 0) + (valType != null ? valType.hashCode() : valTypeId);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeNameKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeNameKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeNameKey.java
index 8a36a03..b10c5b2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeNameKey.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeNameKey.java
@@ -26,19 +26,19 @@ import org.jetbrains.annotations.Nullable;
  */
 public class QueryTypeNameKey {
     /** */
-    private final String space;
+    private final String cacheName;
 
     /** */
     private final String typeName;
 
     /**
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param typeName Type name.
      */
-    public QueryTypeNameKey(@Nullable String space, String typeName) {
+    public QueryTypeNameKey(@Nullable String cacheName, String typeName) {
         assert !F.isEmpty(typeName) : typeName;
 
-        this.space = space;
+        this.cacheName = cacheName;
         this.typeName = typeName;
     }
 
@@ -52,13 +52,13 @@ public class QueryTypeNameKey {
 
         QueryTypeNameKey other = (QueryTypeNameKey)o;
 
-        return (space != null ? space.equals(other.space) : other.space == null) &&
+        return (cacheName != null ? cacheName.equals(other.cacheName) : other.cacheName == null) &&
             typeName.equals(other.typeName);
     }
 
     /** {@inheritDoc} */
     @Override public int hashCode() {
-        return 31 * (space != null ? space.hashCode() : 0) + typeName.hashCode();
+        return 31 * (cacheName != null ? cacheName.hashCode() : 0) + typeName.hashCode();
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryUtils.java
index 1a80a37..245965c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryUtils.java
@@ -163,14 +163,14 @@ public class QueryUtils {
     /**
      * Create type candidate for query entity.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param cctx Cache context.
      * @param qryEntity Query entity.
      * @param mustDeserializeClss Classes which must be deserialized.
      * @return Type candidate.
      * @throws IgniteCheckedException If failed.
      */
-    public static QueryTypeCandidate typeForQueryEntity(String space, GridCacheContext cctx, QueryEntity qryEntity,
+    public static QueryTypeCandidate typeForQueryEntity(String cacheName, GridCacheContext cctx, QueryEntity qryEntity,
         List<Class<?>> mustDeserializeClss) throws IgniteCheckedException {
         GridKernalContext ctx = cctx.kernalContext();
         CacheConfiguration<?,?> ccfg = cctx.config();
@@ -179,7 +179,7 @@ public class QueryUtils {
 
         CacheObjectContext coCtx = binaryEnabled ? ctx.cacheObjects().contextForCache(ccfg) : null;
 
-        QueryTypeDescriptorImpl desc = new QueryTypeDescriptorImpl(space);
+        QueryTypeDescriptorImpl desc = new QueryTypeDescriptorImpl(cacheName);
 
         desc.aliases(qryEntity.getAliases());
 
@@ -244,10 +244,10 @@ public class QueryUtils {
         if (valCls == null || (binaryEnabled && !keyOrValMustDeserialize)) {
             processBinaryMeta(ctx, qryEntity, desc);
 
-            typeId = new QueryTypeIdKey(space, ctx.cacheObjects().typeId(qryEntity.findValueType()));
+            typeId = new QueryTypeIdKey(cacheName, ctx.cacheObjects().typeId(qryEntity.findValueType()));
 
             if (valCls != null)
-                altTypeId = new QueryTypeIdKey(space, valCls);
+                altTypeId = new QueryTypeIdKey(cacheName, valCls);
 
             if (!cctx.customAffinityMapper() && qryEntity.findKeyType() != null) {
                 // Need to setup affinity key for distributed joins.
@@ -270,8 +270,8 @@ public class QueryUtils {
                     desc.affinityKey(affField);
             }
 
-            typeId = new QueryTypeIdKey(space, valCls);
-            altTypeId = new QueryTypeIdKey(space, ctx.cacheObjects().typeId(qryEntity.findValueType()));
+            typeId = new QueryTypeIdKey(cacheName, valCls);
+            altTypeId = new QueryTypeIdKey(cacheName, ctx.cacheObjects().typeId(qryEntity.findValueType()));
         }
 
         return new QueryTypeCandidate(typeId, altTypeId, desc);

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheVisitorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheVisitorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheVisitorImpl.java
index 58c909d..b3fa47c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheVisitorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheVisitorImpl.java
@@ -48,8 +48,8 @@ public class SchemaIndexCacheVisitorImpl implements SchemaIndexCacheVisitor {
     /** Cache context. */
     private final GridCacheContext cctx;
 
-    /** Space name. */
-    private final String spaceName;
+    /** Cache name. */
+    private final String cacheName;
 
     /** Table name. */
     private final String tblName;
@@ -61,14 +61,14 @@ public class SchemaIndexCacheVisitorImpl implements SchemaIndexCacheVisitor {
      * Constructor.
      *
      * @param cctx Cache context.
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param tblName Table name.
      * @param cancel Cancellation token.
      */
-    public SchemaIndexCacheVisitorImpl(GridQueryProcessor qryProc, GridCacheContext cctx, String spaceName,
+    public SchemaIndexCacheVisitorImpl(GridQueryProcessor qryProc, GridCacheContext cctx, String cacheName,
         String tblName, SchemaIndexOperationCancellationToken cancel) {
         this.qryProc = qryProc;
-        this.spaceName = spaceName;
+        this.cacheName = cacheName;
         this.tblName = tblName;
         this.cancel = cancel;
 
@@ -190,7 +190,7 @@ public class SchemaIndexCacheVisitorImpl implements SchemaIndexCacheVisitor {
         /** {@inheritDoc} */
         @Override public void apply(KeyCacheObject key, int part, CacheObject val, GridCacheVersion ver,
             long expiration, long link) throws IgniteCheckedException {
-            if (qryProc.belongsToTable(cctx, spaceName, tblName, key, val))
+            if (qryProc.belongsToTable(cctx, cacheName, tblName, key, val))
                 target.apply(key, part, val, ver, expiration, link);
         }
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
index 726c90c..c45e229 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
@@ -58,7 +58,7 @@ public abstract class SchemaAbstractOperation implements Serializable {
     }
 
     /**
-     * @return Space.
+     * @return Cache name.
      */
     public String cacheName() {
         return cacheName;

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingQueryFilter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingQueryFilter.java b/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingQueryFilter.java
index 935feab..74d349a 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingQueryFilter.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingQueryFilter.java
@@ -25,17 +25,17 @@ import org.jetbrains.annotations.Nullable;
  */
 public interface IndexingQueryFilter {
     /**
-     * Creates optional predicate for space.
+     * Creates optional predicate for cache.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @return Predicate or {@code null} if no filtering is needed.
      */
-    @Nullable public <K, V> IgniteBiPredicate<K, V> forSpace(String spaceName);
+    @Nullable public <K, V> IgniteBiPredicate<K, V> forCache(String cacheName);
 
     /**
      * Is the value required for filtering logic?
      * If false then null instead of value will be passed
-     * to IgniteBiPredicate returned by {@link #forSpace(String)} method.
+     * to IgniteBiPredicate returned by {@link #forCache(String)} method.
      *
      * @return true if value is required for filtering, false otherwise.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingSpi.java
index 4d53bea..8ec4a67 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/indexing/IndexingSpi.java
@@ -25,8 +25,7 @@ import org.apache.ignite.spi.IgniteSpiException;
 import org.jetbrains.annotations.Nullable;
 
 /**
- * Indexing SPI allows user to index cache content. Using indexing SPI user can index data in cache and run
- * Usually cache name will be used as space name, so multiple caches can write to single indexing SPI instance.
+ * Indexing SPI allows user to index cache content. Using indexing SPI user can index data in cache and run queries.
  * <p>
  * <b>NOTE:</b> this SPI (i.e. methods in this interface) should never be used directly. SPIs provide
  * internal view on the subsystem and is used internally by Ignite kernal. In rare use cases when
@@ -66,33 +65,33 @@ public interface IndexingSpi extends IgniteSpi {
     /**
      * Executes query.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param params Query parameters.
      * @param filters System filters.
      * @return Query result. If the iterator implements {@link AutoCloseable} it will be correctly closed.
      * @throws IgniteSpiException If failed.
      */
-    public Iterator<Cache.Entry<?,?>> query(@Nullable String spaceName, Collection<Object> params,
+    public Iterator<Cache.Entry<?,?>> query(@Nullable String cacheName, Collection<Object> params,
         @Nullable IndexingQueryFilter filters) throws IgniteSpiException;
 
     /**
-     * Updates index. Note that key is unique for space, so if space contains multiple indexes
+     * Updates index. Note that key is unique for cache, so if cache contains multiple indexes
      * the key should be removed from indexes other than one being updated.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param key Key.
      * @param val Value.
      * @param expirationTime Expiration time or 0 if never expires.
      * @throws IgniteSpiException If failed.
      */
-    public void store(@Nullable String spaceName, Object key, Object val, long expirationTime) throws IgniteSpiException;
+    public void store(@Nullable String cacheName, Object key, Object val, long expirationTime) throws IgniteSpiException;
 
     /**
      * Removes index entry by key.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param key Key.
      * @throws IgniteSpiException If failed.
      */
-    public void remove(@Nullable String spaceName, Object key) throws IgniteSpiException;
+    public void remove(@Nullable String cacheName, Object key) throws IgniteSpiException;
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/main/java/org/apache/ignite/spi/indexing/noop/NoopIndexingSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/indexing/noop/NoopIndexingSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/indexing/noop/NoopIndexingSpi.java
index 0ed7e33..5677f55 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/indexing/noop/NoopIndexingSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/indexing/noop/NoopIndexingSpi.java
@@ -33,19 +33,19 @@ import org.jetbrains.annotations.Nullable;
 @IgniteSpiNoop
 public class NoopIndexingSpi extends IgniteSpiAdapter implements IndexingSpi {
     /** {@inheritDoc} */
-    @Override public Iterator<Cache.Entry<?,?>> query(@Nullable String spaceName, Collection<Object> params,
+    @Override public Iterator<Cache.Entry<?,?>> query(@Nullable String cacheName, Collection<Object> params,
         @Nullable IndexingQueryFilter filters) throws IgniteSpiException {
         throw new IgniteSpiException("You have to configure custom GridIndexingSpi implementation.");
     }
 
     /** {@inheritDoc} */
-    @Override public void store(@Nullable String spaceName, Object key, Object val, long expirationTime)
+    @Override public void store(@Nullable String cacheName, Object key, Object val, long expirationTime)
         throws IgniteSpiException {
         assert false;
     }
 
     /** {@inheritDoc} */
-    @Override public void remove(@Nullable String spaceName, Object key) throws IgniteSpiException {
+    @Override public void remove(@Nullable String cacheName, Object key) throws IgniteSpiException {
         assert false;
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxExceptionAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxExceptionAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxExceptionAbstractSelfTest.java
index 1d27524..ac294b0 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxExceptionAbstractSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxExceptionAbstractSelfTest.java
@@ -664,13 +664,13 @@ public abstract class IgniteTxExceptionAbstractSelfTest extends GridCacheAbstrac
         }
 
         /** {@inheritDoc} */
-        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String spaceName, Collection<Object> params,
+        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String cacheName, Collection<Object> params,
             @Nullable IndexingQueryFilter filters) throws IgniteSpiException {
             throw new UnsupportedOperationException();
         }
 
         /** {@inheritDoc} */
-        @Override public void store(@Nullable String spaceName, Object key, Object val, long expirationTime)
+        @Override public void store(@Nullable String cacheName, Object key, Object val, long expirationTime)
             throws IgniteSpiException {
             if (fail) {
                 fail = false;
@@ -680,7 +680,7 @@ public abstract class IgniteTxExceptionAbstractSelfTest extends GridCacheAbstrac
         }
 
         /** {@inheritDoc} */
-        @Override public void remove(@Nullable String spaceName, Object k)
+        @Override public void remove(@Nullable String cacheName, Object k)
             throws IgniteSpiException {
             if (fail) {
                 fail = false;

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQuerySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQuerySelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQuerySelfTest.java
index 7349a4e..b6e32d5 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQuerySelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQuerySelfTest.java
@@ -254,7 +254,7 @@ public class IndexingSpiQuerySelfTest extends TestCase {
         }
 
         /** {@inheritDoc} */
-        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String spaceName, Collection<Object> params,
+        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String cacheName, Collection<Object> params,
             @Nullable IndexingQueryFilter filters) throws IgniteSpiException {
             if (params.size() < 2)
                 throw new IgniteSpiException("Range parameters required.");
@@ -278,7 +278,7 @@ public class IndexingSpiQuerySelfTest extends TestCase {
         }
 
         /** {@inheritDoc} */
-        @Override public void store(@Nullable String spaceName, Object key, Object val, long expirationTime)
+        @Override public void store(@Nullable String cacheName, Object key, Object val, long expirationTime)
             throws IgniteSpiException {
             assertFalse(key instanceof BinaryObject);
             assertFalse(val instanceof BinaryObject);
@@ -287,7 +287,7 @@ public class IndexingSpiQuerySelfTest extends TestCase {
         }
 
         /** {@inheritDoc} */
-        @Override public void remove(@Nullable String spaceName, Object key) throws IgniteSpiException {
+        @Override public void remove(@Nullable String cacheName, Object key) throws IgniteSpiException {
             // No-op.
         }
     }
@@ -298,17 +298,17 @@ public class IndexingSpiQuerySelfTest extends TestCase {
     private static class MyBinaryIndexingSpi extends MyIndexingSpi {
 
         /** {@inheritDoc} */
-        @Override public void store(@Nullable String spaceName, Object key, Object val,
+        @Override public void store(@Nullable String cacheName, Object key, Object val,
             long expirationTime) throws IgniteSpiException {
             assertTrue(key instanceof BinaryObject);
 
             assertTrue(val instanceof BinaryObject);
 
-            super.store(spaceName, ((BinaryObject)key).deserialize(), ((BinaryObject)val).deserialize(), expirationTime);
+            super.store(cacheName, ((BinaryObject)key).deserialize(), ((BinaryObject)val).deserialize(), expirationTime);
         }
 
         /** {@inheritDoc} */
-        @Override public void remove(@Nullable String spaceName, Object key) throws IgniteSpiException {
+        @Override public void remove(@Nullable String cacheName, Object key) throws IgniteSpiException {
             assertTrue(key instanceof BinaryObject);
         }
     }
@@ -318,7 +318,7 @@ public class IndexingSpiQuerySelfTest extends TestCase {
      */
     private static class MyBrokenIndexingSpi extends MyIndexingSpi {
         /** {@inheritDoc} */
-        @Override public void store(@Nullable String spaceName, Object key, Object val,
+        @Override public void store(@Nullable String cacheName, Object key, Object val,
             long expirationTime) throws IgniteSpiException {
             throw new IgniteSpiException("Test exception");
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQueryTxSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQueryTxSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQueryTxSelfTest.java
index 9d2b31c..e59deed 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQueryTxSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/IndexingSpiQueryTxSelfTest.java
@@ -133,19 +133,19 @@ public class IndexingSpiQueryTxSelfTest extends GridCacheAbstractSelfTest {
         }
 
         /** {@inheritDoc} */
-        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String spaceName, Collection<Object> params,
+        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String cacheName, Collection<Object> params,
             @Nullable IndexingQueryFilter filters) throws IgniteSpiException {
            return null;
         }
 
         /** {@inheritDoc} */
-        @Override public void store(@Nullable String spaceName, Object key, Object val, long expirationTime)
+        @Override public void store(@Nullable String cacheName, Object key, Object val, long expirationTime)
             throws IgniteSpiException {
             throw new IgniteSpiException("Test exception");
         }
 
         /** {@inheritDoc} */
-        @Override public void remove(@Nullable String spaceName, Object key) throws IgniteSpiException {
+        @Override public void remove(@Nullable String cacheName, Object key) throws IgniteSpiException {
             // No-op.
         }
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
index 2a3d77c..db7bfd6 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
@@ -122,31 +122,31 @@ public class DmlStatementsProcessor {
     /**
      * Handle cache stop.
      *
-     * @param spaceName Cache name.
+     * @param cacheName Cache name.
      */
-    public void onCacheStop(String spaceName) {
-        planCache.remove(spaceName);
+    public void onCacheStop(String cacheName) {
+        planCache.remove(cacheName);
     }
 
     /**
      * Execute DML statement, possibly with few re-attempts in case of concurrent data modifications.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param stmt JDBC statement.
      * @param fieldsQry Original query.
      * @param loc Query locality flag.
-     * @param filters Space name and key filter.
+     * @param filters Cache name and key filter.
      * @param cancel Cancel.
      * @return Update result (modified items count and failed keys).
      * @throws IgniteCheckedException if failed.
      */
-    private UpdateResult updateSqlFields(String spaceName, PreparedStatement stmt, SqlFieldsQuery fieldsQry,
+    private UpdateResult updateSqlFields(String cacheName, PreparedStatement stmt, SqlFieldsQuery fieldsQry,
         boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
         Object[] errKeys = null;
 
         long items = 0;
 
-        UpdatePlan plan = getPlanForStatement(spaceName, stmt, null);
+        UpdatePlan plan = getPlanForStatement(cacheName, stmt, null);
 
         GridCacheContext<?, ?> cctx = plan.tbl.rowDescriptor().context();
 
@@ -194,7 +194,7 @@ public class DmlStatementsProcessor {
     }
 
     /**
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param stmt Prepared statement.
      * @param fieldsQry Initial query.
      * @param cancel Query cancel.
@@ -202,9 +202,9 @@ public class DmlStatementsProcessor {
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings("unchecked")
-    QueryCursorImpl<List<?>> updateSqlFieldsTwoStep(String spaceName, PreparedStatement stmt,
+    QueryCursorImpl<List<?>> updateSqlFieldsTwoStep(String cacheName, PreparedStatement stmt,
         SqlFieldsQuery fieldsQry, GridQueryCancel cancel) throws IgniteCheckedException {
-        UpdateResult res = updateSqlFields(spaceName, stmt, fieldsQry, false, null, cancel);
+        UpdateResult res = updateSqlFields(cacheName, stmt, fieldsQry, false, null, cancel);
 
         QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>)new QueryCursorImpl(Collections.singletonList
             (Collections.singletonList(res.cnt)), null, false);
@@ -216,17 +216,17 @@ public class DmlStatementsProcessor {
 
     /**
      * Execute DML statement on local cache.
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param stmt Prepared statement.
-     * @param filters Space name and key filter.
+     * @param filters Cache name and key filter.
      * @param cancel Query cancel.
      * @return Update result wrapped into {@link GridQueryFieldsResult}
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings("unchecked")
-    GridQueryFieldsResult updateLocalSqlFields(String spaceName, PreparedStatement stmt,
+    GridQueryFieldsResult updateLocalSqlFields(String cacheName, PreparedStatement stmt,
         SqlFieldsQuery fieldsQry, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
-        UpdateResult res = updateSqlFields(spaceName, stmt, fieldsQry, true, filters, cancel);
+        UpdateResult res = updateSqlFields(cacheName, stmt, fieldsQry, true, filters, cancel);
 
         return new GridQueryFieldsResultAdapter(UPDATE_RESULT_META,
             new IgniteSingletonIterator(Collections.singletonList(res.cnt)));
@@ -317,8 +317,9 @@ public class DmlStatementsProcessor {
      * Actually perform SQL DML operation locally.
      * @param cctx Cache context.
      * @param prepStmt Prepared statement for DML query.
-     * @param filters Space name and key filter.
-     * @param failedKeys Keys to restrict UPDATE and DELETE operations with. Null or empty array means no restriction.   @return Pair [number of successfully processed items; keys that have failed to be processed]
+     * @param filters Cache name and key filter.
+     * @param failedKeys Keys to restrict UPDATE and DELETE operations with. Null or empty array means no restriction.
+     * @return Pair [number of successfully processed items; keys that have failed to be processed]
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings({"ConstantConditions", "unchecked"})
@@ -392,28 +393,28 @@ public class DmlStatementsProcessor {
     /**
      * Generate SELECT statements to retrieve data for modifications from and find fast UPDATE or DELETE args,
      * if available.
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param prepStmt JDBC statement.
      * @return Update plan.
      */
     @SuppressWarnings({"unchecked", "ConstantConditions"})
-    private UpdatePlan getPlanForStatement(String spaceName, PreparedStatement prepStmt,
+    private UpdatePlan getPlanForStatement(String cacheName, PreparedStatement prepStmt,
         @Nullable Integer errKeysPos) throws IgniteCheckedException {
         Prepared p = GridSqlQueryParser.prepared(prepStmt);
 
-        spaceName = F.isEmpty(spaceName) ? "default" : spaceName;
+        cacheName = F.isEmpty(cacheName) ? "default" : cacheName;
 
-        ConcurrentMap<String, UpdatePlan> spacePlans = planCache.get(spaceName);
+        ConcurrentMap<String, UpdatePlan> cachePlans = planCache.get(cacheName);
 
-        if (spacePlans == null) {
-            spacePlans = new GridBoundedConcurrentLinkedHashMap<>(PLAN_CACHE_SIZE);
+        if (cachePlans == null) {
+            cachePlans = new GridBoundedConcurrentLinkedHashMap<>(PLAN_CACHE_SIZE);
 
-            spacePlans = U.firstNotNull(planCache.putIfAbsent(spaceName, spacePlans), spacePlans);
+            cachePlans = U.firstNotNull(planCache.putIfAbsent(cacheName, cachePlans), cachePlans);
         }
 
         // getSQL returns field value, so it's fast
         // Don't look for re-runs in cache, we don't cache them
-        UpdatePlan res = (errKeysPos == null ? spacePlans.get(p.getSQL()) : null);
+        UpdatePlan res = (errKeysPos == null ? cachePlans.get(p.getSQL()) : null);
 
         if (res != null)
             return res;
@@ -422,7 +423,7 @@ public class DmlStatementsProcessor {
 
         // Don't cache re-runs
         if (errKeysPos == null)
-            return U.firstNotNull(spacePlans.putIfAbsent(p.getSQL(), res), res);
+            return U.firstNotNull(cachePlans.putIfAbsent(p.getSQL(), res), res);
         else
             return res;
     }


[07/31] ignite git commit: IGNITE-5215 - Allow user to configure memory policy with maxSize smaller than default initialSize. Closes #1938

Posted by sb...@apache.org.
IGNITE-5215 - Allow user to configure memory policy with maxSize smaller than default initialSize. Closes #1938


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/661bb532
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/661bb532
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/661bb532

Branch: refs/heads/ignite-5075
Commit: 661bb532aa53de22610acc6ab1ef1f495cb6e3fe
Parents: 5582ebf
Author: Ivan Rakov <iv...@gmail.com>
Authored: Tue May 23 14:34:25 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue May 23 14:35:33 2017 +0300

----------------------------------------------------------------------
 .../configuration/MemoryConfiguration.java      |  3 ++-
 .../MemoryPolicyConfiguration.java              |  4 +--
 .../IgniteCacheDatabaseSharedManager.java       | 26 +++++++++++++++-----
 3 files changed, 24 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/661bb532/modules/core/src/main/java/org/apache/ignite/configuration/MemoryConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/MemoryConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/MemoryConfiguration.java
index 585335b..e6324dc 100644
--- a/modules/core/src/main/java/org/apache/ignite/configuration/MemoryConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/configuration/MemoryConfiguration.java
@@ -63,7 +63,8 @@ public class MemoryConfiguration implements Serializable {
     private static final long serialVersionUID = 0L;
 
     /** Default memory policy start size (256 MB). */
-    public static final long DFLT_MEMORY_POLICY_INITIAL_SIZE = 256 * 1024 * 1024;
+    @SuppressWarnings("UnnecessaryBoxing")
+    public static final Long DFLT_MEMORY_POLICY_INITIAL_SIZE = new Long(256L * 1024 * 1024);
 
     /** Fraction of available memory to allocate for default MemoryPolicy. */
     private static final double DFLT_MEMORY_POLICY_FRACTION = 0.8;

http://git-wip-us.apache.org/repos/asf/ignite/blob/661bb532/modules/core/src/main/java/org/apache/ignite/configuration/MemoryPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/MemoryPolicyConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/MemoryPolicyConfiguration.java
index 8e4d30e..2716d8e 100644
--- a/modules/core/src/main/java/org/apache/ignite/configuration/MemoryPolicyConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/configuration/MemoryPolicyConfiguration.java
@@ -70,7 +70,7 @@ public final class MemoryPolicyConfiguration implements Serializable {
     private String name = DFLT_MEM_PLC_DEFAULT_NAME;
 
     /** Memory policy start size. */
-    private long initialSize = MemoryConfiguration.DFLT_MEMORY_POLICY_INITIAL_SIZE;
+    private Long initialSize = MemoryConfiguration.DFLT_MEMORY_POLICY_INITIAL_SIZE;
 
     /** Memory policy maximum size. */
     private long maxSize = MemoryConfiguration.DFLT_MEMORY_POLICY_MAX_SIZE;
@@ -145,7 +145,7 @@ public final class MemoryPolicyConfiguration implements Serializable {
      *
      * @return Memory policy start size.
      */
-    public long getInitialSize() {
+    public Long getInitialSize() {
         return initialSize;
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/661bb532/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
index fbb3b0f..17c16b8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/IgniteCacheDatabaseSharedManager.java
@@ -55,11 +55,13 @@ import org.apache.ignite.internal.processors.cache.database.freelist.FreeListImp
 import org.apache.ignite.internal.processors.cache.database.tree.reuse.ReuseList;
 import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture;
 import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.LT;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport;
 import org.apache.ignite.mxbean.MemoryMetricsMXBean;
 import org.jetbrains.annotations.Nullable;
 
+import static org.apache.ignite.configuration.MemoryConfiguration.DFLT_MEMORY_POLICY_INITIAL_SIZE;
 import static org.apache.ignite.configuration.MemoryConfiguration.DFLT_MEM_PLC_DEFAULT_NAME;
 
 /**
@@ -419,18 +421,30 @@ public class IgniteCacheDatabaseSharedManager extends GridCacheSharedManagerAdap
      * @param plcCfg MemoryPolicyConfiguration to validate.
      * @throws IgniteCheckedException If config is invalid.
      */
-    private static void checkPolicySize(MemoryPolicyConfiguration plcCfg) throws IgniteCheckedException {
+    private void checkPolicySize(MemoryPolicyConfiguration plcCfg) throws IgniteCheckedException {
         if (plcCfg.getInitialSize() < MIN_PAGE_MEMORY_SIZE)
             throw new IgniteCheckedException("MemoryPolicy must have size more than 10MB (use " +
                 "MemoryPolicyConfiguration.initialSize property to set correct size in bytes) " +
                 "[name=" + plcCfg.getName() + ", size=" + U.readableSize(plcCfg.getInitialSize(), true) + "]"
             );
 
-        if (plcCfg.getMaxSize() < plcCfg.getInitialSize())
-            throw new IgniteCheckedException("MemoryPolicy maxSize must not be smaller than " +
-                "initialSize [name=" + plcCfg.getName() +
-                ", initSize=" + U.readableSize(plcCfg.getInitialSize(), true) +
-                ", maxSize=" + U.readableSize(plcCfg.getMaxSize(), true) + ']');
+        if (plcCfg.getMaxSize() < plcCfg.getInitialSize()) {
+            // We will know for sure if initialSize has been changed if we compare Longs by "==".
+            if (plcCfg.getInitialSize() == DFLT_MEMORY_POLICY_INITIAL_SIZE) {
+                plcCfg.setInitialSize(plcCfg.getMaxSize());
+
+                LT.warn(log, "MemoryPolicy maxSize=" + U.readableSize(plcCfg.getMaxSize(), true) +
+                    " is smaller than defaultInitialSize=" +
+                    U.readableSize(MemoryConfiguration.DFLT_MEMORY_POLICY_INITIAL_SIZE, true) +
+                    ", setting initialSize to " + U.readableSize(plcCfg.getMaxSize(), true));
+            }
+            else {
+                throw new IgniteCheckedException("MemoryPolicy maxSize must not be smaller than " +
+                    "initialSize [name=" + plcCfg.getName() +
+                    ", initSize=" + U.readableSize(plcCfg.getInitialSize(), true) +
+                    ", maxSize=" + U.readableSize(plcCfg.getMaxSize(), true) + ']');
+            }
+        }
 
         if (U.jvm32Bit() && plcCfg.getInitialSize() > MAX_PAGE_MEMORY_INIT_SIZE_32_BIT)
             throw new IgniteCheckedException("MemoryPolicy initialSize exceeds 2GB on 32-bit JVM (use " +


[30/31] ignite git commit: IGNITE-5284: Splitted IgniteH2Indexing into several classes. This closes #1999.

Posted by sb...@apache.org.
IGNITE-5284: Splitted IgniteH2Indexing into several classes. This closes #1999.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/8c75e4de
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/8c75e4de
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/8c75e4de

Branch: refs/heads/ignite-5075
Commit: 8c75e4de89496e1b80d854fbaa64d3bffa8193bd
Parents: d8eeea8
Author: devozerov <vo...@gridgain.com>
Authored: Wed May 24 15:38:14 2017 +0300
Committer: devozerov <vo...@gridgain.com>
Committed: Wed May 24 15:38:14 2017 +0300

----------------------------------------------------------------------
 .../query/h2/DmlStatementsProcessor.java        |   39 +-
 .../query/h2/GridH2ResultSetIterator.java       |  191 --
 .../query/h2/H2ConnectionWrapper.java           |   67 +
 .../processors/query/h2/H2DatabaseType.java     |  161 ++
 .../processors/query/h2/H2FieldsIterator.java   |   50 +
 .../processors/query/h2/H2KeyValueIterator.java |   48 +
 .../query/h2/H2ResultSetIterator.java           |  191 ++
 .../processors/query/h2/H2RowDescriptor.java    |  479 +++++
 .../internal/processors/query/h2/H2Schema.java  |  135 ++
 .../processors/query/h2/H2SqlFieldMetadata.java |  111 +
 .../processors/query/h2/H2StatementCache.java   |   73 +
 .../processors/query/h2/H2TableDescriptor.java  |  345 ++++
 .../processors/query/h2/H2TableEngine.java      |   89 +
 .../query/h2/H2TwoStepCachedQuery.java          |   49 +
 .../query/h2/H2TwoStepCachedQueryKey.java       |  107 +
 .../internal/processors/query/h2/H2Utils.java   |  299 +++
 .../processors/query/h2/IgniteH2Indexing.java   | 1941 ++----------------
 .../query/h2/sql/GridSqlQuerySplitter.java      |    4 +-
 .../query/h2/twostep/GridMapQueryExecutor.java  |    6 +-
 .../h2/twostep/GridReduceQueryExecutor.java     |   21 +-
 20 files changed, 2413 insertions(+), 1993 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
index e40c328..47b5ef4 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
@@ -125,13 +125,13 @@ public class DmlStatementsProcessor {
      * @param cacheName Cache name.
      */
     public void onCacheStop(String cacheName) {
-        planCache.remove(cacheName);
+        planCache.remove(idx.schema(cacheName));
     }
 
     /**
      * Execute DML statement, possibly with few re-attempts in case of concurrent data modifications.
      *
-     * @param cacheName Cache name.
+     * @param schema Schema.
      * @param stmt JDBC statement.
      * @param fieldsQry Original query.
      * @param loc Query locality flag.
@@ -140,14 +140,13 @@ public class DmlStatementsProcessor {
      * @return Update result (modified items count and failed keys).
      * @throws IgniteCheckedException if failed.
      */
-    private UpdateResult updateSqlFields(String cacheName, PreparedStatement stmt, SqlFieldsQuery fieldsQry,
-        boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel)
-        throws IgniteCheckedException {
+    private UpdateResult updateSqlFields(String schema, PreparedStatement stmt, SqlFieldsQuery fieldsQry,
+        boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
         Object[] errKeys = null;
 
         long items = 0;
 
-        UpdatePlan plan = getPlanForStatement(cacheName, stmt, null);
+        UpdatePlan plan = getPlanForStatement(schema, stmt, null);
 
         GridCacheContext<?, ?> cctx = plan.tbl.rowDescriptor().context();
 
@@ -195,7 +194,7 @@ public class DmlStatementsProcessor {
     }
 
     /**
-     * @param cacheName Cache name.
+     * @param schema Schema.
      * @param stmt Prepared statement.
      * @param fieldsQry Initial query
      * @param cancel Query cancel.
@@ -203,9 +202,9 @@ public class DmlStatementsProcessor {
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings("unchecked")
-    QueryCursorImpl<List<?>> updateSqlFieldsDistributed(String cacheName, PreparedStatement stmt,
+    QueryCursorImpl<List<?>> updateSqlFieldsDistributed(String schema, PreparedStatement stmt,
         SqlFieldsQuery fieldsQry, GridQueryCancel cancel) throws IgniteCheckedException {
-        UpdateResult res = updateSqlFields(cacheName, stmt, fieldsQry, false, null, cancel);
+        UpdateResult res = updateSqlFields(schema, stmt, fieldsQry, false, null, cancel);
 
         QueryCursorImpl<List<?>> resCur = (QueryCursorImpl<List<?>>)new QueryCursorImpl(Collections.singletonList
             (Collections.singletonList(res.cnt)), null, false);
@@ -217,7 +216,8 @@ public class DmlStatementsProcessor {
 
     /**
      * Execute DML statement on local cache.
-     * @param cacheName Cache name.
+     *
+     * @param schema Schema.
      * @param stmt Prepared statement.
      * @param fieldsQry Fields query.
      * @param filters Cache name and key filter.
@@ -226,10 +226,10 @@ public class DmlStatementsProcessor {
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings("unchecked")
-    GridQueryFieldsResult updateSqlFieldsLocal(String cacheName, PreparedStatement stmt,
+    GridQueryFieldsResult updateSqlFieldsLocal(String schema, PreparedStatement stmt,
         SqlFieldsQuery fieldsQry, IndexingQueryFilter filters, GridQueryCancel cancel)
         throws IgniteCheckedException {
-        UpdateResult res = updateSqlFields(cacheName, stmt, fieldsQry, true, filters, cancel);
+        UpdateResult res = updateSqlFields(schema, stmt, fieldsQry, true, filters, cancel);
 
         return new GridQueryFieldsResultAdapter(UPDATE_RESULT_META,
             new IgniteSingletonIterator(Collections.singletonList(res.cnt)));
@@ -333,7 +333,7 @@ public class DmlStatementsProcessor {
         Object[] failedKeys) throws IgniteCheckedException {
         Integer errKeysPos = null;
 
-        UpdatePlan plan = getPlanForStatement(cctx.name(), prepStmt, errKeysPos);
+        UpdatePlan plan = getPlanForStatement(idx.schema(cctx.name()), prepStmt, errKeysPos);
 
         if (plan.fastUpdateArgs != null) {
             assert F.isEmpty(failedKeys) && errKeysPos == null;
@@ -398,23 +398,22 @@ public class DmlStatementsProcessor {
     /**
      * Generate SELECT statements to retrieve data for modifications from and find fast UPDATE or DELETE args,
      * if available.
-     * @param cacheName Cache name.
+     *
+     * @param schema Schema.
      * @param prepStmt JDBC statement.
      * @return Update plan.
      */
     @SuppressWarnings({"unchecked", "ConstantConditions"})
-    private UpdatePlan getPlanForStatement(String cacheName, PreparedStatement prepStmt,
-        @Nullable Integer errKeysPos) throws IgniteCheckedException {
+    private UpdatePlan getPlanForStatement(String schema, PreparedStatement prepStmt, @Nullable Integer errKeysPos)
+        throws IgniteCheckedException {
         Prepared p = GridSqlQueryParser.prepared(prepStmt);
 
-        cacheName = F.isEmpty(cacheName) ? "default" : cacheName;
-
-        ConcurrentMap<String, UpdatePlan> cachePlans = planCache.get(cacheName);
+        ConcurrentMap<String, UpdatePlan> cachePlans = planCache.get(schema);
 
         if (cachePlans == null) {
             cachePlans = new GridBoundedConcurrentLinkedHashMap<>(PLAN_CACHE_SIZE);
 
-            cachePlans = U.firstNotNull(planCache.putIfAbsent(cacheName, cachePlans), cachePlans);
+            cachePlans = U.firstNotNull(planCache.putIfAbsent(schema, cachePlans), cachePlans);
         }
 
         // getSQL returns field value, so it's fast

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/GridH2ResultSetIterator.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/GridH2ResultSetIterator.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/GridH2ResultSetIterator.java
deleted file mode 100644
index fed292a..0000000
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/GridH2ResultSetIterator.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * 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.h2;
-
-import java.lang.reflect.Field;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.NoSuchElementException;
-import org.apache.ignite.IgniteCheckedException;
-import org.apache.ignite.internal.processors.cache.GridCacheContext;
-import org.apache.ignite.internal.processors.query.IgniteSQLException;
-import org.apache.ignite.internal.processors.query.h2.opt.GridH2ValueCacheObject;
-import org.apache.ignite.internal.util.GridCloseableIteratorAdapter;
-import org.apache.ignite.internal.util.typedef.internal.S;
-import org.apache.ignite.internal.util.typedef.internal.U;
-import org.h2.jdbc.JdbcResultSet;
-import org.h2.result.ResultInterface;
-import org.h2.value.Value;
-
-/**
- * Iterator over result set.
- */
-public abstract class GridH2ResultSetIterator<T> extends GridCloseableIteratorAdapter<T> {
-    /** */
-    private static final Field RESULT_FIELD;
-
-    /**
-     * Initialize.
-     */
-    static {
-        try {
-            RESULT_FIELD = JdbcResultSet.class.getDeclaredField("result");
-
-            RESULT_FIELD.setAccessible(true);
-        }
-        catch (NoSuchFieldException e) {
-            throw new IllegalStateException("Check H2 version in classpath.", e);
-        }
-    }
-
-    /** */
-    private static final long serialVersionUID = 0L;
-
-    /** */
-    private final ResultInterface res;
-
-    /** */
-    private final ResultSet data;
-
-    /** */
-    protected final Object[] row;
-
-    /** */
-    private final boolean closeStmt;
-
-    /** */
-    private boolean hasRow;
-
-    /**
-     * @param data Data array.
-     * @param closeStmt If {@code true} closes result set statement when iterator is closed.
-     * @param needCpy {@code True} if need copy cache object's value.
-     * @throws IgniteCheckedException If failed.
-     */
-    protected GridH2ResultSetIterator(ResultSet data, boolean closeStmt, boolean needCpy) throws IgniteCheckedException {
-        this.data = data;
-        this.closeStmt = closeStmt;
-
-        try {
-            res = needCpy ? (ResultInterface)RESULT_FIELD.get(data) : null;
-        }
-        catch (IllegalAccessException e) {
-            throw new IllegalStateException(e); // Must not happen.
-        }
-
-        if (data != null) {
-            try {
-                row = new Object[data.getMetaData().getColumnCount()];
-            }
-            catch (SQLException e) {
-                throw new IgniteCheckedException(e);
-            }
-        }
-        else
-            row = null;
-    }
-
-    /**
-     * @return {@code true} If next row was fetched successfully.
-     */
-    private boolean fetchNext() {
-        if (data == null)
-            return false;
-
-        try {
-            if (!data.next())
-                return false;
-
-            if (res != null) {
-                Value[] values = res.currentRow();
-
-                for (int c = 0; c < row.length; c++) {
-                    Value val = values[c];
-
-                    if (val instanceof GridH2ValueCacheObject) {
-                        GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c];
-
-                        GridCacheContext cctx = valCacheObj.getCacheContext();
-
-                        row[c] = valCacheObj.getObject(cctx != null && cctx.needValueCopy());
-                    }
-                    else
-                        row[c] = val.getObject();
-                }
-            }
-            else {
-                for (int c = 0; c < row.length; c++)
-                    row[c] = data.getObject(c + 1);
-            }
-
-            return true;
-        }
-        catch (SQLException e) {
-            throw new IgniteSQLException(e);
-        }
-    }
-
-    /** {@inheritDoc} */
-    @Override public boolean onHasNext() {
-        return hasRow || (hasRow = fetchNext());
-    }
-
-    /** {@inheritDoc} */
-    @SuppressWarnings("IteratorNextCanNotThrowNoSuchElementException")
-    @Override public T onNext() {
-        if (!hasNext())
-            throw new NoSuchElementException();
-
-        hasRow = false;
-
-        return createRow();
-    }
-
-    /**
-     * @return Row.
-     */
-    protected abstract T createRow();
-
-    /** {@inheritDoc} */
-    @Override public void onRemove() {
-        throw new UnsupportedOperationException();
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onClose() throws IgniteCheckedException {
-        if (data == null)
-            // Nothing to close.
-            return;
-
-        if (closeStmt) {
-            try {
-                U.closeQuiet(data.getStatement());
-            }
-            catch (SQLException e) {
-                throw new IgniteCheckedException(e);
-            }
-        }
-
-        U.closeQuiet(data);
-    }
-
-    /** {@inheritDoc} */
-    @Override public String toString() {
-        return S.toString(GridH2ResultSetIterator.class, this);
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ConnectionWrapper.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ConnectionWrapper.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ConnectionWrapper.java
new file mode 100644
index 0000000..e180c9c
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ConnectionWrapper.java
@@ -0,0 +1,67 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.jetbrains.annotations.Nullable;
+
+import java.sql.Connection;
+
+/**
+ * Wrapper to store connection and flag is schema set or not.
+ */
+public class H2ConnectionWrapper {
+    /** */
+    private Connection conn;
+
+    /** */
+    private volatile String schema;
+
+    /**
+     * @param conn Connection to use.
+     */
+    H2ConnectionWrapper(Connection conn) {
+        this.conn = conn;
+    }
+
+    /**
+     * @return Schema name if schema is set, null otherwise.
+     */
+    public String schema() {
+        return schema;
+    }
+
+    /**
+     * @param schema Schema name set on this connection.
+     */
+    public void schema(@Nullable String schema) {
+        this.schema = schema;
+    }
+
+    /**
+     * @return Connection.
+     */
+    public Connection connection() {
+        return conn;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(H2ConnectionWrapper.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2DatabaseType.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2DatabaseType.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2DatabaseType.java
new file mode 100644
index 0000000..47c7eb9
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2DatabaseType.java
@@ -0,0 +1,161 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.h2.value.DataType;
+
+import java.math.BigDecimal;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Enum that helps to map java types to database types.
+ */
+public enum H2DatabaseType {
+    /** */
+    INT("INT"),
+
+    /** */
+    BOOL("BOOL"),
+
+    /** */
+    TINYINT("TINYINT"),
+
+    /** */
+    SMALLINT("SMALLINT"),
+
+    /** */
+    BIGINT("BIGINT"),
+
+    /** */
+    DECIMAL("DECIMAL"),
+
+    /** */
+    DOUBLE("DOUBLE"),
+
+    /** */
+    REAL("REAL"),
+
+    /** */
+    TIME("TIME"),
+
+    /** */
+    TIMESTAMP("TIMESTAMP"),
+
+    /** */
+    DATE("DATE"),
+
+    /** */
+    VARCHAR("VARCHAR"),
+
+    /** */
+    CHAR("CHAR"),
+
+    /** */
+    BINARY("BINARY"),
+
+    /** */
+    UUID("UUID"),
+
+    /** */
+    ARRAY("ARRAY"),
+
+    /** */
+    GEOMETRY("GEOMETRY"),
+
+    /** */
+    OTHER("OTHER");
+
+    /** Map of Class to enum. */
+    private static final Map<Class<?>, H2DatabaseType> map = new HashMap<>();
+
+    /**
+     * Initialize map of DB types.
+     */
+    static {
+        map.put(int.class, INT);
+        map.put(Integer.class, INT);
+        map.put(boolean.class, BOOL);
+        map.put(Boolean.class, BOOL);
+        map.put(byte.class, TINYINT);
+        map.put(Byte.class, TINYINT);
+        map.put(short.class, SMALLINT);
+        map.put(Short.class, SMALLINT);
+        map.put(long.class, BIGINT);
+        map.put(Long.class, BIGINT);
+        map.put(BigDecimal.class, DECIMAL);
+        map.put(double.class, DOUBLE);
+        map.put(Double.class, DOUBLE);
+        map.put(float.class, REAL);
+        map.put(Float.class, REAL);
+        map.put(Time.class, TIME);
+        map.put(Timestamp.class, TIMESTAMP);
+        map.put(java.util.Date.class, TIMESTAMP);
+        map.put(java.sql.Date.class, DATE);
+        map.put(String.class, VARCHAR);
+        map.put(java.util.UUID.class, UUID);
+        map.put(byte[].class, BINARY);
+    }
+
+    /** */
+    private final String dbType;
+
+    /**
+     * Constructs new instance.
+     *
+     * @param dbType DB type name.
+     */
+    H2DatabaseType(String dbType) {
+        this.dbType = dbType;
+    }
+
+    /**
+     * Resolves enum by class.
+     *
+     * @param cls Class.
+     * @return Enum value.
+     */
+    public static H2DatabaseType fromClass(Class<?> cls) {
+        H2DatabaseType res = map.get(cls);
+
+        if (res != null)
+            return res;
+
+        if (DataType.isGeometryClass(cls))
+            return GEOMETRY;
+
+        return cls.isArray() && !cls.getComponentType().isPrimitive() ? ARRAY : OTHER;
+    }
+
+    /**
+     * Gets DB type name.
+     *
+     * @return DB type name.
+     */
+    public String dBTypeAsString() {
+        return dbType;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(H2DatabaseType.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2FieldsIterator.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2FieldsIterator.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2FieldsIterator.java
new file mode 100644
index 0000000..f300c3f
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2FieldsIterator.java
@@ -0,0 +1,50 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.IgniteCheckedException;
+
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Special field set iterator based on database result set.
+ */
+public class H2FieldsIterator extends H2ResultSetIterator<List<?>> {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * @param data Data.
+     * @throws IgniteCheckedException If failed.
+     */
+    public H2FieldsIterator(ResultSet data) throws IgniteCheckedException {
+        super(data, false, true);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected List<?> createRow() {
+        ArrayList<Object> res = new ArrayList<>(row.length);
+
+        Collections.addAll(res, row);
+
+        return res;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2KeyValueIterator.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2KeyValueIterator.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2KeyValueIterator.java
new file mode 100644
index 0000000..2088e44
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2KeyValueIterator.java
@@ -0,0 +1,48 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.lang.IgniteBiTuple;
+
+import java.sql.ResultSet;
+
+/**
+ * Special key/value iterator based on database result set.
+ */
+public class H2KeyValueIterator<K, V> extends H2ResultSetIterator<IgniteBiTuple<K, V>> {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * @param data Data array.
+     * @throws IgniteCheckedException If failed.
+     */
+    protected H2KeyValueIterator(ResultSet data) throws IgniteCheckedException {
+        super(data, false, true);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override protected IgniteBiTuple<K, V> createRow() {
+        K key = (K)row[0];
+        V val = (V)row[1];
+
+        return new IgniteBiTuple<>(key, val);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java
new file mode 100644
index 0000000..494f069
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java
@@ -0,0 +1,191 @@
+/*
+ * 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.h2;
+
+import java.lang.reflect.Field;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.NoSuchElementException;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2ValueCacheObject;
+import org.apache.ignite.internal.util.GridCloseableIteratorAdapter;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.h2.jdbc.JdbcResultSet;
+import org.h2.result.ResultInterface;
+import org.h2.value.Value;
+
+/**
+ * Iterator over result set.
+ */
+public abstract class H2ResultSetIterator<T> extends GridCloseableIteratorAdapter<T> {
+    /** */
+    private static final Field RESULT_FIELD;
+
+    /**
+     * Initialize.
+     */
+    static {
+        try {
+            RESULT_FIELD = JdbcResultSet.class.getDeclaredField("result");
+
+            RESULT_FIELD.setAccessible(true);
+        }
+        catch (NoSuchFieldException e) {
+            throw new IllegalStateException("Check H2 version in classpath.", e);
+        }
+    }
+
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private final ResultInterface res;
+
+    /** */
+    private final ResultSet data;
+
+    /** */
+    protected final Object[] row;
+
+    /** */
+    private final boolean closeStmt;
+
+    /** */
+    private boolean hasRow;
+
+    /**
+     * @param data Data array.
+     * @param closeStmt If {@code true} closes result set statement when iterator is closed.
+     * @param needCpy {@code True} if need copy cache object's value.
+     * @throws IgniteCheckedException If failed.
+     */
+    protected H2ResultSetIterator(ResultSet data, boolean closeStmt, boolean needCpy) throws IgniteCheckedException {
+        this.data = data;
+        this.closeStmt = closeStmt;
+
+        try {
+            res = needCpy ? (ResultInterface)RESULT_FIELD.get(data) : null;
+        }
+        catch (IllegalAccessException e) {
+            throw new IllegalStateException(e); // Must not happen.
+        }
+
+        if (data != null) {
+            try {
+                row = new Object[data.getMetaData().getColumnCount()];
+            }
+            catch (SQLException e) {
+                throw new IgniteCheckedException(e);
+            }
+        }
+        else
+            row = null;
+    }
+
+    /**
+     * @return {@code true} If next row was fetched successfully.
+     */
+    private boolean fetchNext() {
+        if (data == null)
+            return false;
+
+        try {
+            if (!data.next())
+                return false;
+
+            if (res != null) {
+                Value[] values = res.currentRow();
+
+                for (int c = 0; c < row.length; c++) {
+                    Value val = values[c];
+
+                    if (val instanceof GridH2ValueCacheObject) {
+                        GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c];
+
+                        GridCacheContext cctx = valCacheObj.getCacheContext();
+
+                        row[c] = valCacheObj.getObject(cctx != null && cctx.needValueCopy());
+                    }
+                    else
+                        row[c] = val.getObject();
+                }
+            }
+            else {
+                for (int c = 0; c < row.length; c++)
+                    row[c] = data.getObject(c + 1);
+            }
+
+            return true;
+        }
+        catch (SQLException e) {
+            throw new IgniteSQLException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean onHasNext() {
+        return hasRow || (hasRow = fetchNext());
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("IteratorNextCanNotThrowNoSuchElementException")
+    @Override public T onNext() {
+        if (!hasNext())
+            throw new NoSuchElementException();
+
+        hasRow = false;
+
+        return createRow();
+    }
+
+    /**
+     * @return Row.
+     */
+    protected abstract T createRow();
+
+    /** {@inheritDoc} */
+    @Override public void onRemove() {
+        throw new UnsupportedOperationException();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onClose() throws IgniteCheckedException {
+        if (data == null)
+            // Nothing to close.
+            return;
+
+        if (closeStmt) {
+            try {
+                U.closeQuiet(data.getStatement());
+            }
+            catch (SQLException e) {
+                throw new IgniteCheckedException(e);
+            }
+        }
+
+        U.closeQuiet(data);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(H2ResultSetIterator.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2RowDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2RowDescriptor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2RowDescriptor.java
new file mode 100644
index 0000000..6f5ce3e
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2RowDescriptor.java
@@ -0,0 +1,479 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.processors.cache.CacheObject;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.KeyCacheObject;
+import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
+import org.apache.ignite.internal.processors.query.GridQueryProperty;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2KeyValueRowOffheap;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2KeyValueRowOnheap;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Row;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowFactory;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2ValueCacheObject;
+import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeGuard;
+import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory;
+import org.h2.message.DbException;
+import org.h2.result.SearchRow;
+import org.h2.result.SimpleRow;
+import org.h2.value.DataType;
+import org.h2.value.Value;
+import org.h2.value.ValueArray;
+import org.h2.value.ValueBoolean;
+import org.h2.value.ValueByte;
+import org.h2.value.ValueBytes;
+import org.h2.value.ValueDate;
+import org.h2.value.ValueDecimal;
+import org.h2.value.ValueDouble;
+import org.h2.value.ValueFloat;
+import org.h2.value.ValueGeometry;
+import org.h2.value.ValueInt;
+import org.h2.value.ValueJavaObject;
+import org.h2.value.ValueLong;
+import org.h2.value.ValueNull;
+import org.h2.value.ValueShort;
+import org.h2.value.ValueString;
+import org.h2.value.ValueTime;
+import org.h2.value.ValueTimestamp;
+import org.h2.value.ValueUuid;
+import org.jetbrains.annotations.Nullable;
+
+import java.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.DEFAULT_COLUMNS_COUNT;
+import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.KEY_COL;
+import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.VAL_COL;
+import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.VER_COL;
+
+/**
+ * Row descriptor.
+ */
+public class H2RowDescriptor implements GridH2RowDescriptor {
+    /** Indexing SPI. */
+    private final IgniteH2Indexing idx;
+
+    /** */
+    private final GridQueryTypeDescriptor type;
+
+    /** */
+    private final String[] fields;
+
+    /** */
+    private final int[] fieldTypes;
+
+    /** */
+    private final int keyType;
+
+    /** */
+    private final int valType;
+
+    /** */
+    private final H2Schema schema;
+
+    /** */
+    private final GridUnsafeGuard guard;
+
+    /** */
+    private final boolean snapshotableIdx;
+
+    /** */
+    private final GridQueryProperty[] props;
+
+    /** Id of user-defined key column */
+    private final int keyAliasColumnId;
+
+    /** Id of user-defined value column */
+    private final int valueAliasColumnId;
+
+    /**
+     * @param type Type descriptor.
+     * @param schema Schema.
+     */
+    H2RowDescriptor(IgniteH2Indexing idx, GridQueryTypeDescriptor type, H2Schema schema) {
+        assert type != null;
+        assert schema != null;
+
+        this.idx = idx;
+        this.type = type;
+        this.schema = schema;
+
+        guard = schema.offheap() == null ? null : new GridUnsafeGuard();
+
+        Map<String, Class<?>> allFields = new LinkedHashMap<>();
+
+        allFields.putAll(type.fields());
+
+        fields = allFields.keySet().toArray(new String[allFields.size()]);
+
+        fieldTypes = new int[fields.length];
+
+        Class[] classes = allFields.values().toArray(new Class[fields.length]);
+
+        for (int i = 0; i < fieldTypes.length; i++)
+            fieldTypes[i] = DataType.getTypeFromClass(classes[i]);
+
+        keyType = DataType.getTypeFromClass(type.keyClass());
+        valType = DataType.getTypeFromClass(type.valueClass());
+
+        props = new GridQueryProperty[fields.length];
+
+        for (int i = 0; i < fields.length; i++) {
+            GridQueryProperty p = type.property(fields[i]);
+
+            assert p != null : fields[i];
+
+            props[i] = p;
+        }
+
+        final List<String> fieldsList = Arrays.asList(fields);
+        keyAliasColumnId = (type.keyFieldName() != null) ? DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.keyFieldName()) : -1;
+        valueAliasColumnId = (type.valueFieldName() != null) ? DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.valueFieldName()) : -1;
+
+        // Index is not snapshotable in db-x.
+        snapshotableIdx = false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteH2Indexing indexing() {
+        return idx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridQueryTypeDescriptor type() {
+        return type;
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridCacheContext<?, ?> context() {
+        return schema.cacheContext();
+    }
+
+    /** {@inheritDoc} */
+    @Override public CacheConfiguration configuration() {
+        return schema.cacheContext().config();
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridUnsafeGuard guard() {
+        return guard;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void cache(GridH2Row row) {
+        long ptr = row.pointer();
+
+        assert ptr > 0 : ptr;
+
+        schema.rowCache().put(ptr, row);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void uncache(long ptr) {
+        schema.rowCache().remove(ptr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridUnsafeMemory memory() {
+        return schema.offheap();
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("ConstantConditions")
+    @Override public Value wrap(Object obj, int type) throws IgniteCheckedException {
+        assert obj != null;
+
+        if (obj instanceof CacheObject) { // Handle cache object.
+            CacheObject co = (CacheObject)obj;
+
+            if (type == Value.JAVA_OBJECT)
+                return new GridH2ValueCacheObject(idx.cacheContext(schema.cacheName()), co);
+
+            obj = co.value(idx.objectContext(schema.cacheName()), false);
+        }
+
+        switch (type) {
+            case Value.BOOLEAN:
+                return ValueBoolean.get((Boolean)obj);
+            case Value.BYTE:
+                return ValueByte.get((Byte)obj);
+            case Value.SHORT:
+                return ValueShort.get((Short)obj);
+            case Value.INT:
+                return ValueInt.get((Integer)obj);
+            case Value.FLOAT:
+                return ValueFloat.get((Float)obj);
+            case Value.LONG:
+                return ValueLong.get((Long)obj);
+            case Value.DOUBLE:
+                return ValueDouble.get((Double)obj);
+            case Value.UUID:
+                UUID uuid = (UUID)obj;
+                return ValueUuid.get(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
+            case Value.DATE:
+                return ValueDate.get((Date)obj);
+            case Value.TIME:
+                return ValueTime.get((Time)obj);
+            case Value.TIMESTAMP:
+                if (obj instanceof java.util.Date && !(obj instanceof Timestamp))
+                    obj = new Timestamp(((java.util.Date)obj).getTime());
+
+                return ValueTimestamp.get((Timestamp)obj);
+            case Value.DECIMAL:
+                return ValueDecimal.get((BigDecimal)obj);
+            case Value.STRING:
+                return ValueString.get(obj.toString());
+            case Value.BYTES:
+                return ValueBytes.get((byte[])obj);
+            case Value.JAVA_OBJECT:
+                return ValueJavaObject.getNoCopy(obj, null, null);
+            case Value.ARRAY:
+                Object[] arr = (Object[])obj;
+
+                Value[] valArr = new Value[arr.length];
+
+                for (int i = 0; i < arr.length; i++) {
+                    Object o = arr[i];
+
+                    valArr[i] = o == null ? ValueNull.INSTANCE : wrap(o, DataType.getTypeFromClass(o.getClass()));
+                }
+
+                return ValueArray.get(valArr);
+
+            case Value.GEOMETRY:
+                return ValueGeometry.getFromGeometry(obj);
+        }
+
+        throw new IgniteCheckedException("Failed to wrap value[type=" + type + ", value=" + obj + "]");
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridH2Row createRow(KeyCacheObject key, int partId, @Nullable CacheObject val,
+        GridCacheVersion ver,
+        long expirationTime) throws IgniteCheckedException {
+        GridH2Row row;
+
+        try {
+            if (val == null) // Only can happen for remove operation, can create simple search row.
+                row = GridH2RowFactory.create(wrap(key, keyType));
+            else
+                row = schema.offheap() == null ?
+                    new GridH2KeyValueRowOnheap(this, key, keyType, val, valType, ver, expirationTime) :
+                    new GridH2KeyValueRowOffheap(this, key, keyType, val, valType, ver, expirationTime);
+        }
+        catch (ClassCastException e) {
+            throw new IgniteCheckedException("Failed to convert key to SQL type. " +
+                "Please make sure that you always store each value type with the same key type " +
+                "or configure key type as common super class for all actual keys for this value type.", e);
+        }
+
+        GridCacheContext cctx = idx.cacheContext(schema.cacheName());
+
+        if (cctx.offheapIndex()) {
+            row.ver = ver;
+
+            row.key = key;
+            row.val = val;
+            row.partId = partId;
+        }
+
+        return row;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int valueType() {
+        return valType;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int fieldsCount() {
+        return fields.length;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int fieldType(int col) {
+        return fieldTypes[col];
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object columnValue(Object key, Object val, int col) {
+        try {
+            return props[col].value(key, val);
+        }
+        catch (IgniteCheckedException e) {
+            throw DbException.convert(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setColumnValue(Object key, Object val, Object colVal, int col) {
+        try {
+            props[col].setValue(key, val, colVal);
+        }
+        catch (IgniteCheckedException e) {
+            throw DbException.convert(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isColumnKeyProperty(int col) {
+        return props[col].key();
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridH2KeyValueRowOffheap createPointer(long ptr) {
+        GridH2KeyValueRowOffheap row = (GridH2KeyValueRowOffheap)schema.rowCache().get(ptr);
+
+        if (row != null) {
+            assert row.pointer() == ptr : ptr + " " + row.pointer();
+
+            return row;
+        }
+
+        return new GridH2KeyValueRowOffheap(this, ptr);
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridH2Row cachedRow(long link) {
+        return schema.rowCache().get(link);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean snapshotableIndex() {
+        return snapshotableIdx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isKeyColumn(int columnId) {
+        assert columnId >= 0;
+        return columnId == KEY_COL || columnId == keyAliasColumnId;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isValueColumn(int columnId) {
+        assert columnId >= 0;
+        return columnId == VAL_COL || columnId == valueAliasColumnId;
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("RedundantIfStatement")
+    @Override public boolean isKeyValueOrVersionColumn(int columnId) {
+        assert columnId >= 0;
+
+        if (columnId < DEFAULT_COLUMNS_COUNT)
+            return true;
+
+        if (columnId == keyAliasColumnId)
+            return true;
+
+        if (columnId == valueAliasColumnId)
+            return true;
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean checkKeyIndexCondition(int masks[], int mask) {
+        assert masks != null;
+        assert masks.length > 0;
+
+        if (keyAliasColumnId < 0)
+            return (masks[KEY_COL] & mask) != 0;
+        else
+            return (masks[KEY_COL] & mask) != 0 || (masks[keyAliasColumnId] & mask) != 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void initValueCache(Value valCache[], Value key, Value value, Value version) {
+        assert valCache != null;
+        assert valCache.length > 0;
+
+        valCache[KEY_COL] = key;
+        valCache[VAL_COL] = value;
+        valCache[VER_COL] = version;
+
+        if (keyAliasColumnId > 0)
+            valCache[keyAliasColumnId] = key;
+
+        if (valueAliasColumnId > 0)
+            valCache[valueAliasColumnId] = value;
+    }
+
+    /** {@inheritDoc} */
+    @Override public SearchRow prepareProxyIndexRow(SearchRow row) {
+        if (row == null)
+            return null;
+
+        Value[] data = new Value[row.getColumnCount()];
+        for (int idx = 0; idx < data.length; idx++)
+            data[idx] = row.getValue(idx);
+
+        copyAliasColumnData(data, KEY_COL, keyAliasColumnId);
+        copyAliasColumnData(data, VAL_COL, valueAliasColumnId);
+
+        return new SimpleRow(data);
+    }
+
+    /**
+     * Copies data between original and alias columns
+     *
+     * @param data Array of values.
+     * @param colId Original column id.
+     * @param aliasColId Alias column id.
+     */
+    private void copyAliasColumnData(Value[] data, int colId, int aliasColId) {
+        if (aliasColId <= 0)
+            return;
+
+        if (data[aliasColId] == null && data[colId] != null)
+            data[aliasColId] = data[colId];
+
+        if (data[colId] == null && data[aliasColId] != null)
+            data[colId] = data[aliasColId];
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getAlternativeColumnId(int colId) {
+        if (keyAliasColumnId > 0) {
+            if (colId == KEY_COL)
+                return keyAliasColumnId;
+            else if (colId == keyAliasColumnId)
+                return KEY_COL;
+        }
+        if (valueAliasColumnId > 0) {
+            if (colId == VAL_COL)
+                return valueAliasColumnId;
+            else if (colId == valueAliasColumnId)
+                return VAL_COL;
+        }
+
+        return colId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Schema.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Schema.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Schema.java
new file mode 100644
index 0000000..603a0c1
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Schema.java
@@ -0,0 +1,135 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Row;
+import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory;
+import org.h2.mvstore.cache.CacheLongKeyLIRS;
+import org.jsr166.ConcurrentHashMap8;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * Database schema object.
+ */
+public class H2Schema {
+    /** */
+    private final String cacheName;
+
+    /** */
+    private final String schemaName;
+
+    /** */
+    private final GridUnsafeMemory offheap = null;
+
+    /** */
+    private final ConcurrentMap<String, H2TableDescriptor> tbls = new ConcurrentHashMap8<>();
+
+    /** Cache for deserialized offheap rows. */
+    private final CacheLongKeyLIRS<GridH2Row> rowCache;
+
+    /** */
+    private final GridCacheContext<?, ?> cctx;
+
+    /** */
+    private final CacheConfiguration<?, ?> ccfg;
+
+    /**
+     * @param cacheName Cache name.
+     * @param schemaName Schema name.
+     * @param cctx Cache context.
+     * @param ccfg Cache configuration.
+     */
+    H2Schema(String cacheName, String schemaName, GridCacheContext<?, ?> cctx,
+        CacheConfiguration<?, ?> ccfg) {
+        this.cacheName = cacheName;
+        this.cctx = cctx;
+        this.schemaName = schemaName;
+        this.ccfg = ccfg;
+
+        rowCache = null;
+    }
+
+    /**
+     * @return Cache context.
+     */
+    public GridCacheContext cacheContext() {
+        return cctx;
+    }
+
+    /**
+     * @return Cache name.
+     */
+    public String cacheName() {
+        return cacheName;
+    }
+
+    /**
+     * @return Schema name.
+     */
+    public String schemaName() {
+        return schemaName;
+    }
+
+    /**
+     * @return Unsafe memory.
+     */
+    public GridUnsafeMemory offheap() {
+        return offheap;
+    }
+
+    /**
+     * @return Row cache.
+     */
+    public CacheLongKeyLIRS<GridH2Row> rowCache() {
+        return rowCache;
+    }
+
+    /**
+     * @return Tables.
+     */
+    public Map<String, H2TableDescriptor> tables() {
+        return tbls;
+    }
+
+    /**
+     * @param tbl Table descriptor.
+     */
+    public void add(H2TableDescriptor tbl) {
+        if (tbls.putIfAbsent(tbl.typeName(), tbl) != null)
+            throw new IllegalStateException("Table already registered: " + tbl.fullTableName());
+    }
+
+    /**
+     * @return Escape all.
+     */
+    public boolean escapeAll() {
+        return ccfg.isSqlEscapeAll();
+    }
+
+    /**
+     * Called after the schema was dropped.
+     */
+    public void onDrop() {
+        for (H2TableDescriptor tblDesc : tbls.values())
+            tblDesc.onDrop();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2SqlFieldMetadata.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2SqlFieldMetadata.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2SqlFieldMetadata.java
new file mode 100644
index 0000000..46aa1fc
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2SqlFieldMetadata.java
@@ -0,0 +1,111 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+
+/**
+ * Field descriptor.
+ */
+public class H2SqlFieldMetadata implements GridQueryFieldMetadata {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Schema name. */
+    private String schemaName;
+
+    /** Type name. */
+    private String typeName;
+
+    /** Name. */
+    private String name;
+
+    /** Type. */
+    private String type;
+
+    /**
+     * Required by {@link Externalizable}.
+     */
+    public H2SqlFieldMetadata() {
+        // No-op
+    }
+
+    /**
+     * @param schemaName Schema name.
+     * @param typeName Type name.
+     * @param name Name.
+     * @param type Type.
+     */
+    H2SqlFieldMetadata(@Nullable String schemaName, @Nullable String typeName, String name, String type) {
+        assert name != null && type != null : schemaName + " | " + typeName + " | " + name + " | " + type;
+
+        this.schemaName = schemaName;
+        this.typeName = typeName;
+        this.name = name;
+        this.type = type;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String schemaName() {
+        return schemaName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String typeName() {
+        return typeName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String fieldName() {
+        return name;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String fieldTypeName() {
+        return type;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        U.writeString(out, schemaName);
+        U.writeString(out, typeName);
+        U.writeString(out, name);
+        U.writeString(out, type);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        schemaName = U.readString(in);
+        typeName = U.readString(in);
+        name = U.readString(in);
+        type = U.readString(in);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(H2SqlFieldMetadata.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2StatementCache.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2StatementCache.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2StatementCache.java
new file mode 100644
index 0000000..d395112
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2StatementCache.java
@@ -0,0 +1,73 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+import java.sql.PreparedStatement;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Statement cache.
+ */
+public class H2StatementCache extends LinkedHashMap<String, PreparedStatement> {
+    /** */
+    private int size;
+
+    /** Last usage. */
+    private volatile long lastUsage;
+
+    /**
+     * @param size Size.
+     */
+    H2StatementCache(int size) {
+        super(size, (float)0.75, true);
+
+        this.size = size;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected boolean removeEldestEntry(Map.Entry<String, PreparedStatement> eldest) {
+        boolean rmv = size() > size;
+
+        if (rmv) {
+            PreparedStatement stmt = eldest.getValue();
+
+            U.closeQuiet(stmt);
+        }
+
+        return rmv;
+    }
+
+    /**
+     * The timestamp of the last usage of the cache.
+     *
+     * @return last usage timestamp
+     */
+    public long lastUsage() {
+        return lastUsage;
+    }
+
+    /**
+     * Updates the {@link #lastUsage} timestamp by current time.
+     */
+    public void updateLastUsage() {
+        lastUsage = U.currentTimeMillis();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableDescriptor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableDescriptor.java
new file mode 100644
index 0000000..a9548aa
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableDescriptor.java
@@ -0,0 +1,345 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.QueryIndexType;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.query.GridQueryIndexDescriptor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.database.H2PkHashIndex;
+import org.apache.ignite.internal.processors.query.h2.database.H2RowFactory;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2IndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2SystemIndexFactory;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.processors.query.h2.opt.GridLuceneIndex;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.h2.index.Index;
+import org.h2.result.SortOrder;
+import org.h2.table.Column;
+import org.h2.table.IndexColumn;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.KEY_COL;
+
+/**
+ * Information about table in database.
+ */
+public class H2TableDescriptor implements GridH2SystemIndexFactory {
+    /** Indexing. */
+    private final IgniteH2Indexing idx;
+
+    /** */
+    private final String fullTblName;
+
+    /** */
+    private final GridQueryTypeDescriptor type;
+
+    /** */
+    private final H2Schema schema;
+
+    /** */
+    private GridH2Table tbl;
+
+    /** */
+    private GridLuceneIndex luceneIdx;
+
+    /** */
+    private H2PkHashIndex pkHashIdx;
+
+    /**
+     * Constructor.
+     *
+     * @param idx Indexing.
+     * @param schema Schema.
+     * @param type Type descriptor.
+     */
+    H2TableDescriptor(IgniteH2Indexing idx, H2Schema schema, GridQueryTypeDescriptor type) {
+        this.idx = idx;
+        this.type = type;
+        this.schema = schema;
+
+        String tblName = H2Utils.escapeName(type.tableName(), schema.escapeAll());
+
+        fullTblName = schema.schemaName() + "." + tblName;
+    }
+
+    /**
+     * @return Primary key hash index.
+     */
+    H2PkHashIndex primaryKeyHashIndex() {
+        return pkHashIdx;
+    }
+
+    /**
+     * @return Table.
+     */
+    public GridH2Table table() {
+        return tbl;
+    }
+
+    /**
+     * @param tbl Table.
+     */
+    public void table(GridH2Table tbl) {
+        this.tbl = tbl;
+    }
+
+    /**
+     * @return Schema.
+     */
+    public H2Schema schema() {
+        return schema;
+    }
+
+    /**
+     * @return Schema name.
+     */
+    public String schemaName() {
+        return schema.schemaName();
+    }
+
+    /**
+     * @return Database full table name.
+     */
+    String fullTableName() {
+        return fullTblName;
+    }
+
+    /**
+     * @return type name.
+     */
+    String typeName() {
+        return type.name();
+    }
+
+    /**
+     * @return Type.
+     */
+    GridQueryTypeDescriptor type() {
+        return type;
+    }
+
+    /**
+     * @return Lucene index.
+     */
+    GridLuceneIndex luceneIndex() {
+        return luceneIdx;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(H2TableDescriptor.class, this);
+    }
+
+    /**
+     * Create H2 row factory.
+     *
+     * @param rowDesc Row descriptor.
+     * @return H2 row factory.
+     */
+    H2RowFactory rowFactory(GridH2RowDescriptor rowDesc) {
+        GridCacheContext cctx = schema.cacheContext();
+
+        if (cctx.affinityNode() && cctx.offheapIndex())
+            return new H2RowFactory(rowDesc, cctx);
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public ArrayList<Index> createSystemIndexes(GridH2Table tbl) {
+        ArrayList<Index> idxs = new ArrayList<>();
+
+        IndexColumn keyCol = tbl.indexColumn(KEY_COL, SortOrder.ASCENDING);
+        IndexColumn affCol = tbl.getAffinityKeyColumn();
+
+        if (affCol != null && H2Utils.equals(affCol, keyCol))
+            affCol = null;
+
+        GridH2RowDescriptor desc = tbl.rowDescriptor();
+
+        Index hashIdx = createHashIndex(
+            schema,
+            tbl,
+            "_key_PK_hash",
+            H2Utils.treeIndexColumns(desc, new ArrayList<IndexColumn>(2), keyCol, affCol)
+        );
+
+        if (hashIdx != null)
+            idxs.add(hashIdx);
+
+        // Add primary key index.
+        Index pkIdx = idx.createSortedIndex(
+            schema,
+            "_key_PK",
+            tbl,
+            true,
+            H2Utils.treeIndexColumns(desc, new ArrayList<IndexColumn>(2), keyCol, affCol),
+            -1
+        );
+
+        idxs.add(pkIdx);
+
+        if (type().valueClass() == String.class) {
+            try {
+                luceneIdx = new GridLuceneIndex(idx.kernalContext(), schema.offheap(), schema.cacheName(), type);
+            }
+            catch (IgniteCheckedException e1) {
+                throw new IgniteException(e1);
+            }
+        }
+
+        boolean affIdxFound = false;
+
+        GridQueryIndexDescriptor textIdx = type.textIndex();
+
+        if (textIdx != null) {
+            try {
+                luceneIdx = new GridLuceneIndex(idx.kernalContext(), schema.offheap(), schema.cacheName(), type);
+            }
+            catch (IgniteCheckedException e1) {
+                throw new IgniteException(e1);
+            }
+        }
+
+        // Locate index where affinity column is first (if any).
+        if (affCol != null) {
+            for (GridQueryIndexDescriptor idxDesc : type.indexes().values()) {
+                if (idxDesc.type() != QueryIndexType.SORTED)
+                    continue;
+
+                String firstField = idxDesc.fields().iterator().next();
+
+                String firstFieldName =
+                    schema.escapeAll() ? firstField : H2Utils.escapeName(firstField, false).toUpperCase();
+
+                Column col = tbl.getColumn(firstFieldName);
+
+                IndexColumn idxCol = tbl.indexColumn(col.getColumnId(),
+                    idxDesc.descending(firstField) ? SortOrder.DESCENDING : SortOrder.ASCENDING);
+
+                affIdxFound |= H2Utils.equals(idxCol, affCol);
+            }
+        }
+
+        // Add explicit affinity key index if nothing alike was found.
+        if (affCol != null && !affIdxFound) {
+            idxs.add(idx.createSortedIndex(schema, "AFFINITY_KEY", tbl, false,
+                H2Utils.treeIndexColumns(desc, new ArrayList<IndexColumn>(2), affCol, keyCol), -1));
+        }
+
+        return idxs;
+    }
+
+    /**
+     * Get collection of user indexes.
+     *
+     * @return User indexes.
+     */
+    public Collection<GridH2IndexBase> createUserIndexes() {
+        assert tbl != null;
+
+        ArrayList<GridH2IndexBase> res = new ArrayList<>();
+
+        for (GridQueryIndexDescriptor idxDesc : type.indexes().values()) {
+            GridH2IndexBase idx = createUserIndex(idxDesc);
+
+            res.add(idx);
+        }
+
+        return res;
+    }
+
+    /**
+     * Create user index.
+     *
+     * @param idxDesc Index descriptor.
+     * @return Index.
+     */
+    public GridH2IndexBase createUserIndex(GridQueryIndexDescriptor idxDesc) {
+        String name = schema.escapeAll() ? idxDesc.name() : H2Utils.escapeName(idxDesc.name(), false).toUpperCase();
+
+        IndexColumn keyCol = tbl.indexColumn(KEY_COL, SortOrder.ASCENDING);
+        IndexColumn affCol = tbl.getAffinityKeyColumn();
+
+        List<IndexColumn> cols = new ArrayList<>(idxDesc.fields().size() + 2);
+
+        boolean escapeAll = schema.escapeAll();
+
+        for (String field : idxDesc.fields()) {
+            String fieldName = escapeAll ? field : H2Utils.escapeName(field, false).toUpperCase();
+
+            Column col = tbl.getColumn(fieldName);
+
+            cols.add(tbl.indexColumn(col.getColumnId(),
+                idxDesc.descending(field) ? SortOrder.DESCENDING : SortOrder.ASCENDING));
+        }
+
+        GridH2RowDescriptor desc = tbl.rowDescriptor();
+        if (idxDesc.type() == QueryIndexType.SORTED) {
+            cols = H2Utils.treeIndexColumns(desc, cols, keyCol, affCol);
+            return idx.createSortedIndex(schema, name, tbl, false, cols, idxDesc.inlineSize());
+        }
+        else if (idxDesc.type() == QueryIndexType.GEOSPATIAL) {
+            return H2Utils.createSpatialIndex(tbl, name, cols.toArray(new IndexColumn[cols.size()]));
+        }
+
+        throw new IllegalStateException("Index type: " + idxDesc.type());
+    }
+
+    /**
+     * Create hash index.
+     *
+     * @param schema Schema.
+     * @param tbl Table.
+     * @param idxName Index name.
+     * @param cols Columns.
+     * @return Index.
+     */
+    private Index createHashIndex(H2Schema schema, GridH2Table tbl, String idxName, List<IndexColumn> cols) {
+        GridCacheContext cctx = schema.cacheContext();
+
+        if (cctx.affinityNode() && cctx.offheapIndex()) {
+            assert pkHashIdx == null : pkHashIdx;
+
+            pkHashIdx = new H2PkHashIndex(cctx, tbl, idxName, cols);
+
+            return pkHashIdx;
+        }
+
+        return null;
+    }
+
+    /**
+     * Handle drop.
+     */
+    void onDrop() {
+        idx.removeDataTable(tbl);
+
+        tbl.destroy();
+
+        U.closeQuiet(luceneIdx);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableEngine.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableEngine.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableEngine.java
new file mode 100644
index 0000000..4cf5166
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableEngine.java
@@ -0,0 +1,89 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.internal.processors.query.h2.database.H2RowFactory;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.h2.api.TableEngine;
+import org.h2.command.ddl.CreateTableData;
+import org.h2.table.TableBase;
+import org.jetbrains.annotations.Nullable;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+/**
+ * H2 Table engine.
+ */
+public class H2TableEngine implements TableEngine {
+    /** */
+    private static GridH2RowDescriptor rowDesc0;
+
+    /** */
+    private static H2RowFactory rowFactory0;
+
+    /** */
+    private static H2TableDescriptor tblDesc0;
+
+    /** */
+    private static GridH2Table resTbl0;
+
+    /**
+     * Creates table using given connection, DDL clause for given type descriptor and list of indexes.
+     *
+     * @param conn Connection.
+     * @param sql DDL clause.
+     * @param rowDesc Row descriptor.
+     * @param rowFactory Row factory.
+     * @param tblDesc Table descriptor.
+     * @throws SQLException If failed.
+     * @return Created table.
+     */
+    public static synchronized GridH2Table createTable(Connection conn, String sql,
+        @Nullable GridH2RowDescriptor rowDesc, H2RowFactory rowFactory, H2TableDescriptor tblDesc)
+        throws SQLException {
+        rowDesc0 = rowDesc;
+        rowFactory0 = rowFactory;
+        tblDesc0 = tblDesc;
+
+        try {
+            try (Statement s = conn.createStatement()) {
+                s.execute(sql + " engine \"" + H2TableEngine.class.getName() + "\"");
+            }
+
+            tblDesc.table(resTbl0);
+
+            return resTbl0;
+        }
+        finally {
+            resTbl0 = null;
+            tblDesc0 = null;
+            rowFactory0 = null;
+            rowDesc0 = null;
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public TableBase createTable(CreateTableData createTblData) {
+        resTbl0 = new GridH2Table(createTblData, rowDesc0, rowFactory0, tblDesc0, tblDesc0.schema().cacheName());
+
+        return resTbl0;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQuery.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQuery.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQuery.java
new file mode 100644
index 0000000..dd1b44c
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQuery.java
@@ -0,0 +1,49 @@
+/*
+ * 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.h2;
+
+import org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery;
+import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
+import org.apache.ignite.internal.util.typedef.internal.S;
+
+import java.util.List;
+
+/**
+ * Cached two-step query.
+ */
+public class H2TwoStepCachedQuery {
+    /** */
+    final List<GridQueryFieldMetadata> meta;
+
+    /** */
+    final GridCacheTwoStepQuery twoStepQry;
+
+    /**
+     * @param meta Fields metadata.
+     * @param twoStepQry Query.
+     */
+    public H2TwoStepCachedQuery(List<GridQueryFieldMetadata> meta, GridCacheTwoStepQuery twoStepQry) {
+        this.meta = meta;
+        this.twoStepQry = twoStepQry;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(H2TwoStepCachedQuery.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQueryKey.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQueryKey.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQueryKey.java
new file mode 100644
index 0000000..1452a83
--- /dev/null
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TwoStepCachedQueryKey.java
@@ -0,0 +1,107 @@
+/*
+ * 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.h2;
+
+/**
+ * Key for cached two-step query.
+ */
+public class H2TwoStepCachedQueryKey {
+    /** */
+    private final String cacheName;
+
+    /** */
+    private final String sql;
+
+    /** */
+    private final boolean grpByCollocated;
+
+    /** */
+    private final boolean distributedJoins;
+
+    /** */
+    private final boolean enforceJoinOrder;
+
+    /** */
+    private final boolean isLocal;
+
+    /**
+     * @param cacheName Cache name.
+     * @param sql Sql.
+     * @param grpByCollocated Collocated GROUP BY.
+     * @param distributedJoins Distributed joins enabled.
+     * @param enforceJoinOrder Enforce join order of tables.
+     * @param isLocal Query is local flag.
+     */
+    H2TwoStepCachedQueryKey(String cacheName,
+        String sql,
+        boolean grpByCollocated,
+        boolean distributedJoins,
+        boolean enforceJoinOrder,
+        boolean isLocal) {
+        this.cacheName = cacheName;
+        this.sql = sql;
+        this.grpByCollocated = grpByCollocated;
+        this.distributedJoins = distributedJoins;
+        this.enforceJoinOrder = enforceJoinOrder;
+        this.isLocal = isLocal;
+    }
+
+    /**
+     * @return Cache name.
+     */
+    public String cacheName() {
+        return cacheName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean equals(Object o) {
+        if (this == o)
+            return true;
+
+        if (o == null || getClass() != o.getClass())
+            return false;
+
+        H2TwoStepCachedQueryKey that = (H2TwoStepCachedQueryKey)o;
+
+        if (grpByCollocated != that.grpByCollocated)
+            return false;
+
+        if (distributedJoins != that.distributedJoins)
+            return false;
+
+        if (enforceJoinOrder != that.enforceJoinOrder)
+            return false;
+
+        if (cacheName != null ? !cacheName.equals(that.cacheName) : that.cacheName != null)
+            return false;
+
+        return isLocal == that.isLocal && sql.equals(that.sql);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int hashCode() {
+        int res = cacheName != null ? cacheName.hashCode() : 0;
+        res = 31 * res + sql.hashCode();
+        res = 31 * res + (grpByCollocated ? 1 : 0);
+        res = res + (distributedJoins ? 2 : 0);
+        res = res + (enforceJoinOrder ? 4 : 0);
+        res = res + (isLocal ? 8 : 0);
+
+        return res;
+    }
+}


[06/31] ignite git commit: IGNITE-5054: Minor renames in GridQueryProcessor.

Posted by sb...@apache.org.
IGNITE-5054: Minor renames in GridQueryProcessor.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/5582ebf5
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/5582ebf5
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/5582ebf5

Branch: refs/heads/ignite-5075
Commit: 5582ebf55083e991d9889fba2f87c1e6c850fa67
Parents: 3ef7826
Author: devozerov <vo...@gridgain.com>
Authored: Tue May 23 14:29:35 2017 +0300
Committer: devozerov <vo...@gridgain.com>
Committed: Tue May 23 14:29:35 2017 +0300

----------------------------------------------------------------------
 .../processors/query/GridQueryProcessor.java    | 40 ++++++++++----------
 1 file changed, 20 insertions(+), 20 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/5582ebf5/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
index 1731edc..6a479ab 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
@@ -166,7 +166,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     private ClusterNode crd;
 
     /** Registered spaces. */
-    private final Collection<String> spaces = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
+    private final Collection<String> cacheNames = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
 
     /** ID history for index create/drop discovery messages. */
     private final GridBoundedConcurrentLinkedHashSet<IgniteUuid> dscoMsgIdHist =
@@ -578,7 +578,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
         boolean cacheExists = cacheDesc != null && F.eq(msg.deploymentId(), cacheDesc.deploymentId());
 
-        boolean cacheRegistered = cacheExists && spaces.contains(CU.mask(cacheName));
+        boolean cacheRegistered = cacheExists && cacheNames.contains(cacheName);
 
         // Validate schema state and decide whether we should proceed or not.
         SchemaAbstractOperation op = msg.operation();
@@ -1267,16 +1267,16 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     /**
      * Register cache in indexing SPI.
      *
-     * @param space Space.
+     * @param cacheName Space.
      * @param cctx Cache context.
      * @param cands Candidates.
      * @throws IgniteCheckedException If failed.
      */
-    private void registerCache0(String space, GridCacheContext<?, ?> cctx, Collection<QueryTypeCandidate> cands)
+    private void registerCache0(String cacheName, GridCacheContext<?, ?> cctx, Collection<QueryTypeCandidate> cands)
         throws IgniteCheckedException {
         synchronized (stateMux) {
             if (idx != null)
-                idx.registerCache(space, cctx, cctx.config());
+                idx.registerCache(cacheName, cctx, cctx.config());
 
             try {
                 for (QueryTypeCandidate cand : cands) {
@@ -1284,9 +1284,9 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                     QueryTypeIdKey altTypeId = cand.alternativeTypeId();
                     QueryTypeDescriptorImpl desc = cand.descriptor();
 
-                    if (typesByName.putIfAbsent(new QueryTypeNameKey(space, desc.name()), desc) != null)
+                    if (typesByName.putIfAbsent(new QueryTypeNameKey(cacheName, desc.name()), desc) != null)
                         throw new IgniteCheckedException("Type with name '" + desc.name() + "' already indexed " +
-                            "in cache '" + space + "'.");
+                            "in cache '" + cacheName + "'.");
 
                     types.put(typeId, desc);
 
@@ -1294,25 +1294,25 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                         types.put(altTypeId, desc);
 
                     for (QueryIndexDescriptorImpl idx : desc.indexes0()) {
-                        QueryIndexKey idxKey = new QueryIndexKey(space, idx.name());
+                        QueryIndexKey idxKey = new QueryIndexKey(cacheName, idx.name());
 
                         QueryIndexDescriptorImpl oldIdx = idxs.putIfAbsent(idxKey, idx);
 
                         if (oldIdx != null) {
-                            throw new IgniteException("Duplicate index name [cache=" + space +
+                            throw new IgniteException("Duplicate index name [cache=" + cacheName +
                                 ", idxName=" + idx.name() + ", existingTable=" + oldIdx.typeDescriptor().tableName() +
                                 ", table=" + desc.tableName() + ']');
                         }
                     }
 
                     if (idx != null)
-                        idx.registerType(space, desc);
+                        idx.registerType(cacheName, desc);
                 }
 
-                spaces.add(CU.mask(space));
+                cacheNames.add(CU.mask(cacheName));
             }
             catch (IgniteCheckedException | RuntimeException e) {
-                onCacheStop0(space);
+                onCacheStop0(cacheName);
 
                 throw e;
             }
@@ -1323,9 +1323,9 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * Unregister cache.<p>
      * Use with {@link #busyLock} where appropriate.
      *
-     * @param space Space.
+     * @param cacheName Space.
      */
-    public void onCacheStop0(String space) {
+    public void onCacheStop0(String cacheName) {
         if (idx == null)
             return;
 
@@ -1336,10 +1336,10 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             while (it.hasNext()) {
                 Map.Entry<QueryTypeIdKey, QueryTypeDescriptorImpl> entry = it.next();
 
-                if (F.eq(space, entry.getKey().space())) {
+                if (F.eq(cacheName, entry.getKey().space())) {
                     it.remove();
 
-                    typesByName.remove(new QueryTypeNameKey(space, entry.getValue().name()));
+                    typesByName.remove(new QueryTypeNameKey(cacheName, entry.getValue().name()));
 
                     entry.getValue().markObsolete();
                 }
@@ -1353,7 +1353,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
                 QueryIndexKey idxKey = idxEntry.getKey();
 
-                if (F.eq(space, idxKey.space()))
+                if (F.eq(cacheName, idxKey.space()))
                     idxIt.remove();
             }
 
@@ -1365,13 +1365,13 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
             // Notify indexing.
             try {
-                idx.unregisterCache(space);
+                idx.unregisterCache(cacheName);
             }
             catch (Exception e) {
-                U.error(log, "Failed to clear indexing on cache unregister (will ignore): " + space, e);
+                U.error(log, "Failed to clear indexing on cache unregister (will ignore): " + cacheName, e);
             }
 
-            spaces.remove(CU.mask(space));
+            cacheNames.remove(cacheName);
         }
     }
 


[27/31] ignite git commit: IGNITE-5284: Splitted IgniteH2Indexing into several classes. This closes #1999.

Posted by sb...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQuerySplitter.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQuerySplitter.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQuerySplitter.java
index 9f01346..8fcd7dc 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQuerySplitter.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQuerySplitter.java
@@ -37,6 +37,7 @@ import org.apache.ignite.IgniteException;
 import org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery;
 import org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery;
 import org.apache.ignite.internal.processors.cache.query.QueryTable;
+import org.apache.ignite.internal.processors.query.h2.H2Utils;
 import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.F;
@@ -47,7 +48,6 @@ import org.h2.command.dml.SelectUnion;
 import org.h2.jdbc.JdbcPreparedStatement;
 import org.jetbrains.annotations.Nullable;
 
-import static org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.setupConnection;
 import static org.apache.ignite.internal.processors.query.h2.opt.GridH2CollocationModel.isCollocated;
 import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlConst.TRUE;
 import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlFunctionType.AVG;
@@ -1413,7 +1413,7 @@ public class GridSqlQuerySplitter {
         boolean distributedJoins,
         boolean enforceJoinOrder
     ) throws SQLException, IgniteCheckedException {
-        setupConnection(c, distributedJoins, enforceJoinOrder);
+        H2Utils.setupConnection(c, distributedJoins, enforceJoinOrder);
 
         try (PreparedStatement s = c.prepareStatement(qry)) {
             h2.bindParameters(s, F.asList(params));

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
index 1d8a762..6fff8de 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
@@ -58,6 +58,7 @@ import org.apache.ignite.internal.processors.cache.query.GridCacheQueryMarshalla
 import org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery;
 import org.apache.ignite.internal.processors.cache.query.QueryTable;
 import org.apache.ignite.internal.processors.query.GridQueryCancel;
+import org.apache.ignite.internal.processors.query.h2.H2Utils;
 import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
 import org.apache.ignite.internal.processors.query.h2.opt.DistributedJoinMode;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext;
@@ -87,7 +88,6 @@ import static org.apache.ignite.events.EventType.EVT_CACHE_QUERY_OBJECT_READ;
 import static org.apache.ignite.internal.managers.communication.GridIoPolicy.QUERY_POOL;
 import static org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion.NONE;
 import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.OWNING;
-import static org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.setupConnection;
 import static org.apache.ignite.internal.processors.query.h2.opt.DistributedJoinMode.OFF;
 import static org.apache.ignite.internal.processors.query.h2.opt.DistributedJoinMode.distributedJoinMode;
 import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType.MAP;
@@ -581,7 +581,7 @@ public class GridMapQueryExecutor {
 
             Connection conn = h2.connectionForCache(mainCctx.name());
 
-            setupConnection(conn, distributedJoinMode != OFF, enforceJoinOrder);
+            H2Utils.setupConnection(conn, distributedJoinMode != OFF, enforceJoinOrder);
 
             GridH2QueryContext.set(qctx);
 
@@ -608,7 +608,7 @@ public class GridMapQueryExecutor {
                     // If we are not the target node for this replicated query, just ignore it.
                     if (qry.node() == null ||
                         (segmentId == 0 && qry.node().equals(ctx.localNodeId()))) {
-                        rs = h2.executeSqlQueryWithTimer(mainCctx.name(), conn, qry.query(),
+                        rs = h2.executeSqlQueryWithTimer(h2.schema(mainCctx.name()), conn, qry.query(),
                             F.asList(qry.parameters(params)), true,
                             timeout,
                             qr.cancels[qryIdx]);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
index 1ecbb40..a31263f 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
@@ -65,6 +65,8 @@ import org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery;
 import org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator;
 import org.apache.ignite.internal.processors.query.GridQueryCancel;
 import org.apache.ignite.internal.processors.query.GridRunningQueryInfo;
+import org.apache.ignite.internal.processors.query.h2.H2FieldsIterator;
+import org.apache.ignite.internal.processors.query.h2.H2Utils;
 import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext;
 import org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn;
@@ -100,7 +102,6 @@ import static java.util.Collections.singletonList;
 import static org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion.NONE;
 import static org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.SQL_FIELDS;
 import static org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery.EMPTY_PARAMS;
-import static org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.setupConnection;
 import static org.apache.ignite.internal.processors.query.h2.opt.DistributedJoinMode.OFF;
 import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType.REDUCE;
 import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlQuerySplitter.mergeTableIdentifier;
@@ -787,18 +788,20 @@ public class GridReduceQueryExecutor {
 
                         UUID locNodeId = ctx.localNodeId();
 
-                        setupConnection(r.conn, false, enforceJoinOrder);
+                        H2Utils.setupConnection(r.conn, false, enforceJoinOrder);
 
                         GridH2QueryContext.set(new GridH2QueryContext(locNodeId, locNodeId, qryReqId, REDUCE)
                             .pageSize(r.pageSize).distributedJoinMode(OFF));
 
                         try {
+                            String schema = h2.schema(cacheName);
+
                             if (qry.explain())
-                                return explainPlan(r.conn, cacheName, qry, params);
+                                return explainPlan(r.conn, schema, qry, params);
 
                             GridCacheSqlQuery rdc = qry.reduceQuery();
 
-                            ResultSet res = h2.executeSqlQueryWithTimer(cacheName,
+                            ResultSet res = h2.executeSqlQueryWithTimer(schema,
                                 r.conn,
                                 rdc.query(),
                                 F.asList(rdc.parameters(params)),
@@ -806,7 +809,7 @@ public class GridReduceQueryExecutor {
                                 timeoutMillis,
                                 cancel);
 
-                            resIter = new IgniteH2Indexing.FieldsIterator(res);
+                            resIter = new H2FieldsIterator(res);
                         }
                         finally {
                             GridH2QueryContext.clearThreadLocal();
@@ -1213,18 +1216,18 @@ public class GridReduceQueryExecutor {
 
     /**
      * @param c Connection.
-     * @param cacheName Cache name.
+     * @param schema Schema.
      * @param qry Query.
      * @param params Query parameters.
      * @return Cursor for plans.
      * @throws IgniteCheckedException if failed.
      */
-    private Iterator<List<?>> explainPlan(JdbcConnection c, String cacheName, GridCacheTwoStepQuery qry, Object[] params)
+    private Iterator<List<?>> explainPlan(JdbcConnection c, String schema, GridCacheTwoStepQuery qry, Object[] params)
         throws IgniteCheckedException {
         List<List<?>> lists = new ArrayList<>();
 
         for (int i = 0, mapQrys = qry.mapQueries().size(); i < mapQrys; i++) {
-            ResultSet rs = h2.executeSqlQueryWithTimer(cacheName, c,
+            ResultSet rs = h2.executeSqlQueryWithTimer(schema, c,
                 "SELECT PLAN FROM " + mergeTableIdentifier(i), null, false, 0, null);
 
             lists.add(F.asList(getPlan(rs)));
@@ -1240,7 +1243,7 @@ public class GridReduceQueryExecutor {
 
         GridCacheSqlQuery rdc = qry.reduceQuery();
 
-        ResultSet rs = h2.executeSqlQueryWithTimer(cacheName,
+        ResultSet rs = h2.executeSqlQueryWithTimer(schema,
             c,
             "EXPLAIN " + rdc.query(),
             F.asList(rdc.parameters(params)),


[22/31] ignite git commit: master - BPlusTree: compare with lvl

Posted by sb...@apache.org.
master - BPlusTree: compare with lvl


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/ff813891
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/ff813891
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/ff813891

Branch: refs/heads/ignite-5075
Commit: ff813891dffb24021f4f7b744cf30d58d919dc42
Parents: 33cb5e8
Author: Sergi Vladykin <se...@gmail.com>
Authored: Wed May 24 08:52:24 2017 +0300
Committer: Sergi Vladykin <se...@gmail.com>
Committed: Wed May 24 08:52:24 2017 +0300

----------------------------------------------------------------------
 .../cache/database/tree/BPlusTree.java          | 64 +++++++++++++-------
 1 file changed, 41 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/ff813891/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java
index a4c09d5..4d2110c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java
@@ -253,11 +253,12 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
             int cnt = io.getCount(pageAddr);
 
             int idx;
+
             if (g.findLast)
-                idx = io.isLeaf()? cnt - 1: -cnt - 1; //(-cnt - 1) mimics not_found result of findInsertionPoint
-                //in case of cnt = 0 we end up in 'not found' branch below with idx being 0 after fix() adjustment
+                idx = io.isLeaf() ? cnt - 1 : -cnt - 1; // (-cnt - 1) mimics not_found result of findInsertionPoint
+                // in case of cnt = 0 we end up in 'not found' branch below with idx being 0 after fix() adjustment
             else
-                idx = findInsertionPoint(io, pageAddr, 0, cnt, g.row, g.shift);
+                idx = findInsertionPoint(lvl, io, pageAddr, 0, cnt, g.row, g.shift);
 
             boolean found = idx >= 0;
 
@@ -338,7 +339,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
             assert p.btmLvl == 0 : "split is impossible with replace";
 
             final int cnt = io.getCount(pageAddr);
-            final int idx = findInsertionPoint(io, pageAddr, 0, cnt, p.row, 0);
+            final int idx = findInsertionPoint(lvl, io, pageAddr, 0, cnt, p.row, 0);
 
             if (idx < 0) // Not found, split or merge happened.
                 return RETRY;
@@ -399,7 +400,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
                 return RETRY;
 
             int cnt = io.getCount(pageAddr);
-            int idx = findInsertionPoint(io, pageAddr, 0, cnt, p.row, 0);
+            int idx = findInsertionPoint(lvl, io, pageAddr, 0, cnt, p.row, 0);
 
             if (idx >= 0) // We do not support concurrent put of the same key.
                 throw new IllegalStateException("Duplicate row in index.");
@@ -451,7 +452,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
 
             assert cnt <= Short.MAX_VALUE: cnt;
 
-            int idx = findInsertionPoint(io, leafAddr, 0, cnt, r.row, 0);
+            int idx = findInsertionPoint(lvl, io, leafAddr, 0, cnt, r.row, 0);
 
             if (idx < 0)
                 return RETRY; // We've found exact match on search but now it's gone.
@@ -1205,7 +1206,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
 
             validateDownPages(rootPageId, 0L, rootLvl);
 
-            validateDownKeys(rootPageId, null);
+            validateDownKeys(rootPageId, null, rootLvl);
         }
         finally {
             releasePage(metaPageId, metaPage);
@@ -1217,7 +1218,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
      * @param minRow Minimum row.
      * @throws IgniteCheckedException If failed.
      */
-    private void validateDownKeys(long pageId, L minRow) throws IgniteCheckedException {
+    private void validateDownKeys(long pageId, L minRow, int lvl) throws IgniteCheckedException {
         long page = acquirePage(pageId);
         try {
             long pageAddr = readLock(pageId, page); // No correctness guaranties.
@@ -1232,7 +1233,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
 
                 if (io.isLeaf()) {
                     for (int i = 0; i < cnt; i++) {
-                        if (minRow != null && compare(io, pageAddr, i, minRow) <= 0)
+                        if (minRow != null && compare(lvl, io, pageAddr, i, minRow) <= 0)
                             fail("Wrong sort order: " + U.hexLong(pageId) + " , at " + i + " , minRow: " + minRow);
 
                         minRow = io.getLookupRow(this, pageAddr, i);
@@ -1245,20 +1246,20 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
                 for (int i = 0; i < cnt; i++) {
                     L row = io.getLookupRow(this, pageAddr, i);
 
-                    if (minRow != null && compare(io, pageAddr, i, minRow) <= 0)
+                    if (minRow != null && compare(lvl, io, pageAddr, i, minRow) <= 0)
                         fail("Min row violated: " + row + " , minRow: " + minRow);
 
                     long leftId = inner(io).getLeft(pageAddr, i);
 
                     L leafRow = getGreatestRowInSubTree(leftId);
 
-                    int cmp = compare(io, pageAddr, i, leafRow);
+                    int cmp = compare(lvl, io, pageAddr, i, leafRow);
 
                     if (cmp < 0 || (cmp != 0 && canGetRowFromInner))
                         fail("Wrong inner row: " + U.hexLong(pageId) + " , at: " + i + " , leaf:  " + leafRow +
                             " , inner: " + row);
 
-                    validateDownKeys(leftId, minRow);
+                    validateDownKeys(leftId, minRow, lvl - 1);
 
                     minRow = row;
                 }
@@ -1266,7 +1267,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
                 // Need to handle the rightmost child subtree separately or handle empty routing page.
                 long rightId = inner(io).getLeft(pageAddr, cnt); // The same as getRight(cnt - 1)
 
-                validateDownKeys(rightId, minRow);
+                validateDownKeys(rightId, minRow, lvl - 1);
             }
             finally {
                 readUnlock(pageId, page, pageAddr);
@@ -2694,7 +2695,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
                 assert fwdPageAddr != 0L;
 
                 // TODO GG-11640 log a correct forward page record.
-                Boolean fwdPageWalPlc = Boolean.TRUE;
+                final Boolean fwdPageWalPlc = Boolean.TRUE;
 
                 try {
                     boolean midShift = splitPage(pageId, page, pageAddr, io, fwdId, fwdPageAddr, idx);
@@ -2742,7 +2743,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
                             assert newRootAddr != 0L;
 
                             // Never write full new root page, because it is known to be new.
-                            Boolean newRootPageWalPlc = Boolean.FALSE;
+                            final Boolean newRootPageWalPlc = Boolean.FALSE;
 
                             try {
                                 boolean needWal = needWalDeltaRecord(newRootId, newRootPage, newRootPageWalPlc);
@@ -3650,7 +3651,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
             assert tail.type == Tail.EXACT: tail.type;
 
             if (tail.idx == Short.MIN_VALUE) {
-                int idx = findInsertionPoint(tail.io, tail.buf, 0, tail.getCount(), row, 0);
+                int idx = findInsertionPoint(tail.lvl, tail.io, tail.buf, 0, tail.getCount(), row, 0);
 
                 assert checkIndex(idx): idx;
 
@@ -4173,7 +4174,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
         private byte type;
 
         /** */
-        private final byte lvl;
+        private final int lvl;
 
         /** */
         private short idx = Short.MIN_VALUE;
@@ -4249,7 +4250,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
      * @return Insertion point as in {@link Arrays#binarySearch(Object[], Object, Comparator)}.
      * @throws IgniteCheckedException If failed.
      */
-    private int findInsertionPoint(BPlusIO<L> io, long buf, int low, int cnt, L row, int shift)
+    private int findInsertionPoint(int lvl, BPlusIO<L> io, long buf, int low, int cnt, L row, int shift)
         throws IgniteCheckedException {
         assert row != null;
 
@@ -4258,7 +4259,7 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
         while (low <= high) {
             int mid = (low + high) >>> 1;
 
-            int cmp = compare(io, buf, mid, row);
+            int cmp = compare(lvl, io, buf, mid, row);
 
             if (cmp == 0)
                 cmp = -shift; // We need to fix the case when search row matches multiple data rows.
@@ -4329,6 +4330,19 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
     protected abstract int compare(BPlusIO<L> io, long pageAddr, int idx, L row) throws IgniteCheckedException;
 
     /**
+     * @param lvl Level.
+     * @param io IO.
+     * @param pageAddr Page address.
+     * @param idx Index of row in the given buffer.
+     * @param row Lookup row.
+     * @return Comparison result as in {@link Comparator#compare(Object, Object)}.
+     * @throws IgniteCheckedException If failed.
+     */
+    protected int compare(int lvl, BPlusIO<L> io, long pageAddr, int idx, L row) throws IgniteCheckedException {
+        return compare(io, pageAddr, idx, row);
+    }
+
+    /**
      * Get a full detached data row.
      *
      * @param io IO.
@@ -4421,11 +4435,13 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
          * @throws IgniteCheckedException If failed.
          */
         private int findLowerBound(long pageAddr, BPlusIO<L> io, int cnt) throws IgniteCheckedException {
+            assert io.isLeaf();
+
             // Compare with the first row on the page.
-            int cmp = compare(io, pageAddr, 0, lowerBound);
+            int cmp = compare(0, io, pageAddr, 0, lowerBound);
 
             if (cmp < 0 || (cmp == 0 && lowerShift == 1)) {
-                int idx = findInsertionPoint(io, pageAddr, 0, cnt, lowerBound, lowerShift);
+                int idx = findInsertionPoint(0, io, pageAddr, 0, cnt, lowerBound, lowerShift);
 
                 assert idx < 0;
 
@@ -4444,11 +4460,13 @@ public abstract class BPlusTree<L, T extends L> extends DataStructure implements
          * @throws IgniteCheckedException If failed.
          */
         private int findUpperBound(long pageAddr, BPlusIO<L> io, int low, int cnt) throws IgniteCheckedException {
+            assert io.isLeaf();
+
             // Compare with the last row on the page.
-            int cmp = compare(io, pageAddr, cnt - 1, upperBound);
+            int cmp = compare(0, io, pageAddr, cnt - 1, upperBound);
 
             if (cmp > 0) {
-                int idx = findInsertionPoint(io, pageAddr, low, cnt, upperBound, 1);
+                int idx = findInsertionPoint(0, io, pageAddr, low, cnt, upperBound, 1);
 
                 assert idx < 0;
 


[23/31] ignite git commit: Minor - corrected TODO

Posted by sb...@apache.org.
Minor - corrected TODO


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/a3908bda
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/a3908bda
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/a3908bda

Branch: refs/heads/ignite-5075
Commit: a3908bdab64be29cfbf98aac8e1f74920d22d292
Parents: ff81389
Author: Alexey Goncharuk <al...@gmail.com>
Authored: Wed May 24 10:16:53 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Wed May 24 10:17:24 2017 +0300

----------------------------------------------------------------------
 .../apache/ignite/internal/processors/cache/GridCacheMapEntry.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/a3908bda/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index edf90d0..6b7d6f5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -3405,7 +3405,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                     if (obsoleteVersionExtras() != null)
                         return true;
 
-                    // TODO GG-11241: need keep removed entries in heap map, otherwise removes can be lost.
+                    // TODO IGNITE-5286: need keep removed entries in heap map, otherwise removes can be lost.
                     if (cctx.deferredDelete() && deletedUnlocked())
                         return false;
 


[21/31] ignite git commit: IGNITE-5282: SQL: Correct top-bottom propagation of "keepBinary" flag. This closes #1993.

Posted by sb...@apache.org.
IGNITE-5282: SQL: Correct top-bottom propagation of "keepBinary" flag. This closes #1993.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/33cb5e89
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/33cb5e89
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/33cb5e89

Branch: refs/heads/ignite-5075
Commit: 33cb5e89c011cc0029898fd87e6b47e75809cf0c
Parents: eea7a3b
Author: devozerov <vo...@gridgain.com>
Authored: Wed May 24 00:02:26 2017 +0300
Committer: devozerov <vo...@gridgain.com>
Committed: Wed May 24 00:02:26 2017 +0300

----------------------------------------------------------------------
 .../processors/cache/IgniteCacheProxy.java      | 15 +++++-----
 .../processors/query/GridQueryIndexing.java     | 11 +++++---
 .../processors/query/GridQueryProcessor.java    | 27 +++++++++---------
 .../query/h2/DmlStatementsProcessor.java        | 21 ++++++++------
 .../processors/query/h2/IgniteH2Indexing.java   | 29 +++++++++-----------
 .../cache/GridCacheCrossCacheQuerySelfTest.java | 12 ++++----
 .../h2/GridIndexingSpiAbstractSelfTest.java     |  4 +--
 7 files changed, 62 insertions(+), 57 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
index 40aafeb..a7d0d19 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
@@ -774,20 +774,19 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
 
             convertToBinary(qry);
 
-            final CacheOperationContext opCtxCall = ctx.operationContextPerCall();
+            CacheOperationContext opCtxCall = ctx.operationContextPerCall();
 
-            if (qry instanceof ContinuousQuery)
-                return (QueryCursor<R>)queryContinuous((ContinuousQuery<K, V>)qry, qry.isLocal(),
-                    opCtxCall != null && opCtxCall.isKeepBinary());
+            boolean keepBinary = opCtxCall != null && opCtxCall.isKeepBinary();
 
-            if (qry instanceof SqlQuery) {
-                boolean keepBinary = opCtxCall != null && opCtxCall.isKeepBinary();
+            if (qry instanceof ContinuousQuery)
+                return (QueryCursor<R>)queryContinuous((ContinuousQuery<K, V>)qry, qry.isLocal(), keepBinary);
 
+            if (qry instanceof SqlQuery)
                 return (QueryCursor<R>)ctx.kernalContext().query().querySql(ctx, (SqlQuery)qry, keepBinary);
-            }
 
             if (qry instanceof SqlFieldsQuery)
-                return (FieldsQueryCursor<R>)ctx.kernalContext().query().querySqlFields(ctx, (SqlFieldsQuery)qry);
+                return (FieldsQueryCursor<R>)ctx.kernalContext().query().querySqlFields(ctx, (SqlFieldsQuery)qry,
+                    keepBinary);
 
             if (qry instanceof ScanQuery)
                 return query((ScanQuery)qry, null, projection(qry.isLocal()));

http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
index 1f5e701..4b9c0e2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
@@ -68,23 +68,25 @@ public interface GridQueryIndexing {
      *
      * @param cctx Cache context.
      * @param qry Query.
+     * @param keepBinary Keep binary flag.
      * @return Cursor.
      * @throws IgniteCheckedException If failed.
      */
-    public <K, V> QueryCursor<Cache.Entry<K, V>> queryDistributedSql(GridCacheContext<?,?> cctx, SqlQuery qry)
-        throws IgniteCheckedException;
+    public <K, V> QueryCursor<Cache.Entry<K, V>> queryDistributedSql(GridCacheContext<?,?> cctx, SqlQuery qry,
+        boolean keepBinary) throws IgniteCheckedException;
 
     /**
      * Parses SQL query into two step query and executes it.
      *
      * @param cctx Cache context.
      * @param qry Query.
+     * @param keepBinary Keep binary flag.
      * @param cancel Query cancel.
      * @return Cursor.
      * @throws IgniteCheckedException If failed.
      */
     public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
-        GridQueryCancel cancel) throws IgniteCheckedException;
+        boolean keepBinary, GridQueryCancel cancel) throws IgniteCheckedException;
 
     /**
      * Perform a MERGE statement using data streamer as receiver.
@@ -116,12 +118,13 @@ public interface GridQueryIndexing {
      *
      * @param cctx Cache context.
      * @param qry Query.
+     * @param keepBinary Keep binary flag.
      * @param filter Cache name and key filter.
      * @param cancel Query cancel.
      * @return Cursor.
      */
     public FieldsQueryCursor<List<?>> queryLocalSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
-        IndexingQueryFilter filter, GridQueryCancel cancel) throws IgniteCheckedException;
+        boolean keepBinary, IndexingQueryFilter filter, GridQueryCancel cancel) throws IgniteCheckedException;
 
     /**
      * Executes text query.

http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
index ced78cf..a40c9e9 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
@@ -1651,10 +1651,12 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      *
      * @param cctx Cache context.
      * @param qry Query.
+     * @param keepBinary Keep binary flag.
      * @return Cursor.
      */
     @SuppressWarnings("unchecked")
-    public FieldsQueryCursor<List<?>> querySqlFields(final GridCacheContext<?,?> cctx, final SqlFieldsQuery qry) {
+    public FieldsQueryCursor<List<?>> querySqlFields(final GridCacheContext<?,?> cctx, final SqlFieldsQuery qry,
+        final boolean keepBinary) {
         checkxEnabled();
 
         if (qry.isReplicatedOnly() && qry.getPartitions() != null)
@@ -1677,7 +1679,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                     @Override public FieldsQueryCursor<List<?>> applyx() throws IgniteCheckedException {
                         GridQueryCancel cancel = new GridQueryCancel();
 
-                        final FieldsQueryCursor<List<?>> cursor = idx.queryLocalSqlFields(cctx, qry,
+                        final FieldsQueryCursor<List<?>> cursor = idx.queryLocalSqlFields(cctx, qry, keepBinary,
                             idx.backupFilter(requestTopVer.get(), qry.getPartitions()), cancel);
 
                         Iterable<List<?>> iterExec = new Iterable<List<?>>() {
@@ -1702,7 +1704,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             else {
                 clo = new IgniteOutClosureX<FieldsQueryCursor<List<?>>>() {
                     @Override public FieldsQueryCursor<List<?>> applyx() throws IgniteCheckedException {
-                        return idx.queryDistributedSqlFields(cctx, qry, null);
+                        return idx.queryDistributedSqlFields(cctx, qry, keepBinary, null);
                     }
                 };
             }
@@ -1767,16 +1769,17 @@ public class GridQueryProcessor extends GridProcessorAdapter {
         if ((qry.isReplicatedOnly() && cctx.isReplicatedAffinityNode()) || cctx.isLocal() || qry.isLocal())
             return queryLocalSql(cctx, qry, keepBinary);
 
-        return queryDistributedSql(cctx, qry);
+        return queryDistributedSql(cctx, qry, keepBinary);
     }
 
     /**
      * @param cctx Cache context.
      * @param qry Query.
+     * @param keepBinary Keep binary flag.
      * @return Cursor.
      */
-    public <K,V> QueryCursor<Cache.Entry<K,V>> queryDistributedSql(final GridCacheContext<?,?> cctx,
-        final SqlQuery qry) {
+    private <K,V> QueryCursor<Cache.Entry<K,V>> queryDistributedSql(final GridCacheContext<?,?> cctx,
+        final SqlQuery qry, final boolean keepBinary) {
         checkxEnabled();
 
         if (!busyLock.enterBusy())
@@ -1786,7 +1789,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             return executeQuery(GridCacheQueryType.SQL, qry.getSql(), cctx,
                 new IgniteOutClosureX<QueryCursor<Cache.Entry<K, V>>>() {
                     @Override public QueryCursor<Cache.Entry<K, V>> applyx() throws IgniteCheckedException {
-                        return idx.queryDistributedSql(cctx, qry);
+                        return idx.queryDistributedSql(cctx, qry, keepBinary);
                     }
                 }, true);
         }
@@ -1804,11 +1807,8 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * @param keepBinary Keep binary flag.
      * @return Cursor.
      */
-    public <K, V> QueryCursor<Cache.Entry<K, V>> queryLocalSql(
-        final GridCacheContext<?, ?> cctx,
-        final SqlQuery qry,
-        final boolean keepBinary
-    ) {
+    private <K, V> QueryCursor<Cache.Entry<K, V>> queryLocalSql(final GridCacheContext<?, ?> cctx, final SqlQuery qry,
+        final boolean keepBinary) {
         if (!busyLock.enterBusy())
             throw new IllegalStateException("Failed to execute query (grid is stopping).");
 
@@ -1827,7 +1827,8 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                             qry.getArgs(),
                             cctx.name());
 
-                        return idx.queryLocalSql(cctx, qry, idx.backupFilter(requestTopVer.get(), qry.getPartitions()), keepBinary);
+                        return idx.queryLocalSql(cctx, qry, idx.backupFilter(requestTopVer.get(), qry.getPartitions()),
+                            keepBinary);
                     }
                 }, true);
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
index db7bfd6..e40c328 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
@@ -141,7 +141,8 @@ public class DmlStatementsProcessor {
      * @throws IgniteCheckedException if failed.
      */
     private UpdateResult updateSqlFields(String cacheName, PreparedStatement stmt, SqlFieldsQuery fieldsQry,
-        boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
+        boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel)
+        throws IgniteCheckedException {
         Object[] errKeys = null;
 
         long items = 0;
@@ -196,13 +197,13 @@ public class DmlStatementsProcessor {
     /**
      * @param cacheName Cache name.
      * @param stmt Prepared statement.
-     * @param fieldsQry Initial query.
+     * @param fieldsQry Initial query
      * @param cancel Query cancel.
      * @return Update result wrapped into {@link GridQueryFieldsResult}
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings("unchecked")
-    QueryCursorImpl<List<?>> updateSqlFieldsTwoStep(String cacheName, PreparedStatement stmt,
+    QueryCursorImpl<List<?>> updateSqlFieldsDistributed(String cacheName, PreparedStatement stmt,
         SqlFieldsQuery fieldsQry, GridQueryCancel cancel) throws IgniteCheckedException {
         UpdateResult res = updateSqlFields(cacheName, stmt, fieldsQry, false, null, cancel);
 
@@ -218,14 +219,16 @@ public class DmlStatementsProcessor {
      * Execute DML statement on local cache.
      * @param cacheName Cache name.
      * @param stmt Prepared statement.
+     * @param fieldsQry Fields query.
      * @param filters Cache name and key filter.
      * @param cancel Query cancel.
      * @return Update result wrapped into {@link GridQueryFieldsResult}
      * @throws IgniteCheckedException if failed.
      */
     @SuppressWarnings("unchecked")
-    GridQueryFieldsResult updateLocalSqlFields(String cacheName, PreparedStatement stmt,
-        SqlFieldsQuery fieldsQry, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
+    GridQueryFieldsResult updateSqlFieldsLocal(String cacheName, PreparedStatement stmt,
+        SqlFieldsQuery fieldsQry, IndexingQueryFilter filters, GridQueryCancel cancel)
+        throws IgniteCheckedException {
         UpdateResult res = updateSqlFields(cacheName, stmt, fieldsQry, true, filters, cancel);
 
         return new GridQueryFieldsResultAdapter(UPDATE_RESULT_META,
@@ -266,8 +269,8 @@ public class DmlStatementsProcessor {
 
             final ArrayList<List<?>> data = new ArrayList<>(plan.rowsNum);
 
-            final GridQueryFieldsResult res = idx.queryLocalSqlFields(cctx.name(), plan.selectQry,
-                F.asList(args), null, false, 0, null);
+            final GridQueryFieldsResult res = idx.queryLocalSqlFields(cctx.name(), plan.selectQry, F.asList(args),
+                null, false, 0, null);
 
             QueryCursorImpl<List<?>> stepCur = new QueryCursorImpl<>(new Iterable<List<?>>() {
                 @Override public Iterator<List<?>> iterator() {
@@ -315,8 +318,10 @@ public class DmlStatementsProcessor {
 
     /**
      * Actually perform SQL DML operation locally.
+     *
      * @param cctx Cache context.
      * @param prepStmt Prepared statement for DML query.
+     * @param fieldsQry Fields query.
      * @param filters Cache name and key filter.
      * @param failedKeys Keys to restrict UPDATE and DELETE operations with. Null or empty array means no restriction.
      * @return Pair [number of successfully processed items; keys that have failed to be processed]
@@ -351,7 +356,7 @@ public class DmlStatementsProcessor {
                 .setPageSize(fieldsQry.getPageSize())
                 .setTimeout(fieldsQry.getTimeout(), TimeUnit.MILLISECONDS);
 
-            cur = (QueryCursorImpl<List<?>>) idx.queryDistributedSqlFields(cctx, newFieldsQry, cancel);
+            cur = (QueryCursorImpl<List<?>>) idx.queryDistributedSqlFields(cctx, newFieldsQry, true, cancel);
         }
         else {
             final GridQueryFieldsResult res = idx.queryLocalSqlFields(cctx.name(), plan.selectQry,

http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
index 0ce905b..d3ee6ff 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
@@ -1027,8 +1027,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     @SuppressWarnings("unchecked")
     public GridQueryFieldsResult queryLocalSqlFields(final String cacheName, final String qry,
         @Nullable final Collection<Object> params, final IndexingQueryFilter filter, boolean enforceJoinOrder,
-        final int timeout, final GridQueryCancel cancel)
-        throws IgniteCheckedException {
+        final int timeout, final GridQueryCancel cancel) throws IgniteCheckedException {
         final Connection conn = connectionForCache(cacheName);
 
         setupConnection(conn, false, enforceJoinOrder);
@@ -1046,7 +1045,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             fldsQry.setEnforceJoinOrder(enforceJoinOrder);
             fldsQry.setTimeout(timeout, TimeUnit.MILLISECONDS);
 
-            return dmlProc.updateLocalSqlFields(cacheName, stmt, fldsQry, filter, cancel);
+            return dmlProc.updateSqlFieldsLocal(cacheName, stmt, fldsQry, filter, cancel);
         }
         else if (DdlStatementsProcessor.isDdlStatement(p))
             throw new IgniteSQLException("DDL statements are supported for the whole cluster only",
@@ -1334,19 +1333,17 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
     /** {@inheritDoc} */
     @Override public FieldsQueryCursor<List<?>> queryLocalSqlFields(final GridCacheContext<?, ?> cctx,
-        final SqlFieldsQuery qry, final IndexingQueryFilter filter, final GridQueryCancel cancel)
-        throws IgniteCheckedException {
+        final SqlFieldsQuery qry, final boolean keepBinary, final IndexingQueryFilter filter,
+        final GridQueryCancel cancel) throws IgniteCheckedException {
 
         if (cctx.config().getQueryParallelism() > 1) {
             qry.setDistributedJoins(true);
 
             assert qry.isLocal();
 
-            return queryDistributedSqlFields(cctx, qry, cancel);
+            return queryDistributedSqlFields(cctx, qry, keepBinary, cancel);
         }
         else {
-            final boolean keepBinary = cctx.keepBinary();
-
             final String cacheName = cctx.name();
             final String sql = qry.getSql();
             final Object[] args = qry.getArgs();
@@ -1379,7 +1376,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             assert qry.isLocal();
 
-            return queryDistributedSql(cctx, qry);
+            return queryDistributedSql(cctx, qry, keepBinary);
         }
         else {
             String cacheName = cctx.name();
@@ -1495,7 +1492,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
-    @Override public <K, V> QueryCursor<Cache.Entry<K, V>> queryDistributedSql(GridCacheContext<?, ?> cctx, SqlQuery qry) {
+    @Override public <K, V> QueryCursor<Cache.Entry<K, V>> queryDistributedSql(GridCacheContext<?, ?> cctx,
+        SqlQuery qry, boolean keepBinary) {
         String type = qry.getType();
         String cacheName = cctx.name();
 
@@ -1525,7 +1523,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         if (qry.getTimeout() > 0)
             fqry.setTimeout(qry.getTimeout(), TimeUnit.MILLISECONDS);
 
-        final QueryCursor<List<?>> res = queryDistributedSqlFields(cctx, fqry, null);
+        final QueryCursor<List<?>> res = queryDistributedSqlFields(cctx, fqry, keepBinary, null);
 
         final Iterable<Cache.Entry<K, V>> converted = new Iterable<Cache.Entry<K, V>>() {
             @Override public Iterator<Cache.Entry<K, V>> iterator() {
@@ -1567,7 +1565,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
     /** {@inheritDoc} */
     @Override public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
-        GridQueryCancel cancel) {
+        boolean keepBinary, GridQueryCancel cancel) {
         final String cacheName = cctx.name();
         final String sqlQry = qry.getSql();
 
@@ -1657,7 +1655,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 if (twoStepQry == null) {
                     if (DmlStatementsProcessor.isDmlStatement(prepared)) {
                         try {
-                            return dmlProc.updateSqlFieldsTwoStep(cctx.name(), stmt, qry, cancel);
+                            return dmlProc.updateSqlFieldsDistributed(cctx.name(), stmt, qry, cancel);
                         }
                         catch (IgniteCheckedException e) {
                             throw new IgniteSQLException("Failed to execute DML statement [stmt=" + sqlQry +
@@ -1727,9 +1725,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             cancel = new GridQueryCancel();
 
         QueryCursorImpl<List<?>> cursor = new QueryCursorImpl<>(
-            runQueryTwoStep(cctx, twoStepQry, cctx.keepBinary(), enforceJoinOrder, qry.getTimeout(), cancel,
-                    qry.getArgs(), qry.getPartitions()),
-            cancel);
+            runQueryTwoStep(cctx, twoStepQry, keepBinary, enforceJoinOrder, qry.getTimeout(), cancel,
+                qry.getArgs(), qry.getPartitions()), cancel);
 
         cursor.fieldsMeta(meta);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheCrossCacheQuerySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheCrossCacheQuerySelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheCrossCacheQuerySelfTest.java
index 42a71cd..6344cba 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheCrossCacheQuerySelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheCrossCacheQuerySelfTest.java
@@ -127,7 +127,7 @@ public class GridCacheCrossCacheQuerySelfTest extends GridCommonAbstractTest {
         SqlFieldsQuery qry = new SqlFieldsQuery("select f.productId, p.name, f.price " +
             "from FactPurchase f, \"replicated-prod\".DimProduct p where p.id = f.productId ");
 
-        for (List<?> o : qryProc.querySqlFields(cache.context(), qry).getAll()) {
+        for (List<?> o : qryProc.querySqlFields(cache.context(), qry, false).getAll()) {
             X.println("___ -> " + o);
 
             set1.add((Integer)o.get(0));
@@ -141,7 +141,7 @@ public class GridCacheCrossCacheQuerySelfTest extends GridCommonAbstractTest {
 
         qry = new SqlFieldsQuery("select productId from FactPurchase group by productId");
 
-        for (List<?> o : qryProc.querySqlFields(cache.context(), qry).getAll()) {
+        for (List<?> o : qryProc.querySqlFields(cache.context(), qry, false).getAll()) {
             X.println("___ -> " + o);
 
             assertTrue(set0.add((Integer) o.get(0)));
@@ -160,7 +160,7 @@ public class GridCacheCrossCacheQuerySelfTest extends GridCommonAbstractTest {
             "where p.id = f.productId " +
             "group by f.productId, p.name");
 
-        for (List<?> o : qryProc.querySqlFields(cache.context(), qry).getAll()) {
+        for (List<?> o : qryProc.querySqlFields(cache.context(), qry, false).getAll()) {
             X.println("___ -> " + o);
 
             assertTrue(names.add((String)o.get(0)));
@@ -177,7 +177,7 @@ public class GridCacheCrossCacheQuerySelfTest extends GridCommonAbstractTest {
             "group by f.productId, p.name " +
             "having s >= 15");
 
-        for (List<?> o : qryProc.querySqlFields(cache.context(), qry).getAll()) {
+        for (List<?> o : qryProc.querySqlFields(cache.context(), qry, false).getAll()) {
             X.println("___ -> " + o);
 
             assertTrue(i(o, 1) >= 15);
@@ -190,7 +190,7 @@ public class GridCacheCrossCacheQuerySelfTest extends GridCommonAbstractTest {
         qry = new SqlFieldsQuery("select top 3 distinct productId " +
             "from FactPurchase f order by productId desc ");
 
-        for (List<?> o : qryProc.querySqlFields(cache.context(), qry).getAll()) {
+        for (List<?> o : qryProc.querySqlFields(cache.context(), qry, false).getAll()) {
             X.println("___ -> " + o);
 
             assertEquals(top--, o.get(0));
@@ -203,7 +203,7 @@ public class GridCacheCrossCacheQuerySelfTest extends GridCommonAbstractTest {
         qry = new SqlFieldsQuery("select distinct productId " +
             "from FactPurchase f order by productId desc limit 2 offset 1");
 
-        for (List<?> o : qryProc.querySqlFields(cache.context(), qry).getAll()) {
+        for (List<?> o : qryProc.querySqlFields(cache.context(), qry, false).getAll()) {
             X.println("___ -> " + o);
 
             assertEquals(top--, o.get(0));

http://git-wip-us.apache.org/repos/asf/ignite/blob/33cb5e89/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
index 7ba7d56..97db2c4 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
@@ -468,8 +468,8 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
                 time = now;
                 range *= 3;
 
-                GridQueryFieldsResult res = spi.queryLocalSqlFields("A", sql, Arrays.<Object>asList(1, range), null,
-                    false, 0, null);
+                GridQueryFieldsResult res = spi.queryLocalSqlFields("A", sql, Arrays.<Object>asList(1, range),
+                    null, false, 0, null);
 
                 assert res.iterator().hasNext();
 


[09/31] ignite git commit: IGNITE-5252: Expose getFieldName method to SqlFieldsQuery result. - Fixes #1982.

Posted by sb...@apache.org.
IGNITE-5252: Expose getFieldName method to SqlFieldsQuery result. - Fixes #1982.

Signed-off-by: Sergi Vladykin <se...@gmail.com>


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/647fd195
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/647fd195
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/647fd195

Branch: refs/heads/ignite-5075
Commit: 647fd195b310df10b230b67c92a8df04b5a064e2
Parents: 42018e6
Author: Andrey V. Mashenkov <an...@gmail.com>
Authored: Tue May 23 15:13:37 2017 +0300
Committer: Sergi Vladykin <se...@gmail.com>
Committed: Tue May 23 15:13:37 2017 +0300

----------------------------------------------------------------------
 .../java/org/apache/ignite/IgniteCache.java     | 13 +++++++
 .../ignite/cache/query/FieldsQueryCursor.java   | 39 ++++++++++++++++++++
 .../processors/cache/IgniteCacheProxy.java      | 11 +++++-
 .../processors/cache/QueryCursorImpl.java       | 19 +++++++++-
 .../processors/query/GridQueryIndexing.java     |  5 ++-
 .../processors/query/GridQueryProcessor.java    | 15 ++++----
 .../multijvm/IgniteCacheProcessProxy.java       |  8 ++++
 .../processors/query/h2/IgniteH2Indexing.java   |  5 ++-
 .../query/h2/ddl/DdlStatementsProcessor.java    |  4 +-
 .../cache/SqlFieldsQuerySelfTest.java           | 12 ++++--
 10 files changed, 112 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteCache.java b/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
index 9c8c090..aeabdb9 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
@@ -21,6 +21,7 @@ import java.io.Serializable;
 import java.sql.Timestamp;
 import java.util.Collection;
 import java.util.Date;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
@@ -41,6 +42,7 @@ import org.apache.ignite.cache.CacheEntryProcessor;
 import org.apache.ignite.cache.CacheMetrics;
 import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.cache.CachePeekMode;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.Query;
 import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.QueryDetailMetrics;
@@ -346,6 +348,7 @@ public interface IgniteCache<K, V> extends javax.cache.Cache<K, V>, IgniteAsyncS
 
     /**
      * Queries cache. Accepts any subclass of {@link Query} interface.
+     * See also {@link #query(SqlFieldsQuery)}.
      *
      * @param qry Query.
      * @return Cursor.
@@ -354,10 +357,20 @@ public interface IgniteCache<K, V> extends javax.cache.Cache<K, V>, IgniteAsyncS
      * @see SqlFieldsQuery
      * @see TextQuery
      * @see SpiQuery
+     *
      */
     public <R> QueryCursor<R> query(Query<R> qry);
 
     /**
+     * Queries cache. Accepts {@link SqlFieldsQuery} class.
+     *
+     * @param qry SqlFieldsQuery.
+     * @return Cursor.
+     * @see SqlFieldsQuery
+     */
+    public FieldsQueryCursor<List<?>> query(SqlFieldsQuery qry);
+
+    /**
      * Queries the cache transforming the entries on the server nodes. Can be used, for example,
      * to avoid network overhead in case only one field out of the large is required by client.
      * <p>

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/main/java/org/apache/ignite/cache/query/FieldsQueryCursor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/cache/query/FieldsQueryCursor.java b/modules/core/src/main/java/org/apache/ignite/cache/query/FieldsQueryCursor.java
new file mode 100644
index 0000000..4219bae
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/cache/query/FieldsQueryCursor.java
@@ -0,0 +1,39 @@
+/*
+ * 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.cache.query;
+
+/**
+ * SQL query result cursor. This extends {@link QueryCursor}
+ * to expose fields metadata to public API for SqlFieldsQueries.
+ */
+public interface FieldsQueryCursor<T> extends QueryCursor<T> {
+    /**
+     * Gets field name.
+     *
+     * @param idx field index.
+     * @return Field name.
+     */
+    String getFieldName(int idx);
+
+    /**
+     * Gets number of columns in a row.
+     *
+     * @return row size.
+     */
+    int getColumnsCount();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
index c3a24fa..40aafeb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
@@ -49,6 +49,7 @@ import org.apache.ignite.cache.CacheManager;
 import org.apache.ignite.cache.CacheMetrics;
 import org.apache.ignite.cache.CachePeekMode;
 import org.apache.ignite.cache.query.ContinuousQuery;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.Query;
 import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.QueryDetailMetrics;
@@ -561,7 +562,7 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
                             if (needToConvert) {
                                 Map.Entry<K, V> entry = (Map.Entry<K, V>)next;
 
-                                return (R) new CacheEntryImpl<>(entry.getKey(), entry.getValue());
+                                return (R)new CacheEntryImpl<>(entry.getKey(), entry.getValue());
                             }
 
                             return (R)next;
@@ -753,6 +754,12 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
+    @Override public FieldsQueryCursor<List<?>> query(SqlFieldsQuery qry) {
+        return (FieldsQueryCursor<List<?>>)query((Query)qry);
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
     @Override public <R> QueryCursor<R> query(Query<R> qry) {
         A.notNull(qry, "qry");
 
@@ -780,7 +787,7 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
             }
 
             if (qry instanceof SqlFieldsQuery)
-                return (QueryCursor<R>)ctx.kernalContext().query().querySqlFields(ctx, (SqlFieldsQuery)qry);
+                return (FieldsQueryCursor<R>)ctx.kernalContext().query().querySqlFields(ctx, (SqlFieldsQuery)qry);
 
             if (qry instanceof ScanQuery)
                 return query((ScanQuery)qry, null, projection(qry.isLocal()));

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java
index 24789fc..4fc1054 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java
@@ -25,6 +25,7 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
 import javax.cache.CacheException;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.QueryCancelledException;
 import org.apache.ignite.internal.processors.cache.query.QueryCursorEx;
 import org.apache.ignite.internal.processors.query.GridQueryCancel;
@@ -38,7 +39,7 @@ import static org.apache.ignite.internal.processors.cache.QueryCursorImpl.State.
 /**
  * Query cursor implementation.
  */
-public class QueryCursorImpl<T> implements QueryCursorEx<T> {
+public class QueryCursorImpl<T> implements QueryCursorEx<T>, FieldsQueryCursor<T> {
     /** */
     private final static AtomicReferenceFieldUpdater<QueryCursorImpl, State> STATE_UPDATER =
         AtomicReferenceFieldUpdater.newUpdater(QueryCursorImpl.class, State.class, "state");
@@ -188,6 +189,22 @@ public class QueryCursorImpl<T> implements QueryCursorEx<T> {
         return fieldsMeta;
     }
 
+    /** {@inheritDoc} */
+    @Override public String getFieldName(int idx) {
+        assert this.fieldsMeta != null;
+
+        GridQueryFieldMetadata metadata = fieldsMeta.get(idx);
+
+        return metadata.fieldName();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getColumnsCount() {
+        assert this.fieldsMeta != null;
+
+        return fieldsMeta.size();
+    }
+
     /** Query cursor state */
     protected enum State {
         /** Idle. */IDLE,

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
index 8180cd0..bfa223e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryIndexing.java
@@ -24,6 +24,7 @@ import java.util.List;
 import javax.cache.Cache;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteDataStreamer;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.SqlFieldsQuery;
 import org.apache.ignite.cache.query.SqlQuery;
@@ -82,7 +83,7 @@ public interface GridQueryIndexing {
      * @return Cursor.
      * @throws IgniteCheckedException If failed.
      */
-    public QueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
+    public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
         GridQueryCancel cancel) throws IgniteCheckedException;
 
     /**
@@ -119,7 +120,7 @@ public interface GridQueryIndexing {
      * @param cancel Query cancel.
      * @return Cursor.
      */
-    public QueryCursor<List<?>> queryLocalSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
+    public FieldsQueryCursor<List<?>> queryLocalSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
         IndexingQueryFilter filter, GridQueryCancel cancel) throws IgniteCheckedException;
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
index 6a479ab..0df0f52 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
@@ -24,6 +24,7 @@ import org.apache.ignite.binary.Binarylizable;
 import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.cache.QueryEntity;
 import org.apache.ignite.cache.QueryIndex;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.SqlFieldsQuery;
 import org.apache.ignite.cache.query.SqlQuery;
@@ -1653,7 +1654,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * @return Cursor.
      */
     @SuppressWarnings("unchecked")
-    public QueryCursor<List<?>> querySqlFields(final GridCacheContext<?,?> cctx, final SqlFieldsQuery qry) {
+    public FieldsQueryCursor<List<?>> querySqlFields(final GridCacheContext<?,?> cctx, final SqlFieldsQuery qry) {
         checkxEnabled();
 
         if (qry.isReplicatedOnly() && qry.getPartitions() != null)
@@ -1669,14 +1670,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             throw new IllegalStateException("Failed to execute query (grid is stopping).");
 
         try {
-            IgniteOutClosureX<QueryCursor<List<?>>> clo;
+            IgniteOutClosureX<FieldsQueryCursor<List<?>>> clo;
 
             if (loc) {
-                clo = new IgniteOutClosureX<QueryCursor<List<?>>>() {
-                    @Override public QueryCursor<List<?>> applyx() throws IgniteCheckedException {
+                clo = new IgniteOutClosureX<FieldsQueryCursor<List<?>>>() {
+                    @Override public FieldsQueryCursor<List<?>> applyx() throws IgniteCheckedException {
                         GridQueryCancel cancel = new GridQueryCancel();
 
-                        final QueryCursor<List<?>> cursor = idx.queryLocalSqlFields(cctx, qry,
+                        final FieldsQueryCursor<List<?>> cursor = idx.queryLocalSqlFields(cctx, qry,
                             idx.backupFilter(requestTopVer.get(), qry.getPartitions()), cancel);
 
                         Iterable<List<?>> iterExec = new Iterable<List<?>>() {
@@ -1699,8 +1700,8 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 };
             }
             else {
-                clo = new IgniteOutClosureX<QueryCursor<List<?>>>() {
-                    @Override public QueryCursor<List<?>> applyx() throws IgniteCheckedException {
+                clo = new IgniteOutClosureX<FieldsQueryCursor<List<?>>>() {
+                    @Override public FieldsQueryCursor<List<?>> applyx() throws IgniteCheckedException {
                         return idx.queryDistributedSqlFields(cctx, qry, null);
                     }
                 };

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
index d203794..630e441 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
@@ -20,6 +20,7 @@ package org.apache.ignite.testframework.junits.multijvm;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.locks.Lock;
@@ -38,10 +39,12 @@ import org.apache.ignite.cache.CacheEntry;
 import org.apache.ignite.cache.CacheEntryProcessor;
 import org.apache.ignite.cache.CacheMetrics;
 import org.apache.ignite.cache.CachePeekMode;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.Query;
 import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.QueryDetailMetrics;
 import org.apache.ignite.cache.query.QueryMetrics;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
 import org.apache.ignite.cluster.ClusterGroup;
 import org.apache.ignite.internal.processors.cache.CacheEntryImpl;
 import org.apache.ignite.internal.util.future.IgniteFinishedFutureImpl;
@@ -191,6 +194,11 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
     }
 
     /** {@inheritDoc} */
+    @Override public FieldsQueryCursor<List<?>> query(SqlFieldsQuery qry) {
+        throw new UnsupportedOperationException("Method should be supported.");
+    }
+
+    /** {@inheritDoc} */
     @Override public <T, R> QueryCursor<R> query(Query<T> qry, IgniteClosure<T, R> transformer) {
         throw new UnsupportedOperationException("Method should be supported.");
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
index ce69bb1..c099d77 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
@@ -61,6 +61,7 @@ import org.apache.ignite.IgniteDataStreamer;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cache.QueryIndexType;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.QueryCancelledException;
 import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.SqlFieldsQuery;
@@ -1335,7 +1336,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public QueryCursor<List<?>> queryLocalSqlFields(final GridCacheContext<?, ?> cctx,
+    @Override public FieldsQueryCursor<List<?>> queryLocalSqlFields(final GridCacheContext<?, ?> cctx,
         final SqlFieldsQuery qry, final IndexingQueryFilter filter, final GridQueryCancel cancel)
         throws IgniteCheckedException {
 
@@ -1568,7 +1569,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public QueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
+    @Override public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
         GridQueryCancel cancel) {
         final String space = cctx.name();
         final String sqlQry = qry.getSql();

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
index fe2bfdb..3991777 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
@@ -24,7 +24,7 @@ import java.util.List;
 import java.util.Map;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.cache.QueryIndex;
-import org.apache.ignite.cache.query.QueryCursor;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.IgniteInternalFuture;
 import org.apache.ignite.internal.processors.cache.QueryCursorImpl;
@@ -76,7 +76,7 @@ public class DdlStatementsProcessor {
      * @param stmt H2 statement to parse and execute.
      */
     @SuppressWarnings("unchecked")
-    public QueryCursor<List<?>> runDdlStatement(String sql, PreparedStatement stmt)
+    public FieldsQueryCursor<List<?>> runDdlStatement(String sql, PreparedStatement stmt)
         throws IgniteCheckedException {
         assert stmt instanceof JdbcPreparedStatement;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/647fd195/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/SqlFieldsQuerySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/SqlFieldsQuerySelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/SqlFieldsQuerySelfTest.java
index a23f254..8860b2b 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/SqlFieldsQuerySelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/SqlFieldsQuerySelfTest.java
@@ -21,7 +21,7 @@ import java.io.Serializable;
 import java.util.List;
 import org.apache.ignite.IgniteCache;
 import org.apache.ignite.cache.CacheMode;
-import org.apache.ignite.cache.query.QueryCursor;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.SqlFieldsQuery;
 import org.apache.ignite.cache.query.annotations.QuerySqlField;
 import org.apache.ignite.configuration.CacheConfiguration;
@@ -66,11 +66,17 @@ public class SqlFieldsQuerySelfTest extends GridCommonAbstractTest {
     private void executeQuery() {
         IgniteCache<?, ?> cache = grid(1).cache("person");
 
-        SqlFieldsQuery qry = new SqlFieldsQuery("select name, age from person where age > 10");
+        SqlFieldsQuery qry = new SqlFieldsQuery("select name as \"Full Name\", age from person where age > 10");
 
-        QueryCursor<List<?>> qryCursor = cache.query(qry);
+        FieldsQueryCursor<List<?>> qryCursor = cache.query(qry);
 
         assertEquals(2, qryCursor.getAll().size());
+
+        assertEquals(2, qryCursor.getColumnsCount()); // Row contains "name" and "age" fields.
+
+        assertEquals("Full Name", qryCursor.getFieldName(0));
+
+        assertEquals("AGE", qryCursor.getFieldName(1));
     }
 
 


[17/31] ignite git commit: IGNITE-5281: Indexing: changed "space" to "cacheName". No more "spaces". This closes #1992.

Posted by sb...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
index c099d77..0ce905b 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
@@ -228,10 +228,7 @@ import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType
 
 /**
  * Indexing implementation based on H2 database engine. In this implementation main query language is SQL,
- * fulltext indexing can be performed using Lucene. For each registered space
- * the SPI will create respective schema, for default space (where space name is null) schema
- * with name {@code ""} will be used. To avoid name conflicts user should not explicitly name
- * a schema {@code ""}.
+ * fulltext indexing can be performed using Lucene.
  * <p>
  * For each registered {@link GridQueryTypeDescriptor} this SPI will create respective SQL table with
  * {@code '_key'} and {@code '_val'} fields for key and value, and fields from
@@ -336,8 +333,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** */
     private GridReduceQueryExecutor rdcQryExec;
 
-    /** space name -> schema name */
-    private final Map<String, String> space2schema = new ConcurrentHashMap8<>();
+    /** Cache name -> schema name */
+    private final Map<String, String> cacheName2schema = new ConcurrentHashMap8<>();
 
     /** */
     private AtomicLong qryIdGen;
@@ -429,12 +426,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @return Connection.
      */
-    public Connection connectionForSpace(String space) {
+    public Connection connectionForCache(String cacheName) {
         try {
-            return connectionForThread(schema(space));
+            return connectionForThread(schema(cacheName));
         }
         catch (IgniteCheckedException e) {
             throw new IgniteException(e);
@@ -484,13 +481,13 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public PreparedStatement prepareNativeStatement(String space, String sql) throws SQLException {
-        return prepareStatement(connectionForSpace(space), sql, true);
+    @Override public PreparedStatement prepareNativeStatement(String cacheName, String sql) throws SQLException {
+        return prepareStatement(connectionForCache(cacheName), sql, true);
     }
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
-    @Override public IgniteDataStreamer<?, ?> createStreamer(String spaceName, PreparedStatement nativeStmt,
+    @Override public IgniteDataStreamer<?, ?> createStreamer(String cacheName, PreparedStatement nativeStmt,
         long autoFlushFreq, int nodeBufSize, int nodeParOps, boolean allowOverwrite) {
         Prepared prep = GridSqlQueryParser.prepared(nativeStmt);
 
@@ -498,7 +495,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             throw new IgniteSQLException("Only INSERT operations are supported in streaming mode",
                 IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
 
-        IgniteDataStreamer streamer = ctx.grid().dataStreamer(spaceName);
+        IgniteDataStreamer streamer = ctx.grid().dataStreamer(cacheName);
 
         streamer.autoFlushFrequency(autoFlushFreq);
 
@@ -640,7 +637,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public void store(String spaceName,
+    @Override public void store(String cacheName,
         String typeName,
         KeyCacheObject k,
         int partId,
@@ -648,7 +645,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         GridCacheVersion ver,
         long expirationTime,
         long link) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, spaceName);
+        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl == null)
             return; // Type was rejected.
@@ -674,29 +671,29 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @return Cache object context.
      */
-    private CacheObjectContext objectContext(String space) {
+    private CacheObjectContext objectContext(String cacheName) {
         if (ctx == null)
             return null;
 
-        return ctx.cache().internalCache(space).context().cacheObjectContext();
+        return ctx.cache().internalCache(cacheName).context().cacheObjectContext();
     }
 
     /**
-     * @param space Space.
+     * @param cacheName Cache name.
      * @return Cache object context.
      */
-    private GridCacheContext cacheContext(String space) {
+    private GridCacheContext cacheContext(String cacheName) {
         if (ctx == null)
             return null;
 
-        return ctx.cache().internalCache(space).context();
+        return ctx.cache().internalCache(cacheName).context();
     }
 
     /** {@inheritDoc} */
-    @Override public void remove(String spaceName,
+    @Override public void remove(String cacheName,
         GridQueryTypeDescriptor type,
         KeyCacheObject key,
         int partId,
@@ -705,7 +702,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         if (log.isDebugEnabled())
             log.debug("Removing key from cache query index [locId=" + nodeId + ", key=" + key + ", val=" + val + ']');
 
-        TableDescriptor tbl = tableDescriptor(type.name(), spaceName);
+        TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
 
         if (tbl == null)
             return;
@@ -764,12 +761,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * Add initial user index.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param desc Table descriptor.
      * @param h2Idx User index.
      * @throws IgniteCheckedException If failed.
      */
-    private void addInitialUserIndex(String spaceName, TableDescriptor desc, GridH2IndexBase h2Idx)
+    private void addInitialUserIndex(String cacheName, TableDescriptor desc, GridH2IndexBase h2Idx)
         throws IgniteCheckedException {
         GridH2Table h2Tbl = desc.tbl;
 
@@ -778,7 +775,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         try {
             String sql = indexCreateSql(desc.fullTableName(), h2Idx, false, desc.schema.escapeAll());
 
-            executeSql(spaceName, sql);
+            executeSql(cacheName, sql);
         }
         catch (Exception e) {
             // Rollback and re-throw.
@@ -789,11 +786,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public void dynamicIndexCreate(final String spaceName, final String tblName,
+    @Override public void dynamicIndexCreate(final String cacheName, final String tblName,
         final QueryIndexDescriptorImpl idxDesc, boolean ifNotExists, SchemaIndexCacheVisitor cacheVisitor)
         throws IgniteCheckedException {
         // Locate table.
-        String schemaName = schema(spaceName);
+        String schemaName = schema(cacheName);
 
         Schema schema = schemas.get(schemaName);
 
@@ -834,7 +831,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             // prepared statements are re-built.
             String sql = indexCreateSql(desc.fullTableName(), h2Idx, ifNotExists, schema.escapeAll());
 
-            executeSql(spaceName, sql);
+            executeSql(cacheName, sql);
         }
         catch (Exception e) {
             // Rollback and re-throw.
@@ -846,27 +843,27 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
     /** {@inheritDoc} */
     @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
-    @Override public void dynamicIndexDrop(final String spaceName, String idxName, boolean ifExists)
+    @Override public void dynamicIndexDrop(final String cacheName, String idxName, boolean ifExists)
         throws IgniteCheckedException{
-        String schemaName = schema(spaceName);
+        String schemaName = schema(cacheName);
 
         Schema schema = schemas.get(schemaName);
 
         String sql = indexDropSql(schemaName, idxName, ifExists, schema.escapeAll());
 
-        executeSql(spaceName, sql);
+        executeSql(cacheName, sql);
     }
 
     /**
      * Execute DDL command.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param sql SQL.
      * @throws IgniteCheckedException If failed.
      */
-    private void executeSql(String spaceName, String sql) throws IgniteCheckedException {
+    private void executeSql(String cacheName, String sql) throws IgniteCheckedException {
         try {
-            Connection conn = connectionForSpace(spaceName);
+            Connection conn = connectionForCache(cacheName);
 
             try (PreparedStatement stmt = prepareStatement(conn, sql, false)) {
                 stmt.execute();
@@ -984,12 +981,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
     @SuppressWarnings("unchecked")
     @Override public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalText(
-        String spaceName, String qry, String typeName,
+        String cacheName, String qry, String typeName,
         IndexingQueryFilter filters) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, spaceName);
+        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl != null && tbl.luceneIdx != null) {
-            GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, TEXT, spaceName,
+            GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, TEXT, cacheName,
                 U.currentTimeMillis(), null, true);
 
             try {
@@ -1006,9 +1003,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public void unregisterType(String spaceName, String typeName)
+    @Override public void unregisterType(String cacheName, String typeName)
         throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, spaceName);
+        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl != null)
             removeTable(tbl);
@@ -1017,10 +1014,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * Queries individual fields (generally used by JDBC drivers).
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param qry Query.
      * @param params Query parameters.
-     * @param filter Space name and key filter.
+     * @param filter Cache name and key filter.
      * @param enforceJoinOrder Enforce join order of tables in the query.
      * @param timeout Query timeout in milliseconds.
      * @param cancel Query cancel.
@@ -1028,11 +1025,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @throws IgniteCheckedException If failed.
      */
     @SuppressWarnings("unchecked")
-    public GridQueryFieldsResult queryLocalSqlFields(final String spaceName, final String qry,
+    public GridQueryFieldsResult queryLocalSqlFields(final String cacheName, final String qry,
         @Nullable final Collection<Object> params, final IndexingQueryFilter filter, boolean enforceJoinOrder,
         final int timeout, final GridQueryCancel cancel)
         throws IgniteCheckedException {
-        final Connection conn = connectionForSpace(spaceName);
+        final Connection conn = connectionForCache(cacheName);
 
         setupConnection(conn, false, enforceJoinOrder);
 
@@ -1049,7 +1046,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             fldsQry.setEnforceJoinOrder(enforceJoinOrder);
             fldsQry.setTimeout(timeout, TimeUnit.MILLISECONDS);
 
-            return dmlProc.updateLocalSqlFields(spaceName, stmt, fldsQry, filter, cancel);
+            return dmlProc.updateLocalSqlFields(cacheName, stmt, fldsQry, filter, cancel);
         }
         else if (DdlStatementsProcessor.isDdlStatement(p))
             throw new IgniteSQLException("DDL statements are supported for the whole cluster only",
@@ -1074,12 +1071,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 GridH2QueryContext.set(ctx);
 
                 GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL_FIELDS,
-                    spaceName, U.currentTimeMillis(), cancel, true);
+                    cacheName, U.currentTimeMillis(), cancel, true);
 
                 runs.putIfAbsent(run.id(), run);
 
                 try {
-                    ResultSet rs = executeSqlQueryWithTimer(spaceName, stmt, conn, qry, params, timeout, cancel);
+                    ResultSet rs = executeSqlQueryWithTimer(cacheName, stmt, conn, qry, params, timeout, cancel);
 
                     return new FieldsIterator(rs);
                 }
@@ -1093,9 +1090,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public long streamUpdateQuery(String spaceName, String qry,
+    @Override public long streamUpdateQuery(String cacheName, String qry,
         @Nullable Object[] params, IgniteDataStreamer<?, ?> streamer) throws IgniteCheckedException {
-        final Connection conn = connectionForSpace(spaceName);
+        final Connection conn = connectionForCache(cacheName);
 
         final PreparedStatement stmt;
 
@@ -1235,7 +1232,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * Executes sql query and prints warning if query is too slow..
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param conn Connection,.
      * @param sql Sql query.
      * @param params Parameters.
@@ -1244,21 +1241,21 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Result.
      * @throws IgniteCheckedException If failed.
      */
-    public ResultSet executeSqlQueryWithTimer(String space,
+    public ResultSet executeSqlQueryWithTimer(String cacheName,
         Connection conn,
         String sql,
         @Nullable Collection<Object> params,
         boolean useStmtCache,
         int timeoutMillis,
         @Nullable GridQueryCancel cancel) throws IgniteCheckedException {
-        return executeSqlQueryWithTimer(space, preparedStatementWithParams(conn, sql, params, useStmtCache),
+        return executeSqlQueryWithTimer(cacheName, preparedStatementWithParams(conn, sql, params, useStmtCache),
             conn, sql, params, timeoutMillis, cancel);
     }
 
     /**
      * Executes sql query and prints warning if query is too slow.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @param stmt Prepared statement for query.
      * @param conn Connection.
      * @param sql Sql query.
@@ -1267,7 +1264,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Result.
      * @throws IgniteCheckedException If failed.
      */
-    private ResultSet executeSqlQueryWithTimer(String space, PreparedStatement stmt,
+    private ResultSet executeSqlQueryWithTimer(String cacheName, PreparedStatement stmt,
         Connection conn,
         String sql,
         @Nullable Collection<Object> params,
@@ -1280,7 +1277,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             long time = U.currentTimeMillis() - start;
 
-            long longQryExecTimeout = schemas.get(schema(space)).ccfg.getLongQueryWarningTimeout();
+            long longQryExecTimeout = schemas.get(schema(cacheName)).ccfg.getLongQueryWarningTimeout();
 
             if (time > longQryExecTimeout) {
                 String msg = "Query execution is too long (" + time + " ms): " + sql;
@@ -1350,11 +1347,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         else {
             final boolean keepBinary = cctx.keepBinary();
 
-            final String space = cctx.name();
+            final String cacheName = cctx.name();
             final String sql = qry.getSql();
             final Object[] args = qry.getArgs();
 
-            final GridQueryFieldsResult res = queryLocalSqlFields(space, sql, F.asList(args), filter,
+            final GridQueryFieldsResult res = queryLocalSqlFields(cacheName, sql, F.asList(args), filter,
                 qry.isEnforceJoinOrder(), qry.getTimeout(), cancel);
 
             QueryCursorImpl<List<?>> cursor = new QueryCursorImpl<>(new Iterable<List<?>>() {
@@ -1385,7 +1382,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             return queryDistributedSql(cctx, qry);
         }
         else {
-            String space = cctx.name();
+            String cacheName = cctx.name();
             String type = qry.getType();
             String sqlQry = qry.getSql();
             String alias = qry.getAlias();
@@ -1393,7 +1390,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             GridQueryCancel cancel = new GridQueryCancel();
 
-            final GridCloseableIterator<IgniteBiTuple<K, V>> i = queryLocalSql(space, sqlQry, alias,
+            final GridCloseableIterator<IgniteBiTuple<K, V>> i = queryLocalSql(cacheName, sqlQry, alias,
                 F.asList(params), type, filter, cancel);
 
             return new QueryCursorImpl<Cache.Entry<K, V>>(new Iterable<Cache.Entry<K, V>>() {
@@ -1427,19 +1424,19 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * Executes regular query.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param qry Query.
      * @param alias Table alias.
      * @param params Query parameters.
      * @param type Query return type.
-     * @param filter Space name and key filter.
+     * @param filter Cache name and key filter.
      * @return Queried rows.
      * @throws IgniteCheckedException If failed.
      */
-    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalSql(String spaceName,
+    public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalSql(String cacheName,
         final String qry, String alias, @Nullable final Collection<Object> params, String type,
         final IndexingQueryFilter filter, GridQueryCancel cancel) throws IgniteCheckedException {
-        final TableDescriptor tbl = tableDescriptor(type, spaceName);
+        final TableDescriptor tbl = tableDescriptor(type, cacheName);
 
         if (tbl == null)
             throw new IgniteSQLException("Failed to find SQL table for type: " + type,
@@ -1454,13 +1451,13 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         GridH2QueryContext.set(new GridH2QueryContext(nodeId, nodeId, 0, LOCAL).filter(filter)
             .distributedJoinMode(OFF));
 
-        GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL, spaceName,
+        GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL, cacheName,
             U.currentTimeMillis(), null, true);
 
         runs.put(run.id(), run);
 
         try {
-            ResultSet rs = executeSqlQueryWithTimer(spaceName, conn, sql, params, true, 0, cancel);
+            ResultSet rs = executeSqlQueryWithTimer(cacheName, conn, sql, params, true, 0, cancel);
 
             return new KeyValIterator(rs);
         }
@@ -1500,9 +1497,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     @SuppressWarnings("unchecked")
     @Override public <K, V> QueryCursor<Cache.Entry<K, V>> queryDistributedSql(GridCacheContext<?, ?> cctx, SqlQuery qry) {
         String type = qry.getType();
-        String space = cctx.name();
+        String cacheName = cctx.name();
 
-        TableDescriptor tblDesc = tableDescriptor(type, space);
+        TableDescriptor tblDesc = tableDescriptor(type, cacheName);
 
         if (tblDesc == null)
             throw new IgniteSQLException("Failed to find SQL table for type: " + type,
@@ -1571,10 +1568,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** {@inheritDoc} */
     @Override public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
         GridQueryCancel cancel) {
-        final String space = cctx.name();
+        final String cacheName = cctx.name();
         final String sqlQry = qry.getSql();
 
-        Connection c = connectionForSpace(space);
+        Connection c = connectionForCache(cacheName);
 
         final boolean enforceJoinOrder = qry.isEnforceJoinOrder();
         final boolean distributedJoins = qry.isDistributedJoins();
@@ -1585,7 +1582,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         GridCacheTwoStepQuery twoStepQry = null;
         List<GridQueryFieldMetadata> meta;
 
-        final TwoStepCachedQueryKey cachedQryKey = new TwoStepCachedQueryKey(space, sqlQry, grpByCollocated,
+        final TwoStepCachedQueryKey cachedQryKey = new TwoStepCachedQueryKey(cacheName, sqlQry, grpByCollocated,
             distributedJoins, enforceJoinOrder, qry.isLocal());
         TwoStepCachedQuery cachedQry = twoStepCache.get(cachedQryKey);
 
@@ -1680,7 +1677,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
                 LinkedHashSet<Integer> caches0 = new LinkedHashSet<>();
 
-                // Setup spaces from schemas.
+                // Setup caches from schemas.
                 assert twoStepQry != null;
 
                 int tblCnt = twoStepQry.tablesCount();
@@ -1689,9 +1686,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                     caches0.add(cctx.cacheId());
 
                     for (QueryTable table : twoStepQry.tables()) {
-                        String cacheName = cacheNameForSchemaAndTable(table.schema(), table.table());
+                        String tblCacheName = cacheNameForSchemaAndTable(table.schema(), table.table());
 
-                        int cacheId = CU.cacheId(cacheName);
+                        int cacheId = CU.cacheId(tblCacheName);
 
                         caches0.add(cacheId);
                     }
@@ -1752,8 +1749,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Cache name.
      */
     private String cacheNameForSchemaAndTable(String schemaName, String tblName) {
-        // TODO: This need to be changed.
-        return space(schemaName);
+        return cacheName(schemaName);
     }
 
     /**
@@ -1848,11 +1844,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param type Type description.
      * @throws IgniteCheckedException In case of error.
      */
-    @Override public boolean registerType(String spaceName, GridQueryTypeDescriptor type)
+    @Override public boolean registerType(String cacheName, GridQueryTypeDescriptor type)
         throws IgniteCheckedException {
         validateTypeDescriptor(type);
 
-        String schemaName = schema(spaceName);
+        String schemaName = schema(cacheName);
 
         Schema schema = schemas.get(schemaName);
 
@@ -1861,7 +1857,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         try {
             Connection conn = connectionForThread(schemaName);
 
-            createTable(spaceName, schema, tbl, conn);
+            createTable(cacheName, schema, tbl, conn);
 
             schema.add(tbl);
         }
@@ -1969,14 +1965,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * Create db table by using given table descriptor.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param schema Schema.
      * @param tbl Table descriptor.
      * @param conn Connection.
      * @throws SQLException If failed to create db table.
      * @throws IgniteCheckedException If failed.
      */
-    private void createTable(String spaceName, Schema schema, TableDescriptor tbl, Connection conn)
+    private void createTable(String cacheName, Schema schema, TableDescriptor tbl, Connection conn)
         throws SQLException, IgniteCheckedException {
         assert schema != null;
         assert tbl != null;
@@ -2011,7 +2007,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         GridH2Table h2Tbl = H2TableEngine.createTable(conn, sql.toString(), rowDesc, rowFactory, tbl);
 
         for (GridH2IndexBase usrIdx : tbl.createUserIndexes())
-            addInitialUserIndex(spaceName, tbl, usrIdx);
+            addInitialUserIndex(cacheName, tbl, usrIdx);
 
         if (dataTables.putIfAbsent(h2Tbl.identifier(), h2Tbl) != null)
             throw new IllegalStateException("Table already exists: " + h2Tbl.identifierString());
@@ -2069,14 +2065,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * Gets table descriptor by type and space names.
+     * Gets table descriptor by type and cache names.
      *
      * @param type Type name.
-     * @param space Space name.
+     * @param cacheName Cache name.
      * @return Table descriptor.
      */
-    @Nullable private TableDescriptor tableDescriptor(String type, String space) {
-        Schema s = schemas.get(schema(space));
+    @Nullable private TableDescriptor tableDescriptor(String type, String cacheName) {
+        Schema s = schemas.get(schema(cacheName));
 
         if (s == null)
             return null;
@@ -2100,13 +2096,13 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * Gets database schema from space.
+     * Gets database schema from cache name.
      *
-     * @param space Space name. {@code null} would be converted to an empty string.
-     * @return Schema name. Should not be null since we should not fail for an invalid space name.
+     * @param cacheName Cache name. {@code null} would be converted to an empty string.
+     * @return Schema name. Should not be null since we should not fail for an invalid cache name.
      */
-    private String schema(String space) {
-        return emptyIfNull(space2schema.get(emptyIfNull(space)));
+    private String schema(String cacheName) {
+        return emptyIfNull(cacheName2schema.get(emptyIfNull(cacheName)));
     }
 
     /**
@@ -2127,7 +2123,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public String space(String schemaName) {
+    @Override public String cacheName(String schemaName) {
         assert schemaName != null;
 
         Schema schema = schemas.get(schemaName);
@@ -2139,19 +2135,19 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             schema = schemas.get(escapeName(schemaName, true));
         }
 
-        return schema.spaceName;
+        return schema.cacheName;
     }
 
     /**
      * Rebuild indexes from hash index.
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param type Type descriptor.
      * @throws IgniteCheckedException If failed.
      */
-    @Override public void rebuildIndexesFromHash(String spaceName,
+    @Override public void rebuildIndexesFromHash(String cacheName,
         GridQueryTypeDescriptor type) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(type.name(), spaceName);
+        TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
 
         if (tbl == null)
             return;
@@ -2208,8 +2204,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public void markForRebuildFromHash(String spaceName, GridQueryTypeDescriptor type) {
-        TableDescriptor tbl = tableDescriptor(type.name(), spaceName);
+    @Override public void markForRebuildFromHash(String cacheName, GridQueryTypeDescriptor type) {
+        TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
 
         if (tbl == null)
             return;
@@ -2222,18 +2218,18 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * Gets size (for tests only).
      *
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param typeName Type name.
      * @return Size.
      * @throws IgniteCheckedException If failed or {@code -1} if the type is unknown.
      */
-    long size(String spaceName, String typeName) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, spaceName);
+    long size(String cacheName, String typeName) throws IgniteCheckedException {
+        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl == null)
             return -1;
 
-        Connection conn = connectionForSpace(spaceName);
+        Connection conn = connectionForCache(cacheName);
 
         setupConnection(conn, false, false);
 
@@ -2519,7 +2515,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         conns.clear();
         schemas.clear();
-        space2schema.clear();
+        cacheName2schema.clear();
 
         try (Connection c = DriverManager.getConnection(dbUrl);
              Statement s = c.createStatement()) {
@@ -2539,14 +2535,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public void registerCache(String spaceName, GridCacheContext<?, ?> cctx, CacheConfiguration<?, ?> ccfg)
+    @Override public void registerCache(String cacheName, GridCacheContext<?, ?> cctx, CacheConfiguration<?, ?> ccfg)
         throws IgniteCheckedException {
         String schema = schemaNameFromCacheConf(ccfg);
 
-        if (schemas.putIfAbsent(schema, new Schema(spaceName, schema, cctx, ccfg)) != null)
-            throw new IgniteCheckedException("Cache already registered: " + U.maskName(spaceName));
+        if (schemas.putIfAbsent(schema, new Schema(cacheName, schema, cctx, ccfg)) != null)
+            throw new IgniteCheckedException("Cache already registered: " + U.maskName(cacheName));
 
-        space2schema.put(emptyIfNull(spaceName), schema);
+        cacheName2schema.put(emptyIfNull(cacheName), schema);
 
         createSchema(schema);
 
@@ -2554,14 +2550,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
-    @Override public void unregisterCache(String spaceName) {
-        String schema = schema(spaceName);
+    @Override public void unregisterCache(String cacheName) {
+        String schema = schema(cacheName);
         Schema rmv = schemas.remove(schema);
 
         if (rmv != null) {
-            space2schema.remove(emptyIfNull(rmv.spaceName));
-            mapQryExec.onCacheStop(spaceName);
-            dmlProc.onCacheStop(spaceName);
+            cacheName2schema.remove(emptyIfNull(rmv.cacheName));
+            mapQryExec.onCacheStop(cacheName);
+            dmlProc.onCacheStop(cacheName);
 
             rmv.onDrop();
 
@@ -2569,7 +2565,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 dropSchema(schema);
             }
             catch (IgniteCheckedException e) {
-                U.error(log, "Failed to drop schema on cache stop (will ignore): " + U.maskName(spaceName), e);
+                U.error(log, "Failed to drop schema on cache stop (will ignore): " + U.maskName(cacheName), e);
             }
 
             for (TableDescriptor tblDesc : rmv.tbls.values())
@@ -2580,7 +2576,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 it.hasNext(); ) {
                 Map.Entry<TwoStepCachedQueryKey, TwoStepCachedQuery> e = it.next();
 
-                if (F.eq(e.getKey().space, spaceName))
+                if (F.eq(e.getKey().cacheName, cacheName))
                     it.remove();
             }
         }
@@ -2594,8 +2590,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         final AffinityTopologyVersion topVer0 = topVer != null ? topVer : AffinityTopologyVersion.NONE;
 
         return new IndexingQueryFilter() {
-            @Nullable @Override public <K, V> IgniteBiPredicate<K, V> forSpace(String spaceName) {
-                final GridCacheAdapter<Object, Object> cache = ctx.cache().internalCache(spaceName);
+            @Nullable @Override public <K, V> IgniteBiPredicate<K, V> forCache(String cacheName) {
+                final GridCacheAdapter<Object, Object> cache = ctx.cache().internalCache(cacheName);
 
                 if (cache.context().isReplicated())
                     return null;
@@ -2677,7 +2673,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      */
     private static final class TwoStepCachedQueryKey {
         /** */
-        private final String space;
+        private final String cacheName;
 
         /** */
         private final String sql;
@@ -2695,20 +2691,20 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         private final boolean isLocal;
 
         /**
-         * @param space Space.
+         * @param cacheName Cache name.
          * @param sql Sql.
          * @param grpByCollocated Collocated GROUP BY.
          * @param distributedJoins Distributed joins enabled.
          * @param enforceJoinOrder Enforce join order of tables.
          * @param isLocal Query is local flag.
          */
-        private TwoStepCachedQueryKey(String space,
+        private TwoStepCachedQueryKey(String cacheName,
             String sql,
             boolean grpByCollocated,
             boolean distributedJoins,
             boolean enforceJoinOrder,
             boolean isLocal) {
-            this.space = space;
+            this.cacheName = cacheName;
             this.sql = sql;
             this.grpByCollocated = grpByCollocated;
             this.distributedJoins = distributedJoins;
@@ -2735,7 +2731,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             if (enforceJoinOrder != that.enforceJoinOrder)
                 return false;
 
-            if (space != null ? !space.equals(that.space) : that.space != null)
+            if (cacheName != null ? !cacheName.equals(that.cacheName) : that.cacheName != null)
                 return false;
 
             return isLocal == that.isLocal && sql.equals(that.sql);
@@ -2743,7 +2739,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         /** {@inheritDoc} */
         @Override public int hashCode() {
-            int res = space != null ? space.hashCode() : 0;
+            int res = cacheName != null ? cacheName.hashCode() : 0;
             res = 31 * res + sql.hashCode();
             res = 31 * res + (grpByCollocated ? 1 : 0);
             res = res + (distributedJoins ? 2 : 0);
@@ -3165,7 +3161,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             if (type().valueClass() == String.class) {
                 try {
-                    luceneIdx = new GridLuceneIndex(ctx, schema.offheap, schema.spaceName, type);
+                    luceneIdx = new GridLuceneIndex(ctx, schema.offheap, schema.cacheName, type);
                 }
                 catch (IgniteCheckedException e1) {
                     throw new IgniteException(e1);
@@ -3178,7 +3174,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             if (textIdx != null) {
                 try {
-                    luceneIdx = new GridLuceneIndex(ctx, schema.offheap, schema.spaceName, type);
+                    luceneIdx = new GridLuceneIndex(ctx, schema.offheap, schema.cacheName, type);
                 }
                 catch (IgniteCheckedException e1) {
                     throw new IgniteException(e1);
@@ -3450,7 +3446,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      */
     private class Schema {
         /** */
-        private final String spaceName;
+        private final String cacheName;
 
         /** */
         private final String schemaName;
@@ -3471,14 +3467,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         private final CacheConfiguration<?, ?> ccfg;
 
         /**
-         * @param spaceName Space name.
+         * @param cacheName Cache name.
          * @param schemaName Schema name.
          * @param cctx Cache context.
          * @param ccfg Cache configuration.
          */
-        private Schema(String spaceName, String schemaName, GridCacheContext<?, ?> cctx,
+        private Schema(String cacheName, String schemaName, GridCacheContext<?, ?> cctx,
             CacheConfiguration<?, ?> ccfg) {
-            this.spaceName = spaceName;
+            this.cacheName = cacheName;
             this.cctx = cctx;
             this.schemaName = schemaName;
             this.ccfg = ccfg;
@@ -3653,9 +3649,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 CacheObject co = (CacheObject)obj;
 
                 if (type == Value.JAVA_OBJECT)
-                    return new GridH2ValueCacheObject(cacheContext(schema.spaceName), co);
+                    return new GridH2ValueCacheObject(cacheContext(schema.cacheName), co);
 
-                obj = co.value(objectContext(schema.spaceName), false);
+                obj = co.value(objectContext(schema.cacheName), false);
             }
 
             switch (type) {
@@ -3733,7 +3729,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                     "or configure key type as common super class for all actual keys for this value type.", e);
             }
 
-            GridCacheContext cctx = cacheContext(schema.spaceName);
+            GridCacheContext cctx = cacheContext(schema.cacheName);
 
             if (cctx.offheapIndex()) {
                 row.ver = ver;
@@ -4013,7 +4009,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         /** {@inheritDoc} */
         @Override public TableBase createTable(CreateTableData createTblData) {
-            resTbl0 = new GridH2Table(createTblData, rowDesc0, rowFactory0, tblDesc0, tblDesc0.schema.spaceName);
+            resTbl0 = new GridH2Table(createTblData, rowDesc0, rowFactory0, tblDesc0, tblDesc0.schema.cacheName);
 
             return resTbl0;
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
index 7579fa5..7caf354 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
@@ -90,9 +90,9 @@ public class H2PkHashIndex extends GridH2IndexBase {
         IgniteBiPredicate<Object, Object> p = null;
 
         if (f != null) {
-            String spaceName = getTable().cacheName();
+            String cacheName = getTable().cacheName();
 
-            p = f.forSpace(spaceName);
+            p = f.forCache(cacheName);
         }
 
         KeyCacheObject lowerObj = null;

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
index 814df77..c1c1d9c 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
@@ -167,9 +167,9 @@ public class H2TreeIndex extends GridH2IndexBase {
             IgniteBiPredicate<Object, Object> p = null;
 
             if (f != null) {
-                String spaceName = getTable().cacheName();
+                String cacheName = getTable().cacheName();
 
-                p = f.forSpace(spaceName);
+                p = f.forCache(cacheName);
             }
 
             int seg = threadLocalSegment();

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
index 30fb612..3dabc58 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
@@ -1686,18 +1686,16 @@ public abstract class GridH2IndexBase extends BaseIndex {
          * @param cursor GridCursor.
          * @param time Time for expired rows filtering.
          * @param qryFilter Filter.
-         * @param spaceName Space name.
+         * @param cacheName Cache name.
          */
-        protected FilteringCursor(GridCursor<GridH2Row> cursor,
-            long time,
-            IndexingQueryFilter qryFilter,
-            String spaceName) {
+        protected FilteringCursor(GridCursor<GridH2Row> cursor, long time, IndexingQueryFilter qryFilter,
+            String cacheName) {
             this.cursor = cursor;
 
             this.time = time;
 
             if (qryFilter != null) {
-                this.fltr = qryFilter.forSpace(spaceName);
+                this.fltr = qryFilter.forCache(cacheName);
 
                 this.isValRequired = qryFilter.isValueRequired();
             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
index ec728de..cb9042e 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
@@ -222,7 +222,7 @@ public class GridH2Table extends TableBase {
     }
 
     /**
-     * @return Space name.
+     * @return Cache name.
      */
     @Nullable public String cacheName() {
         return cacheName;

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
index 39256d4..03fedcb 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
@@ -206,7 +206,7 @@ public class GridH2TreeIndex extends GridH2IndexBase implements Comparator<GridS
         int seg = threadLocalSegment();
 
         // Fast path if we don't need to perform any filtering.
-        if (f == null || f.forSpace((getTable()).cacheName()) == null)
+        if (f == null || f.forCache((getTable()).cacheName()) == null)
             try {
                 return treeForRead(seg).size();
             } catch (IgniteCheckedException e) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridLuceneIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridLuceneIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridLuceneIndex.java
index 6671dc6..48c0cb9 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridLuceneIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridLuceneIndex.java
@@ -21,7 +21,6 @@ import java.io.IOException;
 import java.util.Collection;
 import java.util.concurrent.atomic.AtomicLong;
 import org.apache.ignite.IgniteCheckedException;
-import org.apache.ignite.cache.QueryIndexType;
 import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.processors.cache.CacheObject;
 import org.apache.ignite.internal.processors.cache.CacheObjectContext;
@@ -71,7 +70,7 @@ public class GridLuceneIndex implements AutoCloseable {
     public static final String EXPIRATION_TIME_FIELD_NAME = "_gg_expires__";
 
     /** */
-    private final String spaceName;
+    private final String cacheName;
 
     /** */
     private final GridQueryTypeDescriptor type;
@@ -96,14 +95,14 @@ public class GridLuceneIndex implements AutoCloseable {
      *
      * @param ctx Kernal context.
      * @param mem Unsafe memory.
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      * @param type Type descriptor.
      * @throws IgniteCheckedException If failed.
      */
     public GridLuceneIndex(GridKernalContext ctx, @Nullable GridUnsafeMemory mem,
-        @Nullable String spaceName, GridQueryTypeDescriptor type) throws IgniteCheckedException {
+        @Nullable String cacheName, GridQueryTypeDescriptor type) throws IgniteCheckedException {
         this.ctx = ctx;
-        this.spaceName = spaceName;
+        this.cacheName = cacheName;
         this.type = type;
 
         dir = new GridLuceneDirectory(mem == null ? new GridUnsafeMemory(0) : mem);
@@ -141,7 +140,7 @@ public class GridLuceneIndex implements AutoCloseable {
         if (ctx == null)
             return null;
 
-        return ctx.cache().internalCache(spaceName).context().cacheObjectContext();
+        return ctx.cache().internalCache(cacheName).context().cacheObjectContext();
     }
 
     /**
@@ -275,7 +274,7 @@ public class GridLuceneIndex implements AutoCloseable {
         IgniteBiPredicate<K, V> fltr = null;
 
         if (filters != null)
-            fltr = filters.forSpace(spaceName);
+            fltr = filters.forCache(cacheName);
 
         return new It<>(reader, searcher, docs.scoreDocs, fltr);
     }
@@ -382,7 +381,7 @@ public class GridLuceneIndex implements AutoCloseable {
                 ClassLoader ldr = null;
 
                 if (ctx != null && ctx.deploy().enabled())
-                    ldr = ctx.cache().internalCache(spaceName).context().deploy().globalLoader();
+                    ldr = ctx.cache().internalCache(cacheName).context().deploy().globalLoader();
 
                 K k = unmarshall(org.apache.commons.codec.binary.Base64.decodeBase64(doc.get(KEY_FIELD_NAME)), ldr);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
index 6d76eea..1d8a762 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridMapQueryExecutor.java
@@ -579,7 +579,7 @@ public class GridMapQueryExecutor {
                 }
             }
 
-            Connection conn = h2.connectionForSpace(mainCctx.name());
+            Connection conn = h2.connectionForCache(mainCctx.name());
 
             setupConnection(conn, distributedJoinMode != OFF, enforceJoinOrder);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
index 75914ef..1ecbb40 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
@@ -540,10 +540,10 @@ public class GridReduceQueryExecutor {
 
             final long qryReqId = qryIdGen.incrementAndGet();
 
-            final String space = cctx.name();
+            final String cacheName = cctx.name();
 
-            final QueryRun r = new QueryRun(qryReqId, qry.originalSql(), space,
-                h2.connectionForSpace(space), qry.mapQueries().size(), qry.pageSize(),
+            final QueryRun r = new QueryRun(qryReqId, qry.originalSql(), cacheName,
+                h2.connectionForCache(cacheName), qry.mapQueries().size(), qry.pageSize(),
                 U.currentTimeMillis(), cancel);
 
             AffinityTopologyVersion topVer = h2.readyTopologyVersion();
@@ -794,11 +794,11 @@ public class GridReduceQueryExecutor {
 
                         try {
                             if (qry.explain())
-                                return explainPlan(r.conn, space, qry, params);
+                                return explainPlan(r.conn, cacheName, qry, params);
 
                             GridCacheSqlQuery rdc = qry.reduceQuery();
 
-                            ResultSet res = h2.executeSqlQueryWithTimer(space,
+                            ResultSet res = h2.executeSqlQueryWithTimer(cacheName,
                                 r.conn,
                                 rdc.query(),
                                 F.asList(rdc.parameters(params)),
@@ -1030,12 +1030,12 @@ public class GridReduceQueryExecutor {
     }
 
     /**
-     * @param space Cache name.
+     * @param cacheName Cache name.
      * @param topVer Topology version.
      * @return Collection of data nodes.
      */
-    private Collection<ClusterNode> dataNodes(String space, AffinityTopologyVersion topVer) {
-        Collection<ClusterNode> res = ctx.discovery().cacheAffinityNodes(space, topVer);
+    private Collection<ClusterNode> dataNodes(String cacheName, AffinityTopologyVersion topVer) {
+        Collection<ClusterNode> res = ctx.discovery().cacheAffinityNodes(cacheName, topVer);
 
         return res != null ? res : Collections.<ClusterNode>emptySet();
     }
@@ -1049,12 +1049,12 @@ public class GridReduceQueryExecutor {
     private Set<ClusterNode> replicatedUnstableDataNodes(GridCacheContext<?,?> cctx) {
         assert cctx.isReplicated() : cctx.name() + " must be replicated";
 
-        String space = cctx.name();
+        String cacheName = cctx.name();
 
-        Set<ClusterNode> dataNodes = new HashSet<>(dataNodes(space, NONE));
+        Set<ClusterNode> dataNodes = new HashSet<>(dataNodes(cacheName, NONE));
 
         if (dataNodes.isEmpty())
-            throw new CacheException("Failed to find data nodes for cache: " + space);
+            throw new CacheException("Failed to find data nodes for cache: " + cacheName);
 
         // Find all the nodes owning all the partitions for replicated cache.
         for (int p = 0, parts = cctx.affinity().partitions(); p < parts; p++) {
@@ -1213,18 +1213,18 @@ public class GridReduceQueryExecutor {
 
     /**
      * @param c Connection.
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param qry Query.
      * @param params Query parameters.
      * @return Cursor for plans.
      * @throws IgniteCheckedException if failed.
      */
-    private Iterator<List<?>> explainPlan(JdbcConnection c, String space, GridCacheTwoStepQuery qry, Object[] params)
+    private Iterator<List<?>> explainPlan(JdbcConnection c, String cacheName, GridCacheTwoStepQuery qry, Object[] params)
         throws IgniteCheckedException {
         List<List<?>> lists = new ArrayList<>();
 
         for (int i = 0, mapQrys = qry.mapQueries().size(); i < mapQrys; i++) {
-            ResultSet rs = h2.executeSqlQueryWithTimer(space, c,
+            ResultSet rs = h2.executeSqlQueryWithTimer(cacheName, c,
                 "SELECT PLAN FROM " + mergeTableIdentifier(i), null, false, 0, null);
 
             lists.add(F.asList(getPlan(rs)));
@@ -1240,7 +1240,7 @@ public class GridReduceQueryExecutor {
 
         GridCacheSqlQuery rdc = qry.reduceQuery();
 
-        ResultSet rs = h2.executeSqlQueryWithTimer(space,
+        ResultSet rs = h2.executeSqlQueryWithTimer(cacheName,
             c,
             "EXPLAIN " + rdc.query(),
             F.asList(rdc.parameters(params)),

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
index 1241d0c..7e3473f 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
@@ -1020,13 +1020,13 @@ public abstract class DynamicIndexAbstractBasicSelfTest extends DynamicIndexAbst
     /**
      * Synchronously create index.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param tblName Table name.
      * @param idx Index.
      * @param ifNotExists When set to true operation will fail if index already exists.
      * @throws Exception If failed.
      */
-    private void dynamicIndexCreate(String space, String tblName, QueryIndex idx, boolean ifNotExists)
+    private void dynamicIndexCreate(String cacheName, String tblName, QueryIndex idx, boolean ifNotExists)
         throws Exception {
         GridStringBuilder sql = new SB("CREATE INDEX ")
             .a(ifNotExists ? "IF NOT EXISTS " : "")
@@ -1051,32 +1051,32 @@ public abstract class DynamicIndexAbstractBasicSelfTest extends DynamicIndexAbst
 
         sql.a(')');
 
-        executeSql(space, sql.toString());
+        executeSql(cacheName, sql.toString());
     }
 
     /**
      * Synchronously drop index.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param idxName Index name.
      * @param ifExists When set to true operation fill fail if index doesn't exists.
      * @throws Exception if failed.
      */
-    private void dynamicIndexDrop(String space, String idxName, boolean ifExists) throws Exception {
+    private void dynamicIndexDrop(String cacheName, String idxName, boolean ifExists) throws Exception {
         String sql = "DROP INDEX " + (ifExists ? "IF EXISTS " : "") + "\"" + idxName + "\"";
 
-        executeSql(space, sql);
+        executeSql(cacheName, sql);
     }
 
     /**
      * Execute SQL.
      *
-     * @param space Space.
+     * @param cacheName Cache name.
      * @param sql SQL.
      */
-    private void executeSql(String space, String sql) {
+    private void executeSql(String cacheName, String sql) {
         log.info("Executing DDL: " + sql);
 
-        node().cache(space).query(new SqlFieldsQuery(sql)).getAll();
+        node().cache(cacheName).query(new SqlFieldsQuery(sql)).getAll();
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
index f9e2f75..3600022 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
@@ -1033,20 +1033,20 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
      */
     private static class BlockingIndexing extends IgniteH2Indexing {
         /** {@inheritDoc} */
-        @Override public void dynamicIndexCreate(@NotNull String spaceName, String tblName,
+        @Override public void dynamicIndexCreate(@NotNull String cacheName, String tblName,
             QueryIndexDescriptorImpl idxDesc, boolean ifNotExists, SchemaIndexCacheVisitor cacheVisitor)
             throws IgniteCheckedException {
             awaitIndexing(ctx.localNodeId());
 
-            super.dynamicIndexCreate(spaceName, tblName, idxDesc, ifNotExists, cacheVisitor);
+            super.dynamicIndexCreate(cacheName, tblName, idxDesc, ifNotExists, cacheVisitor);
         }
 
         /** {@inheritDoc} */
-        @Override public void dynamicIndexDrop(@NotNull String spaceName, String idxName, boolean ifExists)
+        @Override public void dynamicIndexDrop(@NotNull String cacheName, String idxName, boolean ifExists)
             throws IgniteCheckedException{
             awaitIndexing(ctx.localNodeId());
 
-            super.dynamicIndexDrop(spaceName, idxName, ifExists);
+            super.dynamicIndexDrop(cacheName, idxName, ifExists);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
index ddaea8a..13c0cb2 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteQueryDedicatedPoolTest.java
@@ -191,7 +191,7 @@ public class IgniteQueryDedicatedPoolTest extends GridCommonAbstractTest {
         }
 
         /** {@inheritDoc} */
-        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String spaceName, Collection<Object> params,
+        @Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String cacheName, Collection<Object> params,
             @Nullable IndexingQueryFilter filters) {
             return idx.containsKey(GridIoPolicy.QUERY_POOL) ?
                 Collections.<Cache.Entry<?, ?>>singletonList(
@@ -200,12 +200,12 @@ public class IgniteQueryDedicatedPoolTest extends GridCommonAbstractTest {
         }
 
         /** {@inheritDoc} */
-        @Override public void store(@Nullable String spaceName, Object key, Object val, long expirationTime) {
+        @Override public void store(@Nullable String cacheName, Object key, Object val, long expirationTime) {
             idx.put(key, val);
         }
 
         /** {@inheritDoc} */
-        @Override public void remove(@Nullable String spaceName, Object key) {
+        @Override public void remove(@Nullable String cacheName, Object key) {
             // No-op.
         }
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
index 3832878..7ba7d56 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/GridIndexingSpiAbstractSelfTest.java
@@ -246,32 +246,32 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
     public void testSpi() throws Exception {
         IgniteH2Indexing spi = getIndexing();
 
-        assertEquals(-1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(-1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(-1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(-1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(-1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(-1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         IgniteCache<Integer, BinaryObject> cacheA = ignite0.createCache(cacheACfg());
 
-        assertEquals(0, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(0, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(-1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(0, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(0, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(-1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         IgniteCache<Integer, BinaryObject> cacheB = ignite0.createCache(cacheBCfg());
 
         // Initially all is empty.
-        assertEquals(0, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(0, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(0, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(0, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(0, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(0, spi.size(typeBA.cacheName(), typeBA.name()));
 
-        assertFalse(spi.queryLocalSql(typeAA.space(), "select * from A.A", null, Collections.emptySet(), typeAA.name(), null, null).hasNext());
-        assertFalse(spi.queryLocalSql(typeAB.space(), "select * from A.B", null, Collections.emptySet(), typeAB.name(), null, null).hasNext());
-        assertFalse(spi.queryLocalSql(typeBA.space(), "select * from B.A", null, Collections.emptySet(), typeBA.name(), null, null).hasNext());
+        assertFalse(spi.queryLocalSql(typeAA.cacheName(), "select * from A.A", null, Collections.emptySet(), typeAA.name(), null, null).hasNext());
+        assertFalse(spi.queryLocalSql(typeAB.cacheName(), "select * from A.B", null, Collections.emptySet(), typeAB.name(), null, null).hasNext());
+        assertFalse(spi.queryLocalSql(typeBA.cacheName(), "select * from B.A", null, Collections.emptySet(), typeBA.name(), null, null).hasNext());
 
-        assertFalse(spi.queryLocalSql(typeBA.space(), "select * from B.A, A.B, A.A", null,
+        assertFalse(spi.queryLocalSql(typeBA.cacheName(), "select * from B.A, A.B, A.A", null,
             Collections.emptySet(), typeBA.name(), null, null).hasNext());
 
         try {
-            spi.queryLocalSql(typeBA.space(), "select aa.*, ab.*, ba.* from A.A aa, A.B ab, B.A ba", null,
+            spi.queryLocalSql(typeBA.cacheName(), "select aa.*, ab.*, ba.* from A.A aa, A.B ab, B.A ba", null,
                 Collections.emptySet(), typeBA.name(), null, null).hasNext();
 
             fail("Enumerations of aliases in select block must be prohibited");
@@ -280,60 +280,60 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
             // all fine
         }
 
-        assertFalse(spi.queryLocalSql(typeAB.space(), "select ab.* from A.B ab", null,
+        assertFalse(spi.queryLocalSql(typeAB.cacheName(), "select ab.* from A.B ab", null,
             Collections.emptySet(), typeAB.name(), null, null).hasNext());
 
-        assertFalse(spi.queryLocalSql(typeBA.space(), "select   ba.*   from B.A  as ba", null,
+        assertFalse(spi.queryLocalSql(typeBA.cacheName(), "select   ba.*   from B.A  as ba", null,
             Collections.emptySet(), typeBA.name(), null, null).hasNext());
 
         cacheA.put(1, aa("A", 1, "Vasya", 10).build());
 
-        assertEquals(1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(0, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(0, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(0, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(0, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheA.put(1, ab(1, "Vasya", 20, "Some text about Vasya goes here.").build());
 
-        // In one space all keys must be unique.
-        assertEquals(0, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(0, spi.size(typeBA.space(), typeBA.name()));
+        // In one cache all keys must be unique.
+        assertEquals(0, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(0, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheB.put(1, ba(2, "Petya", 25, true).build());
 
-        // No replacement because of different space.
-        assertEquals(0, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(1, spi.size(typeBA.space(), typeBA.name()));
+        // No replacement because of different cache.
+        assertEquals(0, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheB.put(1, ba(2, "Kolya", 25, true).build());
 
         // Replacement in the same table.
-        assertEquals(0, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(0, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheA.put(2, aa("A", 2, "Valera", 19).build());
 
-        assertEquals(1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheA.put(3, aa("A", 3, "Borya", 18).build());
 
-        assertEquals(2, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(2, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheA.put(4, ab(4, "Vitalya", 20, "Very Good guy").build());
 
-        assertEquals(2, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(2, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(2, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(2, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         // Query data.
         Iterator<IgniteBiTuple<Integer, BinaryObjectImpl>> res =
-            spi.queryLocalSql(typeAA.space(), "from a order by age", null, Collections.emptySet(), typeAA.name(), null, null);
+            spi.queryLocalSql(typeAA.cacheName(), "from a order by age", null, Collections.emptySet(), typeAA.name(), null, null);
 
         assertTrue(res.hasNext());
         assertEquals(aa("A", 3, "Borya", 18).build(), value(res.next()));
@@ -341,7 +341,7 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         assertEquals(aa("A", 2, "Valera", 19).build(), value(res.next()));
         assertFalse(res.hasNext());
 
-        res = spi.queryLocalSql(typeAA.space(), "select aa.* from a aa order by aa.age", null,
+        res = spi.queryLocalSql(typeAA.cacheName(), "select aa.* from a aa order by aa.age", null,
             Collections.emptySet(), typeAA.name(), null, null);
 
         assertTrue(res.hasNext());
@@ -350,7 +350,7 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         assertEquals(aa("A", 2, "Valera", 19).build(), value(res.next()));
         assertFalse(res.hasNext());
 
-        res = spi.queryLocalSql(typeAB.space(), "from b order by name", null, Collections.emptySet(), typeAB.name(), null, null);
+        res = spi.queryLocalSql(typeAB.cacheName(), "from b order by name", null, Collections.emptySet(), typeAB.name(), null, null);
 
         assertTrue(res.hasNext());
         assertEquals(ab(1, "Vasya", 20, "Some text about Vasya goes here.").build(), value(res.next()));
@@ -358,7 +358,7 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         assertEquals(ab(4, "Vitalya", 20, "Very Good guy").build(), value(res.next()));
         assertFalse(res.hasNext());
 
-        res = spi.queryLocalSql(typeAB.space(), "select bb.* from b as bb order by bb.name", null,
+        res = spi.queryLocalSql(typeAB.cacheName(), "select bb.* from b as bb order by bb.name", null,
             Collections.emptySet(), typeAB.name(), null, null);
 
         assertTrue(res.hasNext());
@@ -368,14 +368,14 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         assertFalse(res.hasNext());
 
 
-        res = spi.queryLocalSql(typeBA.space(), "from a", null, Collections.emptySet(), typeBA.name(), null, null);
+        res = spi.queryLocalSql(typeBA.cacheName(), "from a", null, Collections.emptySet(), typeBA.name(), null, null);
 
         assertTrue(res.hasNext());
         assertEquals(ba(2, "Kolya", 25, true).build(), value(res.next()));
         assertFalse(res.hasNext());
 
         // Text queries
-        Iterator<IgniteBiTuple<Integer, BinaryObjectImpl>> txtRes = spi.queryLocalText(typeAB.space(), "good",
+        Iterator<IgniteBiTuple<Integer, BinaryObjectImpl>> txtRes = spi.queryLocalText(typeAB.cacheName(), "good",
             typeAB.name(), null);
 
         assertTrue(txtRes.hasNext());
@@ -410,32 +410,32 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         // Remove
         cacheA.remove(2);
 
-        assertEquals(1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(2, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(1, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(2, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(1, spi.size(typeBA.cacheName(), typeBA.name()));
 
         cacheB.remove(1);
 
-        assertEquals(1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(2, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(0, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(2, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(0, spi.size(typeBA.cacheName(), typeBA.name()));
 
         // Unregister.
-        spi.unregisterType(typeAA.space(), typeAA.name());
+        spi.unregisterType(typeAA.cacheName(), typeAA.name());
 
-        assertEquals(-1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(2, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(0, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(-1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(2, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(0, spi.size(typeBA.cacheName(), typeBA.name()));
 
-        spi.unregisterType(typeAB.space(), typeAB.name());
+        spi.unregisterType(typeAB.cacheName(), typeAB.name());
 
-        assertEquals(-1, spi.size(typeAA.space(), typeAA.name()));
-        assertEquals(-1, spi.size(typeAB.space(), typeAB.name()));
-        assertEquals(0, spi.size(typeBA.space(), typeBA.name()));
+        assertEquals(-1, spi.size(typeAA.cacheName(), typeAA.name()));
+        assertEquals(-1, spi.size(typeAB.cacheName(), typeAB.name()));
+        assertEquals(0, spi.size(typeBA.cacheName(), typeBA.name()));
 
-        spi.unregisterType(typeBA.space(), typeBA.name());
+        spi.unregisterType(typeBA.cacheName(), typeBA.name());
 
-        assertEquals(-1, spi.size(typeAA.space(), typeAA.name()));
+        assertEquals(-1, spi.size(typeAA.cacheName(), typeAA.name()));
     }
 
     /**
@@ -533,7 +533,7 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         private final String name;
 
         /** */
-        private final String space;
+        private final String cacheName;
 
         /** */
         private final Map<String, Class<?>> valFields;
@@ -542,14 +542,14 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         private final GridQueryIndexDescriptor textIdx;
 
         /**
-         * @param space Space name.
+         * @param cacheName Cache name.
          * @param name Type name.
          * @param valFields Fields.
          * @param textIdx Fulltext index.
          */
-        private TypeDesc(String space, String name, Map<String, Class<?>> valFields, GridQueryIndexDescriptor textIdx) {
+        private TypeDesc(String cacheName, String name, Map<String, Class<?>> valFields, GridQueryIndexDescriptor textIdx) {
             this.name = name;
-            this.space = space;
+            this.cacheName = cacheName;
             this.valFields = Collections.unmodifiableMap(valFields);
             this.textIdx = textIdx;
         }
@@ -570,10 +570,10 @@ public abstract class GridIndexingSpiAbstractSelfTest extends GridCommonAbstract
         }
 
         /**
-         * @return Space name.
+         * @return Cache name.
          */
-        String space() {
-            return space;
+        String cacheName() {
+            return cacheName;
         }
 
         /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/cbf0b2a5/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
index 21666d6..9838084 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
@@ -686,7 +686,7 @@ public class GridQueryParsingTest extends GridCommonAbstractTest {
 
         IgniteH2Indexing idx = U.field(qryProcessor, "idx");
 
-        return (JdbcConnection)idx.connectionForSpace(DEFAULT_CACHE_NAME);
+        return (JdbcConnection)idx.connectionForCache(DEFAULT_CACHE_NAME);
     }
 
     /**


[08/31] ignite git commit: IGNITE-5150 - Corrected allocated memory pages count. Closes #1915

Posted by sb...@apache.org.
IGNITE-5150 - Corrected allocated memory pages count. Closes #1915


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/42018e6a
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/42018e6a
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/42018e6a

Branch: refs/heads/ignite-5075
Commit: 42018e6a9d1240c99687d0b39f7ea2b132fa5544
Parents: 661bb53
Author: Ivan Rakov <iv...@gmail.com>
Authored: Tue May 23 15:05:16 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue May 23 15:05:16 2017 +0300

----------------------------------------------------------------------
 .../pagemem/impl/PageMemoryNoStoreImpl.java     | 22 +-------------
 .../pagemem/impl/PageMemoryNoLoadSelfTest.java  | 31 +++++++++++++++++++-
 2 files changed, 31 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/42018e6a/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java
index 1d968c5..b8abfed 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java
@@ -336,20 +336,7 @@ public class PageMemoryNoStoreImpl implements PageMemory {
 
     /** {@inheritDoc} */
     @Override public long loadedPages() {
-        long total = 0;
-
-        for (Segment seg : segments) {
-            seg.readLock().lock();
-
-            try {
-                total += seg.allocatedPages();
-            }
-            finally {
-                seg.readLock().unlock();
-            }
-        }
-
-        return total;
+        return allocatedPages.get();
     }
 
     /**
@@ -757,13 +744,6 @@ public class PageMemoryNoStoreImpl implements PageMemory {
         }
 
         /**
-         * @return Total number of loaded pages for the segment.
-         */
-        private int allocatedPages() {
-            return allocatedPages.get();
-        }
-
-        /**
          * @return Total number of currently acquired pages.
          */
         private int acquiredPages() {

http://git-wip-us.apache.org/repos/asf/ignite/blob/42018e6a/modules/core/src/test/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoLoadSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoLoadSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoLoadSelfTest.java
index 0a283ed..93b68f3 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoLoadSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoLoadSelfTest.java
@@ -25,6 +25,7 @@ import java.util.List;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.configuration.MemoryPolicyConfiguration;
 import org.apache.ignite.internal.mem.DirectMemoryProvider;
+import org.apache.ignite.internal.mem.IgniteOutOfMemoryException;
 import org.apache.ignite.internal.mem.file.MappedFileMemoryProvider;
 import org.apache.ignite.internal.pagemem.FullPageId;
 import org.apache.ignite.internal.pagemem.PageIdAllocator;
@@ -43,6 +44,9 @@ public class PageMemoryNoLoadSelfTest extends GridCommonAbstractTest {
     /** */
     protected static final int PAGE_SIZE = 8 * 1024;
 
+    /** */
+    private static final int MAX_MEMORY_SIZE = 10 * 1024 * 1024;
+
     /** {@inheritDoc} */
     @Override protected void afterTest() throws Exception {
         deleteRecursively(U.resolveWorkDirectory(U.defaultWorkDirectory(), "pagemem", false));
@@ -95,6 +99,31 @@ public class PageMemoryNoLoadSelfTest extends GridCommonAbstractTest {
     /**
      * @throws Exception If failed.
      */
+    public void testLoadedPagesCount() throws Exception {
+        PageMemory mem = memory();
+
+        mem.start();
+
+        int expPages = MAX_MEMORY_SIZE / mem.systemPageSize();
+
+        try {
+            for (int i = 0; i < expPages * 2; i++)
+                allocatePage(mem);
+        }
+        catch (IgniteOutOfMemoryException e) {
+            e.printStackTrace();
+            // Expected.
+
+            assertEquals(mem.loadedPages(), expPages);
+        }
+        finally {
+            mem.stop();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
     public void testPageTearingSequential() throws Exception {
         PageMemory mem = memory();
 
@@ -281,7 +310,7 @@ public class PageMemoryNoLoadSelfTest extends GridCommonAbstractTest {
         File memDir = U.resolveWorkDirectory(U.defaultWorkDirectory(), "pagemem", false);
 
         MemoryPolicyConfiguration plcCfg = new MemoryPolicyConfiguration()
-            .setInitialSize(10 * 1024 * 1024).setMaxSize(10 * 1024 * 1024);
+            .setMaxSize(MAX_MEMORY_SIZE).setInitialSize(MAX_MEMORY_SIZE);
 
         DirectMemoryProvider provider = new MappedFileMemoryProvider(log(), memDir);
 


[12/31] ignite git commit: Merge remote-tracking branch 'origin/master'

Posted by sb...@apache.org.
Merge remote-tracking branch 'origin/master'


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/c04b39a1
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/c04b39a1
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/c04b39a1

Branch: refs/heads/ignite-5075
Commit: c04b39a1be92a500a273b75c58b75d27603bc477
Parents: f353faf 1554a16
Author: sboikov <sb...@gridgain.com>
Authored: Tue May 23 15:34:06 2017 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue May 23 15:34:06 2017 +0300

----------------------------------------------------------------------
 .../java/org/apache/ignite/IgniteCache.java     |  13 +++
 .../ignite/cache/query/FieldsQueryCursor.java   |  39 +++++++
 .../processors/cache/IgniteCacheProxy.java      |  11 +-
 .../processors/cache/QueryCursorImpl.java       |  19 +++-
 .../processors/query/GridQueryIndexing.java     |   5 +-
 .../processors/query/GridQueryProcessor.java    |  15 +--
 .../multijvm/IgniteCacheProcessProxy.java       |   8 ++
 .../processors/query/h2/IgniteH2Indexing.java   |   5 +-
 .../query/h2/ddl/DdlStatementsProcessor.java    |   4 +-
 .../processors/query/h2/opt/GridH2Table.java    | 107 ++++++++++++-------
 .../query/h2/twostep/GridMapQueryExecutor.java  |   2 +-
 .../cache/SqlFieldsQuerySelfTest.java           |  12 ++-
 .../query/IgniteSqlSegmentedIndexSelfTest.java  |  25 +++++
 13 files changed, 205 insertions(+), 60 deletions(-)
----------------------------------------------------------------------



[15/31] ignite git commit: IGNITE-5163: Implemented infrastructure for the new JDBC driver. This closes #1912.

Posted by sb...@apache.org.
IGNITE-5163: Implemented infrastructure for the new JDBC driver. This closes #1912.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/6f1dc3ac
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/6f1dc3ac
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/6f1dc3ac

Branch: refs/heads/ignite-5075
Commit: 6f1dc3ac65d403a634331515cd1f279010d0d092
Parents: c04b39a
Author: tledkov-gridgain <tl...@gridgain.com>
Authored: Tue May 23 15:55:48 2017 +0300
Committer: devozerov <vo...@gridgain.com>
Committed: Tue May 23 15:55:48 2017 +0300

----------------------------------------------------------------------
 .../jdbc/suite/IgniteJdbcDriverTestSuite.java   |   3 +
 .../jdbc/thin/JdbcConnectionSelfTest.java       | 195 +++++++
 .../org/apache/ignite/IgniteJdbcThinDriver.java | 312 +++++++++++
 .../ignite/internal/GridKernalContext.java      |   8 +-
 .../ignite/internal/GridKernalContextImpl.java  |  12 +-
 .../apache/ignite/internal/IgniteKernal.java    |   4 +-
 .../internal/binary/BinaryWriterExImpl.java     |  16 +-
 .../internal/jdbc/thin/JdbcConnection.java      | 529 +++++++++++++++++++
 .../ignite/internal/jdbc/thin/JdbcTcpIo.java    | 207 ++++++++
 .../processors/odbc/OdbcNioListener.java        | 242 ---------
 .../internal/processors/odbc/OdbcProcessor.java | 199 -------
 .../odbc/SqlListenerAbstractMessageParser.java  | 265 ++++++++++
 .../odbc/SqlListenerAbstractObjectReader.java   | 137 +++++
 .../odbc/SqlListenerAbstractObjectWriter.java   | 111 ++++
 .../processors/odbc/SqlListenerNioListener.java | 263 +++++++++
 .../processors/odbc/SqlListenerProcessor.java   | 191 +++++++
 .../odbc/SqlListenerRequestHandlerImpl.java     | 494 +++++++++++++++++
 .../processors/odbc/jdbc/JdbcMessageParser.java |  50 ++
 .../processors/odbc/jdbc/JdbcObjectReader.java  |  33 ++
 .../processors/odbc/jdbc/JdbcObjectWriter.java  |  33 ++
 .../processors/odbc/odbc/OdbcMessageParser.java | 249 +--------
 .../processors/odbc/odbc/OdbcObjectReader.java  |  33 ++
 .../processors/odbc/odbc/OdbcObjectWriter.java  |  32 ++
 .../odbc/odbc/OdbcRequestHandler.java           | 513 ------------------
 .../odbc/OdbcProcessorValidationSelfTest.java   | 182 -------
 .../SqlListenerProcessorValidationSelfTest.java | 184 +++++++
 .../ignite/testframework/GridTestUtils.java     |   2 +-
 .../ignite/testsuites/IgniteBasicTestSuite.java |   4 +-
 .../cpp/odbc/include/ignite/odbc/message.h      |  10 +
 29 files changed, 3124 insertions(+), 1389 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/clients/src/test/java/org/apache/ignite/jdbc/suite/IgniteJdbcDriverTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/jdbc/suite/IgniteJdbcDriverTestSuite.java b/modules/clients/src/test/java/org/apache/ignite/jdbc/suite/IgniteJdbcDriverTestSuite.java
index 75671de..e2f09ba 100644
--- a/modules/clients/src/test/java/org/apache/ignite/jdbc/suite/IgniteJdbcDriverTestSuite.java
+++ b/modules/clients/src/test/java/org/apache/ignite/jdbc/suite/IgniteJdbcDriverTestSuite.java
@@ -81,6 +81,9 @@ public class IgniteJdbcDriverTestSuite extends TestSuite {
         suite.addTest(new TestSuite(org.apache.ignite.internal.jdbc2.JdbcDynamicIndexTransactionalPartitionedSelfTest.class));
         suite.addTest(new TestSuite(org.apache.ignite.internal.jdbc2.JdbcDynamicIndexTransactionalReplicatedSelfTest.class));
 
+        // New thin JDBC
+        suite.addTest(new TestSuite(org.apache.ignite.jdbc.thin.JdbcConnectionSelfTest.class));
+
         return suite;
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcConnectionSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcConnectionSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcConnectionSelfTest.java
new file mode 100644
index 0000000..d7e2bef
--- /dev/null
+++ b/modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcConnectionSelfTest.java
@@ -0,0 +1,195 @@
+/*
+ * 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.jdbc.thin;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.concurrent.Callable;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.OdbcConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Connection test.
+ */
+public class JdbcConnectionSelfTest extends GridCommonAbstractTest {
+    /** IP finder. */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** URL prefix. */
+    private static final String URL_PREFIX = "jdbc:ignite:thin://";
+
+    /** Host. */
+    private static final String HOST = "127.0.0.1";
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setCacheConfiguration(cacheConfiguration(DEFAULT_CACHE_NAME));
+
+        TcpDiscoverySpi disco = new TcpDiscoverySpi();
+
+        disco.setIpFinder(IP_FINDER);
+
+        cfg.setDiscoverySpi(disco);
+
+        cfg.setMarshaller(new BinaryMarshaller());
+
+        cfg.setOdbcConfiguration(new OdbcConfiguration());
+
+        return cfg;
+    }
+
+    /**
+     * @param name Cache name.
+     * @return Cache configuration.
+     * @throws Exception In case of error.
+     */
+    private CacheConfiguration cacheConfiguration(@NotNull String name) throws Exception {
+        CacheConfiguration cfg = defaultCacheConfiguration();
+
+        cfg.setName(name);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        try {
+            Driver drv = DriverManager.getDriver("jdbc:ignite://");
+
+            if (drv != null)
+                DriverManager.deregisterDriver(drv);
+        } catch (SQLException ignored) {
+            // No-op.
+        }
+
+        startGridsMultiThreaded(2);
+
+        Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDefaults() throws Exception {
+        String url = URL_PREFIX + HOST;
+
+        assert DriverManager.getConnection(url) != null;
+        assert DriverManager.getConnection(url + "/") != null;
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testInvalidUrls() throws Exception {
+        GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
+            @Override public Void call() throws Exception {
+                DriverManager.getConnection(URL_PREFIX + "127.0.0.1:80");
+
+                return null;
+            }
+        }, SQLException.class, "Failed to connect to Ignite cluster [host=127.0.0.1, port=80]");
+
+        GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
+            @Override public Void call() throws Exception {
+                DriverManager.getConnection("q");
+
+                return null;
+            }
+        }, SQLException.class, "URL is invalid");
+
+        GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
+            @Override public Void call() throws Exception {
+                DriverManager.getConnection(URL_PREFIX + "127.0.0.1:-1");
+
+                return null;
+            }
+        }, SQLException.class, "Invalid port:");
+
+        GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
+            @Override public Void call() throws Exception {
+                DriverManager.getConnection(URL_PREFIX + "127.0.0.1:0");
+
+                return null;
+            }
+        }, SQLException.class, "Invalid port:");
+
+        GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
+            @Override public Void call() throws Exception {
+                DriverManager.getConnection(URL_PREFIX + "127.0.0.1:100000");
+
+                return null;
+            }
+        }, SQLException.class, "Invalid port:");
+
+        GridTestUtils.assertThrowsAnyCause(log, new Callable<Void>() {
+            @Override public Void call() throws Exception {
+                DriverManager.getConnection(URL_PREFIX + "     :10000");
+
+                return null;
+            }
+        }, SQLException.class, "Host name is empty");
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testClose() throws Exception {
+        String url = URL_PREFIX + HOST;
+
+        final Connection conn = DriverManager.getConnection(url);
+
+        assert conn != null;
+        assert !conn.isClosed();
+
+        conn.close();
+
+        assert conn.isClosed();
+
+        assert !conn.isValid(2): "Connection must be closed";
+
+        GridTestUtils.assertThrows(
+            log,
+            new Callable<Object>() {
+                @Override public Object call() throws Exception {
+                    conn.isValid(-2);
+
+                    return null;
+                }
+            },
+            SQLException.class,
+            "Invalid timeout"
+        );
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/IgniteJdbcThinDriver.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteJdbcThinDriver.java b/modules/core/src/main/java/org/apache/ignite/IgniteJdbcThinDriver.java
new file mode 100644
index 0000000..19e1edd
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteJdbcThinDriver.java
@@ -0,0 +1,312 @@
+/*
+ * 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;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.logging.Logger;
+import org.apache.ignite.cache.affinity.AffinityKey;
+import org.apache.ignite.configuration.OdbcConfiguration;
+import org.apache.ignite.internal.IgniteVersionUtils;
+import org.apache.ignite.internal.jdbc.JdbcDriverPropertyInfo;
+import org.apache.ignite.internal.jdbc.thin.JdbcConnection;
+
+/**
+ * JDBC driver thin implementation for In-Memory Data Grid.
+ * <p>
+ * Driver allows to get distributed data from Ignite cache using standard
+ * SQL queries and standard JDBC API. It will automatically get only fields that
+ * you actually need from objects stored in cache.
+ * <h1 class="header">Limitations</h1>
+ * Data in Ignite cache is usually distributed across several nodes,
+ * so some queries may not work as expected since the query will be sent to each
+ * individual node and results will then be collected and returned as JDBC result set.
+ * Keep in mind following limitations (not applied if data is queried from one node only,
+ * or data is fully co-located or fully replicated on multiple nodes):
+ * <ul>
+ *     <li>
+ *         Joins will work correctly only if joined objects are stored in
+ *         collocated mode. Refer to
+ *         {@link AffinityKey}
+ *         javadoc for more details.
+ *     </li>
+ *     <li>
+ *         Note that if you are connected to local or replicated cache, all data will
+ *         be queried only on one node, not depending on what caches participate in
+ *         the query (some data from partitioned cache can be lost). And visa versa,
+ *         if you are connected to partitioned cache, data from replicated caches
+ *         will be duplicated.
+ *     </li>
+ * </ul>
+ * <h1 class="header">SQL Notice</h1>
+ * Driver allows to query data from several caches. Cache that driver is connected to is
+ * treated as default schema in this case. Other caches can be referenced by their names.\
+ *
+ * <h1 class="header">Dependencies</h1>
+ * JDBC driver is located in main Ignite JAR in {@code IGNITE_HOME/libs} folder.
+ * <h1 class="header">Configuration</h1>
+ *
+ * <p>
+ * JDBC connection URL has the following pattern:
+ * {@code jdbc:ignite://<hostname>:<port>/}<br>
+ * Note the following:
+ * <ul>
+ *     <li>Hostname is required.</li>
+ *     <li>If port is not defined, {@code 10800} is used (default for Ignite thin client).</li>
+ * </ul>
+ * Other properties can be defined in {@link Properties} object passed to
+ * {@link DriverManager#getConnection(String, Properties)} method:
+ * <table class="doctable">
+ *     <tr>
+ *         <th>Name</th>
+ *         <th>Description</th>
+ *         <th>Default</th>
+ *         <th>Optional</th>
+ *     </tr>
+ *     <tr>
+ *         <td><b>ignite.jdbc.distributedJoins</b></td>
+ *         <td>Flag to enable distributed joins.</td>
+ *         <td>{@code false} (distributed joins are disabled)</td>
+ *         <td>Yes</td>
+ *     </tr>
+ *     <tr>
+ *         <td><b>ignite.jdbc.enforceJoinOrder</b></td>
+ *         <td>Flag to enforce join order of tables in the query.</td>
+ *         <td>{@code false} (enforcing join order is disabled)</td>
+ *         <td>Yes</td>
+ *     </tr>
+ * </table>
+ * <h1 class="header">Example</h1>
+ * <pre name="code" class="java">
+ * // Register JDBC driver.
+ * Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
+ *
+ * // Open JDBC connection.
+ * Connection conn = DriverManager.getConnection("jdbc:ignite:thin//localhost:10800");
+ *
+ * // Query persons' names
+ * ResultSet rs = conn.createStatement().executeQuery("select name from Person");
+ *
+ * while (rs.next()) {
+ *     String name = rs.getString(1);
+ *
+ *     ...
+ * }
+ *
+ * // Query persons with specific age
+ * PreparedStatement stmt = conn.prepareStatement("select name, age from Person where age = ?");
+ *
+ * stmt.setInt(1, 30);
+ *
+ * ResultSet rs = stmt.executeQuery();
+ *
+ * while (rs.next()) {
+ *     String name = rs.getString("name");
+ *     int age = rs.getInt("age");
+ *
+ *     ...
+ * }
+ * </pre>
+ */
+@SuppressWarnings("JavadocReference")
+public class IgniteJdbcThinDriver implements Driver {
+    /** Prefix for property names. */
+    private static final String PROP_PREFIX = "ignite.jdbc";
+
+    /** Distributed joins parameter name. */
+    private static final String PARAM_DISTRIBUTED_JOINS = "distributedJoins";
+
+    /** Enforce join order parameter name. */
+    private static final String ENFORCE_JOIN_ORDER = "enforceJoinOrder";
+
+    /** Hostname property name. */
+    public static final String PROP_HOST = PROP_PREFIX + "host";
+
+    /** Port number property name. */
+    public static final String PROP_PORT = PROP_PREFIX + "port";
+
+    /** Distributed joins property name. */
+    public static final String PROP_DISTRIBUTED_JOINS = PROP_PREFIX + PARAM_DISTRIBUTED_JOINS;
+
+    /** Transactions allowed property name. */
+    public static final String PROP_ENFORCE_JOIN_ORDER = PROP_PREFIX + ENFORCE_JOIN_ORDER;
+
+    /** URL prefix. */
+    public static final String URL_PREFIX = "jdbc:ignite:thin://";
+
+    /** Default port. */
+    public static final int DFLT_PORT = OdbcConfiguration.DFLT_TCP_PORT_FROM;
+
+    /** Major version. */
+    private static final int MAJOR_VER = IgniteVersionUtils.VER.major();
+
+    /** Minor version. */
+    private static final int MINOR_VER = IgniteVersionUtils.VER.minor();
+
+    /*
+     * Register driver.
+     */
+    static {
+        try {
+            DriverManager.registerDriver(new IgniteJdbcThinDriver());
+        }
+        catch (SQLException e) {
+            throw new RuntimeException("Failed to register Ignite JDBC driver.", e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Connection connect(String url, Properties props) throws SQLException {
+        if (!parseUrl(url, props))
+            throw new SQLException("URL is invalid: " + url);
+
+        return new JdbcConnection(url, props);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean acceptsURL(String url) throws SQLException {
+        return url.startsWith(URL_PREFIX);
+    }
+
+    /** {@inheritDoc} */
+    @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
+        if (!parseUrl(url, info))
+            throw new SQLException("URL is invalid: " + url);
+
+        List<DriverPropertyInfo> props = Arrays.<DriverPropertyInfo>asList(
+            new JdbcDriverPropertyInfo("Hostname", info.getProperty(PROP_HOST), ""),
+            new JdbcDriverPropertyInfo("Port number", info.getProperty(PROP_PORT), ""),
+            new JdbcDriverPropertyInfo("Distributed Joins", info.getProperty(PROP_DISTRIBUTED_JOINS), ""),
+            new JdbcDriverPropertyInfo("Enforce Join Order", info.getProperty(PROP_ENFORCE_JOIN_ORDER), "")
+        );
+
+        return props.toArray(new DriverPropertyInfo[0]);
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getMajorVersion() {
+        return MAJOR_VER;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getMinorVersion() {
+        return MINOR_VER;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean jdbcCompliant() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException {
+        throw new SQLFeatureNotSupportedException("java.util.logging is not used.");
+    }
+
+    /**
+     * Validates and parses connection URL.
+     *
+     * @param props Properties.
+     * @param url URL.
+     * @return Whether URL is valid.
+     */
+    private boolean parseUrl(String url, Properties props) {
+        if (url == null)
+            return false;
+
+        if (url.startsWith(URL_PREFIX) && url.length() > URL_PREFIX.length())
+            return parseJdbcUrl(url, props);
+
+        return false;
+    }
+
+    /**
+     * @param url Url.
+     * @param props Properties.
+     * @return Whether URL is valid.
+     */
+    private boolean parseJdbcUrl(String url, Properties props) {
+        url = url.substring(URL_PREFIX.length());
+
+        String[] parts = url.split("\\?");
+
+        if (parts.length > 2)
+            return false;
+
+        if (parts.length == 2)
+            if (!parseParameters(parts[1], "&", props))
+                return false;
+
+        parts = parts[0].split("/");
+
+        assert parts.length > 0;
+
+        if (parts.length > 1)
+            return false;
+
+        url = parts[0];
+
+        parts = url.split(":");
+
+        assert parts.length > 0;
+
+        if (parts.length > 2)
+            return false;
+
+        props.setProperty(PROP_HOST, parts[0]);
+
+        try {
+            props.setProperty(PROP_PORT, String.valueOf(parts.length == 2 ? Integer.valueOf(parts[1]) : DFLT_PORT));
+        }
+        catch (NumberFormatException ignored) {
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Validates and parses URL parameters.
+     *
+     * @param val Parameters string.
+     * @param delim Delimiter.
+     * @param props Properties.
+     * @return Whether URL parameters string is valid.
+     */
+    private boolean parseParameters(String val, String delim, Properties props) {
+        String[] params = val.split(delim);
+
+        for (String param : params) {
+            String[] pair = param.split("=");
+
+            if (pair.length != 2 || pair[0].isEmpty() || pair[1].isEmpty())
+                return false;
+
+            props.setProperty(PROP_PREFIX + pair[0], pair[1]);
+        }
+
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
index 010bd21..7a01200 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContext.java
@@ -48,7 +48,7 @@ import org.apache.ignite.internal.processors.igfs.IgfsProcessorAdapter;
 import org.apache.ignite.internal.processors.job.GridJobProcessor;
 import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor;
 import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor;
-import org.apache.ignite.internal.processors.odbc.OdbcProcessor;
+import org.apache.ignite.internal.processors.odbc.SqlListenerProcessor;
 import org.apache.ignite.internal.processors.platform.PlatformProcessor;
 import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor;
 import org.apache.ignite.internal.processors.pool.PoolProcessor;
@@ -330,11 +330,11 @@ public interface GridKernalContext extends Iterable<GridComponent> {
     public GridQueryProcessor query();
 
     /**
-     * Gets ODBC processor.
+     * Gets SQL listener processor.
      *
-     * @return ODBC processor.
+     * @return SQL listener processor.
      */
-    public OdbcProcessor odbc();
+    public SqlListenerProcessor sqlListener();
 
     /**
      * @return Plugin processor.

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
index bbc9846..262c5eb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
@@ -64,7 +64,7 @@ import org.apache.ignite.internal.processors.job.GridJobProcessor;
 import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor;
 import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor;
 import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor;
-import org.apache.ignite.internal.processors.odbc.OdbcProcessor;
+import org.apache.ignite.internal.processors.odbc.SqlListenerProcessor;
 import org.apache.ignite.internal.processors.platform.PlatformProcessor;
 import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor;
 import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor;
@@ -160,7 +160,7 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
 
     /** */
     @GridToStringInclude
-    private OdbcProcessor odbcProc;
+    private SqlListenerProcessor sqlListenerProc;
 
     /** */
     @GridToStringInclude
@@ -567,8 +567,8 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
             pluginProc = (IgnitePluginProcessor)comp;
         else if (comp instanceof GridQueryProcessor)
             qryProc = (GridQueryProcessor)comp;
-        else if (comp instanceof OdbcProcessor)
-            odbcProc = (OdbcProcessor)comp;
+        else if (comp instanceof SqlListenerProcessor)
+            sqlListenerProc = (SqlListenerProcessor)comp;
         else if (comp instanceof DataStructuresProcessor)
             dataStructuresProc = (DataStructuresProcessor)comp;
         else if (comp instanceof ClusterProcessor)
@@ -824,8 +824,8 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
     }
 
     /** {@inheritDoc} */
-    @Override public OdbcProcessor odbc() {
-        return odbcProc;
+    @Override public SqlListenerProcessor sqlListener() {
+        return sqlListenerProc;
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
index 40476a7..c36fd7e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
@@ -125,7 +125,7 @@ import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor;
 import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor;
 import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor;
 import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor;
-import org.apache.ignite.internal.processors.odbc.OdbcProcessor;
+import org.apache.ignite.internal.processors.odbc.SqlListenerProcessor;
 import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor;
 import org.apache.ignite.internal.processors.platform.PlatformProcessor;
 import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor;
@@ -924,7 +924,7 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
             startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx));
             startProcessor(new GridCacheProcessor(ctx));startProcessor(new GridClusterStateProcessor(ctx));
             startProcessor(new GridQueryProcessor(ctx));
-            startProcessor(new OdbcProcessor(ctx));
+            startProcessor(new SqlListenerProcessor(ctx));
             startProcessor(new GridServiceProcessor(ctx));
             startProcessor(new GridTaskSessionProcessor(ctx));
             startProcessor(new GridJobProcessor(ctx));

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
index 7b5e9d3..7efe4b3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
@@ -938,7 +938,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeByteFieldPrimitive(byte val) {
+    public void writeByteFieldPrimitive(byte val) {
         out.unsafeEnsure(1 + 1);
 
         out.unsafeWriteByte(GridBinaryMarshaller.BYTE);
@@ -965,7 +965,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeShortFieldPrimitive(short val) {
+    public void writeShortFieldPrimitive(short val) {
         out.unsafeEnsure(1 + 2);
 
         out.unsafeWriteByte(GridBinaryMarshaller.SHORT);
@@ -985,7 +985,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeIntFieldPrimitive(int val) {
+    public void writeIntFieldPrimitive(int val) {
         out.unsafeEnsure(1 + 4);
 
         out.unsafeWriteByte(GridBinaryMarshaller.INT);
@@ -1005,7 +1005,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeLongFieldPrimitive(long val) {
+    public void writeLongFieldPrimitive(long val) {
         out.unsafeEnsure(1 + 8);
 
         out.unsafeWriteByte(GridBinaryMarshaller.LONG);
@@ -1025,7 +1025,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeFloatFieldPrimitive(float val) {
+    public void writeFloatFieldPrimitive(float val) {
         out.unsafeEnsure(1 + 4);
 
         out.unsafeWriteByte(GridBinaryMarshaller.FLOAT);
@@ -1045,7 +1045,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeDoubleFieldPrimitive(double val) {
+    public void writeDoubleFieldPrimitive(double val) {
         out.unsafeEnsure(1 + 8);
 
         out.unsafeWriteByte(GridBinaryMarshaller.DOUBLE);
@@ -1065,7 +1065,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeCharFieldPrimitive(char val) {
+    public void writeCharFieldPrimitive(char val) {
         out.unsafeEnsure(1 + 2);
 
         out.unsafeWriteByte(GridBinaryMarshaller.CHAR);
@@ -1085,7 +1085,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
     /**
      * @param val Value.
      */
-    void writeBooleanFieldPrimitive(boolean val) {
+    public void writeBooleanFieldPrimitive(boolean val) {
         out.unsafeEnsure(1 + 1);
 
         out.unsafeWriteByte(GridBinaryMarshaller.BOOLEAN);

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcConnection.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcConnection.java b/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcConnection.java
new file mode 100644
index 0000000..25d62b4
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcConnection.java
@@ -0,0 +1,529 @@
+/*
+ * 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.jdbc.thin;
+
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.CallableStatement;
+import java.sql.Clob;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.NClob;
+import java.sql.PreparedStatement;
+import java.sql.SQLClientInfoException;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.sql.SQLWarning;
+import java.sql.SQLXML;
+import java.sql.Savepoint;
+import java.sql.Statement;
+import java.sql.Struct;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.Executor;
+import java.util.logging.Logger;
+
+import static java.sql.ResultSet.CONCUR_READ_ONLY;
+import static java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT;
+import static java.sql.ResultSet.TYPE_FORWARD_ONLY;
+import static org.apache.ignite.IgniteJdbcThinDriver.PROP_DISTRIBUTED_JOINS;
+import static org.apache.ignite.IgniteJdbcThinDriver.PROP_ENFORCE_JOIN_ORDER;
+import static org.apache.ignite.IgniteJdbcThinDriver.PROP_HOST;
+import static org.apache.ignite.IgniteJdbcThinDriver.PROP_PORT;
+
+/**
+ * JDBC connection implementation.
+ *
+ * See documentation of {@link org.apache.ignite.IgniteJdbcThinDriver} for details.
+ */
+public class JdbcConnection implements Connection {
+    /** Logger. */
+    private static final Logger LOG = Logger.getLogger(JdbcConnection.class.getName());
+
+    /** Cache name. */
+    private String schemaName;
+
+    /** Closed flag. */
+    private boolean closed;
+
+    /** Current transaction isolation. */
+    private int txIsolation;
+
+    /** Auto commit flag. */
+    private boolean autoCommit;
+
+    /** Current transaction holdability. */
+    private int holdability;
+
+    /** Timeout. */
+    private int timeout;
+
+    /** Ignite endpoint. */
+    private JdbcTcpIo cliIo;
+
+    /**
+     * Creates new connection.
+     *
+     * @param url Connection URL.
+     * @param props Additional properties.
+     * @throws SQLException In case Ignite client failed to start.
+     */
+    public JdbcConnection(String url, Properties props) throws SQLException {
+        assert url != null;
+        assert props != null;
+
+        holdability = HOLD_CURSORS_OVER_COMMIT;
+        autoCommit = true;
+        txIsolation = Connection.TRANSACTION_NONE;
+
+        boolean distributedJoins = Boolean.parseBoolean(props.getProperty(PROP_DISTRIBUTED_JOINS, "false"));
+        boolean enforceJoinOrder = Boolean.parseBoolean(props.getProperty(PROP_ENFORCE_JOIN_ORDER, "false"));
+
+        String host = props.getProperty(PROP_HOST);
+        String portStr = props.getProperty(PROP_PORT);
+
+        try {
+            int port = Integer.parseInt(portStr);
+
+            if (port <= 0 || port > 0xFFFF)
+                throw new SQLException("Invalid port: " + portStr);
+        }
+        catch (NumberFormatException e) {
+            throw new SQLException("Invalid port: " + portStr, e);
+        }
+
+        if (host == null || host.trim().isEmpty())
+            throw new SQLException("Host name is empty.");
+
+        String endpoint = host.trim() + ":" + portStr.trim();
+
+        try {
+            cliIo = new JdbcTcpIo(endpoint, distributedJoins, enforceJoinOrder);
+
+            cliIo.start();
+        }
+        catch (Exception e) {
+            cliIo.close();
+
+            throw new SQLException("Failed to connect to Ignite cluster [host=" + host + ", port=" + portStr + ']', e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Statement createStatement() throws SQLException {
+        return createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, HOLD_CURSORS_OVER_COMMIT);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Statement createStatement(int resSetType, int resSetConcurrency) throws SQLException {
+        return createStatement(resSetType, resSetConcurrency, HOLD_CURSORS_OVER_COMMIT);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Statement createStatement(int resSetType, int resSetConcurrency,
+        int resSetHoldability) throws SQLException {
+        ensureNotClosed();
+
+        checkCursorOptions(resSetType, resSetConcurrency, resSetHoldability);
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public PreparedStatement prepareStatement(String sql) throws SQLException {
+        return prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, HOLD_CURSORS_OVER_COMMIT);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PreparedStatement prepareStatement(String sql, int resSetType,
+        int resSetConcurrency) throws SQLException {
+        return prepareStatement(sql, resSetType, resSetConcurrency, HOLD_CURSORS_OVER_COMMIT);
+    }
+
+    /** {@inheritDoc} */
+    @Override public PreparedStatement prepareStatement(String sql, int resSetType, int resSetConcurrency,
+        int resSetHoldability) throws SQLException {
+        ensureNotClosed();
+
+        checkCursorOptions(resSetType, resSetConcurrency, resSetHoldability);
+
+        return null;
+    }
+
+    /**
+     * @param resSetType Cursor option.
+     * @param resSetConcurrency Cursor option.
+     * @param resSetHoldability Cursor option.
+     * @throws SQLException If options unsupported.
+     */
+    private void checkCursorOptions(int resSetType, int resSetConcurrency,
+        int resSetHoldability) throws SQLException {
+        if (resSetType != TYPE_FORWARD_ONLY)
+            throw new SQLFeatureNotSupportedException("Invalid result set type (only forward is supported.)");
+
+        if (resSetConcurrency != CONCUR_READ_ONLY)
+            throw new SQLFeatureNotSupportedException("Invalid concurrency (updates are not supported).");
+
+        if (resSetHoldability != HOLD_CURSORS_OVER_COMMIT)
+            LOG.warning("Transactions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public CallableStatement prepareCall(String sql) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Callable functions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public CallableStatement prepareCall(String sql, int resSetType, int resSetConcurrency)
+        throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Callable functions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public String nativeSQL(String sql) throws SQLException {
+        ensureNotClosed();
+
+        return sql;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setAutoCommit(boolean autoCommit) throws SQLException {
+        ensureNotClosed();
+
+        this.autoCommit = autoCommit;
+
+        if (!autoCommit)
+            LOG.warning("Transactions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean getAutoCommit() throws SQLException {
+        ensureNotClosed();
+
+        if (!autoCommit)
+            LOG.warning("Transactions are not supported.");
+
+        return autoCommit;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void commit() throws SQLException {
+        ensureNotClosed();
+
+        LOG.warning("Transactions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void rollback() throws SQLException {
+        ensureNotClosed();
+
+        LOG.warning("Transactions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() throws SQLException {
+        if (closed)
+            return;
+
+        closed = true;
+
+        cliIo.close();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isClosed() throws SQLException {
+        return closed;
+    }
+
+    /** {@inheritDoc} */
+    @Override public DatabaseMetaData getMetaData() throws SQLException {
+        ensureNotClosed();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setReadOnly(boolean readOnly) throws SQLException {
+        ensureNotClosed();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isReadOnly() throws SQLException {
+        ensureNotClosed();
+
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setCatalog(String catalog) throws SQLException {
+        ensureNotClosed();
+    }
+
+    /** {@inheritDoc} */
+    @Override public String getCatalog() throws SQLException {
+        ensureNotClosed();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setTransactionIsolation(int level) throws SQLException {
+        ensureNotClosed();
+
+        LOG.warning("Transactions are not supported.");
+
+        txIsolation = level;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getTransactionIsolation() throws SQLException {
+        ensureNotClosed();
+
+        LOG.warning("Transactions are not supported.");
+
+        return txIsolation;
+    }
+
+    /** {@inheritDoc} */
+    @Override public SQLWarning getWarnings() throws SQLException {
+        ensureNotClosed();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void clearWarnings() throws SQLException {
+        ensureNotClosed();
+    }
+
+    /** {@inheritDoc} */
+    @Override public Map<String, Class<?>> getTypeMap() throws SQLException {
+        throw new SQLFeatureNotSupportedException("Types mapping is not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Types mapping is not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setHoldability(int holdability) throws SQLException {
+        ensureNotClosed();
+
+        if (holdability != HOLD_CURSORS_OVER_COMMIT)
+            LOG.warning("Transactions are not supported.");
+
+        this.holdability = holdability;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getHoldability() throws SQLException {
+        ensureNotClosed();
+
+        return holdability;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Savepoint setSavepoint() throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Savepoints are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public Savepoint setSavepoint(String name) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Savepoints are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void rollback(Savepoint savepoint) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Savepoints are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Savepoints are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public CallableStatement prepareCall(String sql, int resSetType, int resSetConcurrency,
+        int resSetHoldability) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Callable functions are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Auto generated keys are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public PreparedStatement prepareStatement(String sql, int[] colIndexes) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Auto generated keys are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public PreparedStatement prepareStatement(String sql, String[] colNames) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("Auto generated keys are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public Clob createClob() throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("SQL-specific types are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public Blob createBlob() throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("SQL-specific types are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public NClob createNClob() throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("SQL-specific types are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public SQLXML createSQLXML() throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("SQL-specific types are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isValid(int timeout) throws SQLException {
+        if (timeout < 0)
+            throw new SQLException("Invalid timeout: " + timeout);
+
+        return !closed;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setClientInfo(String name, String val) throws SQLClientInfoException {
+        throw new UnsupportedOperationException("Client info is not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setClientInfo(Properties props) throws SQLClientInfoException {
+        throw new UnsupportedOperationException("Client info is not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public String getClientInfo(String name) throws SQLException {
+        ensureNotClosed();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Properties getClientInfo() throws SQLException {
+        ensureNotClosed();
+
+        return new Properties();
+    }
+
+    /** {@inheritDoc} */
+    @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("SQL-specific types are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @Override public Struct createStruct(String typeName, Object[] attrs) throws SQLException {
+        ensureNotClosed();
+
+        throw new SQLFeatureNotSupportedException("SQL-specific types are not supported.");
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override public <T> T unwrap(Class<T> iface) throws SQLException {
+        if (!isWrapperFor(iface))
+            throw new SQLException("Connection is not a wrapper for " + iface.getName());
+
+        return (T)this;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isWrapperFor(Class<?> iface) throws SQLException {
+        return iface != null && iface == Connection.class;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setSchema(String schema) throws SQLException {
+        schemaName = schema;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String getSchema() throws SQLException {
+        return schemaName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void abort(Executor executor) throws SQLException {
+        close();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setNetworkTimeout(Executor executor, int ms) throws SQLException {
+        if (ms < 0)
+            throw new IllegalArgumentException("Timeout is below zero: " + ms);
+
+        timeout = ms;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getNetworkTimeout() throws SQLException {
+        return timeout;
+    }
+
+    /**
+     * Ensures that connection is not closed.
+     *
+     * @throws SQLException If connection is closed.
+     */
+    private void ensureNotClosed() throws SQLException {
+        if (closed)
+            throw new SQLException("Connection is closed.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcTcpIo.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcTcpIo.java b/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcTcpIo.java
new file mode 100644
index 0000000..4946b41
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcTcpIo.java
@@ -0,0 +1,207 @@
+/*
+ * 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.jdbc.thin;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.util.logging.Logger;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+import org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;
+import org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream;
+import org.apache.ignite.internal.processors.odbc.SqlListenerProtocolVersion;
+import org.apache.ignite.internal.processors.odbc.SqlListenerRequest;
+import org.apache.ignite.internal.processors.odbc.SqlListenerNioListener;
+import org.apache.ignite.internal.util.ipc.IpcEndpoint;
+import org.apache.ignite.internal.util.ipc.IpcEndpointFactory;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * JDBC IO layer implementation based on blocking IPC streams.
+ */
+public class JdbcTcpIo {
+    /** Current version. */
+    private static final SqlListenerProtocolVersion CURRENT_VER = SqlListenerProtocolVersion.create(2, 1, 0);
+
+    /** Initial output stream capacity. */
+    private static final int HANDSHAKE_MSG_SIZE = 10;
+
+    /** Logger. */
+    private static final Logger log = Logger.getLogger(JdbcTcpIo.class.getName());
+
+    /** Server endpoint address. */
+    private final String endpointAddr;
+
+    /** Endpoint. */
+    private IpcEndpoint endpoint;
+
+    /** Output stream. */
+    private BufferedOutputStream out;
+
+    /** Input stream. */
+    private BufferedInputStream in;
+
+    /** Distributed joins. */
+    private boolean distributedJoins;
+
+    /** Enforce join order. */
+    private boolean enforceJoinOrder;
+
+    /** Closed flag. */
+    private boolean closed;
+
+    /**
+     * @param endpointAddr Endpoint.
+     * @param distributedJoins Distributed joins flag.
+     * @param enforceJoinOrder Enforce join order flag.
+     */
+    JdbcTcpIo(String endpointAddr, boolean distributedJoins, boolean enforceJoinOrder) {
+        assert endpointAddr != null;
+
+        this.endpointAddr = endpointAddr;
+        this.distributedJoins = distributedJoins;
+        this.enforceJoinOrder= enforceJoinOrder;
+    }
+
+    /**
+     * @throws IgniteCheckedException On error.
+     * @throws IOException On IO error in handshake.
+     */
+    public void start() throws IgniteCheckedException, IOException {
+        endpoint = IpcEndpointFactory.connectEndpoint(endpointAddr, null);
+
+        out = new BufferedOutputStream(endpoint.outputStream());
+        in = new BufferedInputStream(endpoint.inputStream());
+
+        handshake();
+    }
+
+    /**
+     * @throws IOException On error.
+     * @throws IgniteCheckedException On error.
+     */
+    public void handshake() throws IOException, IgniteCheckedException {
+        BinaryWriterExImpl writer = new BinaryWriterExImpl(null, new BinaryHeapOutputStream(HANDSHAKE_MSG_SIZE),
+            null, null);
+
+        writer.writeByte((byte)SqlListenerRequest.HANDSHAKE);
+
+        writer.writeShort(CURRENT_VER.major());
+        writer.writeShort(CURRENT_VER.minor());
+        writer.writeShort(CURRENT_VER.maintenance());
+
+        writer.writeByte(SqlListenerNioListener.JDBC_CLIENT);
+
+        writer.writeBoolean(distributedJoins);
+        writer.writeBoolean(enforceJoinOrder);
+
+        send(writer.array());
+
+        BinaryReaderExImpl reader = new BinaryReaderExImpl(null, new BinaryHeapInputStream(read()),
+            null, null, false);
+
+        boolean accepted = reader.readBoolean();
+
+        if (accepted)
+            return;
+
+        short maj = reader.readShort();
+        short min = reader.readShort();
+        short maintenance = reader.readShort();
+
+        String err = reader.readString();
+
+        SqlListenerProtocolVersion ver = SqlListenerProtocolVersion.create(maj, min, maintenance);
+
+        throw new IgniteCheckedException("Handshake failed [driverProtocolVer=" + CURRENT_VER +
+            ", remoteNodeProtocolVer=" + ver + ", err=" + err + ']');
+    }
+
+    /**
+     * @param req ODBC request.
+     * @throws IOException On error.
+     */
+    private void send(byte[] req) throws IOException {
+        int size = req.length;
+
+        out.write(size & 0xFF);
+        out.write((size >> 8) & 0xFF);
+        out.write((size >> 16) & 0xFF);
+        out.write((size >> 24) & 0xFF);
+
+        out.write(req);
+
+        out.flush();
+    }
+
+    /**
+     * @return Bytes of a response from server.
+     * @throws IOException On error.
+     * @throws IgniteCheckedException On error.
+     */
+    private byte[] read() throws IOException, IgniteCheckedException {
+        byte[] sizeBytes = read(4);
+
+        int msgSize  = (((0xFF & sizeBytes[3]) << 24) | ((0xFF & sizeBytes[2]) << 16)
+            | ((0xFF & sizeBytes[1]) << 8) + (0xFF & sizeBytes[0]));
+
+        return read(msgSize);
+    }
+
+    /**
+     * @param size Count of bytes to read from stream.
+     * @return Read bytes.
+     * @throws IOException On error.
+     * @throws IgniteCheckedException On error.
+     */
+    private byte [] read(int size) throws IOException, IgniteCheckedException {
+        int off = 0;
+
+        byte[] data = new byte[size];
+
+        while (off != size) {
+            int res = in.read(data, off, size - off);
+
+            if (res == -1)
+                throw new IgniteCheckedException("Failed to read incoming message (not enough data).");
+
+            off += res;
+        }
+
+        return data;
+    }
+
+    /**
+     * Close the client IO.
+     */
+    public void close() {
+        if (closed)
+            return;
+
+        // Clean up resources.
+        U.closeQuiet(out);
+        U.closeQuiet(in);
+
+        if (endpoint != null)
+            endpoint.close();
+
+        closed = true;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcNioListener.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcNioListener.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcNioListener.java
deleted file mode 100644
index cdb3de3..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcNioListener.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * 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.odbc;
-
-import org.apache.ignite.IgniteLogger;
-import org.apache.ignite.internal.GridKernalContext;
-import org.apache.ignite.internal.binary.BinaryReaderExImpl;
-import org.apache.ignite.internal.binary.BinaryWriterExImpl;
-import org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;
-import org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream;
-import org.apache.ignite.internal.binary.streams.BinaryInputStream;
-import org.apache.ignite.internal.processors.odbc.odbc.OdbcMessageParser;
-import org.apache.ignite.internal.processors.odbc.odbc.OdbcRequestHandler;
-import org.apache.ignite.internal.util.GridSpinBusyLock;
-import org.apache.ignite.internal.util.nio.GridNioServerListenerAdapter;
-import org.apache.ignite.internal.util.nio.GridNioSession;
-import org.apache.ignite.internal.util.nio.GridNioSessionMetaKey;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * ODBC message listener.
- */
-public class OdbcNioListener extends GridNioServerListenerAdapter<byte[]> {
-    /** Current version. */
-    private static final SqlListenerProtocolVersion CURRENT_VER = SqlListenerProtocolVersion.create(2, 1, 0);
-
-    /** Supported versions. */
-    private static final Set<SqlListenerProtocolVersion> SUPPORTED_VERS = new HashSet<>();
-
-    /** Connection-related metadata key. */
-    private static final int CONN_CTX_META_KEY = GridNioSessionMetaKey.nextUniqueKey();
-
-    /** Request ID generator. */
-    private static final AtomicLong REQ_ID_GEN = new AtomicLong();
-
-    /** Busy lock. */
-    private final GridSpinBusyLock busyLock;
-
-    /** Kernal context. */
-    private final GridKernalContext ctx;
-
-    /** Maximum allowed cursors. */
-    private final int maxCursors;
-
-    /** Logger. */
-    private final IgniteLogger log;
-
-    static {
-        SUPPORTED_VERS.add(CURRENT_VER);
-    }
-
-    /**
-     * Constructor.
-     *
-     * @param ctx Context.
-     * @param busyLock Shutdown busy lock.
-     * @param maxCursors Maximum allowed cursors.
-     */
-    public OdbcNioListener(GridKernalContext ctx, GridSpinBusyLock busyLock, int maxCursors) {
-        this.ctx = ctx;
-        this.busyLock = busyLock;
-        this.maxCursors = maxCursors;
-
-        log = ctx.log(getClass());
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onConnected(GridNioSession ses) {
-        if (log.isDebugEnabled())
-            log.debug("SQL client connected: " + ses.remoteAddress());
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onDisconnected(GridNioSession ses, @Nullable Exception e) {
-        if (log.isDebugEnabled()) {
-            if (e == null)
-                log.debug("SQL client disconnected: " + ses.remoteAddress());
-            else
-                log.debug("SQL client disconnected due to an error [addr=" + ses.remoteAddress() + ", err=" + e + ']');
-        }
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onMessage(GridNioSession ses, byte[] msg) {
-        assert msg != null;
-
-        SqlListenerConnectionContext connCtx = ses.meta(CONN_CTX_META_KEY);
-
-        if (connCtx == null) {
-            onHandshake(ses, msg);
-
-            return;
-        }
-
-        SqlListenerMessageParser parser = connCtx.parser();
-
-        SqlListenerRequest req;
-
-        try {
-            req = parser.decode(msg);
-        }
-        catch (Exception e) {
-            log.error("Failed to parse SQL client request [err=" + e + ']');
-
-            ses.close();
-
-            return;
-        }
-
-        assert req != null;
-
-        req.requestId(REQ_ID_GEN.incrementAndGet());
-
-        try {
-            long startTime = 0;
-
-            if (log.isDebugEnabled()) {
-                startTime = System.nanoTime();
-
-                log.debug("SQL client request received [reqId=" + req.requestId() + ", addr=" + ses.remoteAddress() +
-                    ", req=" + req + ']');
-            }
-
-            SqlListenerRequestHandler handler = connCtx.handler();
-
-            SqlListenerResponse resp = handler.handle(req);
-
-            if (log.isDebugEnabled()) {
-                long dur = (System.nanoTime() - startTime) / 1000;
-
-                log.debug("SQL client request processed [reqId=" + req.requestId() + ", dur(mcs)=" + dur  +
-                    ", resp=" + resp.status() + ']');
-            }
-
-            byte[] outMsg = parser.encode(resp);
-
-            ses.send(outMsg);
-        }
-        catch (Exception e) {
-            log.error("Failed to process SQL client request [reqId=" + req.requestId() + ", err=" + e + ']');
-
-            ses.send(parser.encode(new SqlListenerResponse(SqlListenerResponse.STATUS_FAILED, e.toString())));
-        }
-    }
-
-    /**
-     * Perform handshake.
-     *
-     * @param ses Session.
-     * @param msg Message bytes.
-     */
-    private void onHandshake(GridNioSession ses, byte[] msg) {
-        BinaryInputStream stream = new BinaryHeapInputStream(msg);
-
-        BinaryReaderExImpl reader = new BinaryReaderExImpl(null, stream, null, true);
-
-        byte cmd = reader.readByte();
-
-        if (cmd != SqlListenerRequest.HANDSHAKE) {
-            log.error("Unexpected SQL client request (will close session): " + ses.remoteAddress());
-
-            ses.close();
-
-            return;
-        }
-
-        short verMajor = reader.readShort();
-        short verMinor = reader.readShort();
-        short verMaintenance = reader.readShort();
-
-        SqlListenerProtocolVersion ver = SqlListenerProtocolVersion.create(verMajor, verMinor, verMaintenance);
-
-        String errMsg = null;
-
-        if (SUPPORTED_VERS.contains(ver)) {
-            // Prepare context.
-            SqlListenerConnectionContext connCtx = prepareContext(ver, reader);
-
-            ses.addMeta(CONN_CTX_META_KEY, connCtx);
-        }
-        else {
-            log.warning("Unsupported version: " + ver.toString());
-
-            errMsg = "Unsupported version.";
-        }
-
-        // Send response.
-        BinaryWriterExImpl writer = new BinaryWriterExImpl(null, new BinaryHeapOutputStream(8), null, null);
-
-        if (errMsg == null) {
-            writer.writeBoolean(true);
-        }
-        else {
-            writer.writeBoolean(false);
-            writer.writeShort(CURRENT_VER.major());
-            writer.writeShort(CURRENT_VER.minor());
-            writer.writeShort(CURRENT_VER.maintenance());
-            writer.doWriteString(errMsg);
-        }
-
-        ses.send(writer.array());
-    }
-
-    /**
-     * Prepare context.
-     *
-     * @param ver Version.
-     * @param reader Reader.
-     * @return Context.
-     */
-    private SqlListenerConnectionContext prepareContext(SqlListenerProtocolVersion ver, BinaryReaderExImpl reader) {
-        // TODO: Switch between ODBC and JDBC.
-        boolean distributedJoins = reader.readBoolean();
-        boolean enforceJoinOrder = reader.readBoolean();
-
-        OdbcRequestHandler handler =
-            new OdbcRequestHandler(ctx, busyLock, maxCursors, distributedJoins, enforceJoinOrder);
-
-        OdbcMessageParser parser = new OdbcMessageParser(ctx);
-
-        return new SqlListenerConnectionContext(handler, parser);
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcProcessor.java
deleted file mode 100644
index 6b8b5a3..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/OdbcProcessor.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * 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.odbc;
-
-import java.net.InetAddress;
-import java.nio.ByteOrder;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.LinkedBlockingQueue;
-import org.apache.ignite.IgniteCheckedException;
-import org.apache.ignite.configuration.IgniteConfiguration;
-import org.apache.ignite.configuration.OdbcConfiguration;
-import org.apache.ignite.internal.GridKernalContext;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.internal.processors.GridProcessorAdapter;
-import org.apache.ignite.internal.util.GridSpinBusyLock;
-import org.apache.ignite.internal.util.HostAndPortRange;
-import org.apache.ignite.internal.util.nio.GridNioAsyncNotifyFilter;
-import org.apache.ignite.internal.util.nio.GridNioCodecFilter;
-import org.apache.ignite.internal.util.nio.GridNioFilter;
-import org.apache.ignite.internal.util.nio.GridNioServer;
-import org.apache.ignite.internal.util.nio.GridNioSession;
-import org.apache.ignite.internal.util.typedef.F;
-import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.marshaller.Marshaller;
-import org.apache.ignite.spi.IgnitePortProtocol;
-import org.apache.ignite.thread.IgniteThreadPoolExecutor;
-
-/**
- * ODBC processor.
- */
-public class OdbcProcessor extends GridProcessorAdapter {
-    /** Default number of selectors. */
-    private static final int DFLT_SELECTOR_CNT = Math.min(4, Runtime.getRuntime().availableProcessors());
-
-    /** Default TCP_NODELAY flag. */
-    private static final boolean DFLT_TCP_NODELAY = true;
-
-    /** Default TCP direct buffer flag. */
-    private static final boolean DFLT_TCP_DIRECT_BUF = false;
-
-    /** Busy lock. */
-    private final GridSpinBusyLock busyLock = new GridSpinBusyLock();
-
-    /** ODBC TCP Server. */
-    private GridNioServer<byte[]> srv;
-
-    /** ODBC executor service. */
-    private ExecutorService odbcExecSvc;
-
-    /**
-     * @param ctx Kernal context.
-     */
-    public OdbcProcessor(GridKernalContext ctx) {
-        super(ctx);
-    }
-
-    /** {@inheritDoc} */
-    @Override public void start(boolean activeOnStart) throws IgniteCheckedException {
-        IgniteConfiguration cfg = ctx.config();
-
-        OdbcConfiguration odbcCfg = cfg.getOdbcConfiguration();
-
-        if (odbcCfg != null) {
-            try {
-                Marshaller marsh = cfg.getMarshaller();
-
-                if (marsh != null && !(marsh instanceof BinaryMarshaller))
-                    throw new IgniteCheckedException("ODBC can only be used with BinaryMarshaller (please set it " +
-                        "through IgniteConfiguration.setMarshaller())");
-
-                HostAndPortRange hostPort;
-
-                if (F.isEmpty(odbcCfg.getEndpointAddress())) {
-                    hostPort = new HostAndPortRange(OdbcConfiguration.DFLT_TCP_HOST,
-                        OdbcConfiguration.DFLT_TCP_PORT_FROM,
-                        OdbcConfiguration.DFLT_TCP_PORT_TO
-                    );
-                }
-                else {
-                    hostPort = HostAndPortRange.parse(odbcCfg.getEndpointAddress(),
-                        OdbcConfiguration.DFLT_TCP_PORT_FROM,
-                        OdbcConfiguration.DFLT_TCP_PORT_TO,
-                        "Failed to parse ODBC endpoint address"
-                    );
-                }
-
-                assertParameter(odbcCfg.getThreadPoolSize() > 0, "threadPoolSize > 0");
-
-                odbcExecSvc = new IgniteThreadPoolExecutor(
-                    "odbc",
-                    cfg.getIgniteInstanceName(),
-                    odbcCfg.getThreadPoolSize(),
-                    odbcCfg.getThreadPoolSize(),
-                    0,
-                    new LinkedBlockingQueue<Runnable>());
-
-                InetAddress host;
-
-                try {
-                    host = InetAddress.getByName(hostPort.host());
-                }
-                catch (Exception e) {
-                    throw new IgniteCheckedException("Failed to resolve ODBC host: " + hostPort.host(), e);
-                }
-
-                Exception lastErr = null;
-
-                for (int port = hostPort.portFrom(); port <= hostPort.portTo(); port++) {
-                    try {
-                        GridNioFilter[] filters = new GridNioFilter[] {
-                            new GridNioAsyncNotifyFilter(ctx.igniteInstanceName(), odbcExecSvc, log) {
-                                @Override public void onSessionOpened(GridNioSession ses) throws IgniteCheckedException {
-                                    proceedSessionOpened(ses);
-                                }
-                            },
-                            new GridNioCodecFilter(new SqlListenerBufferedParser(), log, false)
-                        };
-
-                        GridNioServer<byte[]> srv0 = GridNioServer.<byte[]>builder()
-                            .address(host)
-                            .port(port)
-                            .listener(new OdbcNioListener(ctx, busyLock, odbcCfg.getMaxOpenCursors()))
-                            .logger(log)
-                            .selectorCount(DFLT_SELECTOR_CNT)
-                            .igniteInstanceName(ctx.igniteInstanceName())
-                            .serverName("odbc")
-                            .tcpNoDelay(DFLT_TCP_NODELAY)
-                            .directBuffer(DFLT_TCP_DIRECT_BUF)
-                            .byteOrder(ByteOrder.nativeOrder())
-                            .socketSendBufferSize(odbcCfg.getSocketSendBufferSize())
-                            .socketReceiveBufferSize(odbcCfg.getSocketReceiveBufferSize())
-                            .filters(filters)
-                            .directMode(false)
-                            .build();
-
-                        srv0.start();
-
-                        srv = srv0;
-
-                        ctx.ports().registerPort(port, IgnitePortProtocol.TCP, getClass());
-
-                        log.info("ODBC processor has started on TCP port " + port);
-
-                        lastErr = null;
-
-                        break;
-                    }
-                    catch (Exception e) {
-                        lastErr = e;
-                    }
-                }
-
-                assert (srv != null && lastErr == null) || (srv == null && lastErr != null);
-
-                if (lastErr != null)
-                    throw new IgniteCheckedException("Failed to bind to any [host:port] from the range [" +
-                        "address=" + hostPort + ", lastErr=" + lastErr + ']');
-            }
-            catch (Exception e) {
-                throw new IgniteCheckedException("Failed to start ODBC processor.", e);
-            }
-        }
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onKernalStop(boolean cancel) {
-        if (srv != null) {
-            busyLock.block();
-
-            srv.stop();
-
-            ctx.ports().deregisterPorts(getClass());
-
-            if (odbcExecSvc != null) {
-                U.shutdownNow(getClass(), odbcExecSvc, log);
-
-                odbcExecSvc = null;
-            }
-
-            if (log.isDebugEnabled())
-                log.debug("ODBC processor stopped.");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractMessageParser.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractMessageParser.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractMessageParser.java
new file mode 100644
index 0000000..9d731ab
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractMessageParser.java
@@ -0,0 +1,265 @@
+/*
+ * 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.odbc;
+
+import java.util.Collection;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryWriterExImpl;
+
+/**
+ * ODBC message parser.
+ */
+public abstract class SqlListenerAbstractMessageParser implements SqlListenerMessageParser {
+    /** Initial output stream capacity. */
+    protected static final int INIT_CAP = 1024;
+
+    /** Kernal context. */
+    protected GridKernalContext ctx;
+
+    /** Logger. */
+    private final IgniteLogger log;
+
+    /** Object reader. */
+    private SqlListenerAbstractObjectReader objReader;
+
+    /** Object writer. */
+    private SqlListenerAbstractObjectWriter objWriter;
+
+    /**
+     * @param ctx Context.
+     * @param objReader Object reader.
+     * @param objWriter Object writer.
+     */
+    protected SqlListenerAbstractMessageParser(final GridKernalContext ctx, SqlListenerAbstractObjectReader objReader,
+        SqlListenerAbstractObjectWriter objWriter) {
+        this.ctx = ctx;
+
+        log = ctx.log(getClass());
+
+        this.objReader = objReader;
+        this.objWriter = objWriter;
+    }
+
+    /** {@inheritDoc} */
+    @Override public SqlListenerRequest decode(byte[] msg) {
+        assert msg != null;
+
+        BinaryReaderExImpl reader = createReader(msg);
+
+        byte cmd = reader.readByte();
+
+        SqlListenerRequest res;
+
+        switch (cmd) {
+            case SqlListenerRequest.QRY_EXEC: {
+                String cache = reader.readString();
+                String sql = reader.readString();
+                int argsNum = reader.readInt();
+
+                Object[] params = new Object[argsNum];
+
+                for (int i = 0; i < argsNum; ++i)
+                    params[i] = objReader.readObject(reader);
+
+                res = new SqlListenerQueryExecuteRequest(cache, sql, params);
+
+                break;
+            }
+
+            case SqlListenerRequest.QRY_FETCH: {
+                long queryId = reader.readLong();
+                int pageSize = reader.readInt();
+
+                res = new SqlListenerQueryFetchRequest(queryId, pageSize);
+
+                break;
+            }
+
+            case SqlListenerRequest.QRY_CLOSE: {
+                long queryId = reader.readLong();
+
+                res = new SqlListenerQueryCloseRequest(queryId);
+
+                break;
+            }
+
+            case SqlListenerRequest.META_COLS: {
+                String cache = reader.readString();
+                String table = reader.readString();
+                String column = reader.readString();
+
+                res = new OdbcQueryGetColumnsMetaRequest(cache, table, column);
+
+                break;
+            }
+
+            case SqlListenerRequest.META_TBLS: {
+                String catalog = reader.readString();
+                String schema = reader.readString();
+                String table = reader.readString();
+                String tableType = reader.readString();
+
+                res = new OdbcQueryGetTablesMetaRequest(catalog, schema, table, tableType);
+
+                break;
+            }
+
+            case SqlListenerRequest.META_PARAMS: {
+                String cacheName = reader.readString();
+                String sqlQuery = reader.readString();
+
+                res = new OdbcQueryGetParamsMetaRequest(cacheName, sqlQuery);
+
+                break;
+            }
+
+            default:
+                throw new IgniteException("Unknown ODBC command: [cmd=" + cmd + ']');
+        }
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] encode(SqlListenerResponse msg) {
+        assert msg != null;
+
+        // Creating new binary writer
+        BinaryWriterExImpl writer = createWriter(INIT_CAP);
+
+        // Writing status.
+        writer.writeByte((byte) msg.status());
+
+        if (msg.status() != SqlListenerResponse.STATUS_SUCCESS) {
+            writer.writeString(msg.error());
+
+            return writer.array();
+        }
+
+        Object res0 = msg.response();
+
+        if (res0 == null)
+            return writer.array();
+        else if (res0 instanceof SqlListenerQueryExecuteResult) {
+            SqlListenerQueryExecuteResult res = (SqlListenerQueryExecuteResult) res0;
+
+            if (log.isDebugEnabled())
+                log.debug("Resulting query ID: " + res.getQueryId());
+
+            writer.writeLong(res.getQueryId());
+
+            Collection<SqlListenerColumnMeta> metas = res.getColumnsMetadata();
+
+            assert metas != null;
+
+            writer.writeInt(metas.size());
+
+            for (SqlListenerColumnMeta meta : metas)
+                meta.write(writer);
+        }
+        else if (res0 instanceof SqlListenerQueryFetchResult) {
+            SqlListenerQueryFetchResult res = (SqlListenerQueryFetchResult) res0;
+
+            if (log.isDebugEnabled())
+                log.debug("Resulting query ID: " + res.queryId());
+
+            writer.writeLong(res.queryId());
+
+            Collection<?> items0 = res.items();
+
+            assert items0 != null;
+
+            writer.writeBoolean(res.last());
+
+            writer.writeInt(items0.size());
+
+            for (Object row0 : items0) {
+                if (row0 != null) {
+                    Collection<?> row = (Collection<?>)row0;
+
+                    writer.writeInt(row.size());
+
+                    for (Object obj : row)
+                        objWriter.writeObject(writer, obj);
+                }
+            }
+        }
+        else if (res0 instanceof SqlListenerQueryCloseResult) {
+            SqlListenerQueryCloseResult res = (SqlListenerQueryCloseResult) res0;
+
+            if (log.isDebugEnabled())
+                log.debug("Resulting query ID: " + res.getQueryId());
+
+            writer.writeLong(res.getQueryId());
+        }
+        else if (res0 instanceof OdbcQueryGetColumnsMetaResult) {
+            OdbcQueryGetColumnsMetaResult res = (OdbcQueryGetColumnsMetaResult) res0;
+
+            Collection<SqlListenerColumnMeta> columnsMeta = res.meta();
+
+            assert columnsMeta != null;
+
+            writer.writeInt(columnsMeta.size());
+
+            for (SqlListenerColumnMeta columnMeta : columnsMeta)
+                columnMeta.write(writer);
+        }
+        else if (res0 instanceof OdbcQueryGetTablesMetaResult) {
+            OdbcQueryGetTablesMetaResult res = (OdbcQueryGetTablesMetaResult) res0;
+
+            Collection<OdbcTableMeta> tablesMeta = res.meta();
+
+            assert tablesMeta != null;
+
+            writer.writeInt(tablesMeta.size());
+
+            for (OdbcTableMeta tableMeta : tablesMeta)
+                tableMeta.writeBinary(writer);
+        }
+        else if (res0 instanceof OdbcQueryGetParamsMetaResult) {
+            OdbcQueryGetParamsMetaResult res = (OdbcQueryGetParamsMetaResult) res0;
+
+            byte[] typeIds = res.typeIds();
+
+            objWriter.writeObject(writer, typeIds);
+        }
+        else
+            assert false : "Should not reach here.";
+
+        return writer.array();
+    }
+
+    /**
+     * Create reader.
+     *
+     * @param msg Input message.
+     * @return Reader.
+     */
+    protected abstract BinaryReaderExImpl createReader(byte[] msg);
+
+    /**
+     * Create writer.
+     *
+     * @param cap Initial capacity.
+     * @return Binary writer instance.
+     */
+    protected abstract BinaryWriterExImpl createWriter(int cap);
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectReader.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectReader.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectReader.java
new file mode 100644
index 0000000..18162e6
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/SqlListenerAbstractObjectReader.java
@@ -0,0 +1,137 @@
+/*
+ * 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.odbc;
+
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
+import org.apache.ignite.internal.binary.BinaryUtils;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Binary reader with marshaling non-primitive and non-embedded objects with JDK marshaller.
+ */
+@SuppressWarnings("unchecked")
+public abstract class SqlListenerAbstractObjectReader {
+    /**
+     * @param reader Reader.
+     * @return Read object.
+     * @throws BinaryObjectException On error.
+     */
+    @Nullable public Object readObject(BinaryReaderExImpl reader) throws BinaryObjectException {
+        byte type = reader.readByte();
+
+        switch (type) {
+            case GridBinaryMarshaller.NULL:
+                return null;
+
+            case GridBinaryMarshaller.BOOLEAN:
+                return reader.readBoolean();
+
+            case GridBinaryMarshaller.BYTE:
+                return reader.readByte();
+
+            case GridBinaryMarshaller.CHAR:
+                return reader.readChar();
+
+            case GridBinaryMarshaller.SHORT:
+                return reader.readShort();
+
+            case GridBinaryMarshaller.INT:
+                return reader.readInt();
+
+            case GridBinaryMarshaller.LONG:
+                return reader.readLong();
+
+            case GridBinaryMarshaller.FLOAT:
+                return reader.readFloat();
+
+            case GridBinaryMarshaller.DOUBLE:
+                return reader.readDouble();
+
+            case GridBinaryMarshaller.STRING:
+                return BinaryUtils.doReadString(reader.in());
+
+            case GridBinaryMarshaller.DECIMAL:
+                return BinaryUtils.doReadDecimal(reader.in());
+
+            case GridBinaryMarshaller.UUID:
+                return BinaryUtils.doReadUuid(reader.in());
+
+            case GridBinaryMarshaller.TIME:
+                return BinaryUtils.doReadTime(reader.in());
+
+            case GridBinaryMarshaller.TIMESTAMP:
+                return BinaryUtils.doReadTimestamp(reader.in());
+
+            case GridBinaryMarshaller.DATE:
+                return BinaryUtils.doReadDate(reader.in());
+
+            case GridBinaryMarshaller.BOOLEAN_ARR:
+                return BinaryUtils.doReadBooleanArray(reader.in());
+
+            case GridBinaryMarshaller.BYTE_ARR:
+                return BinaryUtils.doReadByteArray(reader.in());
+
+            case GridBinaryMarshaller.CHAR_ARR:
+                return BinaryUtils.doReadCharArray(reader.in());
+
+            case GridBinaryMarshaller.SHORT_ARR:
+                return BinaryUtils.doReadShortArray(reader.in());
+
+            case GridBinaryMarshaller.INT_ARR:
+                return BinaryUtils.doReadIntArray(reader.in());
+
+            case GridBinaryMarshaller.FLOAT_ARR:
+                return BinaryUtils.doReadFloatArray(reader.in());
+
+            case GridBinaryMarshaller.DOUBLE_ARR:
+                return BinaryUtils.doReadDoubleArray(reader.in());
+
+            case GridBinaryMarshaller.STRING_ARR:
+                return BinaryUtils.doReadStringArray(reader.in());
+
+            case GridBinaryMarshaller.DECIMAL_ARR:
+                return BinaryUtils.doReadDecimalArray(reader.in());
+
+            case GridBinaryMarshaller.UUID_ARR:
+                return BinaryUtils.doReadUuidArray(reader.in());
+
+            case GridBinaryMarshaller.TIME_ARR:
+                return BinaryUtils.doReadTimeArray(reader.in());
+
+            case GridBinaryMarshaller.TIMESTAMP_ARR:
+                return BinaryUtils.doReadTimestampArray(reader.in());
+
+            case GridBinaryMarshaller.DATE_ARR:
+                return BinaryUtils.doReadDateArray(reader.in());
+
+            default:
+                reader.in().position(reader.in().position() - 1);
+
+                return readCustomObject(reader);
+        }
+    }
+
+    /**
+     * @param reader Reader.
+     * @return An object is unmarshaled by marshaller.
+     * @throws BinaryObjectException On error.
+     */
+    protected abstract Object readCustomObject(BinaryReaderExImpl reader) throws BinaryObjectException;
+}


[11/31] ignite git commit: ignite-5212 Allow custom affinity function for data structures cache

Posted by sb...@apache.org.
ignite-5212 Allow custom affinity function for data structures cache


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/f353faf1
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/f353faf1
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/f353faf1

Branch: refs/heads/ignite-5075
Commit: f353faf1be5f26cf4ea069d13a9194bcf18840bb
Parents: 42018e6
Author: Vladislav Pyatkov <vl...@gmail.com>
Authored: Tue May 23 15:33:39 2017 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue May 23 15:33:39 2017 +0300

----------------------------------------------------------------------
 .../configuration/AtomicConfiguration.java      |  25 +++
 .../org/apache/ignite/internal/IgnitionEx.java  |   1 +
 .../AtomicCacheAffinityConfigurationTest.java   | 175 +++++++++++++++++++
 .../IgniteCacheDataStructuresSelfTestSuite.java |   3 +
 4 files changed, 204 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/f353faf1/modules/core/src/main/java/org/apache/ignite/configuration/AtomicConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/AtomicConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/AtomicConfiguration.java
index 573e803..a9f1ea2 100644
--- a/modules/core/src/main/java/org/apache/ignite/configuration/AtomicConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/configuration/AtomicConfiguration.java
@@ -19,6 +19,7 @@ package org.apache.ignite.configuration;
 
 import org.apache.ignite.IgniteAtomicSequence;
 import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.cache.affinity.AffinityFunction;
 import org.apache.ignite.internal.util.typedef.internal.S;
 
 import static org.apache.ignite.cache.CacheMode.PARTITIONED;
@@ -45,6 +46,9 @@ public class AtomicConfiguration {
     /** Number of backups. */
     private int backups = DFLT_BACKUPS;
 
+    /** Affinity function */
+    private AffinityFunction aff;
+
     /**
      * @return Number of backup nodes.
      */
@@ -107,6 +111,27 @@ public class AtomicConfiguration {
         return this;
     }
 
+    /**
+     * Gets atomic cache affinity function.
+     *
+     * @return Affinity function or null, if not set.
+     */
+    public AffinityFunction getAffinity() {
+        return aff;
+    }
+
+    /**
+     * Sets atomic cache affinity function.
+     *
+     * @param aff Affinity function.
+     * @return {@code this} for chaining.
+     */
+    public AtomicConfiguration setAffinity(AffinityFunction aff) {
+        this.aff = aff;
+
+        return this;
+    }
+
     /** {@inheritDoc} */
     @Override public String toString() {
         return S.toString(AtomicConfiguration.class, this);

http://git-wip-us.apache.org/repos/asf/ignite/blob/f353faf1/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
index 4b34891..e19fe70 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
@@ -2421,6 +2421,7 @@ public class IgnitionEx {
             ccfg.setWriteSynchronizationMode(FULL_SYNC);
             ccfg.setCacheMode(cfg.getCacheMode());
             ccfg.setNodeFilter(CacheConfiguration.ALL_NODES);
+            ccfg.setAffinity(cfg.getAffinity());
             ccfg.setRebalanceOrder(-1); //Prior to user caches.
 
             if (cfg.getCacheMode() == PARTITIONED)

http://git-wip-us.apache.org/repos/asf/ignite/blob/f353faf1/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/AtomicCacheAffinityConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/AtomicCacheAffinityConfigurationTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/AtomicCacheAffinityConfigurationTest.java
new file mode 100644
index 0000000..7b7d9b5
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/AtomicCacheAffinityConfigurationTest.java
@@ -0,0 +1,175 @@
+/*
+ * 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.cache;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.cache.affinity.AffinityFunction;
+import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
+import org.apache.ignite.configuration.AtomicConfiguration;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ */
+public class AtomicCacheAffinityConfigurationTest extends GridCommonAbstractTest {
+    /** Affinity function. */
+    private AffinityFunction affinityFunction;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        return super.getConfiguration(igniteInstanceName)
+            .setAtomicConfiguration(new AtomicConfiguration()
+            .setCacheMode(CacheMode.PARTITIONED)
+            .setAffinity(affinityFunction));
+    }
+
+    /**
+     * @throws Exception If failed.
+     *
+     */
+    public void testRendezvousAffinity() throws Exception {
+        try {
+            affinityFunction = new RendezvousAffinityFunction(false, 10);
+
+            startGrids(3);
+
+            for (int i = 0; i < 3; i++) {
+                IgniteEx igniteEx = grid(i);
+
+                CacheConfiguration cConf = igniteEx.context().cache().cache("ignite-atomics-sys-cache").configuration();
+
+                AffinityFunction aff = cConf.getAffinity();
+
+                assertNotNull(aff);
+
+                assertEquals(aff.partitions(), affinityFunction.partitions());
+
+                assertEquals(aff.getClass(), affinityFunction.getClass());
+            }
+
+            checkAtomics();
+        }
+        finally {
+            stopAllGrids();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testTestAffinity() throws Exception {
+        try {
+            affinityFunction = new TestAffinityFunction("Some value");
+
+            startGrids(3);
+
+            for (int i = 0; i < 3; i++) {
+                IgniteEx igniteEx = grid(i);
+
+                CacheConfiguration cConf = igniteEx.context().cache().cache("ignite-atomics-sys-cache").configuration();
+
+                TestAffinityFunction aff = (TestAffinityFunction)cConf.getAffinity();
+
+                assertNotNull(aff);
+
+                assertEquals(aff.partitions(), affinityFunction.partitions());
+
+                assertEquals(aff.getCustomAttribute(), ((TestAffinityFunction)affinityFunction).getCustomAttribute());
+            }
+
+            checkAtomics();
+        }
+        finally {
+            stopAllGrids();
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testDefaultAffinity() throws Exception {
+        try {
+            affinityFunction = null;
+
+            startGrids(3);
+
+            for (int i = 0; i < 3; i++) {
+                IgniteEx igniteEx = grid(i);
+
+                CacheConfiguration cConf = igniteEx.context().cache().cache("ignite-atomics-sys-cache").configuration();
+
+                assertNotNull(cConf.getAffinity());
+            }
+
+            checkAtomics();
+        }
+        finally {
+            stopAllGrids();
+        }
+    }
+
+    /**
+     *
+     */
+    private void checkAtomics() {
+        Ignite node0 = grid(0);
+
+        node0.atomicLong("l1", 0, true).incrementAndGet();
+        node0.atomicSequence("s1", 10, true);
+
+        for (int i = 0; i < 3; i++) {
+            assertEquals(1, ignite(i).atomicLong("l1", 0, false).get());
+
+            assertNotNull(ignite(i).atomicSequence("s1", 0, false));
+
+            ignite(i).atomicSequence("s1", 0, false).getAndIncrement();
+        }
+    }
+
+    /**
+     * Test affinity function.
+     */
+    private static class TestAffinityFunction extends RendezvousAffinityFunction {
+        /** */
+        private String customAttr;
+
+        /**
+         * Default constructor.
+         */
+        public TestAffinityFunction() {
+            // No-op.
+        }
+
+        /**
+         * @param customAttr Custom attribute.
+         */
+        TestAffinityFunction(String customAttr) {
+            this.customAttr = customAttr;
+        }
+
+        /**
+         * @return Custom attribute.
+         */
+        String getCustomAttribute() {
+            return customAttr;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/f353faf1/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheDataStructuresSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheDataStructuresSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheDataStructuresSelfTestSuite.java
index 84e7953..568af94 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheDataStructuresSelfTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheDataStructuresSelfTestSuite.java
@@ -18,6 +18,7 @@
 package org.apache.ignite.testsuites;
 
 import junit.framework.TestSuite;
+import org.apache.ignite.internal.processors.cache.AtomicCacheAffinityConfigurationTest;
 import org.apache.ignite.internal.processors.cache.datastructures.GridCacheQueueCleanupSelfTest;
 import org.apache.ignite.internal.processors.cache.datastructures.GridCacheQueueMultiNodeConsistencySelfTest;
 import org.apache.ignite.internal.processors.cache.datastructures.IgniteClientDataStructuresTest;
@@ -168,6 +169,8 @@ public class IgniteCacheDataStructuresSelfTestSuite extends TestSuite {
 
         suite.addTest(new TestSuite(IgnitePartitionedQueueNoBackupsTest.class));
 
+        suite.addTestSuite(AtomicCacheAffinityConfigurationTest.class);
+
         return suite;
     }
 }


[24/31] ignite git commit: Minor - corrected TODO

Posted by sb...@apache.org.
Minor - corrected TODO


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/b131ff0a
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/b131ff0a
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/b131ff0a

Branch: refs/heads/ignite-5075
Commit: b131ff0a5470096522f960619513cfaa0d6f136b
Parents: a3908bd
Author: Alexey Goncharuk <al...@gmail.com>
Authored: Wed May 24 10:19:49 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Wed May 24 10:19:49 2017 +0300

----------------------------------------------------------------------
 .../apache/ignite/internal/processors/cache/GridCacheMapEntry.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/b131ff0a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index 6b7d6f5..15e4469 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -3448,7 +3448,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
                             // Version has changed since entry passed the filter. Do it again.
                             continue;
 
-                        // TODO GG-11241: need keep removed entries in heap map, otherwise removes can be lost.
+                        // TODO IGNITE-5286: need keep removed entries in heap map, otherwise removes can be lost.
                         if (cctx.deferredDelete() && deletedUnlocked())
                             return false;
 


[26/31] ignite git commit: IGNITE-5121: REST API call with empty cache name to call "default." - Fixes #1920.

Posted by sb...@apache.org.
IGNITE-5121: REST API call with empty cache name to call "default." - Fixes #1920.

Signed-off-by: shroman <rs...@yahoo.com>


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/d8eeea84
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/d8eeea84
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/d8eeea84

Branch: refs/heads/ignite-5075
Commit: d8eeea84bef33d33470052fbb86c96d75490c9b8
Parents: 8c9b1bd
Author: shroman <rs...@yahoo.com>
Authored: Wed May 24 17:19:26 2017 +0900
Committer: shroman <rs...@yahoo.com>
Committed: Wed May 24 17:19:26 2017 +0900

----------------------------------------------------------------------
 .../rest/handlers/GridRestCommandHandlerAdapter.java   |  3 +++
 .../rest/handlers/cache/GridCacheCommandHandler.java   |  2 +-
 .../rest/handlers/query/QueryCommandHandler.java       | 13 +++++++------
 3 files changed, 11 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/d8eeea84/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/GridRestCommandHandlerAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/GridRestCommandHandlerAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/GridRestCommandHandlerAdapter.java
index 31c26b3..def11dd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/GridRestCommandHandlerAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/GridRestCommandHandlerAdapter.java
@@ -24,6 +24,9 @@ import org.apache.ignite.internal.GridKernalContext;
  * Abstract command handler.
  */
 public abstract class GridRestCommandHandlerAdapter implements GridRestCommandHandler {
+    /** Used cache name in case the name was not defined in a request. */
+    protected static final String DFLT_CACHE_NAME = "default";
+
     /** Kernal context. */
     protected final GridKernalContext ctx;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/d8eeea84/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cache/GridCacheCommandHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cache/GridCacheCommandHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cache/GridCacheCommandHandler.java
index 18cd6af..9edf37e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cache/GridCacheCommandHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cache/GridCacheCommandHandler.java
@@ -360,7 +360,7 @@ public class GridCacheCommandHandler extends GridRestCommandHandlerAdapter {
 
         GridRestCacheRequest req0 = (GridRestCacheRequest)req;
 
-        final String cacheName = req0.cacheName();
+        final String cacheName = req0.cacheName() == null ? DFLT_CACHE_NAME: req0.cacheName();
 
         final Object key = req0.key();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/d8eeea84/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java
index ee728a6..e7cc3dd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java
@@ -219,11 +219,11 @@ public class QueryCommandHandler extends GridRestCommandHandlerAdapter {
         assert req instanceof RestQueryRequest : "Invalid type of query request.";
 
         if (req.command() != CLOSE_SQL_QUERY) {
-            Integer pageSize = ((RestQueryRequest) req).pageSize();
+            Integer pageSize = ((RestQueryRequest)req).pageSize();
 
             if (pageSize == null)
                 return new GridFinishedFuture<>(
-                        new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("pageSize"))
+                    new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("pageSize"))
                 );
         }
 
@@ -232,17 +232,17 @@ public class QueryCommandHandler extends GridRestCommandHandlerAdapter {
             case EXECUTE_SQL_FIELDS_QUERY:
             case EXECUTE_SCAN_QUERY: {
                 return ctx.closure().callLocalSafe(
-                        new ExecuteQueryCallable(ctx, (RestQueryRequest) req, qryCurs), false);
+                    new ExecuteQueryCallable(ctx, (RestQueryRequest)req, qryCurs), false);
             }
 
             case FETCH_SQL_QUERY: {
                 return ctx.closure().callLocalSafe(
-                        new FetchQueryCallable((RestQueryRequest) req, qryCurs), false);
+                    new FetchQueryCallable((RestQueryRequest)req, qryCurs), false);
             }
 
             case CLOSE_SQL_QUERY: {
                 return ctx.closure().callLocalSafe(
-                        new CloseQueryCallable((RestQueryRequest) req, qryCurs), false);
+                    new CloseQueryCallable((RestQueryRequest)req, qryCurs), false);
             }
         }
 
@@ -315,7 +315,8 @@ public class QueryCommandHandler extends GridRestCommandHandlerAdapter {
                         throw new IgniteException("Incorrect query type [type=" + req.queryType() + "]");
                 }
 
-                IgniteCache<Object, Object> cache = ctx.grid().cache(req.cacheName());
+                IgniteCache<Object, Object> cache = ctx.grid().cache(
+                    req.cacheName() == null ? DFLT_CACHE_NAME : req.cacheName());
 
                 if (cache == null)
                     return new GridRestResponse(GridRestResponse.STATUS_FAILED,


[16/31] ignite git commit: Results printout for IO latency test and new metrics

Posted by sb...@apache.org.
Results printout for IO latency test and new metrics

(cherry picked)


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/018b25b2
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/018b25b2
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/018b25b2

Branch: refs/heads/ignite-5075
Commit: 018b25b29c3c491db7e44963e8c79677d77ceb23
Parents: 6f1dc3a
Author: Yakov Zhdanov <yz...@gridgain.com>
Authored: Tue May 23 17:39:37 2017 +0300
Committer: Yakov Zhdanov <yz...@gridgain.com>
Committed: Tue May 23 17:44:33 2017 +0300

----------------------------------------------------------------------
 .../managers/communication/GridIoManager.java   | 380 +++++++++++++++----
 .../communication/IgniteIoTestMessage.java      | 362 +++++++++++++++++-
 2 files changed, 672 insertions(+), 70 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/018b25b2/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
index 147f94d..68bfd07 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
@@ -18,9 +18,11 @@
 package org.apache.ignite.internal.managers.communication;
 
 import java.io.Serializable;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -64,12 +66,12 @@ import org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener;
 import org.apache.ignite.internal.processors.platform.message.PlatformMessageFilter;
 import org.apache.ignite.internal.processors.pool.PoolProcessor;
 import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
-import org.apache.ignite.internal.util.GridAtomicLong;
 import org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashSet;
 import org.apache.ignite.internal.util.StripedCompositeReadWriteLock;
 import org.apache.ignite.internal.util.future.GridFinishedFuture;
 import org.apache.ignite.internal.util.future.GridFutureAdapter;
 import org.apache.ignite.internal.util.lang.GridTuple3;
+import org.apache.ignite.internal.util.lang.IgnitePair;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.X;
@@ -341,10 +343,15 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
 
                 IgniteIoTestMessage msg0 = (IgniteIoTestMessage)msg;
 
+                msg0.senderNodeId(nodeId);
+
                 if (msg0.request()) {
                     IgniteIoTestMessage res = new IgniteIoTestMessage(msg0.id(), false, null);
 
                     res.flags(msg0.flags());
+                    res.onRequestProcessed();
+
+                    res.copyDataFromRequest(msg0);
 
                     try {
                         sendToGridTopic(node, GridTopic.TOPIC_IO_TEST, res, GridIoPolicy.SYSTEM_POOL);
@@ -356,10 +363,12 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                 else {
                     IoTestFuture fut = ioTestMap().get(msg0.id());
 
+                    msg0.onResponseProcessed();
+
                     if (fut == null)
                         U.warn(log, "Failed to find IO test future [msg=" + msg0 + ']');
                     else
-                        fut.onResponse();
+                        fut.onResponse(msg0);
                 }
             }
         });
@@ -404,7 +413,11 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
      * @param procFromNioThread If {@code true} message is processed from NIO thread.
      * @return Response future.
      */
-    public IgniteInternalFuture sendIoTest(ClusterNode node, byte[] payload, boolean procFromNioThread) {
+    public IgniteInternalFuture<List<IgniteIoTestMessage>> sendIoTest(
+        ClusterNode node,
+        byte[] payload,
+        boolean procFromNioThread
+    ) {
         long id = ioTestId.getAndIncrement();
 
         IoTestFuture fut = new IoTestFuture(id, 1);
@@ -445,7 +458,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
      * @param warmup Warmup duration in milliseconds.
      * @param duration Test duration in milliseconds.
      * @param threads Thread count.
-     * @param maxLatency Max latency in nanoseconds.
+     * @param latencyLimit Max latency in nanoseconds.
      * @param rangesCnt Ranges count in resulting histogram.
      * @param payLoadSize Payload size in bytes.
      * @param procFromNioThread {@code True} to process requests in NIO threads.
@@ -455,7 +468,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
         final long warmup,
         final long duration,
         final int threads,
-        final long maxLatency,
+        final long latencyLimit,
         final int rangesCnt,
         final int payLoadSize,
         final boolean procFromNioThread,
@@ -469,8 +482,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
         final LongAdder8 cnt = new LongAdder8();
         final long sleepDuration = 5000;
         final byte[] payLoad = new byte[payLoadSize];
-        final Map<UUID, long[]>[] res = new Map[threads];
-        final ConcurrentMap<UUID, GridAtomicLong> maxLatencies = new ConcurrentHashMap8<>();
+        final Map<UUID, IoTestThreadLocalNodeResults>[] res = new Map[threads];
 
         boolean failed = true;
 
@@ -489,7 +501,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                                 "[warmup=" + warmup +
                                 ", duration=" + duration +
                                 ", threads=" + threads +
-                                ", maxLatency=" + maxLatency +
+                                ", latencyLimit=" + latencyLimit +
                                 ", rangesCnt=" + rangesCnt +
                                 ", payLoadSize=" + payLoadSize +
                                 ", procFromNioThreads=" + procFromNioThread + ']'
@@ -529,22 +541,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                         // At this point all threads have finished the test and
                         // stored data to the resulting array of maps.
                         // Need to iterate it over and sum values for all threads.
-                        Map<UUID, long[]> res0 = new HashMap<>();
-
-                        for (Map<UUID, long[]> r : res) {
-                            for (Entry<UUID, long[]> e : r.entrySet()) {
-                                long[] r0 = res0.get(e.getKey());
-
-                                if (r0 == null)
-                                    res0.put(e.getKey(), e.getValue());
-                                else {
-                                    for (int i = 0; i < rangesCnt + 1; i++)
-                                        r0[i] += e.getValue()[i];
-                                }
-                            }
-                        }
-
-                        printIoTestResults(maxLatency / (1000 * rangesCnt), res0, maxLatencies);
+                        printIoTestResults(res);
                     }
                     catch (InterruptedException | BrokenBarrierException e) {
                         U.error(log, "IO test failed.", e);
@@ -566,7 +563,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                         boolean failed = true;
                         ThreadLocalRandom rnd = ThreadLocalRandom.current();
                         int size = nodes.size();
-                        Map<UUID, long[]> res0 = res[i0];
+                        Map<UUID, IoTestThreadLocalNodeResults> res0 = res[i0];
 
                         try {
                             boolean warmupFinished0 = false;
@@ -582,38 +579,22 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
 
                                 ClusterNode node = nodes.get(rnd.nextInt(size));
 
-                                long start = System.nanoTime();
-
-                                sendIoTest(node, payLoad, procFromNioThread).get();
-
-                                long latency = System.nanoTime() - start;
+                                List<IgniteIoTestMessage> msgs = sendIoTest(node, payLoad, procFromNioThread).get();
 
                                 cnt.increment();
 
-                                long[] latencies = res0.get(node.id());
-
-                                if (latencies == null)
-                                    res0.put(node.id(), latencies = new long[rangesCnt + 1]);
-
-                                if (latency >= maxLatency) {
-                                    latencies[rangesCnt]++; // Timed out.
+                                for (IgniteIoTestMessage msg : msgs) {
+                                    UUID nodeId = msg.senderNodeId();
 
-                                    GridAtomicLong maxLatency = maxLatencies.get(node.id());
+                                    assert nodeId != null;
 
-                                    if (maxLatency == null) {
-                                        GridAtomicLong old = maxLatencies.putIfAbsent(node.id(),
-                                            maxLatency = new GridAtomicLong());
+                                    IoTestThreadLocalNodeResults nodeRes = res0.get(nodeId);
 
-                                        if (old != null)
-                                            maxLatency = old;
-                                    }
+                                    if (nodeRes == null)
+                                        res0.put(nodeId,
+                                            nodeRes = new IoTestThreadLocalNodeResults(rangesCnt, latencyLimit));
 
-                                    maxLatency.setIfGreater(latency);
-                                }
-                                else {
-                                    int idx = (int)Math.floor((1.0 * latency) / ((1.0 * maxLatency) / rangesCnt));
-
-                                    latencies[idx]++;
+                                    nodeRes.onResult(msg);
                                 }
                             }
 
@@ -641,30 +622,44 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
     }
 
     /**
-     * @param binLatencyMcs Bin latency in microseconds.
-     * @param res Resulting map.
-     * @param maxLatencies Max latency for each node.
+     * @param rawRes Resulting map.
      */
     private void printIoTestResults(
-        long binLatencyMcs,
-        Map<UUID, long[]> res,
-        ConcurrentMap<UUID, GridAtomicLong> maxLatencies
+        Map<UUID, IoTestThreadLocalNodeResults>[] rawRes
     ) {
+        Map<UUID, IoTestNodeResults> res = new HashMap<>();
+
+        for (Map<UUID, IoTestThreadLocalNodeResults> r : rawRes) {
+            for (Entry<UUID, IoTestThreadLocalNodeResults> e : r.entrySet()) {
+                IoTestNodeResults r0 = res.get(e.getKey());
+
+                if (r0 == null)
+                    res.put(e.getKey(), r0 = new IoTestNodeResults());
+
+                r0.add(e.getValue());
+            }
+        }
+
+        SimpleDateFormat dateFmt = new SimpleDateFormat("HH:mm:ss,SSS");
+
         StringBuilder b = new StringBuilder(U.nl())
-            .append("IO test results (round-trip count per each latency bin) " +
-                "[binLatency=" + binLatencyMcs + "mcs]")
+            .append("IO test results (round-trip count per each latency bin).")
             .append(U.nl());
 
-        for (Entry<UUID, long[]> e : res.entrySet()) {
+        for (Entry<UUID, IoTestNodeResults> e : res.entrySet()) {
             ClusterNode node = ctx.discovery().node(e.getKey());
 
+            long binLatencyMcs = e.getValue().binLatencyMcs();
+
             b.append("Node ID: ").append(e.getKey()).append(" (addrs=")
-                .append(node != null ? node.addresses().toString() : "n/a").append(')').append(U.nl());
+                .append(node != null ? node.addresses().toString() : "n/a")
+                .append(", binLatency=").append(binLatencyMcs).append("mcs")
+                .append(')').append(U.nl());
 
             b.append("Latency bin, mcs | Count exclusive | Percentage exclusive | " +
                 "Count inclusive | Percentage inclusive ").append(U.nl());
 
-            long[] nodeRes = e.getValue();
+            long[] nodeRes = e.getValue().resLatency;
 
             long sum = 0;
 
@@ -688,15 +683,49 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                         curSum, (100.0 * curSum) / sum));
             }
 
-            GridAtomicLong maxLatency = maxLatencies.get(e.getKey());
+            b.append(U.nl()).append("Total latency (ns): ").append(U.nl())
+                .append(String.format("%15d", e.getValue().totalLatency)).append(U.nl());
+
+            b.append(U.nl()).append("Max latencies (ns):").append(U.nl());
+            format(b, e.getValue().maxLatency, dateFmt);
+
+            b.append(U.nl()).append("Max request send queue times (ns):").append(U.nl());
+            format(b, e.getValue().maxReqSendQueueTime, dateFmt);
+
+            b.append(U.nl()).append("Max request receive queue times (ns):").append(U.nl());
+            format(b, e.getValue().maxReqRcvQueueTime, dateFmt);
+
+            b.append(U.nl()).append("Max response send queue times (ns):").append(U.nl());
+            format(b, e.getValue().maxResSendQueueTime, dateFmt);
+
+            b.append(U.nl()).append("Max response receive queue times (ns):").append(U.nl());
+            format(b, e.getValue().maxResRcvQueueTime, dateFmt);
 
-            b.append("Max latency (ns): ").append(maxLatency != null ? maxLatency.get() : -1).append(U.nl());
+            b.append(U.nl()).append("Max request wire times (millis):").append(U.nl());
+            format(b, e.getValue().maxReqWireTimeMillis, dateFmt);
+
+            b.append(U.nl()).append("Max response wire times (millis):").append(U.nl());
+            format(b, e.getValue().maxResWireTimeMillis, dateFmt);
+
+            b.append(U.nl());
         }
 
         if (log.isInfoEnabled())
             log.info(b.toString());
     }
 
+    /**
+     * @param b Builder.
+     * @param pairs Pairs to format.
+     * @param dateFmt Formatter.
+     */
+    private void format(StringBuilder b, Collection<IgnitePair<Long>> pairs, SimpleDateFormat dateFmt) {
+        for (IgnitePair<Long> p : pairs) {
+            b.append(String.format("%15d", p.get1())).append(" ")
+                .append(dateFmt.format(new Date(p.get2()))).append(U.nl());
+        }
+    }
+
     /** {@inheritDoc} */
     @SuppressWarnings({"deprecation", "SynchronizationOnLocalVariableOrMethodParameter"})
     @Override public void onKernalStart0() throws IgniteCheckedException {
@@ -2857,12 +2886,15 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
     /**
      *
      */
-    private class IoTestFuture extends GridFutureAdapter<Object> {
+    private class IoTestFuture extends GridFutureAdapter<List<IgniteIoTestMessage>> {
         /** */
         private final long id;
 
         /** */
-        private int cntr;
+        private final int cntr;
+
+        /** */
+        private final List<IgniteIoTestMessage> ress;
 
         /**
          * @param id ID.
@@ -2873,24 +2905,28 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
 
             this.id = id;
             this.cntr = cntr;
+
+            ress = new ArrayList<>(cntr);
         }
 
         /**
          *
          */
-        void onResponse() {
+        void onResponse(IgniteIoTestMessage res) {
             boolean complete;
 
             synchronized (this) {
-                complete = --cntr == 0;
+                ress.add(res);
+
+                complete = cntr == ress.size();
             }
 
             if (complete)
-                onDone();
+                onDone(ress);
         }
 
         /** {@inheritDoc} */
-        @Override public boolean onDone(@Nullable Object res, @Nullable Throwable err) {
+        @Override public boolean onDone(List<IgniteIoTestMessage> res, @Nullable Throwable err) {
             if (super.onDone(res, err)) {
                 ioTestMap().remove(id);
 
@@ -2905,4 +2941,210 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
             return S.toString(IoTestFuture.class, this);
         }
     }
+
+    /**
+     *
+     */
+    private static class IoTestThreadLocalNodeResults {
+        /** */
+        private final long[] resLatency;
+
+        /** */
+        private final int rangesCnt;
+
+        /** */
+        private long totalLatency;
+
+        /** */
+        private long maxLatency;
+
+        /** */
+        private long maxLatencyTs;
+
+        /** */
+        private long maxReqSendQueueTime;
+
+        /** */
+        private long maxReqSendQueueTimeTs;
+
+        /** */
+        private long maxReqRcvQueueTime;
+
+        /** */
+        private long maxReqRcvQueueTimeTs;
+
+        /** */
+        private long maxResSendQueueTime;
+
+        /** */
+        private long maxResSendQueueTimeTs;
+
+        /** */
+        private long maxResRcvQueueTime;
+
+        /** */
+        private long maxResRcvQueueTimeTs;
+
+        /** */
+        private long maxReqWireTimeMillis;
+
+        /** */
+        private long maxReqWireTimeTs;
+
+        /** */
+        private long maxResWireTimeMillis;
+
+        /** */
+        private long maxResWireTimeTs;
+
+        /** */
+        private final long latencyLimit;
+
+        /**
+         * @param rangesCnt Ranges count.
+         * @param latencyLimit
+         */
+        public IoTestThreadLocalNodeResults(int rangesCnt, long latencyLimit) {
+            this.rangesCnt = rangesCnt;
+            this.latencyLimit = latencyLimit;
+
+            resLatency = new long[rangesCnt + 1];
+        }
+
+        /**
+         * @param msg
+         */
+        public void onResult(IgniteIoTestMessage msg) {
+            long now = System.currentTimeMillis();
+
+            long latency = msg.responseProcessedTs() - msg.requestCreateTs();
+
+            int idx = latency >= latencyLimit ?
+                rangesCnt /* Timed out. */ :
+                (int)Math.floor((1.0 * latency) / ((1.0 * latencyLimit) / rangesCnt));
+
+            resLatency[idx]++;
+
+            totalLatency += latency;
+
+            if (maxLatency < latency) {
+                maxLatency = latency;
+                maxLatencyTs = now;
+            }
+
+            long reqSndQueueTime = msg.requestSendTs() - msg.requestCreateTs();
+
+            if (maxReqSendQueueTime < reqSndQueueTime) {
+                maxReqSendQueueTime = reqSndQueueTime;
+                maxReqSendQueueTimeTs = now;
+            }
+
+            long reqRcvQueueTime = msg.requestProcessTs() - msg.requestReceiveTs();
+
+            if (maxReqRcvQueueTime < reqRcvQueueTime) {
+                maxReqRcvQueueTime = reqRcvQueueTime;
+                maxReqRcvQueueTimeTs = now;
+            }
+
+            long resSndQueueTime = msg.responseSendTs() - msg.requestProcessTs();
+
+            if (maxResSendQueueTime < resSndQueueTime) {
+                maxResSendQueueTime = resSndQueueTime;
+                maxResSendQueueTimeTs = now;
+            }
+
+            long resRcvQueueTime = msg.responseProcessedTs() - msg.responseReceiveTs();
+
+            if (maxResRcvQueueTime < resRcvQueueTime) {
+                maxResRcvQueueTime = resRcvQueueTime;
+                maxResRcvQueueTimeTs = now;
+            }
+
+            long reqWireTimeMillis = msg.requestReceivedTsMillis() - msg.requestSendTsMillis();
+
+            if (maxReqWireTimeMillis < reqWireTimeMillis) {
+                maxReqWireTimeMillis = reqWireTimeMillis;
+                maxReqWireTimeTs = now;
+            }
+
+            long resWireTimeMillis = msg.responseRecievedTsMillis() - msg.requestSendTsMillis();
+
+            if (maxResWireTimeMillis < resWireTimeMillis) {
+                maxResWireTimeMillis = resWireTimeMillis;
+                maxResWireTimeTs = now;
+            }
+        }
+    }
+
+    /**
+     *
+     */
+    private static class IoTestNodeResults {
+        /** */
+        private long latencyLimit;
+
+        /** */
+        private long[] resLatency;
+
+        /** */
+        private long totalLatency;
+
+        /** */
+        private Collection<IgnitePair<Long>> maxLatency = new ArrayList<>();
+
+        /** */
+        private Collection<IgnitePair<Long>> maxReqSendQueueTime = new ArrayList<>();
+
+        /** */
+        private Collection<IgnitePair<Long>> maxReqRcvQueueTime = new ArrayList<>();
+
+        /** */
+        private Collection<IgnitePair<Long>> maxResSendQueueTime = new ArrayList<>();
+
+        /** */
+        private Collection<IgnitePair<Long>> maxResRcvQueueTime = new ArrayList<>();
+
+        /** */
+        private Collection<IgnitePair<Long>> maxReqWireTimeMillis = new ArrayList<>();
+
+        /** */
+        private Collection<IgnitePair<Long>> maxResWireTimeMillis = new ArrayList<>();
+
+        /**
+         * @param res Node results to add.
+         */
+        public void add(IoTestThreadLocalNodeResults res) {
+            if (resLatency == null) {
+                resLatency = res.resLatency.clone();
+                latencyLimit = res.latencyLimit;
+            }
+            else {
+                assert latencyLimit == res.latencyLimit;
+                assert resLatency.length == res.resLatency.length;
+
+                for (int i = 0; i < resLatency.length; i++)
+                    resLatency[i] += res.resLatency[i];
+            }
+
+            totalLatency += res.totalLatency;
+
+            maxLatency.add(F.pair(res.maxLatency, res.maxLatencyTs));
+            maxReqSendQueueTime.add(F.pair(res.maxReqSendQueueTime, res.maxReqSendQueueTimeTs));
+            maxReqRcvQueueTime.add(F.pair(res.maxReqRcvQueueTime, res.maxReqRcvQueueTimeTs));
+            maxResSendQueueTime.add(F.pair(res.maxResSendQueueTime, res.maxResSendQueueTimeTs));
+            maxResRcvQueueTime.add(F.pair(res.maxResRcvQueueTime, res.maxResRcvQueueTimeTs));
+            maxReqWireTimeMillis.add(F.pair(res.maxReqWireTimeMillis, res.maxReqWireTimeTs));
+            maxResWireTimeMillis.add(F.pair(res.maxResWireTimeMillis, res.maxResWireTimeTs));
+        }
+
+        /**
+         * @return Bin latency in microseconds.
+         */
+        public long binLatencyMcs() {
+            if (resLatency == null)
+                throw new IllegalStateException();
+
+            return latencyLimit / (1000 * (resLatency.length - 1));
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/018b25b2/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
index 0a41622..3e0fa76 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/IgniteIoTestMessage.java
@@ -18,6 +18,8 @@
 package org.apache.ignite.internal.managers.communication;
 
 import java.nio.ByteBuffer;
+import java.util.UUID;
+import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -45,6 +47,43 @@ public class IgniteIoTestMessage implements Message {
     /** */
     private byte payload[];
 
+    /** */
+    private long reqCreateTs;
+
+    /** */
+    private long reqSndTs;
+
+    /** */
+    private long reqSndTsMillis;
+
+    /** */
+    private long reqRcvTs;
+
+    /** */
+    private long reqRcvTsMillis;
+
+    /** */
+    private long reqProcTs;
+
+    /** */
+    private long resSndTs;
+
+    /** */
+    private long resSndTsMillis;
+
+    /** */
+    private long resRcvTs;
+
+    /** */
+    private long resRcvTsMillis;
+
+    /** */
+    private long resProcTs;
+
+    /** */
+    @GridDirectTransient
+    private UUID sndNodeId;
+
     /**
      *
      */
@@ -61,6 +100,8 @@ public class IgniteIoTestMessage implements Message {
         this.id = id;
         this.req = req;
         this.payload = payload;
+
+        reqCreateTs = System.nanoTime();
     }
 
     /**
@@ -126,10 +167,173 @@ public class IgniteIoTestMessage implements Message {
         return id;
     }
 
+    /**
+     * @return Request create timestamp.
+     */
+    public long requestCreateTs() {
+        return reqCreateTs;
+    }
+
+    /**
+     * @return Request send timestamp.
+     */
+    public long requestSendTs() {
+        return reqSndTs;
+    }
+
+    /**
+     * @return Request receive timestamp.
+     */
+    public long requestReceiveTs() {
+        return reqRcvTs;
+    }
+
+    /**
+     * @return Request process started timestamp.
+     */
+    public long requestProcessTs() {
+        return reqProcTs;
+    }
+
+    /**
+     * @return Response send timestamp.
+     */
+    public long responseSendTs() {
+        return resSndTs;
+    }
+
+    /**
+     * @return Response receive timestamp.
+     */
+    public long responseReceiveTs() {
+        return resRcvTs;
+    }
+
+    /**
+     * @return Response process timestamp.
+     */
+    public long responseProcessTs() {
+        return resProcTs;
+    }
+
+    /**
+     * @return Request send timestamp (millis).
+     */
+    public long requestSendTsMillis() {
+        return reqSndTsMillis;
+    }
+
+    /**
+     * @return Request received timestamp (millis).
+     */
+    public long requestReceivedTsMillis() {
+        return reqRcvTsMillis;
+    }
+
+    /**
+     * @return Response send timestamp (millis).
+     */
+    public long responseSendTsMillis() {
+        return resSndTsMillis;
+    }
+
+    /**
+     * @return Response received timestamp (millis).
+     */
+    public long responseRecievedTsMillis() {
+        return resRcvTsMillis;
+    }
+
+    /**
+     * This method is called to initialize tracing variables.
+     * TODO: introduce direct message lifecycle API?
+     */
+    public void onAfterRead() {
+        if (req && reqRcvTs == 0) {
+            reqRcvTs = System.nanoTime();
+
+            reqRcvTsMillis = System.currentTimeMillis();
+        }
+
+        if (!req && resRcvTs == 0) {
+            resRcvTs = System.nanoTime();
+
+            resRcvTsMillis = System.currentTimeMillis();
+        }
+    }
+
+    /**
+     * This method is called to initialize tracing variables.
+     * TODO: introduce direct message lifecycle API?
+     */
+    public void onBeforeWrite() {
+        if (req && reqSndTs == 0) {
+            reqSndTs = System.nanoTime();
+
+            reqSndTsMillis = System.currentTimeMillis();
+        }
+
+        if (!req && resSndTs == 0) {
+            resSndTs = System.nanoTime();
+
+            resSndTsMillis = System.currentTimeMillis();
+        }
+    }
+
+    /**
+     *
+     */
+    public void copyDataFromRequest(IgniteIoTestMessage req) {
+        reqCreateTs = req.reqCreateTs;
+
+        reqSndTs = req.reqSndTs;
+        reqSndTsMillis = req.reqSndTsMillis;
+
+        reqRcvTs = req.reqRcvTs;
+        reqRcvTsMillis = req.reqRcvTsMillis;
+    }
+
+    /**
+     *
+     */
+    public void onRequestProcessed() {
+        reqProcTs = System.nanoTime();
+    }
+
+    /**
+     *
+     */
+    public void onResponseProcessed() {
+        resProcTs = System.nanoTime();
+    }
+
+    /**
+     * @return Response processed timestamp.
+     */
+    public long responseProcessedTs() {
+        return resProcTs;
+    }
+
+    /**
+     * @return Sender node ID.
+     */
+    public UUID senderNodeId() {
+        return sndNodeId;
+    }
+
+    /**
+     * @param sndNodeId Sender node ID.
+     */
+    public void senderNodeId(UUID sndNodeId) {
+        this.sndNodeId = sndNodeId;
+    }
+
     /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 
+        onBeforeWrite();
+
         if (!writer.isHeaderWritten()) {
             if (!writer.writeHeader(directType(), fieldsCount()))
                 return false;
@@ -162,6 +366,72 @@ public class IgniteIoTestMessage implements Message {
 
                 writer.incrementState();
 
+            case 4:
+                if (!writer.writeLong("reqCreateTs", reqCreateTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 5:
+                if (!writer.writeLong("reqProcTs", reqProcTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 6:
+                if (!writer.writeLong("reqRcvTs", reqRcvTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 7:
+                if (!writer.writeLong("reqRcvTsMillis", reqRcvTsMillis))
+                    return false;
+
+                writer.incrementState();
+
+            case 8:
+                if (!writer.writeLong("reqSndTs", reqSndTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 9:
+                if (!writer.writeLong("reqSndTsMillis", reqSndTsMillis))
+                    return false;
+
+                writer.incrementState();
+
+            case 10:
+                if (!writer.writeLong("resProcTs", resProcTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 11:
+                if (!writer.writeLong("resRcvTs", resRcvTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 12:
+                if (!writer.writeLong("resRcvTsMillis", resRcvTsMillis))
+                    return false;
+
+                writer.incrementState();
+
+            case 13:
+                if (!writer.writeLong("resSndTs", resSndTs))
+                    return false;
+
+                writer.incrementState();
+
+            case 14:
+                if (!writer.writeLong("resSndTsMillis", resSndTsMillis))
+                    return false;
+
+                writer.incrementState();
+
         }
 
         return true;
@@ -207,8 +477,98 @@ public class IgniteIoTestMessage implements Message {
 
                 reader.incrementState();
 
+            case 4:
+                reqCreateTs = reader.readLong("reqCreateTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 5:
+                reqProcTs = reader.readLong("reqProcTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 6:
+                reqRcvTs = reader.readLong("reqRcvTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 7:
+                reqRcvTsMillis = reader.readLong("reqRcvTsMillis");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 8:
+                reqSndTs = reader.readLong("reqSndTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 9:
+                reqSndTsMillis = reader.readLong("reqSndTsMillis");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 10:
+                resProcTs = reader.readLong("resProcTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 11:
+                resRcvTs = reader.readLong("resRcvTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 12:
+                resRcvTsMillis = reader.readLong("resRcvTsMillis");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 13:
+                resSndTs = reader.readLong("resSndTs");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
+            case 14:
+                resSndTsMillis = reader.readLong("resSndTsMillis");
+
+                if (!reader.isLastRead())
+                    return false;
+
+                reader.incrementState();
+
         }
 
+        onAfterRead();
+
         return reader.afterMessageRead(IgniteIoTestMessage.class);
     }
 
@@ -219,7 +579,7 @@ public class IgniteIoTestMessage implements Message {
 
     /** {@inheritDoc} */
     @Override public byte fieldsCount() {
-        return 4;
+        return 15;
     }
 
     /** {@inheritDoc} */


[28/31] ignite git commit: IGNITE-5284: Splitted IgniteH2Indexing into several classes. This closes #1999.

Posted by sb...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/8c75e4de/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
index d3ee6ff..8e6eeba 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
@@ -17,35 +17,22 @@
 
 package org.apache.ignite.internal.processors.query.h2;
 
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.math.BigDecimal;
 import java.sql.Connection;
-import java.sql.Date;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
 import java.sql.Statement;
-import java.sql.Time;
-import java.sql.Timestamp;
 import java.sql.Types;
 import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
-import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
@@ -60,7 +47,6 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteDataStreamer;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
-import org.apache.ignite.cache.QueryIndexType;
 import org.apache.ignite.cache.query.FieldsQueryCursor;
 import org.apache.ignite.cache.query.QueryCancelledException;
 import org.apache.ignite.cache.query.QueryCursor;
@@ -97,9 +83,7 @@ import org.apache.ignite.internal.processors.query.GridQueryCancel;
 import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
 import org.apache.ignite.internal.processors.query.GridQueryFieldsResult;
 import org.apache.ignite.internal.processors.query.GridQueryFieldsResultAdapter;
-import org.apache.ignite.internal.processors.query.GridQueryIndexDescriptor;
 import org.apache.ignite.internal.processors.query.GridQueryIndexing;
-import org.apache.ignite.internal.processors.query.GridQueryProperty;
 import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
 import org.apache.ignite.internal.processors.query.GridRunningQueryInfo;
 import org.apache.ignite.internal.processors.query.IgniteSQLException;
@@ -115,16 +99,11 @@ import org.apache.ignite.internal.processors.query.h2.database.io.H2InnerIO;
 import org.apache.ignite.internal.processors.query.h2.database.io.H2LeafIO;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2DefaultTableEngine;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2IndexBase;
-import org.apache.ignite.internal.processors.query.h2.opt.GridH2SystemIndexFactory;
-import org.apache.ignite.internal.processors.query.h2.opt.GridH2KeyValueRowOffheap;
-import org.apache.ignite.internal.processors.query.h2.opt.GridH2KeyValueRowOnheap;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2Row;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowFactory;
 import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
-import org.apache.ignite.internal.processors.query.h2.opt.GridH2ValueCacheObject;
-import org.apache.ignite.internal.processors.query.h2.opt.GridLuceneIndex;
 import org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser;
 import org.apache.ignite.internal.processors.query.h2.sql.GridSqlQuerySplitter;
 import org.apache.ignite.internal.processors.query.h2.twostep.GridMapQueryExecutor;
@@ -135,16 +114,12 @@ import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
 import org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap;
 import org.apache.ignite.internal.util.GridEmptyCloseableIterator;
 import org.apache.ignite.internal.util.GridSpinBusyLock;
-import org.apache.ignite.internal.util.GridStringBuilder;
 import org.apache.ignite.internal.util.lang.GridCloseableIterator;
 import org.apache.ignite.internal.util.lang.GridPlainRunnable;
 import org.apache.ignite.internal.util.lang.IgniteInClosure2X;
-import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeGuard;
-import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.LT;
-import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.SB;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiClosure;
@@ -159,49 +134,18 @@ import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.spi.indexing.IndexingQueryFilter;
 import org.h2.api.ErrorCode;
 import org.h2.api.JavaObjectSerializer;
-import org.h2.api.TableEngine;
-import org.h2.command.CommandInterface;
 import org.h2.command.Prepared;
-import org.h2.command.ddl.CreateTableData;
 import org.h2.command.dml.Insert;
 import org.h2.engine.Session;
 import org.h2.engine.SysProperties;
 import org.h2.index.Cursor;
 import org.h2.index.Index;
-import org.h2.jdbc.JdbcConnection;
 import org.h2.jdbc.JdbcPreparedStatement;
 import org.h2.jdbc.JdbcStatement;
-import org.h2.message.DbException;
-import org.h2.mvstore.cache.CacheLongKeyLIRS;
-import org.h2.result.SearchRow;
-import org.h2.result.SimpleRow;
-import org.h2.result.SortOrder;
 import org.h2.server.web.WebServer;
-import org.h2.table.Column;
 import org.h2.table.IndexColumn;
-import org.h2.table.TableBase;
 import org.h2.tools.Server;
 import org.h2.util.JdbcUtils;
-import org.h2.value.DataType;
-import org.h2.value.Value;
-import org.h2.value.ValueArray;
-import org.h2.value.ValueBoolean;
-import org.h2.value.ValueByte;
-import org.h2.value.ValueBytes;
-import org.h2.value.ValueDate;
-import org.h2.value.ValueDecimal;
-import org.h2.value.ValueDouble;
-import org.h2.value.ValueFloat;
-import org.h2.value.ValueGeometry;
-import org.h2.value.ValueInt;
-import org.h2.value.ValueJavaObject;
-import org.h2.value.ValueLong;
-import org.h2.value.ValueNull;
-import org.h2.value.ValueShort;
-import org.h2.value.ValueString;
-import org.h2.value.ValueTime;
-import org.h2.value.ValueTimestamp;
-import org.h2.value.ValueUuid;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 
@@ -219,10 +163,6 @@ import static org.apache.ignite.internal.processors.query.QueryUtils.VAL_FIELD_N
 import static org.apache.ignite.internal.processors.query.QueryUtils.VER_FIELD_NAME;
 import static org.apache.ignite.internal.processors.query.h2.opt.DistributedJoinMode.OFF;
 import static org.apache.ignite.internal.processors.query.h2.opt.DistributedJoinMode.distributedJoinMode;
-import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.DEFAULT_COLUMNS_COUNT;
-import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.KEY_COL;
-import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.VAL_COL;
-import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.VER_COL;
 import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType.LOCAL;
 import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType.PREPARE;
 
@@ -244,11 +184,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         PageIO.registerH2(H2InnerIO.VERSIONS, H2LeafIO.VERSIONS);
         H2ExtrasInnerIO.register();
         H2ExtrasLeafIO.register();
-    }
 
-    /** Spatial index class name. */
-    private static final String SPATIAL_IDX_CLS =
-        "org.apache.ignite.internal.processors.query.h2.opt.GridH2SpatialIndex";
+        // Initialize system properties for H2.
+        System.setProperty("h2.objectCache", "false");
+        System.setProperty("h2.serializeJavaObject", "false");
+        System.setProperty("h2.objectCacheMaxPerElementSize", "0"); // Avoid ValueJavaObject caching.
+    }
 
     /** Default DB options. */
     private static final String DB_OPTIONS = ";LOCK_MODE=3;MULTI_THREADED=1;DB_CLOSE_ON_EXIT=FALSE" +
@@ -262,7 +203,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
     /** Dummy metadata for update result. */
     public static final List<GridQueryFieldMetadata> UPDATE_RESULT_META = Collections.<GridQueryFieldMetadata>
-        singletonList(new SqlFieldMetadata(null, null, "UPDATED", Long.class.getName()));
+        singletonList(new H2SqlFieldMetadata(null, null, "UPDATED", Long.class.getName()));
 
     /** */
     private static final int PREPARED_STMT_CACHE_SIZE = 256;
@@ -270,15 +211,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** */
     private static final int TWO_STEP_QRY_CACHE_SIZE = 1024;
 
-    /** */
-    private static final Field COMMAND_FIELD;
-
-    /** */
-    private static final char ESC_CH = '\"';
-
-    /** */
-    private static final String ESC_STR = ESC_CH + "" + ESC_CH;
-
     /** The period of clean up the {@link #stmtCache}. */
     private final Long CLEANUP_STMT_CACHE_PERIOD = Long.getLong(IGNITE_H2_INDEXING_CACHE_CLEANUP_PERIOD, 10_000);
 
@@ -289,25 +221,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** */
     private GridTimeoutProcessor.CancelableTask stmtCacheCleanupTask;
 
-    /*
-     * Command in H2 prepared statement.
-     */
-    static {
-        // Initialize system properties for H2.
-        System.setProperty("h2.objectCache", "false");
-        System.setProperty("h2.serializeJavaObject", "false");
-        System.setProperty("h2.objectCacheMaxPerElementSize", "0"); // Avoid ValueJavaObject caching.
-
-        try {
-            COMMAND_FIELD = JdbcPreparedStatement.class.getDeclaredField("command");
-
-            COMMAND_FIELD.setAccessible(true);
-        }
-        catch (NoSuchFieldException e) {
-            throw new IllegalStateException("Check H2 version in classpath.", e);
-        }
-    }
-
     /** Logger. */
     @LoggerResource
     private IgniteLogger log;
@@ -319,7 +232,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     private Marshaller marshaller;
 
     /** Collection of schemaNames and registered tables. */
-    private final ConcurrentMap<String, Schema> schemas = new ConcurrentHashMap8<>();
+    private final ConcurrentMap<String, H2Schema> schemas = new ConcurrentHashMap8<>();
 
     /** */
     private String dbUrl = "jdbc:h2:mem:";
@@ -346,9 +259,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     private final ConcurrentMap<Long, GridRunningQueryInfo> runs = new ConcurrentHashMap8<>();
 
     /** */
-    private final ThreadLocal<ConnectionWrapper> connCache = new ThreadLocal<ConnectionWrapper>() {
-        @Nullable @Override public ConnectionWrapper get() {
-            ConnectionWrapper c = super.get();
+    private final ThreadLocal<H2ConnectionWrapper> connCache = new ThreadLocal<H2ConnectionWrapper>() {
+        @Nullable @Override public H2ConnectionWrapper get() {
+            H2ConnectionWrapper c = super.get();
 
             boolean reconnect = true;
 
@@ -371,7 +284,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             return c;
         }
 
-        @Nullable @Override protected ConnectionWrapper initialValue() {
+        @Nullable @Override protected H2ConnectionWrapper initialValue() {
             Connection c;
 
             try {
@@ -383,7 +296,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             conns.add(c);
 
-            return new ConnectionWrapper(c);
+            return new H2ConnectionWrapper(c);
         }
     };
 
@@ -400,10 +313,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     private final ConcurrentMap<QueryTable, GridH2Table> dataTables = new ConcurrentHashMap8<>();
 
     /** Statement cache. */
-    private final ConcurrentHashMap<Thread, StatementCache> stmtCache = new ConcurrentHashMap<>();
+    private final ConcurrentHashMap<Thread, H2StatementCache> stmtCache = new ConcurrentHashMap<>();
 
     /** */
-    private final GridBoundedConcurrentLinkedHashMap<TwoStepCachedQueryKey, TwoStepCachedQuery> twoStepCache =
+    private final GridBoundedConcurrentLinkedHashMap<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery> twoStepCache =
         new GridBoundedConcurrentLinkedHashMap<>(TWO_STEP_QRY_CACHE_SIZE);
 
     /** */
@@ -430,8 +343,16 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Connection.
      */
     public Connection connectionForCache(String cacheName) {
+        return connectionForSchema(schema(cacheName));
+    }
+
+    /**
+     * @param schema Schema.
+     * @return Connection.
+     */
+    public Connection connectionForSchema(String schema) {
         try {
-            return connectionForThread(schema(cacheName));
+            return connectionForThread(schema);
         }
         catch (IgniteCheckedException e) {
             throw new IgniteException(e);
@@ -449,10 +370,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         if (useStmtCache) {
             Thread curThread = Thread.currentThread();
 
-            StatementCache cache = stmtCache.get(curThread);
+            H2StatementCache cache = stmtCache.get(curThread);
 
             if (cache == null) {
-                StatementCache cache0 = new StatementCache(PREPARED_STMT_CACHE_SIZE);
+                H2StatementCache cache0 = new H2StatementCache(PREPARED_STMT_CACHE_SIZE);
 
                 cache = stmtCache.putIfAbsent(curThread, cache0);
 
@@ -518,7 +439,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @throws IgniteCheckedException In case of error.
      */
     private Connection connectionForThread(@Nullable String schema) throws IgniteCheckedException {
-        ConnectionWrapper c = connCache.get();
+        H2ConnectionWrapper c = connCache.get();
 
         if (c == null)
             throw new IgniteCheckedException("Failed to get DB connection for thread (check log for details).");
@@ -645,7 +566,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         GridCacheVersion ver,
         long expirationTime,
         long link) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
+        H2TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl == null)
             return; // Type was rejected.
@@ -653,39 +574,27 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         if (expirationTime == 0)
             expirationTime = Long.MAX_VALUE;
 
-        tbl.tbl.update(k, partId, v, ver, expirationTime, false, link);
+        tbl.table().update(k, partId, v, ver, expirationTime, false, link);
 
-        if (tbl.luceneIdx != null)
-            tbl.luceneIdx.store(k, v, ver, expirationTime);
-    }
-
-    /**
-     * @param o Object.
-     * @return {@code true} If it is a binary object.
-     */
-    private boolean isBinary(CacheObject o) {
-        if (ctx == null)
-            return false;
-
-        return ctx.cacheObjects().isBinaryObject(o);
+        if (tbl.luceneIndex() != null)
+            tbl.luceneIndex().store(k, v, ver, expirationTime);
     }
 
     /**
      * @param cacheName Cache name.
      * @return Cache object context.
      */
-    private CacheObjectContext objectContext(String cacheName) {
-        if (ctx == null)
-            return null;
+    public CacheObjectContext objectContext(String cacheName) {
+        GridCacheContext cctx = cacheContext(cacheName);
 
-        return ctx.cache().internalCache(cacheName).context().cacheObjectContext();
+        return cctx != null ? cctx.cacheObjectContext() : null;
     }
 
     /**
      * @param cacheName Cache name.
      * @return Cache object context.
      */
-    private GridCacheContext cacheContext(String cacheName) {
+    public GridCacheContext cacheContext(String cacheName) {
         if (ctx == null)
             return null;
 
@@ -702,14 +611,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         if (log.isDebugEnabled())
             log.debug("Removing key from cache query index [locId=" + nodeId + ", key=" + key + ", val=" + val + ']');
 
-        TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
+        H2TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
 
         if (tbl == null)
             return;
 
-        if (tbl.tbl.update(key, partId, val, ver, 0, true, 0)) {
-            if (tbl.luceneIdx != null)
-                tbl.luceneIdx.remove(key);
+        if (tbl.table().update(key, partId, val, ver, 0, true, 0)) {
+            if (tbl.luceneIndex() != null)
+                tbl.luceneIndex().remove(key);
         }
     }
 
@@ -719,7 +628,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param tbl Table to unregister.
      * @throws IgniteCheckedException If failed to unregister.
      */
-    private void removeTable(TableDescriptor tbl) throws IgniteCheckedException {
+    private void removeTable(H2TableDescriptor tbl) throws IgniteCheckedException {
         assert tbl != null;
 
         if (log.isDebugEnabled())
@@ -755,7 +664,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         tbl.onDrop();
 
-        tbl.schema.tbls.remove(tbl.typeName());
+        tbl.schema().tables().remove(tbl.typeName());
     }
 
     /**
@@ -766,14 +675,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param h2Idx User index.
      * @throws IgniteCheckedException If failed.
      */
-    private void addInitialUserIndex(String cacheName, TableDescriptor desc, GridH2IndexBase h2Idx)
+    private void addInitialUserIndex(String cacheName, H2TableDescriptor desc, GridH2IndexBase h2Idx)
         throws IgniteCheckedException {
-        GridH2Table h2Tbl = desc.tbl;
+        GridH2Table h2Tbl = desc.table();
 
         h2Tbl.proposeUserIndex(h2Idx);
 
         try {
-            String sql = indexCreateSql(desc.fullTableName(), h2Idx, false, desc.schema.escapeAll());
+            String sql = H2Utils.indexCreateSql(desc.fullTableName(), h2Idx, false, desc.schema().escapeAll());
 
             executeSql(cacheName, sql);
         }
@@ -792,15 +701,15 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         // Locate table.
         String schemaName = schema(cacheName);
 
-        Schema schema = schemas.get(schemaName);
+        H2Schema schema = schemas.get(schemaName);
 
-        TableDescriptor desc = (schema != null ? schema.tbls.get(tblName) : null);
+        H2TableDescriptor desc = (schema != null ? schema.tables().get(tblName) : null);
 
         if (desc == null)
             throw new IgniteCheckedException("Table not found in internal H2 database [schemaName=" + schemaName +
                 ", tblName=" + tblName + ']');
 
-        GridH2Table h2Tbl = desc.tbl;
+        GridH2Table h2Tbl = desc.table();
 
         // Create index.
         final GridH2IndexBase h2Idx = desc.createUserIndex(idxDesc);
@@ -829,7 +738,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             // At this point index is in consistent state, promote it through H2 SQL statement, so that cached
             // prepared statements are re-built.
-            String sql = indexCreateSql(desc.fullTableName(), h2Idx, ifNotExists, schema.escapeAll());
+            String sql = H2Utils.indexCreateSql(desc.fullTableName(), h2Idx, ifNotExists, schema.escapeAll());
 
             executeSql(cacheName, sql);
         }
@@ -847,9 +756,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         throws IgniteCheckedException{
         String schemaName = schema(cacheName);
 
-        Schema schema = schemas.get(schemaName);
+        H2Schema schema = schemas.get(schemaName);
 
-        String sql = indexDropSql(schemaName, idxName, ifExists, schema.escapeAll());
+        String sql = H2Utils.indexDropSql(schemaName, idxName, ifExists, schema.escapeAll());
 
         executeSql(cacheName, sql);
     }
@@ -875,54 +784,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * Generate {@code CREATE INDEX} SQL statement for given params.
-     * @param fullTblName Fully qualified table name.
-     * @param h2Idx H2 index.
-     * @param ifNotExists Quietly skip index creation if it exists.
-     * @return Statement string.
-     */
-    private static String indexCreateSql(String fullTblName, GridH2IndexBase h2Idx, boolean ifNotExists,
-        boolean escapeAll) {
-        boolean spatial = F.eq(SPATIAL_IDX_CLS, h2Idx.getClass().getName());
-
-        GridStringBuilder sb = new SB("CREATE ")
-            .a(spatial ? "SPATIAL " : "")
-            .a("INDEX ")
-            .a(ifNotExists ? "IF NOT EXISTS " : "")
-            .a(escapeName(h2Idx.getName(), escapeAll))
-            .a(" ON ")
-            .a(fullTblName)
-            .a(" (");
-
-        boolean first = true;
-
-        for (IndexColumn col : h2Idx.getIndexColumns()) {
-            if (first)
-                first = false;
-            else
-                sb.a(", ");
-
-            sb.a("\"" + col.columnName + "\"").a(" ").a(col.sortType == SortOrder.ASCENDING ? "ASC" : "DESC");
-        }
-
-        sb.a(')');
-
-        return sb.toString();
-    }
-
-    /**
-     * Generate {@code CREATE INDEX} SQL statement for given params.
-     * @param schemaName <b>Quoted</b> schema name.
-     * @param idxName Index name.
-     * @param ifExists Quietly skip index drop if it exists.
-     * @param escapeAll Escape flag.
-     * @return Statement string.
-     */
-    private static String indexDropSql(String schemaName, String idxName, boolean ifExists, boolean escapeAll) {
-        return "DROP INDEX " + (ifExists ? "IF EXISTS " : "") + schemaName + '.' + escapeName(idxName, escapeAll);
-    }
-
-    /**
      * Create sorted index.
      *
      * @param schema Schema.
@@ -932,7 +793,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param cols Columns.
      * @return Index.
      */
-    private GridH2IndexBase createSortedIndex(Schema schema, String name, GridH2Table tbl, boolean pk,
+    public GridH2IndexBase createSortedIndex(H2Schema schema, String name, GridH2Table tbl, boolean pk,
         List<IndexColumn> cols, int inlineSize) {
         try {
             GridCacheContext cctx = schema.cacheContext();
@@ -949,50 +810,20 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         }
     }
 
-    /**
-     * Create spatial index.
-     *
-     * @param tbl Table.
-     * @param idxName Index name.
-     * @param cols Columns.
-     */
-    private GridH2IndexBase createSpatialIndex(GridH2Table tbl, String idxName, IndexColumn[] cols
-    ) {
-        try {
-            Class<?> cls = Class.forName(SPATIAL_IDX_CLS);
-
-            Constructor<?> ctor = cls.getConstructor(
-                GridH2Table.class,
-                String.class,
-                Integer.TYPE,
-                IndexColumn[].class);
-
-            if (!ctor.isAccessible())
-                ctor.setAccessible(true);
-
-            final int segments = tbl.rowDescriptor().configuration().getQueryParallelism();
-
-            return (GridH2IndexBase)ctor.newInstance(tbl, idxName, segments, cols);
-        }
-        catch (Exception e) {
-            throw new IgniteException("Failed to instantiate: " + SPATIAL_IDX_CLS, e);
-        }
-    }
-
     @SuppressWarnings("unchecked")
     @Override public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalText(
         String cacheName, String qry, String typeName,
         IndexingQueryFilter filters) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
+        H2TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
-        if (tbl != null && tbl.luceneIdx != null) {
+        if (tbl != null && tbl.luceneIndex() != null) {
             GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, TEXT, cacheName,
                 U.currentTimeMillis(), null, true);
 
             try {
                 runs.put(run.id(), run);
 
-                return tbl.luceneIdx.query(qry, filters);
+                return tbl.luceneIndex().query(qry, filters);
             }
             finally {
                 runs.remove(run.id());
@@ -1005,7 +836,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** {@inheritDoc} */
     @Override public void unregisterType(String cacheName, String typeName)
         throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
+        H2TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl != null)
             removeTable(tbl);
@@ -1028,9 +859,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     public GridQueryFieldsResult queryLocalSqlFields(final String cacheName, final String qry,
         @Nullable final Collection<Object> params, final IndexingQueryFilter filter, boolean enforceJoinOrder,
         final int timeout, final GridQueryCancel cancel) throws IgniteCheckedException {
-        final Connection conn = connectionForCache(cacheName);
+        final String schema = schema(cacheName);
+
+        final Connection conn = connectionForSchema(schema);
 
-        setupConnection(conn, false, enforceJoinOrder);
+        H2Utils.setupConnection(conn, false, enforceJoinOrder);
 
         final PreparedStatement stmt = preparedStatementWithParams(conn, qry, params, true);
 
@@ -1045,7 +878,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             fldsQry.setEnforceJoinOrder(enforceJoinOrder);
             fldsQry.setTimeout(timeout, TimeUnit.MILLISECONDS);
 
-            return dmlProc.updateSqlFieldsLocal(cacheName, stmt, fldsQry, filter, cancel);
+            return dmlProc.updateSqlFieldsLocal(schema, stmt, fldsQry, filter, cancel);
         }
         else if (DdlStatementsProcessor.isDdlStatement(p))
             throw new IgniteSQLException("DDL statements are supported for the whole cluster only",
@@ -1054,7 +887,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         List<GridQueryFieldMetadata> meta;
 
         try {
-            meta = meta(stmt.getMetaData());
+            meta = H2Utils.meta(stmt.getMetaData());
         }
         catch (SQLException e) {
             throw new IgniteCheckedException("Cannot prepare query metadata", e);
@@ -1075,9 +908,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 runs.putIfAbsent(run.id(), run);
 
                 try {
-                    ResultSet rs = executeSqlQueryWithTimer(cacheName, stmt, conn, qry, params, timeout, cancel);
+                    ResultSet rs = executeSqlQueryWithTimer(schema, stmt, conn, qry, params, timeout, cancel);
 
-                    return new FieldsIterator(rs);
+                    return new H2FieldsIterator(rs);
                 }
                 finally {
                     GridH2QueryContext.clearThreadLocal();
@@ -1106,58 +939,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * @param rsMeta Metadata.
-     * @return List of fields metadata.
-     * @throws SQLException If failed.
-     */
-    private static List<GridQueryFieldMetadata> meta(ResultSetMetaData rsMeta) throws SQLException {
-        List<GridQueryFieldMetadata> meta = new ArrayList<>(rsMeta.getColumnCount());
-
-        for (int i = 1; i <= rsMeta.getColumnCount(); i++) {
-            String schemaName = rsMeta.getSchemaName(i);
-            String typeName = rsMeta.getTableName(i);
-            String name = rsMeta.getColumnLabel(i);
-            String type = rsMeta.getColumnClassName(i);
-
-            if (type == null) // Expression always returns NULL.
-                type = Void.class.getName();
-
-            meta.add(new SqlFieldMetadata(schemaName, typeName, name, type));
-        }
-
-        return meta;
-    }
-
-    /**
-     * @param stmt Prepared statement.
-     * @return Command type.
-     */
-    private static int commandType(PreparedStatement stmt) {
-        try {
-            return ((CommandInterface)COMMAND_FIELD.get(stmt)).getCommandType();
-        }
-        catch (IllegalAccessException e) {
-            throw new IllegalStateException(e);
-        }
-    }
-
-    /**
-     * Stores rule for constructing schemaName according to cache configuration.
-     *
-     * @param ccfg Cache configuration.
-     * @return Proper schema name according to ANSI-99 standard.
-     */
-    private static String schemaNameFromCacheConf(CacheConfiguration<?, ?> ccfg) {
-        if (ccfg.getSqlSchema() == null)
-            return escapeName(ccfg.getName(), true);
-
-        if (ccfg.getSqlSchema().charAt(0) == ESC_CH)
-            return ccfg.getSqlSchema();
-
-        return ccfg.isSqlEscapeAll() ? escapeName(ccfg.getSqlSchema(), true) : ccfg.getSqlSchema().toUpperCase();
-    }
-
-    /**
      * Prepares sql statement.
      *
      * @param conn Connection.
@@ -1210,7 +991,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         }
 
         if (timeoutMillis > 0)
-            session(conn).setQueryTimeout(timeoutMillis);
+            H2Utils.session(conn).setQueryTimeout(timeoutMillis);
 
         try {
             return stmt.executeQuery();
@@ -1224,14 +1005,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         }
         finally {
             if (timeoutMillis > 0)
-                session(conn).setQueryTimeout(0);
+                H2Utils.session(conn).setQueryTimeout(0);
         }
     }
 
     /**
      * Executes sql query and prints warning if query is too slow..
      *
-     * @param cacheName Cache name.
+     * @param schema Schema.
      * @param conn Connection,.
      * @param sql Sql query.
      * @param params Parameters.
@@ -1240,21 +1021,21 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Result.
      * @throws IgniteCheckedException If failed.
      */
-    public ResultSet executeSqlQueryWithTimer(String cacheName,
+    public ResultSet executeSqlQueryWithTimer(String schema,
         Connection conn,
         String sql,
         @Nullable Collection<Object> params,
         boolean useStmtCache,
         int timeoutMillis,
         @Nullable GridQueryCancel cancel) throws IgniteCheckedException {
-        return executeSqlQueryWithTimer(cacheName, preparedStatementWithParams(conn, sql, params, useStmtCache),
+        return executeSqlQueryWithTimer(schema, preparedStatementWithParams(conn, sql, params, useStmtCache),
             conn, sql, params, timeoutMillis, cancel);
     }
 
     /**
      * Executes sql query and prints warning if query is too slow.
      *
-     * @param cacheName Cache name.
+     * @param schema Schema.
      * @param stmt Prepared statement for query.
      * @param conn Connection.
      * @param sql Sql query.
@@ -1263,7 +1044,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Result.
      * @throws IgniteCheckedException If failed.
      */
-    private ResultSet executeSqlQueryWithTimer(String cacheName, PreparedStatement stmt,
+    private ResultSet executeSqlQueryWithTimer(String schema, PreparedStatement stmt,
         Connection conn,
         String sql,
         @Nullable Collection<Object> params,
@@ -1276,7 +1057,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             long time = U.currentTimeMillis() - start;
 
-            long longQryExecTimeout = schemas.get(schema(cacheName)).ccfg.getLongQueryWarningTimeout();
+            long longQryExecTimeout = schemas.get(schema).cacheContext().config().getLongQueryWarningTimeout();
 
             if (time > longQryExecTimeout) {
                 String msg = "Query execution is too long (" + time + " ms): " + sql;
@@ -1319,18 +1100,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         }
     }
 
-    /**
-     * @param conn Connection to use.
-     * @param distributedJoins If distributed joins are enabled.
-     * @param enforceJoinOrder Enforce join order of tables.
-     */
-    public static void setupConnection(Connection conn, boolean distributedJoins, boolean enforceJoinOrder) {
-        Session s = session(conn);
-
-        s.setForceJoinOrder(enforceJoinOrder);
-        s.setJoinBatchEnabled(distributedJoins);
-    }
-
     /** {@inheritDoc} */
     @Override public FieldsQueryCursor<List<?>> queryLocalSqlFields(final GridCacheContext<?, ?> cctx,
         final SqlFieldsQuery qry, final boolean keepBinary, final IndexingQueryFilter filter,
@@ -1369,6 +1138,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
     @Override public <K, V> QueryCursor<Cache.Entry<K,V>> queryLocalSql(final GridCacheContext<?, ?> cctx,
         final SqlQuery qry, final IndexingQueryFilter filter, final boolean keepBinary) throws IgniteCheckedException {
         if (cctx.config().getQueryParallelism() > 1) {
@@ -1390,7 +1160,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             final GridCloseableIterator<IgniteBiTuple<K, V>> i = queryLocalSql(cacheName, sqlQry, alias,
                 F.asList(params), type, filter, cancel);
 
-            return new QueryCursorImpl<Cache.Entry<K, V>>(new Iterable<Cache.Entry<K, V>>() {
+            return new QueryCursorImpl<>(new Iterable<Cache.Entry<K, V>>() {
                 @Override public Iterator<Cache.Entry<K, V>> iterator() {
                     return new ClIter<Cache.Entry<K, V>>() {
                         @Override public void close() throws Exception {
@@ -1430,10 +1200,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Queried rows.
      * @throws IgniteCheckedException If failed.
      */
+    @SuppressWarnings("unchecked")
     public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalSql(String cacheName,
         final String qry, String alias, @Nullable final Collection<Object> params, String type,
         final IndexingQueryFilter filter, GridQueryCancel cancel) throws IgniteCheckedException {
-        final TableDescriptor tbl = tableDescriptor(type, cacheName);
+        final H2TableDescriptor tbl = tableDescriptor(type, cacheName);
 
         if (tbl == null)
             throw new IgniteSQLException("Failed to find SQL table for type: " + type,
@@ -1443,7 +1214,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         Connection conn = connectionForThread(tbl.schemaName());
 
-        setupConnection(conn, false, false);
+        H2Utils.setupConnection(conn, false, false);
 
         GridH2QueryContext.set(new GridH2QueryContext(nodeId, nodeId, 0, LOCAL).filter(filter)
             .distributedJoinMode(OFF));
@@ -1454,9 +1225,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         runs.put(run.id(), run);
 
         try {
-            ResultSet rs = executeSqlQueryWithTimer(cacheName, conn, sql, params, true, 0, cancel);
+            ResultSet rs = executeSqlQueryWithTimer(schema(cacheName), conn, sql, params, true, 0, cancel);
 
-            return new KeyValIterator(rs);
+            return new H2KeyValueIterator(rs);
         }
         finally {
             GridH2QueryContext.clearThreadLocal();
@@ -1485,7 +1256,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     ) {
         return new Iterable<List<?>>() {
             @Override public Iterator<List<?>> iterator() {
-                return rdcQryExec.query(cctx, qry, keepCacheObj, enforceJoinOrder, timeoutMillis, cancel, params, parts);
+                return rdcQryExec.query(cctx, qry, keepCacheObj, enforceJoinOrder, timeoutMillis, cancel, params,
+                    parts);
             }
         };
     }
@@ -1497,7 +1269,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         String type = qry.getType();
         String cacheName = cctx.name();
 
-        TableDescriptor tblDesc = tableDescriptor(type, cacheName);
+        H2TableDescriptor tblDesc = tableDescriptor(type, cacheName);
 
         if (tblDesc == null)
             throw new IgniteSQLException("Failed to find SQL table for type: " + type,
@@ -1555,21 +1327,15 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         };
     }
 
-    /**
-     * @param c Connection.
-     * @return Session.
-     */
-    public static Session session(Connection c) {
-        return (Session)((JdbcConnection)c).getSession();
-    }
-
     /** {@inheritDoc} */
-    @Override public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx, SqlFieldsQuery qry,
-        boolean keepBinary, GridQueryCancel cancel) {
+    @Override public FieldsQueryCursor<List<?>> queryDistributedSqlFields(GridCacheContext<?, ?> cctx,
+        SqlFieldsQuery qry, boolean keepBinary, GridQueryCancel cancel) {
         final String cacheName = cctx.name();
         final String sqlQry = qry.getSql();
 
-        Connection c = connectionForCache(cacheName);
+        String schema = schema(cctx.name());
+
+        Connection c = connectionForSchema(schema);
 
         final boolean enforceJoinOrder = qry.isEnforceJoinOrder();
         final boolean distributedJoins = qry.isDistributedJoins();
@@ -1580,9 +1346,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         GridCacheTwoStepQuery twoStepQry = null;
         List<GridQueryFieldMetadata> meta;
 
-        final TwoStepCachedQueryKey cachedQryKey = new TwoStepCachedQueryKey(cacheName, sqlQry, grpByCollocated,
+        final H2TwoStepCachedQueryKey cachedQryKey = new H2TwoStepCachedQueryKey(cacheName, sqlQry, grpByCollocated,
             distributedJoins, enforceJoinOrder, qry.isLocal());
-        TwoStepCachedQuery cachedQry = twoStepCache.get(cachedQryKey);
+        H2TwoStepCachedQuery cachedQry = twoStepCache.get(cachedQryKey);
 
         if (cachedQry != null) {
             twoStepQry = cachedQry.twoStepQry.copy();
@@ -1592,7 +1358,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
             final UUID locNodeId = ctx.localNodeId();
 
             // Here we will just parse the statement, no need to optimize it at all.
-            setupConnection(c, /*distributedJoins*/false, /*enforceJoinOrder*/true);
+            H2Utils.setupConnection(c, /*distributedJoins*/false, /*enforceJoinOrder*/true);
 
             GridH2QueryContext.set(new GridH2QueryContext(locNodeId, locNodeId, 0, PREPARE)
                 .distributedJoinMode(distributedJoinMode));
@@ -1606,7 +1372,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 try {
                     while (true) {
                         try {
-                            // Do not cache this statement because the whole two step query object will be cached later on.
+                            // Do not cache this statement because the whole query object will be cached later on.
                             stmt = prepareStatement(c, sqlQry, false);
 
                             break;
@@ -1655,7 +1421,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 if (twoStepQry == null) {
                     if (DmlStatementsProcessor.isDmlStatement(prepared)) {
                         try {
-                            return dmlProc.updateSqlFieldsDistributed(cctx.name(), stmt, qry, cancel);
+                            return dmlProc.updateSqlFieldsDistributed(schema, stmt, qry, cancel);
                         }
                         catch (IgniteCheckedException e) {
                             throw new IgniteSQLException("Failed to execute DML statement [stmt=" + sqlQry +
@@ -1702,7 +1468,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 twoStepQry.cacheIds(cacheIds);
                 twoStepQry.local(qry.isLocal());
 
-                meta = meta(stmt.getMetaData());
+                meta = H2Utils.meta(stmt.getMetaData());
             }
             catch (IgniteCheckedException e) {
                 throw new CacheException("Failed to bind parameters: [qry=" + sqlQry + ", params=" +
@@ -1731,7 +1497,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         cursor.fieldsMeta(meta);
 
         if (cachedQry == null && !twoStepQry.explain()) {
-            cachedQry = new TwoStepCachedQuery(meta, twoStepQry.copy());
+            cachedQry = new H2TwoStepCachedQuery(meta, twoStepQry.copy());
             twoStepCache.putIfAbsent(cachedQryKey, cachedQry);
         }
 
@@ -1752,16 +1518,16 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /**
      * @throws IllegalStateException if segmented indices used with non-segmented indices.
      */
-    private void checkCacheIndexSegmentation(List<Integer> caches) {
-        if (caches.isEmpty())
+    private void checkCacheIndexSegmentation(List<Integer> cacheIds) {
+        if (cacheIds.isEmpty())
             return; // Nothing to check
 
         GridCacheSharedContext sharedCtx = ctx.cache().context();
 
         int expectedParallelism = 0;
 
-        for (int i = 0; i < caches.size(); i++) {
-            GridCacheContext cctx = sharedCtx.cacheContext(caches.get(i));
+        for (Integer cacheId : cacheIds) {
+            GridCacheContext cctx = sharedCtx.cacheContext(cacheId);
 
             assert cctx != null;
 
@@ -1770,8 +1536,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
             if (expectedParallelism == 0)
                 expectedParallelism = cctx.config().getQueryParallelism();
-            else if (cctx.config().getQueryParallelism() != expectedParallelism)
-                throw new IllegalStateException("Using indexes with different parallelism levels in same query is forbidden.");
+            else if (cctx.config().getQueryParallelism() != expectedParallelism) {
+                throw new IllegalStateException("Using indexes with different parallelism levels in same query is " +
+                    "forbidden.");
+            }
         }
     }
 
@@ -1784,7 +1552,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return Prepared statement.
      * @throws IgniteCheckedException In case of error.
      */
-    private String generateQuery(String qry, String tableAlias, TableDescriptor tbl) throws IgniteCheckedException {
+    private String generateQuery(String qry, String tableAlias, H2TableDescriptor tbl) throws IgniteCheckedException {
         assert tbl != null;
 
         final String qry0 = qry;
@@ -1847,9 +1615,9 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         String schemaName = schema(cacheName);
 
-        Schema schema = schemas.get(schemaName);
+        H2Schema schema = schemas.get(schemaName);
 
-        TableDescriptor tbl = new TableDescriptor(schema, type);
+        H2TableDescriptor tbl = new H2TableDescriptor(this, schema, type);
 
         try {
             Connection conn = connectionForThread(schemaName);
@@ -1895,68 +1663,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         }
 
         if (type.keyFieldName() != null && !type.fields().containsKey(type.keyFieldName())) {
-            throw new IgniteCheckedException(
-                    MessageFormat.format("Name ''{0}'' must be amongst fields since it is configured as ''keyFieldName'' [type=" +
-                            type.name() + "]", type.keyFieldName()));
+            throw new IgniteCheckedException(MessageFormat.format("Name ''{0}'' must be amongst fields since it " +
+                "is configured as ''keyFieldName'' [type=" + type.name() + "]", type.keyFieldName()));
         }
 
         if (type.valueFieldName() != null && !type.fields().containsKey(type.valueFieldName())) {
-            throw new IgniteCheckedException(
-                    MessageFormat.format("Name ''{0}'' must be amongst fields since it is configured as ''valueFieldName'' [type=" +
-                            type.name() + "]", type.valueFieldName()));
-        }
-    }
-
-    /**
-     * Returns empty string, if {@code nullableString} is empty.
-     *
-     * @param nullableString String for convertion. Could be null.
-     * @return Non null string. Could be empty.
-     */
-    private static String emptyIfNull(String nullableString) {
-        return nullableString == null ? "" : nullableString;
-    }
-
-    /**
-     * Escapes name to be valid SQL identifier. Currently just replaces '.' and '$' sign with '_'.
-     *
-     * @param name Name.
-     * @param escapeAll Escape flag.
-     * @return Escaped name.
-     */
-    public static String escapeName(String name, boolean escapeAll) {
-        if (name == null) // It is possible only for a cache name.
-            return ESC_STR;
-
-        if (escapeAll)
-            return ESC_CH + name + ESC_CH;
-
-        SB sb = null;
-
-        for (int i = 0; i < name.length(); i++) {
-            char ch = name.charAt(i);
-
-            if (!Character.isLetter(ch) && !Character.isDigit(ch) && ch != '_' &&
-                !(ch == '"' && (i == 0 || i == name.length() - 1)) && ch != '-') {
-                // Class name can also contain '$' or '.' - these should be escaped.
-                assert ch == '$' || ch == '.';
-
-                if (sb == null)
-                    sb = new SB();
-
-                sb.a(name.substring(sb.length(), i));
-
-                // Replace illegal chars with '_'.
-                sb.a('_');
-            }
+            throw new IgniteCheckedException(MessageFormat.format("Name ''{0}'' must be amongst fields since it " +
+                "is configured as ''valueFieldName'' [type=" + type.name() + "]", type.valueFieldName()));
         }
-
-        if (sb == null)
-            return name;
-
-        sb.a(name.substring(sb.length(), name.length()));
-
-        return sb.toString();
     }
 
     /**
@@ -1969,7 +1683,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @throws SQLException If failed to create db table.
      * @throws IgniteCheckedException If failed.
      */
-    private void createTable(String cacheName, Schema schema, TableDescriptor tbl, Connection conn)
+    private void createTable(String cacheName, H2Schema schema, H2TableDescriptor tbl, Connection conn)
         throws SQLException, IgniteCheckedException {
         assert schema != null;
         assert tbl != null;
@@ -1990,14 +1704,14 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         sql.a(',').a(VER_FIELD_NAME).a(" OTHER INVISIBLE");
 
         for (Map.Entry<String, Class<?>> e : tbl.type().fields().entrySet())
-            sql.a(',').a(escapeName(e.getKey(), escapeAll)).a(' ').a(dbTypeFromClass(e.getValue()));
+            sql.a(',').a(H2Utils.escapeName(e.getKey(), escapeAll)).a(' ').a(dbTypeFromClass(e.getValue()));
 
         sql.a(')');
 
         if (log.isDebugEnabled())
             log.debug("Creating DB table with SQL: " + sql);
 
-        GridH2RowDescriptor rowDesc = new RowDescriptor(tbl.type(), schema);
+        GridH2RowDescriptor rowDesc = new H2RowDescriptor(this, tbl.type(), schema);
 
         H2RowFactory rowFactory = tbl.rowFactory(rowDesc);
 
@@ -2032,6 +1746,13 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
+     * @param h2Tbl Remove data table.
+     */
+    public void removeDataTable(GridH2Table h2Tbl) {
+        dataTables.remove(h2Tbl.identifier(), h2Tbl);
+    }
+
+    /**
      * Find table for index.
      *
      * @param schemaName Schema name.
@@ -2058,7 +1779,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @return DB type name.
      */
     private String dbTypeFromClass(Class<?> cls) {
-        return DBTypeEnum.fromClass(cls).dBTypeAsString();
+        return H2DatabaseType.fromClass(cls).dBTypeAsString();
     }
 
     /**
@@ -2068,28 +1789,15 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param cacheName Cache name.
      * @return Table descriptor.
      */
-    @Nullable private TableDescriptor tableDescriptor(String type, String cacheName) {
-        Schema s = schemas.get(schema(cacheName));
-
-        if (s == null)
-            return null;
-
-        return s.tbls.get(type);
-    }
+    @Nullable private H2TableDescriptor tableDescriptor(String type, String cacheName) {
+        String schemaName = schema(cacheName);
 
-    /**
-     * Gets collection of table for given schema name.
-     *
-     * @param schema Schema name.
-     * @return Collection of table descriptors.
-     */
-    private Collection<TableDescriptor> tables(String schema) {
-        Schema s = schemas.get(schema);
+        H2Schema schema = schemas.get(schemaName);
 
-        if (s == null)
-            return Collections.emptySet();
+        if (schema == null)
+            return null;
 
-        return s.tbls.values();
+        return schema.tables().get(type);
     }
 
     /**
@@ -2098,8 +1806,13 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param cacheName Cache name. {@code null} would be converted to an empty string.
      * @return Schema name. Should not be null since we should not fail for an invalid cache name.
      */
-    private String schema(String cacheName) {
-        return emptyIfNull(cacheName2schema.get(emptyIfNull(cacheName)));
+    public String schema(String cacheName) {
+        String res = cacheName2schema.get(cacheName);
+
+        if (res == null)
+            res = "";
+
+        return res;
     }
 
     /**
@@ -2108,8 +1821,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     private void cleanupStatementCache() {
         long cur = U.currentTimeMillis();
 
-        for (Iterator<Map.Entry<Thread, StatementCache>> it = stmtCache.entrySet().iterator(); it.hasNext(); ) {
-            Map.Entry<Thread, StatementCache> entry = it.next();
+        for (Iterator<Map.Entry<Thread, H2StatementCache>> it = stmtCache.entrySet().iterator(); it.hasNext(); ) {
+            Map.Entry<Thread, H2StatementCache> entry = it.next();
 
             Thread t = entry.getKey();
 
@@ -2123,16 +1836,16 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     @Override public String cacheName(String schemaName) {
         assert schemaName != null;
 
-        Schema schema = schemas.get(schemaName);
+        H2Schema schema = schemas.get(schemaName);
 
         // For the compatibility with conversion from """" to "" inside h2 lib
         if (schema == null) {
-            assert schemaName.isEmpty() || schemaName.charAt(0) != ESC_CH;
+            assert schemaName.isEmpty() || schemaName.charAt(0) != H2Utils.ESC_CH;
 
-            schema = schemas.get(escapeName(schemaName, true));
+            schema = schemas.get(H2Utils.escapeName(schemaName, true));
         }
 
-        return schema.cacheName;
+        return schema.cacheName();
     }
 
     /**
@@ -2142,22 +1855,23 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @param type Type descriptor.
      * @throws IgniteCheckedException If failed.
      */
+    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
     @Override public void rebuildIndexesFromHash(String cacheName,
         GridQueryTypeDescriptor type) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
+        H2TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
 
         if (tbl == null)
             return;
 
-        assert tbl.tbl != null;
+        assert tbl.table() != null;
 
-        assert tbl.tbl.rebuildFromHashInProgress();
+        assert tbl.table().rebuildFromHashInProgress();
 
-        H2PkHashIndex hashIdx = tbl.pkHashIdx;
+        H2PkHashIndex hashIdx = tbl.primaryKeyHashIndex();
 
         Cursor cursor = hashIdx.find((Session)null, null, null);
 
-        int cacheId = CU.cacheId(tbl.schema.ccfg.getName());
+        int cacheId = CU.cacheId(tbl.schema().cacheName());
 
         GridCacheContext cctx = ctx.cache().context().cacheContext(cacheId);
 
@@ -2173,12 +1887,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                     synchronized (entry) {
                         // TODO : How to correctly get current value and link here?
 
-                        GridH2Row row = tbl.tbl.rowDescriptor().createRow(entry.key(), entry.partition(),
+                        GridH2Row row = tbl.table().rowDescriptor().createRow(entry.key(), entry.partition(),
                             dataRow.value(), entry.version(), entry.expireTime());
 
                         row.link(dataRow.link());
 
-                        List<Index> indexes = tbl.tbl.getAllIndexes();
+                        List<Index> indexes = tbl.table().getAllIndexes();
 
                         for (int i = 2; i < indexes.size(); i++) {
                             Index idx = indexes.get(i);
@@ -2197,19 +1911,19 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         }
 
-        tbl.tbl.markRebuildFromHashInProgress(false);
+        tbl.table().markRebuildFromHashInProgress(false);
     }
 
     /** {@inheritDoc} */
     @Override public void markForRebuildFromHash(String cacheName, GridQueryTypeDescriptor type) {
-        TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
+        H2TableDescriptor tbl = tableDescriptor(type.name(), cacheName);
 
         if (tbl == null)
             return;
 
-        assert tbl.tbl != null;
+        assert tbl.table() != null;
 
-        tbl.tbl.markRebuildFromHashInProgress(true);
+        tbl.table().markRebuildFromHashInProgress(true);
     }
 
     /**
@@ -2221,18 +1935,18 @@ public class IgniteH2Indexing implements GridQueryIndexing {
      * @throws IgniteCheckedException If failed or {@code -1} if the type is unknown.
      */
     long size(String cacheName, String typeName) throws IgniteCheckedException {
-        TableDescriptor tbl = tableDescriptor(typeName, cacheName);
+        H2TableDescriptor tbl = tableDescriptor(typeName, cacheName);
 
         if (tbl == null)
             return -1;
 
         Connection conn = connectionForCache(cacheName);
 
-        setupConnection(conn, false, false);
+        H2Utils.setupConnection(conn, false, false);
 
         try {
-            ResultSet rs = executeSqlQuery(conn, prepareStatement(conn, "SELECT COUNT(*) FROM " + tbl.fullTableName(), false),
-                0, null);
+            ResultSet rs = executeSqlQuery(conn, prepareStatement(conn, "SELECT COUNT(*) FROM " + tbl.fullTableName(),
+                false), 0, null);
 
             if (!rs.next())
                 throw new IllegalStateException();
@@ -2409,6 +2123,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
         // Local node goes the last to allow parallel execution.
         if (locNode != null) {
+            assert locNodeHnd != null;
+
             if (specialize != null)
                 msg = specialize.apply(locNode, msg);
 
@@ -2503,7 +2219,7 @@ public class IgniteH2Indexing implements GridQueryIndexing {
 
 //        unregisterMBean(); TODO https://issues.apache.org/jira/browse/IGNITE-2139
         if (ctx != null && !ctx.cache().context().database().persistenceEnabled()) {
-            for (Schema schema : schemas.values())
+            for (H2Schema schema : schemas.values())
                 schema.onDrop();
         }
 
@@ -2534,12 +2250,12 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** {@inheritDoc} */
     @Override public void registerCache(String cacheName, GridCacheContext<?, ?> cctx, CacheConfiguration<?, ?> ccfg)
         throws IgniteCheckedException {
-        String schema = schemaNameFromCacheConf(ccfg);
+        String schema = H2Utils.schemaNameFromCacheConfiguration(ccfg);
 
-        if (schemas.putIfAbsent(schema, new Schema(cacheName, schema, cctx, ccfg)) != null)
+        if (schemas.putIfAbsent(schema, new H2Schema(cacheName, schema, cctx, ccfg)) != null)
             throw new IgniteCheckedException("Cache already registered: " + U.maskName(cacheName));
 
-        cacheName2schema.put(emptyIfNull(cacheName), schema);
+        cacheName2schema.put(cacheName, schema);
 
         createSchema(schema);
 
@@ -2549,10 +2265,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     /** {@inheritDoc} */
     @Override public void unregisterCache(String cacheName) {
         String schema = schema(cacheName);
-        Schema rmv = schemas.remove(schema);
+        H2Schema rmv = schemas.remove(schema);
 
         if (rmv != null) {
-            cacheName2schema.remove(emptyIfNull(rmv.cacheName));
+            cacheName2schema.remove(rmv.cacheName());
             mapQryExec.onCacheStop(cacheName);
             dmlProc.onCacheStop(cacheName);
 
@@ -2562,28 +2278,26 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                 dropSchema(schema);
             }
             catch (IgniteCheckedException e) {
-                U.error(log, "Failed to drop schema on cache stop (will ignore): " + U.maskName(cacheName), e);
+                U.error(log, "Failed to drop schema on cache stop (will ignore): " + cacheName, e);
             }
 
-            for (TableDescriptor tblDesc : rmv.tbls.values())
-                for (Index idx : tblDesc.tbl.getIndexes())
+            for (H2TableDescriptor tblDesc : rmv.tables().values())
+                for (Index idx : tblDesc.table().getIndexes())
                     idx.close(null);
 
-            for (Iterator<Map.Entry<TwoStepCachedQueryKey, TwoStepCachedQuery>> it = twoStepCache.entrySet().iterator();
-                it.hasNext(); ) {
-                Map.Entry<TwoStepCachedQueryKey, TwoStepCachedQuery> e = it.next();
+            for (Iterator<Map.Entry<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery>> it =
+                twoStepCache.entrySet().iterator(); it.hasNext();) {
+                Map.Entry<H2TwoStepCachedQueryKey, H2TwoStepCachedQuery> e = it.next();
 
-                if (F.eq(e.getKey().cacheName, cacheName))
+                if (F.eq(e.getKey().cacheName(), cacheName))
                     it.remove();
             }
         }
     }
 
     /** {@inheritDoc} */
-    @Override public IndexingQueryFilter backupFilter(
-        @Nullable final AffinityTopologyVersion topVer,
-        @Nullable final int[] parts
-    ) {
+    @Override public IndexingQueryFilter backupFilter(@Nullable final AffinityTopologyVersion topVer,
+        @Nullable final int[] parts) {
         final AffinityTopologyVersion topVer0 = topVer != null ? topVer : AffinityTopologyVersion.NONE;
 
         return new IndexingQueryFilter() {
@@ -2665,172 +2379,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
         rdcQryExec.onDisconnected(reconnectFut);
     }
 
-    /**
-     * Key for cached two-step query.
-     */
-    private static final class TwoStepCachedQueryKey {
-        /** */
-        private final String cacheName;
-
-        /** */
-        private final String sql;
-
-        /** */
-        private final boolean grpByCollocated;
-
-        /** */
-        private final boolean distributedJoins;
-
-        /** */
-        private final boolean enforceJoinOrder;
-
-        /** */
-        private final boolean isLocal;
-
-        /**
-         * @param cacheName Cache name.
-         * @param sql Sql.
-         * @param grpByCollocated Collocated GROUP BY.
-         * @param distributedJoins Distributed joins enabled.
-         * @param enforceJoinOrder Enforce join order of tables.
-         * @param isLocal Query is local flag.
-         */
-        private TwoStepCachedQueryKey(String cacheName,
-            String sql,
-            boolean grpByCollocated,
-            boolean distributedJoins,
-            boolean enforceJoinOrder,
-            boolean isLocal) {
-            this.cacheName = cacheName;
-            this.sql = sql;
-            this.grpByCollocated = grpByCollocated;
-            this.distributedJoins = distributedJoins;
-            this.enforceJoinOrder = enforceJoinOrder;
-            this.isLocal = isLocal;
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean equals(Object o) {
-            if (this == o)
-                return true;
-
-            if (o == null || getClass() != o.getClass())
-                return false;
-
-            TwoStepCachedQueryKey that = (TwoStepCachedQueryKey)o;
-
-            if (grpByCollocated != that.grpByCollocated)
-                return false;
-
-            if (distributedJoins != that.distributedJoins)
-                return false;
-
-            if (enforceJoinOrder != that.enforceJoinOrder)
-                return false;
-
-            if (cacheName != null ? !cacheName.equals(that.cacheName) : that.cacheName != null)
-                return false;
-
-            return isLocal == that.isLocal && sql.equals(that.sql);
-        }
-
-        /** {@inheritDoc} */
-        @Override public int hashCode() {
-            int res = cacheName != null ? cacheName.hashCode() : 0;
-            res = 31 * res + sql.hashCode();
-            res = 31 * res + (grpByCollocated ? 1 : 0);
-            res = res + (distributedJoins ? 2 : 0);
-            res = res + (enforceJoinOrder ? 4 : 0);
-            res = res + (isLocal ? 8 : 0);
-
-            return res;
-        }
-    }
-
-    /**
-     * Cached two-step query.
-     */
-    private static final class TwoStepCachedQuery {
-        /** */
-        final List<GridQueryFieldMetadata> meta;
-
-        /** */
-        final GridCacheTwoStepQuery twoStepQry;
-
-        /**
-         * @param meta Fields metadata.
-         * @param twoStepQry Query.
-         */
-        public TwoStepCachedQuery(List<GridQueryFieldMetadata> meta, GridCacheTwoStepQuery twoStepQry) {
-            this.meta = meta;
-            this.twoStepQry = twoStepQry;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String toString() {
-            return S.toString(TwoStepCachedQuery.class, this);
-        }
-    }
-
-    /**
-     * @param c1 First column.
-     * @param c2 Second column.
-     * @return {@code true} If they are the same.
-     */
-    private static boolean equal(IndexColumn c1, IndexColumn c2) {
-        return c1.column.getColumnId() == c2.column.getColumnId();
-    }
-
-    /**
-     * @param cols Columns list.
-     * @param col Column to find.
-     * @return {@code true} If found.
-     */
-    private static boolean containsColumn(List<IndexColumn> cols, IndexColumn col) {
-        for (int i = cols.size() - 1; i >= 0; i--) {
-            if (equal(cols.get(i), col))
-                return true;
-        }
-
-        return false;
-    }
-
-    /**
-     * Check whether columns list contains key or key alias column.
-     *
-     * @param desc Row descriptor.
-     * @param cols Columns list.
-     * @return Result.
-     */
-    private static boolean containsKeyColumn(GridH2RowDescriptor desc, List<IndexColumn> cols) {
-        for (int i = cols.size() - 1; i >= 0; i--) {
-            if (desc.isKeyColumn(cols.get(i).column.getColumnId()))
-                return true;
-        }
-
-        return false;
-    }
-
-    /**
-     * @param desc Row descriptor.
-     * @param cols Columns list.
-     * @param keyCol Primary key column.
-     * @param affCol Affinity key column.
-     * @return The same list back.
-     */
-    private static List<IndexColumn> treeIndexColumns(GridH2RowDescriptor desc, List<IndexColumn> cols, IndexColumn keyCol, IndexColumn affCol) {
-        assert keyCol != null;
-
-        if (!containsKeyColumn(desc, cols))
-            cols.add(keyCol);
-
-        if (affCol != null && !containsColumn(cols, affCol))
-            cols.add(affCol);
-
-        return cols;
-    }
-
-
     /** {@inheritDoc} */
     @Override public Collection<GridRunningQueryInfo> runningQueries(long duration) {
         Collection<GridRunningQueryInfo> res = new ArrayList<>();
@@ -2862,1153 +2410,10 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
-     * Wrapper to store connection and flag is schema set or not.
+     * Closeable iterator.
      */
-    private static class ConnectionWrapper {
-        /** */
-        private Connection conn;
-
-        /** */
-        private volatile String schema;
-
-        /**
-         * @param conn Connection to use.
-         */
-        ConnectionWrapper(Connection conn) {
-            this.conn = conn;
-        }
-
-        /**
-         * @return Schema name if schema is set, null otherwise.
-         */
-        public String schema() {
-            return schema;
-        }
-
-        /**
-         * @param schema Schema name set on this connection.
-         */
-        public void schema(@Nullable String schema) {
-            this.schema = schema;
-        }
-
-        /**
-         * @return Connection.
-         */
-        public Connection connection() {
-            return conn;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String toString() {
-            return S.toString(ConnectionWrapper.class, this);
-        }
+    private interface ClIter<X> extends AutoCloseable, Iterator<X> {
+        // No-op.
     }
 
-    /**
-     * Enum that helps to map java types to database types.
-     */
-    private enum DBTypeEnum {
-        /** */
-        INT("INT"),
-
-        /** */
-        BOOL("BOOL"),
-
-        /** */
-        TINYINT("TINYINT"),
-
-        /** */
-        SMALLINT("SMALLINT"),
-
-        /** */
-        BIGINT("BIGINT"),
-
-        /** */
-        DECIMAL("DECIMAL"),
-
-        /** */
-        DOUBLE("DOUBLE"),
-
-        /** */
-        REAL("REAL"),
-
-        /** */
-        TIME("TIME"),
-
-        /** */
-        TIMESTAMP("TIMESTAMP"),
-
-        /** */
-        DATE("DATE"),
-
-        /** */
-        VARCHAR("VARCHAR"),
-
-        /** */
-        CHAR("CHAR"),
-
-        /** */
-        BINARY("BINARY"),
-
-        /** */
-        UUID("UUID"),
-
-        /** */
-        ARRAY("ARRAY"),
-
-        /** */
-        GEOMETRY("GEOMETRY"),
-
-        /** */
-        OTHER("OTHER");
-
-        /** Map of Class to enum. */
-        private static final Map<Class<?>, DBTypeEnum> map = new HashMap<>();
-
-        /**
-         * Initialize map of DB types.
-         */
-        static {
-            map.put(int.class, INT);
-            map.put(Integer.class, INT);
-            map.put(boolean.class, BOOL);
-            map.put(Boolean.class, BOOL);
-            map.put(byte.class, TINYINT);
-            map.put(Byte.class, TINYINT);
-            map.put(short.class, SMALLINT);
-            map.put(Short.class, SMALLINT);
-            map.put(long.class, BIGINT);
-            map.put(Long.class, BIGINT);
-            map.put(BigDecimal.class, DECIMAL);
-            map.put(double.class, DOUBLE);
-            map.put(Double.class, DOUBLE);
-            map.put(float.class, REAL);
-            map.put(Float.class, REAL);
-            map.put(Time.class, TIME);
-            map.put(Timestamp.class, TIMESTAMP);
-            map.put(java.util.Date.class, TIMESTAMP);
-            map.put(java.sql.Date.class, DATE);
-            map.put(String.class, VARCHAR);
-            map.put(UUID.class, UUID);
-            map.put(byte[].class, BINARY);
-        }
-
-        /** */
-        private final String dbType;
-
-        /**
-         * Constructs new instance.
-         *
-         * @param dbType DB type name.
-         */
-        DBTypeEnum(String dbType) {
-            this.dbType = dbType;
-        }
-
-        /**
-         * Resolves enum by class.
-         *
-         * @param cls Class.
-         * @return Enum value.
-         */
-        public static DBTypeEnum fromClass(Class<?> cls) {
-            DBTypeEnum res = map.get(cls);
-
-            if (res != null)
-                return res;
-
-            if (DataType.isGeometryClass(cls))
-                return GEOMETRY;
-
-            return cls.isArray() && !cls.getComponentType().isPrimitive() ? ARRAY : OTHER;
-        }
-
-        /**
-         * Gets DB type name.
-         *
-         * @return DB type name.
-         */
-        public String dBTypeAsString() {
-            return dbType;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String toString() {
-            return S.toString(DBTypeEnum.class, this);
-        }
-    }
-
-    /**
-     * Information about table in database.
-     */
-    private class TableDescriptor implements GridH2SystemIndexFactory {
-        /** */
-        private final String fullTblName;
-
-        /** */
-        private final GridQueryTypeDescriptor type;
-
-        /** */
-        private final Schema schema;
-
-        /** */
-        private GridH2Table tbl;
-
-        /** */
-        private GridLuceneIndex luceneIdx;
-
-        /** */
-        private H2PkHashIndex pkHashIdx;
-
-        /**
-         * @param schema Schema.
-         * @param type Type descriptor.
-         */
-        TableDescriptor(Schema schema, GridQueryTypeDescriptor type) {
-            this.type = type;
-            this.schema = schema;
-
-            String tblName = escapeName(type.tableName(), schema.escapeAll());
-
-            fullTblName = schema.schemaName + "." + tblName;
-        }
-
-        /**
-         * @return Schema name.
-         */
-        public String schemaName() {
-            return schema.schemaName;
-        }
-
-        /**
-         * @return Database full table name.
-         */
-        String fullTableName() {
-            return fullTblName;
-        }
-
-        /**
-         * @return type name.
-         */
-        String typeName() {
-            return type.name();
-        }
-
-        /**
-         * @return Type.
-         */
-        GridQueryTypeDescriptor type() {
-            return type;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String toString() {
-            return S.toString(TableDescriptor.class, this);
-        }
-
-        /**
-         * Create H2 row factory.
-         *
-         * @param rowDesc Row descriptor.
-         * @return H2 row factory.
-         */
-        H2RowFactory rowFactory(GridH2RowDescriptor rowDesc) {
-            GridCacheContext cctx = schema.cacheContext();
-
-            if (cctx.affinityNode() && cctx.offheapIndex())
-                return new H2RowFactory(rowDesc, cctx);
-
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public ArrayList<Index> createSystemIndexes(GridH2Table tbl) {
-            ArrayList<Index> idxs = new ArrayList<>();
-
-            IndexColumn keyCol = tbl.indexColumn(KEY_COL, SortOrder.ASCENDING);
-            IndexColumn affCol = tbl.getAffinityKeyColumn();
-
-            if (affCol != null && equal(affCol, keyCol))
-                affCol = null;
-
-            GridH2RowDescriptor desc = tbl.rowDescriptor();
-
-            Index hashIdx = createHashIndex(
-                schema,
-                tbl,
-                "_key_PK_hash",
-                treeIndexColumns(desc, new ArrayList<IndexColumn>(2), keyCol, affCol)
-            );
-
-            if (hashIdx != null)
-                idxs.add(hashIdx);
-
-            // Add primary key index.
-            Index pkIdx = createSortedIndex(
-                schema,
-                "_key_PK",
-                tbl,
-                true,
-                treeIndexColumns(desc, new ArrayList<IndexColumn>(2), keyCol, affCol),
-                -1
-            );
-
-            idxs.add(pkIdx);
-
-            if (type().valueClass() == String.class) {
-                try {
-                    luceneIdx = new GridLuceneIndex(ctx, schema.offheap, schema.cacheName, type);
-                }
-                catch (IgniteCheckedException e1) {
-                    throw new IgniteException(e1);
-                }
-            }
-
-            boolean affIdxFound = false;
-
-            GridQueryIndexDescriptor textIdx = type.textIndex();
-
-            if (textIdx != null) {
-                try {
-                    luceneIdx = new GridLuceneIndex(ctx, schema.offheap, schema.cacheName, type);
-                }
-                catch (IgniteCheckedException e1) {
-                    throw new IgniteException(e1);
-                }
-            }
-
-            // Locate index where affinity column is first (if any).
-            if (affCol != null) {
-                for (GridQueryIndexDescriptor idxDesc : type.indexes().values()) {
-                    if (idxDesc.type() != QueryIndexType.SORTED)
-                        continue;
-
-                    String firstField = idxDesc.fields().iterator().next();
-
-                    String firstFieldName =
-                        schema.escapeAll() ? firstField : escapeName(firstField, false).toUpperCase();
-
-                    Column col = tbl.getColumn(firstFieldName);
-
-                    IndexColumn idxCol = tbl.indexColumn(col.getColumnId(),
-                        idxDesc.descending(firstField) ? SortOrder.DESCENDING : SortOrder.ASCENDING);
-
-                    affIdxFound |= equal(idxCol, affCol);
-                }
-            }
-
-            // Add explicit affinity key index if nothing alike was found.
-            if (affCol != null && !affIdxFound) {
-                idxs.add(createSortedIndex(schema, "AFFINITY_KEY", tbl, false,
-                    treeIndexColumns(desc, new ArrayList<IndexColumn>(2), affCol, keyCol), -1));
-            }
-
-            return idxs;
-        }
-
-        /**
-         * Get collection of user indexes.
-         *
-         * @return User indexes.
-         */
-        public Collection<GridH2IndexBase> createUserIndexes() {
-            assert tbl != null;
-
-            ArrayList<GridH2IndexBase> res = new ArrayList<>();
-
-            for (GridQueryIndexDescriptor idxDesc : type.indexes().values()) {
-                GridH2IndexBase idx = createUserIndex(idxDesc);
-
-                res.add(idx);
-            }
-
-            return res;
-        }
-
-        /**
-         * Create user index.
-         *
-         * @param idxDesc Index descriptor.
-         * @return Index.
-         */
-        private GridH2IndexBase createUserIndex(GridQueryIndexDescriptor idxDesc) {
-            String name = schema.escapeAll() ? idxDesc.name() : escapeName(idxDesc.name(), false).toUpperCase();
-
-            IndexColumn keyCol = tbl.indexColumn(KEY_COL, SortOrder.ASCENDING);
-            IndexColumn affCol = tbl.getAffinityKeyColumn();
-
-            List<IndexColumn> cols = new ArrayList<>(idxDesc.fields().size() + 2);
-
-            boolean escapeAll = schema.escapeAll();
-
-            for (String field : idxDesc.fields()) {
-                String fieldName = escapeAll ? field : escapeName(field, false).toUpperCase();
-
-                Column col = tbl.getColumn(fieldName);
-
-                cols.add(tbl.indexColumn(col.getColumnId(),
-                    idxDesc.descending(field) ? SortOrder.DESCENDING : SortOrder.ASCENDING));
-            }
-
-            GridH2RowDescriptor desc = tbl.rowDescriptor();
-            if (idxDesc.type() == QueryIndexType.SORTED) {
-                cols = treeIndexColumns(desc, cols, keyCol, affCol);
-                return createSortedIndex(schema, name, tbl, false, cols, idxDesc.inlineSize());
-            }
-            else if (idxDesc.type() == QueryIndexType.GEOSPATIAL) {
-                return createSpatialIndex(tbl, name, cols.toArray(new IndexColumn[cols.size()]));
-            }
-
-            throw new IllegalStateException("Index type: " + idxDesc.type());
-        }
-
-        /**
-         * Create hash index.
-         *
-         * @param schema Schema.
-         * @param tbl Table.
-         * @param idxName Index name.
-         * @param cols Columns.
-         * @return Index.
-         */
-        private Index createHashIndex(Schema schema, GridH2Table tbl, String idxName, List<IndexColumn> cols) {
-            GridCacheContext cctx = schema.cacheContext();
-
-            if (cctx.affinityNode() && cctx.offheapIndex()) {
-                assert pkHashIdx == null : pkHashIdx;
-
-                pkHashIdx = new H2PkHashIndex(cctx, tbl, idxName, cols);
-
-                return pkHashIdx;
-            }
-
-            return null;
-        }
-
-        /**
-         *
-         */
-        void onDrop() {
-            dataTables.remove(tbl.identifier(), tbl);
-
-            tbl.destroy();
-
-            U.closeQuiet(luceneIdx);
-        }
-    }
-
-    /**
-     * Special field set iterator based on database result set.
-     */
-    public static class FieldsIterator extends GridH2ResultSetIterator<List<?>> {
-        /** */
-        private static final long serialVersionUID = 0L;
-
-        /**
-         * @param data Data.
-         * @throws IgniteCheckedException If failed.
-         */
-        public FieldsIterator(ResultSet data) throws IgniteCheckedException {
-            super(data, false, true);
-        }
-
-        /** {@inheritDoc} */
-        @Override protected List<?> createRow() {
-            ArrayList<Object> res = new ArrayList<>(row.length);
-
-            Collections.addAll(res, row);
-
-            return res;
-        }
-    }
-
-    /**
-     * Special key/value iterator based on database result set.
-     */
-    private static class KeyValIterator<K, V> extends GridH2ResultSetIterator<IgniteBiTuple<K, V>> {
-        /** */
-        private static final long serialVersionUID = 0L;
-
-        /**
-         * @param data Data array.
-         * @throws IgniteCheckedException If failed.
-         */
-        protected KeyValIterator(ResultSet data) throws IgniteCheckedException {
-            super(data, false, true);
-        }
-
-        /** {@inheritDoc} */
-        @SuppressWarnings("unchecked")
-        @Override protected IgniteBiTuple<K, V> createRow() {
-            K key = (K)row[0];
-            V val = (V)row[1];
-
-            return new IgniteBiTuple<>(key, val);
-        }
-    }
-
-    /**
-     * Closeable iterator.
-     */
-    private interface ClIter<X> extends AutoCloseable, Iterator<X> {
-        // No-op.
-    }
-
-    /**
-     * Field descriptor.
-     */
-    static class SqlFieldMetadata implements GridQueryFieldMetadata {
-        /** */
-        private static final long serialVersionUID = 0L;
-
-        /** Schema name. */
-        private String schemaName;
-
-        /** Type name. */
-        private String typeName;
-
-        /** Name. */
-        private String name;
-
-        /** Type. */
-        private String type;
-
-        /**
-         * Required by {@link Externalizable}.
-         */
-        public SqlFieldMetadata() {
-            // No-op
-        }
-
-        /**
-         * @param schemaName Schema name.
-         * @param typeName Type name.
-         * @param name Name.
-         * @param type Type.
-         */
-        SqlFieldMetadata(@Nullable String schemaName, @Nullable String typeName, String name, String type) {
-            assert name != null && type != null : schemaName + " | " + typeName + " | " + name + " | " + type;
-
-            this.schemaName = schemaName;
-            this.typeName = typeName;
-            this.name = name;
-            this.type = type;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String schemaName() {
-            return schemaName;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String typeName() {
-            return typeName;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String fieldName() {
-            return name;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String fieldTypeName() {
-            return type;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void writeExternal(ObjectOutput out) throws IOException {
-            U.writeString(out, schemaName);
-            U.writeString(out, typeName);
-            U.writeString(out, name);
-            U.writeString(out, type);
-        }
-
-        /** {@inheritDoc} */
-        @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
-            schemaName = U.readString(in);
-            typeName = U.readString(in);
-            name = U.readString(in);
-            type = U.readString(in);
-        }
-
-        /** {@inheritDoc} */
-        @Override public String toString() {
-            return S.toString(SqlFieldMetadata.class, this);
-        }
-    }
-
-    /**
-     * Database schema object.
-     */
-    private class Schema {
-        /** */
-        private final String cacheName;
-
-        /** */
-        private final String schemaName;
-
-        /** */
-        private final GridUnsafeMemory offheap = null;
-
-        /** */
-        private final ConcurrentMap<String, TableDescriptor> tbls = new ConcurrentHashMap8<>();
-
-        /** Cache for deserialized offheap rows. */
-        private final CacheLongKeyLIRS<GridH2Row> rowCache;
-
-        /** */
-        private final GridCacheContext<?, ?> cctx;
-
-        /** */
-        private final CacheConfiguration<?, ?> ccfg;
-
-        /**
-         * @param cacheName Cache name.
-         * @param schemaName Schema name.
-         * @param cctx Cache context.
-         * @param ccfg Cache configuration.
-         */
-        private Schema(String cacheName, String schemaName, GridCacheContext<?, ?> cctx,
-            CacheConfiguration<?, ?> ccfg) {
-            this.cacheName = cacheName;
-            this.cctx = cctx;
-            this.schemaName = schemaName;
-            this.ccfg = ccfg;
-
-            rowCache = null;
-        }
-
-        /**
-         * @return Cache context.
-         */
-        public GridCacheContext cacheContext() {
-            return cctx;
-        }
-
-        /**
-         * @param tbl Table descriptor.
-         */
-        public void add(TableDescriptor tbl) {
-            if (tbls.putIfAbsent(tbl.typeName(), tbl) != null)
-                throw new IllegalStateException("Table already registered: " + tbl.fullTableName());
-        }
-
-        /**
-         * @return Escape all.
-         */
-        public boolean escapeAll() {
-            return ccfg.isSqlEscapeAll();
-        }
-
-        /**
-         * Called after the schema was dropped.
-         */
-        public void onDrop() {
-            for (TableDescriptor tblDesc : tbls.values())
-                tblDesc.onDrop();
-        }
-    }
-
-    /**
-     * Row descriptor.
-     */
-    private class RowDescriptor implements GridH2RowDescriptor {
-        /** */
-        private final GridQueryTypeDescriptor type;
-
-        /** */
-        private final String[] fields;
-
-        /** */
-        private final int[] fieldTypes;
-
-        /** */
-        private final int keyType;
-
-        /** */
-        private final int valType;
-
-        /** */
-        private final Schema schema;
-
-        /** */
-        private final GridUnsafeGuard guard;
-
-        /** */
-        private final boolean snapshotableIdx;
-
-        /** */
-        private final GridQueryProperty[] props;
-
-        /** Id of user-defined key column */
-        private final int keyAliasColumnId;
-
-        /** Id of user-defined value column */
-        private final int valueAliasColumnId;
-
-        /**
-         * @param type Type descriptor.
-         * @param schema Schema.
-         */
-        RowDescriptor(GridQueryTypeDescriptor type, Schema schema) {
-            assert type != null;
-            assert schema != null;
-
-            this.type = type;
-            this.schema = schema;
-
-            guard = schema.offheap == null ? null : new GridUnsafeGuard();
-
-            Map<String, Class<?>> allFields = new LinkedHashMap<>();
-
-            allFields.putAll(type.fields());
-
-            fields = allFields.keySet().toArray(new String[allFields.size()]);
-
-            fieldTypes = new int[fields.length];
-
-            Class[] classes = allFields.values().toArray(new Class[fields.length]);
-
-            for (int i = 0; i < fieldTypes.length; i++)
-                fieldTypes[i] = DataType.getTypeFromClass(classes[i]);
-
-            keyType = DataType.getTypeFromClass(type.keyClass());
-            valType = DataType.getTypeFromClass(type.valueClass());
-
-            props = new GridQueryProperty[fields.length];
-
-            for (int i = 0; i < fields.length; i++) {
-                GridQueryProperty p = type.property(fields[i]);
-
-                assert p != null : fields[i];
-
-                props[i] = p;
-            }
-
-            final List<String> fieldsList = Arrays.asList(fields);
-            keyAliasColumnId = (type.keyFieldName() != null) ? DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.keyFieldName()) : -1;
-            valueAliasColumnId = (type.valueFieldName() != null) ? DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.valueFieldName()) : -1;
-
-            // Index is not snapshotable in db-x.
-            snapshotableIdx = false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgniteH2Indexing indexing() {
-            return IgniteH2Indexing.this;
-        }
-
-        /** {@inheritDoc} */
-        @Override public GridQueryTypeDescriptor type() {
-            return type;
-        }
-
-        /** {@inheritDoc} */
-        @Override public GridCacheContext<?, ?> context() {
-            return schema.cacheContext();
-        }
-
-        /** {@inheritDoc} */
-        @Override public CacheConfiguration configuration() {
-            return schema.ccfg;
-        }
-
-        /** {@inheritDoc} */
-        @Override public GridUnsafeGuard guard() {
-            return guard;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void cache(GridH2Row row) {
-            long ptr = row.pointer();
-
-            assert ptr > 0 : ptr;
-
-            schema.rowCache.put(ptr, row);
-        }
-
-        /** {@inheritDoc} */
-        @Override public void uncache(long ptr) {
-            schema.rowCache.remove(ptr);
-        }
-
-        /** {@inheritDoc} */
-        @Override public GridUnsafeMemory memory() {
-            return schema.offheap;
-        }
-
-        /** {@inheritDoc} */
-        @Override public Value wrap(Object obj, int type) throws IgniteCheckedException {
-            assert obj != null;
-
-            if (obj instanceof CacheObject) { // Handle cache object.
-                CacheObject co = (CacheObject)obj;
-
-                if (type == Value.JAVA_OBJECT)
-                    return new GridH2ValueCacheObject(cacheContext(schema.cacheName), co);
-
-                obj = co.value(objectContext(schema.cacheName), false);
-            }
-
-            switch (type) {
-                case Value.BOOLEAN:
-                    return ValueBoolean.get((Boolean)obj);
-                case Value.BYTE:
-                    return ValueByte.get((Byte)obj);
-                case Value.SHORT:
-                    return ValueShort.get((Short)obj);
-                case Value.INT:
-                    return ValueInt.get((Integer)obj);
-                case Value.FLOAT:
-                    return ValueFloat.get((Float)obj);
-                case Value.LONG:
-                    return ValueLong.get((Long)obj);
-                case Value.DOUBLE:
-                    return ValueDouble.get((Double)obj);
-                case Value.UUID:
-                    UUID uuid = (UUID)obj;
-                    return ValueUuid.get(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
-                case Value.DATE:
-                    return ValueDate.get((Date)obj);
-                case Value.TIME:
-                    return ValueTime.get((Time)obj);
-                case Value.TIMESTAMP:
-                    if (obj instanceof java.util.Date && !(obj instanceof Timestamp))
-                        obj = new Timestamp(((java.util.Date)obj).getTime());
-
-                    return ValueTimestamp.get((Timestamp)obj);
-                case Value.DECIMAL:
-                    return ValueDecimal.get((BigDecimal)obj);
-                case Val

<TRUNCATED>

[02/31] ignite git commit: IGNITE-4947 - Move to Ignite 2.0 test suites - Fixes #1986.

Posted by sb...@apache.org.
IGNITE-4947 - Move to Ignite 2.0 test suites - Fixes #1986.

Signed-off-by: Alexey Goncharuk <al...@gmail.com>


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/98a1758d
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/98a1758d
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/98a1758d

Branch: refs/heads/ignite-5075
Commit: 98a1758d438060357d3d370ee797e6b6197664a3
Parents: ca94cf3
Author: dpavlov <dp...@gridgain.com>
Authored: Tue May 23 10:10:04 2017 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue May 23 10:10:04 2017 +0300

----------------------------------------------------------------------
 examples/config/filesystem/example-igfs.xml     |   4 +
 modules/clients/src/test/config/jdbc-config.xml |   6 -
 .../internal/jdbc2/JdbcMetadataSelfTest.java    |   5 +-
 .../internal/jdbc2/JdbcResultSetSelfTest.java   |  24 ++--
 .../ignite/jdbc/JdbcMetadataSelfTest.java       |   4 +-
 .../ignite/jdbc/JdbcResultSetSelfTest.java      | 121 +++++++++++++++----
 .../apache/ignite/IgniteSystemProperties.java   |   2 +-
 .../ignite/binary/BinaryBasicNameMapper.java    |   2 +-
 .../apache/ignite/internal/IgniteKernal.java    |   2 +-
 .../internal/binary/BinaryClassDescriptor.java  |   1 +
 .../ignite/internal/binary/BinaryContext.java   |  58 ++++-----
 .../GridClientOptimizedMarshaller.java          |   2 +-
 .../GridClientZipOptimizedMarshaller.java       |   2 +-
 .../optimized/OptimizedClassDescriptor.java     |   2 +-
 .../optimized/OptimizedMarshaller.java          |   2 +-
 .../marshaller/optimized/package-info.java      |  22 ++++
 .../apache/ignite/marshaller/Marshaller.java    |   3 -
 .../ignite/marshaller/jdk/JdkMarshaller.java    |   5 +-
 modules/core/src/test/config/example-cache.xml  |   5 +-
 .../src/test/config/spring-start-nodes-attr.xml |   4 +-
 .../core/src/test/config/spring-start-nodes.xml |   4 +-
 .../config/websession/example-cache-base.xml    |   5 +-
 .../IgniteExternalizableAbstractTest.java       |  15 +--
 ...dbcPojoStoreOptimizedMarshallerSelfTest.java |  31 -----
 ...ptimizedMarshallerWithSqlEscapeSelfTest.java |  28 -----
 .../apache/ignite/igfs/IgfsPathSelfTest.java    |   7 +-
 .../internal/GridLifecycleAwareSelfTest.java    |   3 +-
 .../BinarySimpleNameTestPropertySelfTest.java   |  17 +++
 .../managers/GridManagerStopSelfTest.java       |   3 +-
 .../GridDiscoveryManagerAttributesSelfTest.java |   2 +-
 .../optimized/OptimizedMarshallerTest.java      |   8 ++
 .../marshaller/optimized/package-info.java      |  22 ++++
 .../CacheStartupInDeploymentModesTest.java      |  37 ------
 .../cache/GridCacheEntryMemorySizeSelfTest.java |   2 +-
 ...ridCacheStoreManagerDeserializationTest.java |   4 +-
 .../cache/GridCacheVersionSelfTest.java         |   7 +-
 .../distributed/CacheAffinityEarlyTest.java     |   7 +-
 .../CacheGetFutureHangsSelfTest.java            |   6 +-
 .../IgniteCacheCreatePutMultiNodeSelfTest.java  |   7 +-
 .../distributed/IgniteCacheCreatePutTest.java   |   7 +-
 .../IgniteCachePartitionLossPolicySelfTest.java |   1 +
 .../CacheEntryProcessorNonSerializableTest.java |   5 +-
 .../igfs/IgfsAbstractBaseSelfTest.java          |  10 --
 .../processors/igfs/IgfsFileInfoSelfTest.java   |  16 ++-
 .../IgfsPrimaryOptimziedMarshallerSelfTest.java |  28 -----
 .../service/ClosureServiceClientsNodesTest.java |   4 +-
 ...namicProxySerializationMultiJvmSelfTest.java |  13 --
 .../GridMarshallerPerformanceTest.java          |   8 +-
 .../IgniteMessagingWithClientTest.java          |   4 +-
 ...pClientDiscoveryMarshallerCheckSelfTest.java |   4 +-
 .../TcpDiscoveryMarshallerCheckSelfTest.java    |   4 +-
 .../config/GridTestProperties.java              |   3 +-
 .../configvariations/ConfigVariations.java      |  14 +--
 .../testframework/junits/GridAbstractTest.java  |  33 +++++
 .../junits/IgniteTestResources.java             |   8 +-
 ...naryObjectsTxDeadlockDetectionTestSuite.java |  37 ------
 .../testsuites/IgniteBinaryBasicTestSuite.java  |  14 +--
 .../IgniteBinaryCacheFullApiTestSuite.java      |  37 ------
 .../testsuites/IgniteBinaryCacheTestSuite.java  |   4 -
 ...ObjectsCacheDataStructuresSelfTestSuite.java |  42 -------
 ...BinaryObjectsCacheExpiryPolicyTestSuite.java |  38 ------
 ...gniteBinaryObjectsCacheRestartTestSuite.java |  37 ------
 .../IgniteBinaryObjectsCacheTestSuite2.java     |  37 ------
 .../IgniteBinaryObjectsCacheTestSuite3.java     |   2 -
 .../IgniteBinaryObjectsCacheTestSuite4.java     |  37 ------
 ...IgniteBinaryObjectsComputeGridTestSuite.java |   4 -
 .../ignite/testsuites/IgniteCacheTestSuite.java |   4 -
 ...teBasicConfigVariationsFullApiTestSuite.java |   2 +-
 .../ignite/testsuites/IgniteIgfsTestSuite.java  |   3 -
 .../testsuites/IgniteKernalSelfTestSuite.java   |   4 -
 .../IgniteMarshallerSelfTestSuite.java          |   8 +-
 ...essagingConfigVariationFullApiTestSuite.java |   2 +-
 ...ServiceConfigVariationsFullApiTestSuite.java |   2 +-
 .../webapp/META-INF/ignite-webapp-config.xml    |  15 +--
 .../test/config/hadoop-fs-open-test/grid-0.xml  |   3 +-
 .../test/config/hadoop-fs-open-test/grid-1.xml  |   3 +-
 .../test/config/hadoop-fs-open-test/grid-2.xml  |   3 +-
 .../test/config/igfs-cli-config-dual-async.xml  |   3 +-
 .../test/config/igfs-cli-config-dual-sync.xml   |   3 +-
 .../src/test/config/igfs-cli-config-primary.xml |   3 +-
 .../src/test/config/igfs-cli-config-proxy.xml   |   3 +-
 .../IgniteHadoopFileSystemAbstractSelfTest.java |   4 +-
 .../cache/IgniteCacheNoClassQuerySelfTest.java  |   4 +-
 .../h2/sql/AbstractH2CompareQueryTest.java      |   4 +-
 .../FetchingQueryCursorStressTest.java          |   4 +-
 .../IgniteBinaryCacheQueryTestSuite.java        |   4 -
 .../IgniteBinaryCacheQueryTestSuite2.java       |   4 -
 .../IgniteBinaryCacheQueryTestSuite3.java       |  39 ------
 .../IgniteBinaryCacheQueryTestSuite4.java       |  39 ------
 .../Apache.Ignite.Core.Tests/MarshallerTest.cs  |   2 +-
 .../GridSpringBeanSerializationSelfTest.java    |  15 ++-
 .../webapp2/META-INF/ignite-webapp-config.xml   |  15 +--
 .../ignite-int-max-values-onheap-config.xml     |   4 +-
 modules/yardstick/config/ignite-jdbc-config.xml |   4 +-
 94 files changed, 376 insertions(+), 769 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/examples/config/filesystem/example-igfs.xml
----------------------------------------------------------------------
diff --git a/examples/config/filesystem/example-igfs.xml b/examples/config/filesystem/example-igfs.xml
index 454dc9f..9e45450 100644
--- a/examples/config/filesystem/example-igfs.xml
+++ b/examples/config/filesystem/example-igfs.xml
@@ -50,6 +50,10 @@
         Configuration below demonstrates how to setup a IgniteFs node with file data.
     -->
     <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
+        <property name="marshaller">
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
+        </property>
+
         <property name="fileSystemConfiguration">
             <list>
                 <bean class="org.apache.ignite.configuration.FileSystemConfiguration">

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/clients/src/test/config/jdbc-config.xml
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/config/jdbc-config.xml b/modules/clients/src/test/config/jdbc-config.xml
index 7bba410..b05fe64 100644
--- a/modules/clients/src/test/config/jdbc-config.xml
+++ b/modules/clients/src/test/config/jdbc-config.xml
@@ -31,12 +31,6 @@
 
         <property name="localHost" value="127.0.0.1"/>
 
-        <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <property name="requireSerializable" value="false"/>
-            </bean>
-        </property>
-
         <property name="discoverySpi">
             <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                 <property name="ipFinder">

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcMetadataSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcMetadataSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcMetadataSelfTest.java
index e382b9d..736e343 100755
--- a/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcMetadataSelfTest.java
+++ b/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcMetadataSelfTest.java
@@ -32,6 +32,7 @@ import org.apache.ignite.cache.query.annotations.QuerySqlField;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.ConnectorConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -40,7 +41,6 @@ import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 import org.jetbrains.annotations.NotNull;
 
 import static java.sql.Types.INTEGER;
-import static java.sql.Types.OTHER;
 import static java.sql.Types.VARCHAR;
 import static org.apache.ignite.IgniteJdbcDriver.CFG_URL_PREFIX;
 import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
@@ -192,6 +192,7 @@ public class JdbcMetadataSelfTest extends GridCommonAbstractTest {
      * @throws Exception If failed.
      */
     public void testGetColumns() throws Exception {
+        final boolean primitivesInformationIsLostAfterStore = ignite(0).configuration().getMarshaller() instanceof BinaryMarshaller;
         try (Connection conn = DriverManager.getConnection(BASE_URL)) {
             DatabaseMetaData meta = conn.getMetaData();
 
@@ -219,7 +220,7 @@ public class JdbcMetadataSelfTest extends GridCommonAbstractTest {
                 } else if ("AGE".equals(name) || "ORGID".equals(name)) {
                     assertEquals(INTEGER, rs.getInt("DATA_TYPE"));
                     assertEquals("INTEGER", rs.getString("TYPE_NAME"));
-                    assertEquals(0, rs.getInt("NULLABLE"));
+                    assertEquals(primitivesInformationIsLostAfterStore ? 1 : 0, rs.getInt("NULLABLE"));
                 }
 
                 cnt++;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcResultSetSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcResultSetSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcResultSetSelfTest.java
index 43cd586..54514c7 100644
--- a/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcResultSetSelfTest.java
+++ b/modules/clients/src/test/java/org/apache/ignite/internal/jdbc2/JdbcResultSetSelfTest.java
@@ -30,11 +30,15 @@ import java.sql.Time;
 import java.sql.Timestamp;
 import java.util.Arrays;
 import java.util.concurrent.Callable;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteBinary;
 import org.apache.ignite.IgniteCache;
 import org.apache.ignite.cache.query.annotations.QuerySqlField;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.ConnectorConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -45,6 +49,7 @@ import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 import static org.apache.ignite.IgniteJdbcDriver.CFG_URL_PREFIX;
 import static org.apache.ignite.cache.CacheMode.PARTITIONED;
 import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+import static org.apache.ignite.jdbc.JdbcResultSetSelfTest.assertEqualsToStringRepresentation;
 
 /**
  * Result set test.
@@ -509,6 +514,9 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
      * @throws Exception If failed.
      */
     public void testObject() throws Exception {
+        final Ignite ignite = ignite(0);
+        final boolean binaryMarshaller = ignite.configuration().getMarshaller() instanceof BinaryMarshaller;
+        final IgniteBinary binary = binaryMarshaller ? ignite.binary() : null;
         ResultSet rs = stmt.executeQuery(SQL);
 
         TestObjectField f1 = new TestObjectField(100, "AAAA");
@@ -518,19 +526,19 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
 
         assertTrue(rs.next());
 
-        assertEquals(f1.toString(), rs.getObject("f1"));
-        assertEquals(f1.toString(), rs.getObject(16));
+        assertEqualsToStringRepresentation(f1, binary, rs.getObject("f1"));
+        assertEqualsToStringRepresentation(f1, binary, rs.getObject(16));
 
-        assertEquals(f2.toString(), rs.getObject("f2"));
-        assertEquals(f2.toString(), rs.getObject(17));
+        assertEqualsToStringRepresentation(f2, binary, rs.getObject("f2"));
+        assertEqualsToStringRepresentation(f2, binary, rs.getObject(17));
 
         assertNull(rs.getObject("f3"));
         assertTrue(rs.wasNull());
         assertNull(rs.getObject(18));
         assertTrue(rs.wasNull());
 
-        assertEquals(o.toString(), rs.getObject("_val"));
-        assertEquals(o.toString(), rs.getObject(19));
+        assertEqualsToStringRepresentation(o, binary, rs.getObject("_val"));
+        assertEqualsToStringRepresentation(o, binary, rs.getObject(19));
 
         assertFalse(rs.next());
     }
@@ -815,10 +823,10 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
     @SuppressWarnings("PackageVisibleField")
     private static class TestObjectField implements Serializable {
         /** */
-        final int a;
+        @GridToStringInclude final int a;
 
         /** */
-        final String b;
+        @GridToStringInclude final String b;
 
         /**
          * @param a A.

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcMetadataSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcMetadataSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcMetadataSelfTest.java
index a02f489..be148c4 100644
--- a/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcMetadataSelfTest.java
+++ b/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcMetadataSelfTest.java
@@ -32,6 +32,7 @@ import org.apache.ignite.cache.query.annotations.QuerySqlField;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.ConnectorConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -183,6 +184,7 @@ public class JdbcMetadataSelfTest extends GridCommonAbstractTest {
      * @throws Exception If failed.
      */
     public void testGetColumns() throws Exception {
+        final boolean primitivesInformationIsLostAfterStore = ignite(0).configuration().getMarshaller() instanceof BinaryMarshaller;
         try (Connection conn = DriverManager.getConnection(URL)) {
             DatabaseMetaData meta = conn.getMetaData();
 
@@ -210,7 +212,7 @@ public class JdbcMetadataSelfTest extends GridCommonAbstractTest {
                 } else if ("AGE".equals(name) || "ORGID".equals(name)) {
                     assert rs.getInt("DATA_TYPE") == INTEGER;
                     assert "INTEGER".equals(rs.getString("TYPE_NAME"));
-                    assert rs.getInt("NULLABLE") == 0;
+                    assert rs.getInt("NULLABLE") == (primitivesInformationIsLostAfterStore ? 1 : 0);
                 }
                 if ("_KEY".equals(name)) {
                     assert rs.getInt("DATA_TYPE") == OTHER;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcResultSetSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcResultSetSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcResultSetSelfTest.java
index 140ff36..2dac8b7 100644
--- a/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcResultSetSelfTest.java
+++ b/modules/clients/src/test/java/org/apache/ignite/jdbc/JdbcResultSetSelfTest.java
@@ -17,30 +17,33 @@
 
 package org.apache.ignite.jdbc;
 
-import java.io.Serializable;
-import java.math.BigDecimal;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.sql.Date;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.concurrent.Callable;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteBinary;
 import org.apache.ignite.IgniteCache;
+import org.apache.ignite.binary.BinaryObject;
 import org.apache.ignite.cache.query.annotations.QuerySqlField;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.ConnectorConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
 import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.math.BigDecimal;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.sql.*;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.concurrent.Callable;
 
 import static org.apache.ignite.cache.CacheMode.PARTITIONED;
 import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
@@ -69,7 +72,7 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
     @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
         IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
 
-        CacheConfiguration<?,?> cache = defaultCacheConfiguration();
+        CacheConfiguration<?, ?> cache = defaultCacheConfiguration();
 
         cache.setCacheMode(PARTITIONED);
         cache.setBackups(1);
@@ -440,9 +443,82 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
     }
 
     /**
+     * This does extended toString compare. <br> Actual toString in case binary is enabled is called at {@link
+     * org.apache.ignite.internal.processors.cache.query.jdbc.GridCacheQueryJdbcTask.JdbcDriverJob#execute()},  <br>
+     * org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcTask.java:312 <br> and then strings are
+     * compared in assertions <p> And for binary marshaller result of such BinaryObjectImpl.toString will be unexpected
+     * by this test: <br> <code>org.apache.ignite.jdbc.JdbcResultSetSelfTest$TestObjectField [idHash=1624306582,
+     * hash=11433031, a=100, b=AAAA]</code> <br>
+     *
+     * @param originalObj object initially placed to cache
+     * @param binary optional parameter, if absent, direct toString compare is used
+     * @param resSetObj object returned by result set
+     */
+    public static void assertEqualsToStringRepresentation(
+        final Object originalObj,
+        @Nullable final IgniteBinary binary,
+        final Object resSetObj) {
+        if (binary != null) {
+            final BinaryObject origObjAsBinary = binary.toBinary(originalObj);
+            final String strFromResSet = Objects.toString(resSetObj);
+            for (Field declaredField : originalObj.getClass().getDeclaredFields()) {
+                checkFieldPresenceInToString(origObjAsBinary, strFromResSet, declaredField.getName());
+            }
+        }
+        else
+            assertEquals(originalObj.toString(), Objects.toString(resSetObj));
+    }
+
+    /**
+     * Checks particular field from original binary object
+     *
+     * @param original binary object representation of original object
+     * @param strToCheck string from result set, to be checked for presence of all fields
+     * @param fieldName field name have being checked
+     */
+    private static void checkFieldPresenceInToString(final BinaryObject original,
+        final String strToCheck,
+        final String fieldName) {
+
+        final Object fieldVal = original.field(fieldName);
+        String strValToSearch = Objects.toString(fieldVal);
+        if (fieldVal != null) {
+            final Class<?> aCls = fieldVal.getClass();
+            if (aCls.isArray()) {
+                final Class<?> elemCls = aCls.getComponentType();
+                if (elemCls == Byte.TYPE)
+                    strValToSearch = Arrays.toString((byte[])fieldVal);
+            }
+            else if (BinaryObject.class.isAssignableFrom(aCls)) {
+                // hack to avoid search of unpredictable toString representation like
+                // JdbcResultSetSelfTest$TestObjectField [idHash=1518952510, hash=11433031, a=100, b=AAAA]
+                // in toString
+                // other way to fix: iterate on binary object fields: final BinaryObject binVal = (BinaryObject)fieldVal;
+                strValToSearch = "";
+            }
+        }
+        assertTrue("Expected to find field "
+                + fieldName + " having value " + strValToSearch
+                + " in toString representation [" + strToCheck + "]",
+            strToCheck.contains(fieldName + "=" + strValToSearch));
+    }
+
+    /**
+     * @param str initial toString representation from binary object
+     * @return same representation with removed ID hash value
+     */
+    private static String removeIdHash(String str) {
+        return str.replaceAll("idHash=(\\d)*", "idHash=...");
+    }
+
+    /**
      * @throws Exception If failed.
      */
     public void testObject() throws Exception {
+        final Ignite ignite = ignite(0);
+        final boolean binaryMarshaller = ignite.configuration().getMarshaller() instanceof BinaryMarshaller;
+        final IgniteBinary binary = binaryMarshaller ? ignite.binary() : null;
+
         ResultSet rs = stmt.executeQuery(SQL);
 
         TestObjectField f1 = new TestObjectField(100, "AAAA");
@@ -451,20 +527,19 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
         TestObject o = createObjectWithData(1);
 
         assertTrue(rs.next());
+        assertEqualsToStringRepresentation(f1, binary, rs.getObject("f1"));
+        assertEqualsToStringRepresentation(f1, binary, rs.getObject(16));
 
-        assertEquals(f1.toString(), rs.getObject("f1"));
-        assertEquals(f1.toString(), rs.getObject(16));
-
-        assertEquals(f2.toString(), rs.getObject("f2"));
-        assertEquals(f2.toString(), rs.getObject(17));
+        assertEqualsToStringRepresentation(f2, binary, rs.getObject("f2"));
+        assertEqualsToStringRepresentation(f2, binary, rs.getObject(17));
 
         assertNull(rs.getObject("f3"));
         assertTrue(rs.wasNull());
         assertNull(rs.getObject(18));
         assertTrue(rs.wasNull());
 
-        assertEquals(o.toString(), rs.getObject("_val"));
-        assertEquals(o.toString(), rs.getObject(19));
+        assertEqualsToStringRepresentation(o, binary, rs.getObject("_val"));
+        assertEqualsToStringRepresentation(o, binary, rs.getObject(19));
 
         assertFalse(rs.next());
     }
@@ -684,10 +759,10 @@ public class JdbcResultSetSelfTest extends GridCommonAbstractTest {
     @SuppressWarnings("PackageVisibleField")
     private static class TestObjectField implements Serializable {
         /** */
-        final int a;
+        @GridToStringInclude final int a;
 
         /** */
-        final String b;
+        @GridToStringInclude final String b;
 
         /**
          * @param a A.

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
index d48b1c7..75fa3f0 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
@@ -23,8 +23,8 @@ import java.util.Iterator;
 import java.util.Map;
 import java.util.Properties;
 import javax.net.ssl.HostnameVerifier;
-import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.lang.IgnitePredicate;
 import org.jetbrains.annotations.Nullable;
 
 /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/binary/BinaryBasicNameMapper.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/binary/BinaryBasicNameMapper.java b/modules/core/src/main/java/org/apache/ignite/binary/BinaryBasicNameMapper.java
index 156716c..697108f 100644
--- a/modules/core/src/main/java/org/apache/ignite/binary/BinaryBasicNameMapper.java
+++ b/modules/core/src/main/java/org/apache/ignite/binary/BinaryBasicNameMapper.java
@@ -37,7 +37,7 @@ public class BinaryBasicNameMapper implements BinaryNameMapper {
     }
 
     /**
-     * @param isSimpleName Whether to use simple name of class or not.
+     * @param isSimpleName Whether to use simple (no package) name of class or not.
      * <p>
      * Defaults to {@link #DFLT_SIMPLE_NAME}.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
index 2c8c964..40476a7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
@@ -100,6 +100,7 @@ import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager;
 import org.apache.ignite.internal.managers.failover.GridFailoverManager;
 import org.apache.ignite.internal.managers.indexing.GridIndexingManager;
 import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.internal.processors.GridProcessor;
 import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor;
 import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
@@ -169,7 +170,6 @@ import org.apache.ignite.lifecycle.LifecycleAware;
 import org.apache.ignite.lifecycle.LifecycleBean;
 import org.apache.ignite.lifecycle.LifecycleEventType;
 import org.apache.ignite.marshaller.MarshallerExclusions;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.mxbean.ClusterLocalNodeMetricsMXBean;
 import org.apache.ignite.mxbean.IgniteMXBean;
 import org.apache.ignite.mxbean.StripedExecutorMXBean;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryClassDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryClassDescriptor.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryClassDescriptor.java
index f6e637f..7194f49 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryClassDescriptor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryClassDescriptor.java
@@ -40,6 +40,7 @@ import org.apache.ignite.binary.BinaryObjectException;
 import org.apache.ignite.binary.BinaryReflectiveSerializer;
 import org.apache.ignite.binary.BinarySerializer;
 import org.apache.ignite.binary.Binarylizable;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.internal.processors.cache.CacheObjectImpl;
 import org.apache.ignite.internal.processors.query.QueryUtils;
 import org.apache.ignite.internal.util.GridUnsafe;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
index f339253..da46496 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
@@ -17,6 +17,34 @@
 
 package org.apache.ignite.internal.binary;
 
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.math.BigDecimal;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentMap;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
@@ -36,6 +64,7 @@ import org.apache.ignite.cache.affinity.AffinityKeyMapped;
 import org.apache.ignite.configuration.BinaryConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.igfs.IgfsPath;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.internal.processors.cache.binary.BinaryMetadataKey;
 import org.apache.ignite.internal.processors.closure.GridClosureProcessor;
 import org.apache.ignite.internal.processors.datastructures.CollocatedQueueItemKey;
@@ -91,35 +120,6 @@ import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.math.BigDecimal;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentMap;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-
 import static org.apache.ignite.internal.MarshallerPlatformIds.JAVA_ID;
 
 /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientOptimizedMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientOptimizedMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientOptimizedMarshaller.java
index 75f1807..257b34c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientOptimizedMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientOptimizedMarshaller.java
@@ -24,9 +24,9 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.internal.MarshallerContextImpl;
 import org.apache.ignite.internal.client.marshaller.GridClientMarshaller;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.internal.processors.rest.client.message.GridClientMessage;
 import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.plugin.PluginProvider;
 import org.jetbrains.annotations.Nullable;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientZipOptimizedMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientZipOptimizedMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientZipOptimizedMarshaller.java
index bc8220f..8865b2d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientZipOptimizedMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientZipOptimizedMarshaller.java
@@ -26,9 +26,9 @@ import java.util.List;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipInputStream;
 import java.util.zip.ZipOutputStream;
-
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.client.marshaller.GridClientMarshaller;
+import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.internal.processors.rest.client.message.GridClientMessage;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedClassDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedClassDescriptor.java b/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedClassDescriptor.java
index 4c0ce17..ccd9946 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedClassDescriptor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedClassDescriptor.java
@@ -47,11 +47,11 @@ import java.util.UUID;
 import java.util.concurrent.ConcurrentMap;
 
 import org.apache.ignite.internal.util.GridUnsafe;
+import org.apache.ignite.internal.util.SerializableTransient;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.marshaller.MarshallerContext;
 import org.apache.ignite.marshaller.MarshallerExclusions;
-import org.apache.ignite.internal.util.SerializableTransient;
 import org.apache.ignite.marshaller.MarshallerUtils;
 
 import static java.lang.reflect.Modifier.isFinal;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshaller.java
index 575c9a4..0a54be2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshaller.java
@@ -70,7 +70,7 @@ import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALL
  * &lt;bean id="grid.custom.cfg" class="org.apache.ignite.configuration.IgniteConfiguration" singleton="true"&gt;
  *     ...
  *     &lt;property name="marshaller"&gt;
- *         &lt;bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller"&gt;
+ *         &lt;bean class="OptimizedMarshaller"&gt;
  *             &lt;property name="requireSerializable"&gt;true&lt;/property&gt;
  *         &lt;/bean&gt;
  *     &lt;/property&gt;

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/package-info.java b/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/package-info.java
new file mode 100644
index 0000000..7f58f9c
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/marshaller/optimized/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Contains Optimized marshaller.
+ */
+package org.apache.ignite.internal.marshaller.optimized;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/marshaller/Marshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/Marshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/Marshaller.java
index 8ffeacd..3ab27ac 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/Marshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/Marshaller.java
@@ -19,10 +19,8 @@ package org.apache.ignite.marshaller;
 
 import java.io.InputStream;
 import java.io.OutputStream;
-
 import org.apache.ignite.IgniteBinary;
 import org.apache.ignite.IgniteCheckedException;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -34,7 +32,6 @@ import org.jetbrains.annotations.Nullable;
  * <ul>
  * <li>Default binary marshaller. Will be used when no other marshaller is explicitly set to the
  * configuration. For more information, see {@link IgniteBinary}.</li>
- * <li>{@link OptimizedMarshaller}</li>
  * <li>{@link org.apache.ignite.marshaller.jdk.JdkMarshaller}</li>
  * </ul>
  * <p>

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
index 8c27841..6759c40 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
@@ -21,8 +21,8 @@ import java.io.InputStream;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.OutputStream;
+import org.apache.ignite.IgniteBinary;
 import org.apache.ignite.IgniteCheckedException;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.internal.util.io.GridByteArrayInputStream;
 import org.apache.ignite.internal.util.io.GridByteArrayOutputStream;
 import org.apache.ignite.internal.util.typedef.internal.S;
@@ -37,7 +37,8 @@ import org.jetbrains.annotations.Nullable;
  * <h2 class="header">Mandatory</h2>
  * This marshaller has no mandatory configuration parameters.
  * <h2 class="header">Java Example</h2>
- * {@code JdkMarshaller} needs to be explicitly configured to override default {@link OptimizedMarshaller}.
+ * {@code JdkMarshaller} needs to be explicitly configured to override default <b>binary marshaller</b> -
+ * see {@link IgniteBinary}.
  * <pre name="code" class="java">
  * JdkMarshaller marshaller = new JdkMarshaller();
  *

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/config/example-cache.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/config/example-cache.xml b/modules/core/src/test/config/example-cache.xml
index 596f7ad..fdae325 100644
--- a/modules/core/src/test/config/example-cache.xml
+++ b/modules/core/src/test/config/example-cache.xml
@@ -44,10 +44,7 @@
         <property name="peerClassLoadingEnabled" value="true"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <!-- Set to false to allow non-serializable objects in examples, default is true. -->
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!-- Enable cache events for examples. -->

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/config/spring-start-nodes-attr.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/config/spring-start-nodes-attr.xml b/modules/core/src/test/config/spring-start-nodes-attr.xml
index b329973..09cd934 100644
--- a/modules/core/src/test/config/spring-start-nodes-attr.xml
+++ b/modules/core/src/test/config/spring-start-nodes-attr.xml
@@ -37,9 +37,7 @@
         <property name="connectorConfiguration"><null/></property>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <property name="discoverySpi">

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/config/spring-start-nodes.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/config/spring-start-nodes.xml b/modules/core/src/test/config/spring-start-nodes.xml
index 9b2ee94..5de58f0 100644
--- a/modules/core/src/test/config/spring-start-nodes.xml
+++ b/modules/core/src/test/config/spring-start-nodes.xml
@@ -31,9 +31,7 @@
         <property name="connectorConfiguration"><null/></property>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <property name="discoverySpi">

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/config/websession/example-cache-base.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/config/websession/example-cache-base.xml b/modules/core/src/test/config/websession/example-cache-base.xml
index f8fb6d9..8777528 100644
--- a/modules/core/src/test/config/websession/example-cache-base.xml
+++ b/modules/core/src/test/config/websession/example-cache-base.xml
@@ -30,10 +30,7 @@
         <property name="peerClassLoadingEnabled" value="true"/>
 
         <property name="marshaller">
-            <bean class="org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller">
-                <!-- Set to false to allow non-serializable objects in examples, default is true. -->
-                <property name="requireSerializable" value="false"/>
-            </bean>
+            <bean class="org.apache.ignite.internal.binary.BinaryMarshaller" />
         </property>
 
         <!-- Enable cache events for examples. -->

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/IgniteExternalizableAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/IgniteExternalizableAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/IgniteExternalizableAbstractTest.java
index de8dfbe..361d80f 100644
--- a/modules/core/src/test/java/org/apache/ignite/IgniteExternalizableAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/IgniteExternalizableAbstractTest.java
@@ -19,32 +19,25 @@ package org.apache.ignite;
 
 import java.util.ArrayList;
 import java.util.List;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.marshaller.Marshaller;
-import org.apache.ignite.marshaller.MarshallerContext;
-import org.apache.ignite.marshaller.MarshallerContextTestImpl;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 
 /**
  * Base externalizable test class.
  */
 public class IgniteExternalizableAbstractTest extends GridCommonAbstractTest {
-    /** */
-    private static final MarshallerContext CTX = new MarshallerContextTestImpl();
-
     /**
      * @return Marshallers.
      */
-    protected List<Marshaller> getMarshallers() {
+    protected List<Marshaller> getMarshallers() throws IgniteCheckedException {
         List<Marshaller> marshallers = new ArrayList<>();
 
-        OptimizedMarshaller opt = new OptimizedMarshaller();
-
-        opt.setContext(CTX);
+        BinaryMarshaller bin = createStandaloneBinaryMarshaller();
 
         marshallers.add(new JdkMarshaller());
-        marshallers.add(opt);
+        marshallers.add(bin);
 
         return marshallers;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerSelfTest.java
deleted file mode 100644
index f69a593..0000000
--- a/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerSelfTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.cache.store.jdbc;
-
-import org.apache.ignite.marshaller.Marshaller;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
-
-/**
- * Test for {@link CacheJdbcPojoStore} with optimized marshaller.
- */
-public class CacheJdbcPojoStoreOptimizedMarshallerSelfTest extends CacheJdbcPojoStoreAbstractSelfTest {
-    /** {@inheritDoc} */
-    @Override protected Marshaller marshaller(){
-        return new OptimizedMarshaller();
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest.java b/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest.java
deleted file mode 100644
index d1ce726..0000000
--- a/modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.cache.store.jdbc;
-
-/**
- * Test for {@link CacheJdbcPojoStore} with optimized marshaller and enabled SQL escaping.
- */
-public class CacheJdbcPojoStoreOptimizedMarshallerWithSqlEscapeSelfTest extends CacheJdbcPojoStoreOptimizedMarshallerSelfTest {
-    /** {@inheritDoc} */
-    @Override protected boolean sqlEscapeAll(){
-        return true;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/igfs/IgfsPathSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/igfs/IgfsPathSelfTest.java b/modules/core/src/test/java/org/apache/ignite/igfs/IgfsPathSelfTest.java
index e16385e..465a440 100644
--- a/modules/core/src/test/java/org/apache/ignite/igfs/IgfsPathSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/igfs/IgfsPathSelfTest.java
@@ -35,7 +35,12 @@ import org.jetbrains.annotations.Nullable;
  */
 public class IgfsPathSelfTest extends GridCommonAbstractTest {
     /** Marshaller to test {@link Externalizable} interface. */
-    private final Marshaller marshaller = new OptimizedMarshaller();
+    private final Marshaller marshaller;
+
+    /** Ctor. */
+    public IgfsPathSelfTest() throws IgniteCheckedException {
+        marshaller = createStandaloneBinaryMarshaller();
+    }
 
     /**
      * Test public methods of igfs path.

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/GridLifecycleAwareSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/GridLifecycleAwareSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/GridLifecycleAwareSelfTest.java
index 61d6069..a9d3823 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/GridLifecycleAwareSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/GridLifecycleAwareSelfTest.java
@@ -23,6 +23,7 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.configuration.ConnectorConfiguration;
 import org.apache.ignite.configuration.ConnectorMessageInterceptor;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.client.ssl.GridSslContextFactory;
 import org.apache.ignite.lifecycle.LifecycleAware;
 import org.apache.ignite.lifecycle.LifecycleBean;
@@ -105,7 +106,7 @@ public class GridLifecycleAwareSelfTest extends GridAbstractLifecycleAwareSelfTe
 
     /**
      */
-    private static class TestMarshaller extends OptimizedMarshaller implements LifecycleAware {
+    private static class TestMarshaller extends BinaryMarshaller implements LifecycleAware {
         /** */
         private final TestLifecycleAware lifecycleAware = new TestLifecycleAware(null);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/binary/BinarySimpleNameTestPropertySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinarySimpleNameTestPropertySelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/binary/BinarySimpleNameTestPropertySelfTest.java
index 8f2df9e..b9077d1 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinarySimpleNameTestPropertySelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/binary/BinarySimpleNameTestPropertySelfTest.java
@@ -20,6 +20,8 @@ package org.apache.ignite.internal.binary;
 import org.apache.ignite.IgniteBinary;
 import org.apache.ignite.binary.BinaryObject;
 import org.apache.ignite.binary.BinaryObjectBuilder;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.testframework.config.GridTestProperties;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 
@@ -30,6 +32,19 @@ import static org.apache.ignite.testframework.config.GridTestProperties.MARSH_CL
  * Tests testing framewrok, epecially BINARY_MARSHALLER_USE_SIMPLE_NAME_MAPPER test property.
  */
 public class BinarySimpleNameTestPropertySelfTest extends GridCommonAbstractTest {
+    /**
+     * flag for facade disabled test. As we use binary marshaller by default al
+     */
+    private boolean enableJdkMarshaller;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        final IgniteConfiguration configuration = super.getConfiguration(igniteInstanceName);
+        if (enableJdkMarshaller)
+            configuration.setMarshaller(new JdkMarshaller());
+        return configuration;
+    }
+
     /** {@inheritDoc} */
     @Override protected void afterTest() throws Exception {
         super.afterTest();
@@ -62,9 +77,11 @@ public class BinarySimpleNameTestPropertySelfTest extends GridCommonAbstractTest
     }
 
     /**
+     * Check if Binary facade is disabled test. Test uses JDK marshaller to provide warranty facade is not available
      * @throws Exception If failed.
      */
     public void testBinaryDisabled() throws Exception {
+        enableJdkMarshaller = true;
         assertNull(startGrid().binary());
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/managers/GridManagerStopSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/managers/GridManagerStopSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/managers/GridManagerStopSelfTest.java
index f9845c8..283ef87 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/managers/GridManagerStopSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/managers/GridManagerStopSelfTest.java
@@ -18,6 +18,7 @@
 package org.apache.ignite.internal.managers;
 
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager;
 import org.apache.ignite.internal.managers.collision.GridCollisionManager;
 import org.apache.ignite.internal.managers.communication.GridIoManager;
@@ -123,7 +124,7 @@ public class GridManagerStopSelfTest extends GridCommonAbstractTest {
         injectLogger(spi);
 
         ctx.config().setCommunicationSpi(spi);
-        ctx.config().setMarshaller(new OptimizedMarshaller());
+        ctx.config().setMarshaller(new BinaryMarshaller());
 
         GridIoManager mgr = new GridIoManager(ctx);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
index 10a7a30..2345dd6 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/managers/discovery/GridDiscoveryManagerAttributesSelfTest.java
@@ -28,9 +28,9 @@ import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_SERVICES_COMPATIBILITY_MODE;
-import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2;
 import static org.apache.ignite.configuration.DeploymentMode.CONTINUOUS;
 import static org.apache.ignite.configuration.DeploymentMode.SHARED;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshallerTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshallerTest.java b/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshallerTest.java
index 2698042..14b49a4 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshallerTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshallerTest.java
@@ -33,6 +33,7 @@ import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.compute.ComputeJobAdapter;
 import org.apache.ignite.compute.ComputeTask;
+import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.GridMarshallerTestInheritedBean;
 import org.apache.ignite.marshaller.Marshaller;
@@ -273,6 +274,13 @@ public class OptimizedMarshallerTest extends GridCommonAbstractTest {
         assertEquals(outItf.checkAfterUnmarshalled(), 17);
     }
 
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration configuration = super.getConfiguration(igniteInstanceName);
+        configuration.setMarshaller(marshaller());
+        return configuration;
+    }
+
     /**
      * @throws Exception If failed.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/package-info.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/package-info.java b/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/package-info.java
new file mode 100644
index 0000000..d255fac
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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 description. -->
+ * Optimized marchalling test package.
+ */
+package org.apache.ignite.internal.marshaller.optimized;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
index 949147e..d6711c2 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/CacheStartupInDeploymentModesTest.java
@@ -73,26 +73,6 @@ public class CacheStartupInDeploymentModesTest extends GridCommonAbstractTest {
     /**
      * @throws Exception If fail.
      */
-    public void testFailedInIsolatedMode() throws Exception {
-        deploymentMode = DeploymentMode.ISOLATED;
-        marshaller = new OptimizedMarshaller();
-
-        doCheckFailed();
-    }
-
-    /**
-     * @throws Exception If fail.
-     */
-    public void testFailedInPrivateMode() throws Exception {
-        deploymentMode = DeploymentMode.PRIVATE;
-        marshaller = new OptimizedMarshaller();
-
-        doCheckFailed();
-    }
-
-    /**
-     * @throws Exception If fail.
-     */
     public void testStartedInIsolatedMode() throws Exception {
         deploymentMode = DeploymentMode.ISOLATED;
         marshaller = new BinaryMarshaller();
@@ -133,22 +113,6 @@ public class CacheStartupInDeploymentModesTest extends GridCommonAbstractTest {
     }
 
     /**
-     * @throws Exception If failed.
-     */
-    private void doCheckFailed() throws Exception {
-        try {
-            startGridsMultiThreaded(2);
-        }
-        catch (Exception e) {
-            assert e.getMessage().contains("Cache can be started in PRIVATE or ISOLATED deployment mode only ");
-
-            return;
-        }
-
-        fail("Unexpected start of the caches!");
-    }
-
-    /**
      * @param cache IgniteCache
      */
     private void checkPutCache(IgniteCache cache) {
@@ -224,6 +188,5 @@ public class CacheStartupInDeploymentModesTest extends GridCommonAbstractTest {
                 ", name='" + name + '\'' +
                 '}';
         }
-
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheEntryMemorySizeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheEntryMemorySizeSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheEntryMemorySizeSelfTest.java
index b10ff70..6939258 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheEntryMemorySizeSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheEntryMemorySizeSelfTest.java
@@ -144,7 +144,7 @@ public class GridCacheEntryMemorySizeSelfTest extends GridCommonAbstractTest {
      * @return Marshaller.
      */
     protected Marshaller createMarshaller() throws IgniteCheckedException {
-        Marshaller marsh = new OptimizedMarshaller();
+        Marshaller marsh = createStandaloneBinaryMarshaller();
 
         marsh.setContext(new MarshallerContext() {
             @Override public boolean registerClassName(byte platformId, int typeId, String clsName) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheStoreManagerDeserializationTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheStoreManagerDeserializationTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheStoreManagerDeserializationTest.java
index 81a17bb..7a21714 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheStoreManagerDeserializationTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheStoreManagerDeserializationTest.java
@@ -37,7 +37,7 @@ import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.processors.cache.extras.GridCacheObsoleteEntryExtras;
 import org.apache.ignite.internal.processors.cache.store.CacheLocalStore;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -88,7 +88,7 @@ public class GridCacheStoreManagerDeserializationTest extends GridCommonAbstract
         if (igniteInstanceName != null && igniteInstanceName.toLowerCase().startsWith("binary"))
             c.setMarshaller(new BinaryMarshaller());
         else
-            c.setMarshaller(new OptimizedMarshaller());
+            c.setMarshaller(new JdkMarshaller());
 
         TcpDiscoverySpi disco = new TcpDiscoverySpi();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheVersionSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheVersionSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheVersionSelfTest.java
index b69255f..9cec7ec 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheVersionSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheVersionSelfTest.java
@@ -20,8 +20,7 @@ package org.apache.ignite.internal.processors.cache;
 import java.util.concurrent.Callable;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersionEx;
-import org.apache.ignite.marshaller.MarshallerContextTestImpl;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 
@@ -81,9 +80,7 @@ public class GridCacheVersionSelfTest extends GridCommonAbstractTest {
         GridCacheVersion ver = version(1, 1);
         GridCacheVersionEx verEx = new GridCacheVersionEx(2, 2, 0, ver);
 
-        OptimizedMarshaller marsh = new OptimizedMarshaller(false);
-
-        marsh.setContext(new MarshallerContextTestImpl());
+        Marshaller marsh = createStandaloneBinaryMarshaller();
 
         byte[] verBytes = marsh.marshal(ver);
         byte[] verExBytes = marsh.marshal(verEx);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheAffinityEarlyTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheAffinityEarlyTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheAffinityEarlyTest.java
index 051ca00..46669ac 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheAffinityEarlyTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheAffinityEarlyTest.java
@@ -29,7 +29,7 @@ import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteInternalFuture;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -66,10 +66,7 @@ public class CacheAffinityEarlyTest extends GridCommonAbstractTest {
 
         cfg.setDiscoverySpi(discoSpi);
 
-        OptimizedMarshaller marsh = new OptimizedMarshaller();
-        marsh.setRequireSerializable(false);
-
-        cfg.setMarshaller(marsh);
+        cfg.setMarshaller(new BinaryMarshaller());
 
         return cfg;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheGetFutureHangsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheGetFutureHangsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheGetFutureHangsSelfTest.java
index 1aec352..eb430f6 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheGetFutureHangsSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheGetFutureHangsSelfTest.java
@@ -30,6 +30,7 @@ import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.T2;
 import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
@@ -67,10 +68,7 @@ public class CacheGetFutureHangsSelfTest extends GridCommonAbstractTest {
 
         ((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1);
 
-        OptimizedMarshaller marsh = new OptimizedMarshaller();
-        marsh.setRequireSerializable(false);
-
-        cfg.setMarshaller(marsh);
+        cfg.setMarshaller(new BinaryMarshaller());
 
         CacheConfiguration ccfg = defaultCacheConfiguration();
         ccfg.setCacheMode(CacheMode.PARTITIONED);

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutMultiNodeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutMultiNodeSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutMultiNodeSelfTest.java
index 3b7fa4f..23fc941 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutMultiNodeSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutMultiNodeSelfTest.java
@@ -29,7 +29,7 @@ import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteInternalFuture;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
@@ -55,10 +55,7 @@ public class IgniteCacheCreatePutMultiNodeSelfTest extends GridCommonAbstractTes
 
         cfg.setDiscoverySpi(discoSpi);
 
-        OptimizedMarshaller marsh = new OptimizedMarshaller();
-        marsh.setRequireSerializable(false);
-
-        cfg.setMarshaller(marsh);
+        cfg.setMarshaller(new BinaryMarshaller());
 
         return cfg;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutTest.java
index c754b38..113cea4 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheCreatePutTest.java
@@ -26,8 +26,8 @@ import org.apache.ignite.cache.CacheAtomicityMode;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -67,10 +67,7 @@ public class IgniteCacheCreatePutTest extends GridCommonAbstractTest {
 
         cfg.setDiscoverySpi(discoSpi);
 
-        OptimizedMarshaller marsh = new OptimizedMarshaller();
-        marsh.setRequireSerializable(false);
-
-        cfg.setMarshaller(marsh);
+        cfg.setMarshaller(new BinaryMarshaller());
 
         CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCachePartitionLossPolicySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCachePartitionLossPolicySelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCachePartitionLossPolicySelfTest.java
index 480dc20..5bbeef9 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCachePartitionLossPolicySelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCachePartitionLossPolicySelfTest.java
@@ -141,6 +141,7 @@ public class IgniteCachePartitionLossPolicySelfTest extends GridCommonAbstractTe
     }
 
     /**
+     * See also https://issues.apache.org/jira/browse/IGNITE-5078
      * @throws Exception if failed.
      */
     public void testIgnore() throws Exception {

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheEntryProcessorNonSerializableTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheEntryProcessorNonSerializableTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheEntryProcessorNonSerializableTest.java
index b29f2bb..72928b3 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheEntryProcessorNonSerializableTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheEntryProcessorNonSerializableTest.java
@@ -30,7 +30,7 @@ import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.NearCacheConfiguration;
 import org.apache.ignite.internal.IgniteEx;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
+import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -83,7 +83,8 @@ public class CacheEntryProcessorNonSerializableTest extends GridCommonAbstractTe
         ((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1);
 
         cfg.setClientMode(client);
-        cfg.setMarshaller(new OptimizedMarshaller());
+        //set custom marshaller to get expected exception
+        cfg.setMarshaller(new JdkMarshaller());
 
         return cfg;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractBaseSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractBaseSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractBaseSelfTest.java
index d215815..acc6742 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractBaseSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsAbstractBaseSelfTest.java
@@ -218,13 +218,6 @@ public abstract class IgfsAbstractBaseSelfTest extends IgfsCommonAbstractTest {
     }
 
     /**
-     * @return Use optimized marshaller flag.
-     */
-    protected boolean useOptimizedMarshaller() {
-        return false;
-    }
-
-    /**
      * @return Whether append is supported.
      */
     protected boolean appendSupported() {
@@ -386,9 +379,6 @@ public abstract class IgfsAbstractBaseSelfTest extends IgfsCommonAbstractTest {
 
         IgniteConfiguration cfg = new IgniteConfiguration();
 
-        if (useOptimizedMarshaller())
-            cfg.setMarshaller(new OptimizedMarshaller());
-
         cfg.setIgniteInstanceName(igniteInstanceName);
 
         TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsFileInfoSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsFileInfoSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsFileInfoSelfTest.java
index 47af49b..a81bba5 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsFileInfoSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsFileInfoSelfTest.java
@@ -17,23 +17,27 @@
 
 package org.apache.ignite.internal.processors.igfs;
 
+import java.io.Externalizable;
+import java.util.Random;
+import java.util.concurrent.Callable;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.marshaller.MarshallerContextTestImpl;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.jetbrains.annotations.Nullable;
 
-import java.io.Externalizable;
-import java.util.Random;
-import java.util.concurrent.Callable;
-
 /**
  * {@link IgfsEntryInfo} test case.
  */
 public class IgfsFileInfoSelfTest extends IgfsCommonAbstractTest {
     /** Marshaller to test {@link Externalizable} interface. */
-    private final Marshaller marshaller = new OptimizedMarshaller();
+    private final Marshaller marshaller;
+
+    /** Ctor. */
+    public IgfsFileInfoSelfTest() throws IgniteCheckedException {
+        marshaller = createStandaloneBinaryMarshaller();
+    }
+
 
     /**
      * Test node info serialization.

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsPrimaryOptimziedMarshallerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsPrimaryOptimziedMarshallerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsPrimaryOptimziedMarshallerSelfTest.java
deleted file mode 100644
index e4ad1f4..0000000
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsPrimaryOptimziedMarshallerSelfTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.igfs;
-
-/**
- * Tests for PRIMARY mode with optimized marshaller.
- */
-public class IgfsPrimaryOptimziedMarshallerSelfTest extends IgfsPrimarySelfTest {
-    /** {@inheritDoc} */
-    @Override protected boolean useOptimizedMarshaller() {
-        return true;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/internal/processors/service/ClosureServiceClientsNodesTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/ClosureServiceClientsNodesTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/ClosureServiceClientsNodesTest.java
index 68f68b1..c1af323 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/ClosureServiceClientsNodesTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/ClosureServiceClientsNodesTest.java
@@ -27,10 +27,10 @@ import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cluster.ClusterGroup;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.lang.GridAbsPredicate;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.lang.IgniteCallable;
-import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.services.Service;
@@ -59,7 +59,7 @@ public class ClosureServiceClientsNodesTest extends GridCommonAbstractTest {
     @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
         IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
 
-        cfg.setMarshaller(new OptimizedMarshaller(false));
+        cfg.setMarshaller(new BinaryMarshaller());
 
         cfg.setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(ipFinder).setForceServerMode(true));
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/98a1758d/modules/core/src/test/java/org/apache/ignite/marshaller/DynamicProxySerializationMultiJvmSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/marshaller/DynamicProxySerializationMultiJvmSelfTest.java b/modules/core/src/test/java/org/apache/ignite/marshaller/DynamicProxySerializationMultiJvmSelfTest.java
index 3e1e6f7..51e7196 100644
--- a/modules/core/src/test/java/org/apache/ignite/marshaller/DynamicProxySerializationMultiJvmSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/marshaller/DynamicProxySerializationMultiJvmSelfTest.java
@@ -58,19 +58,6 @@ public class DynamicProxySerializationMultiJvmSelfTest extends GridCommonAbstrac
     /**
      * @throws Exception If failed.
      */
-    public void testOptimizedMarshaller() throws Exception {
-        marshFactory = new Callable<Marshaller>() {
-            @Override public Marshaller call() throws Exception {
-                return new OptimizedMarshaller(false);
-            }
-        };
-
-        doTestMarshaller();
-    }
-
-    /**
-     * @throws Exception If failed.
-     */
     public void testBinaryMarshaller() throws Exception {
         marshFactory = new Callable<Marshaller>() {
             @Override public Marshaller call() throws Exception {


[20/31] ignite git commit: Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/ignite

Posted by sb...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/ignite


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/eea7a3b9
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/eea7a3b9
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/eea7a3b9

Branch: refs/heads/ignite-5075
Commit: eea7a3b914f59df1bb4e2b2d27ca36af2acdde2f
Parents: b887587 cbf0b2a
Author: Denis Magda <dm...@gridgain.com>
Authored: Tue May 23 13:52:56 2017 -0700
Committer: Denis Magda <dm...@gridgain.com>
Committed: Tue May 23 13:52:56 2017 -0700

----------------------------------------------------------------------
 examples/config/filesystem/example-igfs.xml     |    4 +
 .../store/cassandra/CassandraCacheStore.java    |   15 +-
 .../ignite/tests/IgnitePersistentStoreTest.java |   62 +-
 .../persistence/loadall_blob/ignite-config.xml  |   90 ++
 .../loadall_blob/persistence-settings.xml       |   29 +
 modules/clients/src/test/config/jdbc-config.xml |    6 -
 .../internal/jdbc2/JdbcMetadataSelfTest.java    |    5 +-
 .../internal/jdbc2/JdbcResultSetSelfTest.java   |   24 +-
 .../ignite/jdbc/JdbcMetadataSelfTest.java       |    4 +-
 .../ignite/jdbc/JdbcResultSetSelfTest.java      |  121 +-
 .../jdbc/suite/IgniteJdbcDriverTestSuite.java   |    3 +
 .../jdbc/thin/JdbcConnectionSelfTest.java       |  195 +++
 .../java/org/apache/ignite/IgniteCache.java     |   13 +
 .../org/apache/ignite/IgniteJdbcThinDriver.java |  312 ++++
 .../apache/ignite/IgniteSystemProperties.java   |    7 +-
 .../ignite/binary/BinaryBasicNameMapper.java    |    2 +-
 .../rendezvous/RendezvousAffinityFunction.java  |   20 +-
 .../ignite/cache/query/FieldsQueryCursor.java   |   39 +
 .../store/jdbc/CacheAbstractJdbcStore.java      |    6 +-
 .../configuration/AtomicConfiguration.java      |   25 +
 .../configuration/MemoryConfiguration.java      |    3 +-
 .../MemoryPolicyConfiguration.java              |    4 +-
 .../ignite/configuration/TopologyValidator.java |   10 +-
 .../internal/ComputeTaskInternalFuture.java     |    3 -
 .../ignite/internal/GridKernalContext.java      |    8 +-
 .../ignite/internal/GridKernalContextImpl.java  |   12 +-
 .../apache/ignite/internal/IgniteKernal.java    |    6 +-
 .../internal/IgniteNeedReconnectException.java  |    2 +-
 .../org/apache/ignite/internal/IgnitionEx.java  |    1 +
 .../internal/binary/BinaryClassDescriptor.java  |    1 +
 .../ignite/internal/binary/BinaryContext.java   |   58 +-
 .../internal/binary/BinaryWriterExImpl.java     |   16 +-
 .../GridClientOptimizedMarshaller.java          |    2 +-
 .../GridClientZipOptimizedMarshaller.java       |    2 +-
 .../internal/jdbc/thin/JdbcConnection.java      |  529 +++++++
 .../ignite/internal/jdbc/thin/JdbcTcpIo.java    |  207 +++
 .../ignite/internal/jdbc2/JdbcConnection.java   |    3 +-
 .../managers/communication/GridIoManager.java   |  366 ++++-
 .../communication/GridIoMessageFactory.java     |    2 +
 .../communication/IgniteIoTestMessage.java      |  362 ++++-
 .../discovery/GridDiscoveryManager.java         |   19 +-
 .../managers/indexing/GridIndexingManager.java  |   19 +-
 .../optimized/OptimizedClassDescriptor.java     |    2 +-
 .../optimized/OptimizedMarshaller.java          |    2 +-
 .../marshaller/optimized/package-info.java      |   22 +
 .../mem/unsafe/UnsafeMemoryProvider.java        |   18 +-
 .../pagemem/impl/PageMemoryNoStoreImpl.java     |   22 +-
 .../affinity/AffinityTopologyVersion.java       |    9 +
 .../affinity/GridAffinityAssignmentCache.java   |    3 -
 .../cache/CacheAffinitySharedManager.java       |  286 ++--
 .../CacheClientReconnectDiscoveryData.java      |  133 ++
 .../internal/processors/cache/CacheData.java    |  157 ++
 .../cache/CacheJoinNodeDiscoveryData.java       |  147 ++
 .../cache/CacheNodeCommonDiscoveryData.java     |   82 +
 .../cache/CacheStoreBalancingWrapper.java       |    3 -
 .../processors/cache/ClusterCachesInfo.java     |  913 +++++++++++
 .../cache/DynamicCacheChangeBatch.java          |   92 +-
 .../cache/DynamicCacheChangeRequest.java        |  102 +-
 .../cache/DynamicCacheDescriptor.java           |  171 +--
 .../processors/cache/ExchangeActions.java       |  338 +++++
 .../processors/cache/GridCacheAdapter.java      |   12 +-
 .../cache/GridCacheAffinityManager.java         |    2 +-
 .../processors/cache/GridCacheContext.java      |   48 +-
 .../cache/GridCacheDeploymentManager.java       |    2 +-
 .../cache/GridCacheFutureAdapter.java           |    1 +
 .../processors/cache/GridCacheLogger.java       |    2 +-
 .../cache/GridCacheMultiTxFuture.java           |    3 -
 .../processors/cache/GridCacheMvccManager.java  |    3 -
 .../GridCachePartitionExchangeManager.java      |   57 +-
 .../processors/cache/GridCacheProcessor.java    | 1413 +++++-------------
 .../cache/GridCacheSharedContext.java           |   17 +-
 .../processors/cache/GridCacheUtils.java        |  146 +-
 .../processors/cache/IgniteCacheProxy.java      |   11 +-
 .../processors/cache/QueryCursorImpl.java       |   19 +-
 .../IgniteCacheDatabaseSharedManager.java       |   51 +-
 .../dht/GridClientPartitionTopology.java        |    2 +-
 .../dht/GridDhtAffinityAssignmentRequest.java   |   36 +-
 .../dht/GridDhtAffinityAssignmentResponse.java  |   36 +-
 .../dht/GridDhtAssignmentFetchFuture.java       |   63 +-
 .../distributed/dht/GridDhtCacheAdapter.java    |    3 -
 .../distributed/dht/GridDhtEmbeddedFuture.java  |    3 -
 .../distributed/dht/GridDhtGetSingleFuture.java |    3 -
 .../dht/GridDhtPartitionTopologyImpl.java       |   12 +-
 .../distributed/dht/GridDhtTxFinishFuture.java  |    3 -
 .../GridDhtAtomicAbstractUpdateRequest.java     |    2 +
 .../dht/preloader/GridDhtForceKeysFuture.java   |    7 +-
 .../dht/preloader/GridDhtPartitionDemander.java |   13 +-
 .../GridDhtPartitionsExchangeFuture.java        |  166 +-
 .../dht/preloader/GridDhtPreloader.java         |    4 +-
 .../distributed/near/GridNearGetFuture.java     |    3 -
 .../distributed/near/GridNearLockFuture.java    |    3 -
 .../processors/cache/local/GridLocalCache.java  |   31 +-
 .../cache/local/GridLocalLockFuture.java        |   41 +-
 .../cache/query/GridCacheQueryManager.java      |   53 +-
 .../continuous/CacheContinuousQueryHandler.java |   42 +-
 .../continuous/CacheContinuousQueryManager.java |   11 +-
 .../store/GridCacheStoreManagerAdapter.java     |    4 +-
 .../cluster/GridClusterStateProcessor.java      |   26 +-
 .../continuous/GridContinuousProcessor.java     |    3 -
 .../datastreamer/DataStreamerFuture.java        |    3 -
 .../GridAtomicCacheQueueImpl.java               |    7 +-
 .../processors/igfs/IgfsDataManager.java        |    3 -
 .../marshaller/MarshallerMappingTransport.java  |    3 -
 .../processors/odbc/OdbcNioListener.java        |  242 ---
 .../internal/processors/odbc/OdbcProcessor.java |  199 ---
 .../odbc/SqlListenerAbstractMessageParser.java  |  265 ++++
 .../odbc/SqlListenerAbstractObjectReader.java   |  137 ++
 .../odbc/SqlListenerAbstractObjectWriter.java   |  111 ++
 .../processors/odbc/SqlListenerNioListener.java |  263 ++++
 .../processors/odbc/SqlListenerProcessor.java   |  191 +++
 .../odbc/SqlListenerRequestHandlerImpl.java     |  494 ++++++
 .../processors/odbc/jdbc/JdbcMessageParser.java |   50 +
 .../processors/odbc/jdbc/JdbcObjectReader.java  |   33 +
 .../processors/odbc/jdbc/JdbcObjectWriter.java  |   33 +
 .../processors/odbc/odbc/OdbcMessageParser.java |  249 +--
 .../processors/odbc/odbc/OdbcObjectReader.java  |   33 +
 .../processors/odbc/odbc/OdbcObjectWriter.java  |   32 +
 .../odbc/odbc/OdbcRequestHandler.java           |  513 -------
 .../platform/cache/PlatformCache.java           |   28 +-
 .../processors/query/GridQueryIndexing.java     |   90 +-
 .../processors/query/GridQueryProcessor.java    |  289 ++--
 .../processors/query/QueryIndexKey.java         |   20 +-
 .../query/QueryTypeDescriptorImpl.java          |   16 +-
 .../processors/query/QueryTypeIdKey.java        |   26 +-
 .../processors/query/QueryTypeNameKey.java      |   12 +-
 .../internal/processors/query/QueryUtils.java   |   14 +-
 .../schema/SchemaIndexCacheVisitorImpl.java     |   12 +-
 .../processors/query/schema/SchemaKey.java      |   59 -
 .../message/SchemaProposeDiscoveryMessage.java  |    7 +-
 .../operation/SchemaAbstractOperation.java      |   27 +-
 .../operation/SchemaIndexAbstractOperation.java |    7 +-
 .../operation/SchemaIndexCreateOperation.java   |    8 +-
 .../operation/SchemaIndexDropOperation.java     |    7 +-
 .../service/GridServiceDeploymentFuture.java    |    3 -
 .../ignite/internal/util/IgniteUtils.java       |   17 +
 .../util/future/GridEmbeddedFuture.java         |    3 -
 .../util/nio/GridNioEmbeddedFuture.java         |    3 -
 .../internal/util/nio/GridNioFutureImpl.java    |    3 -
 .../ignite/internal/util/nio/GridNioServer.java |    3 -
 .../internal/util/worker/GridWorkerFuture.java  |    3 -
 .../node/VisorAffinityTopologyVersion.java      |   87 ++
 .../visor/node/VisorNodeDataCollectorJob.java   |    6 +
 .../node/VisorNodeDataCollectorJobResult.java   |   38 +
 .../visor/node/VisorNodeDataCollectorTask.java  |    4 +
 .../node/VisorNodeDataCollectorTaskResult.java  |   28 +-
 .../apache/ignite/marshaller/Marshaller.java    |    3 -
 .../ignite/marshaller/jdk/JdkMarshaller.java    |    5 +-
 .../org/apache/ignite/spi/IgniteSpiAdapter.java |    2 +-
 .../communication/tcp/TcpCommunicationSpi.java  |    3 -
 .../ignite/spi/discovery/DiscoveryDataBag.java  |   18 +-
 .../spi/discovery/tcp/TcpDiscoverySpi.java      |    4 +-
 .../spi/indexing/IndexingQueryFilter.java       |    8 +-
 .../apache/ignite/spi/indexing/IndexingSpi.java |   17 +-
 .../spi/indexing/noop/NoopIndexingSpi.java      |    6 +-
 modules/core/src/test/config/example-cache.xml  |    5 +-
 .../core/src/test/config/examples.properties    |    1 +
 .../src/test/config/spring-start-nodes-attr.xml |    4 +-
 .../core/src/test/config/spring-start-nodes.xml |    4 +-
 .../config/websession/example-cache-base.xml    |    5 +-
 .../IgniteExternalizableAbstractTest.java       |   15 +-
 ...ityFunctionBackupFilterAbstractSelfTest.java |   13 +-
 ...dbcPojoStoreOptimizedMarshallerSelfTest.java |   31 -
 ...ptimizedMarshallerWithSqlEscapeSelfTest.java |   28 -
 .../apache/ignite/igfs/IgfsPathSelfTest.java    |    7 +-
 .../internal/GridLifecycleAwareSelfTest.java    |    3 +-
 .../internal/GridNodeMetricsLogSelfTest.java    |   13 +-
 .../BinarySimpleNameTestPropertySelfTest.java   |   17 +
 .../managers/GridManagerStopSelfTest.java       |    3 +-
 .../GridDiscoveryManagerAttributesSelfTest.java |    2 +-
 .../optimized/OptimizedMarshallerTest.java      |    8 +
 .../marshaller/optimized/package-info.java      |   22 +
 .../pagemem/impl/PageMemoryNoLoadSelfTest.java  |   31 +-
 .../AtomicCacheAffinityConfigurationTest.java   |  175 +++
 .../processors/cache/CacheGetFromJobTest.java   |    5 +
 .../CacheStartupInDeploymentModesTest.java      |   37 -
 .../GridCacheAbstractLocalStoreSelfTest.java    |   41 +-
 .../cache/GridCacheEntryMemorySizeSelfTest.java |    2 +-
 .../cache/GridCacheP2PUndeploySelfTest.java     |   12 -
 ...ridCacheStoreManagerDeserializationTest.java |    4 +-
 .../cache/GridCacheVersionSelfTest.java         |    7 +-
 .../cache/IgniteCacheContainsKeyAtomicTest.java |  103 ++
 ...gniteCacheP2pUnmarshallingNearErrorTest.java |    6 +-
 .../processors/cache/IgniteCacheStartTest.java  |  191 +++
 .../cache/IgniteDynamicCacheStartSelfTest.java  |    2 +-
 ...niteTopologyValidatorGridSplitCacheTest.java |    8 +-
 .../IgniteTxExceptionAbstractSelfTest.java      |    6 +-
 .../distributed/CacheAffinityEarlyTest.java     |    7 +-
 .../CacheDiscoveryDataConcurrentJoinTest.java   |  198 +++
 .../CacheGetFutureHangsSelfTest.java            |    6 +-
 .../CacheLateAffinityAssignmentTest.java        |    4 +-
 .../cache/distributed/CacheStartOnJoinTest.java |   10 +
 .../IgniteCacheCreatePutMultiNodeSelfTest.java  |    7 +-
 .../distributed/IgniteCacheCreatePutTest.java   |    7 +-
 .../IgniteCachePartitionLossPolicySelfTest.java |    1 +
 .../IgniteCrossCacheTxStoreSelfTest.java        |   12 +-
 ...ePartitionedBasicStoreMultiNodeSelfTest.java |   22 +-
 .../paged/PageEvictionMultinodeTest.java        |   22 +-
 .../cache/query/IndexingSpiQuerySelfTest.java   |   14 +-
 .../cache/query/IndexingSpiQueryTxSelfTest.java |    6 +-
 .../CacheEntryProcessorNonSerializableTest.java |    5 +-
 .../igfs/IgfsAbstractBaseSelfTest.java          |   10 -
 .../processors/igfs/IgfsFileInfoSelfTest.java   |   16 +-
 .../IgfsPrimaryOptimziedMarshallerSelfTest.java |   28 -
 .../odbc/OdbcProcessorValidationSelfTest.java   |  182 ---
 .../SqlListenerProcessorValidationSelfTest.java |  184 +++
 .../service/ClosureServiceClientsNodesTest.java |    4 +-
 .../loadtests/hashmap/GridCacheTestContext.java |    4 +
 ...namicProxySerializationMultiJvmSelfTest.java |   13 -
 .../GridMarshallerPerformanceTest.java          |    8 +-
 .../IgniteMessagingWithClientTest.java          |    4 +-
 ...pClientDiscoveryMarshallerCheckSelfTest.java |    4 +-
 .../TcpDiscoveryMarshallerCheckSelfTest.java    |    4 +-
 .../ignite/testframework/GridTestUtils.java     |    2 +-
 .../config/GridTestProperties.java              |    3 +-
 .../configvariations/ConfigVariations.java      |   14 +-
 .../testframework/junits/GridAbstractTest.java  |   33 +
 .../junits/IgniteTestResources.java             |    8 +-
 .../multijvm/IgniteCacheProcessProxy.java       |    8 +
 ...naryObjectsTxDeadlockDetectionTestSuite.java |   37 -
 .../ignite/testsuites/IgniteBasicTestSuite.java |    4 +-
 .../testsuites/IgniteBinaryBasicTestSuite.java  |   14 +-
 .../IgniteBinaryCacheFullApiTestSuite.java      |   37 -
 .../testsuites/IgniteBinaryCacheTestSuite.java  |    4 -
 ...ObjectsCacheDataStructuresSelfTestSuite.java |   42 -
 ...BinaryObjectsCacheExpiryPolicyTestSuite.java |   38 -
 ...gniteBinaryObjectsCacheRestartTestSuite.java |   37 -
 .../IgniteBinaryObjectsCacheTestSuite2.java     |   37 -
 .../IgniteBinaryObjectsCacheTestSuite3.java     |    2 -
 .../IgniteBinaryObjectsCacheTestSuite4.java     |   37 -
 ...IgniteBinaryObjectsComputeGridTestSuite.java |    4 -
 .../IgniteCacheDataStructuresSelfTestSuite.java |    3 +
 .../ignite/testsuites/IgniteCacheTestSuite.java |    4 -
 .../testsuites/IgniteCacheTestSuite3.java       |    2 +-
 .../testsuites/IgniteCacheTestSuite4.java       |    7 +
 ...teBasicConfigVariationsFullApiTestSuite.java |    2 +-
 .../ignite/testsuites/IgniteIgfsTestSuite.java  |    3 -
 .../testsuites/IgniteKernalSelfTestSuite.java   |    4 -
 .../IgniteMarshallerSelfTestSuite.java          |    8 +-
 ...essagingConfigVariationFullApiTestSuite.java |    2 +-
 ...ServiceConfigVariationsFullApiTestSuite.java |    2 +-
 .../IgniteTopologyValidatorTestSuit.java        |   44 -
 .../IgniteTopologyValidatorTestSuite.java       |   50 +
 .../webapp/META-INF/ignite-webapp-config.xml    |   15 +-
 .../hadoop/impl/igfs/HadoopIgfsFuture.java      |    3 -
 .../external/HadoopExternalTaskExecutor.java    |    3 -
 .../test/config/hadoop-fs-open-test/grid-0.xml  |    3 +-
 .../test/config/hadoop-fs-open-test/grid-1.xml  |    3 +-
 .../test/config/hadoop-fs-open-test/grid-2.xml  |    3 +-
 .../test/config/igfs-cli-config-dual-async.xml  |    3 +-
 .../test/config/igfs-cli-config-dual-sync.xml   |    3 +-
 .../src/test/config/igfs-cli-config-primary.xml |    3 +-
 .../src/test/config/igfs-cli-config-proxy.xml   |    3 +-
 .../IgniteHadoopFileSystemAbstractSelfTest.java |    4 +-
 .../cache/query/GridCacheTwoStepQuery.java      |   84 +-
 .../processors/cache/query/QueryTable.java      |  164 ++
 .../query/h2/DmlStatementsProcessor.java        |   53 +-
 .../processors/query/h2/IgniteH2Indexing.java   |  368 ++---
 .../query/h2/database/H2PkHashIndex.java        |    4 +-
 .../query/h2/database/H2TreeIndex.java          |    4 +-
 .../query/h2/ddl/DdlStatementsProcessor.java    |   25 +-
 .../query/h2/opt/GridH2CollocationModel.java    |    6 +-
 .../query/h2/opt/GridH2IndexBase.java           |   14 +-
 .../processors/query/h2/opt/GridH2Table.java    |  177 ++-
 .../query/h2/opt/GridH2TreeIndex.java           |    2 +-
 .../query/h2/opt/GridLuceneIndex.java           |   15 +-
 .../query/h2/sql/GridSqlDropIndex.java          |   14 +-
 .../query/h2/sql/GridSqlQueryParser.java        |    2 +-
 .../query/h2/sql/GridSqlQuerySplitter.java      |   21 +-
 .../query/h2/twostep/GridMapQueryExecutor.java  |   21 +-
 .../h2/twostep/GridReduceQueryExecutor.java     |  263 ++--
 .../h2/twostep/msg/GridH2QueryRequest.java      |   13 +-
 .../twostep/msg/GridH2ValueMessageFactory.java  |    4 +
 .../cache/IgniteCacheNoClassQuerySelfTest.java  |    4 +-
 .../cache/SqlFieldsQuerySelfTest.java           |   12 +-
 .../DynamicIndexAbstractBasicSelfTest.java      |   26 +-
 .../DynamicIndexAbstractConcurrentSelfTest.java |   74 +-
 .../cache/index/SchemaExchangeSelfTest.java     |    2 +-
 .../query/IgniteQueryDedicatedPoolTest.java     |    6 +-
 .../query/IgniteSqlSegmentedIndexSelfTest.java  |   25 +
 .../h2/GridIndexingSpiAbstractSelfTest.java     |  136 +-
 .../h2/sql/AbstractH2CompareQueryTest.java      |    4 +-
 .../query/h2/sql/GridQueryParsingTest.java      |    6 +-
 .../FetchingQueryCursorStressTest.java          |    4 +-
 .../IgniteBinaryCacheQueryTestSuite.java        |    4 -
 .../IgniteBinaryCacheQueryTestSuite2.java       |    4 -
 .../IgniteBinaryCacheQueryTestSuite3.java       |   39 -
 .../IgniteBinaryCacheQueryTestSuite4.java       |   39 -
 .../ignite/ml/math/d3-matrix-template.html      |   17 +-
 .../ignite/ml/math/d3-vector-template.html      |   15 +-
 .../core/include/ignite/cache/query/query_sql.h |    2 +
 .../ignite/cache/query/query_sql_fields.h       |    3 +
 .../cpp/odbc/include/ignite/odbc/message.h      |   10 +
 .../Apache.Ignite.Core.Tests.csproj             |    1 +
 .../Binary/BinaryDateTimeTest.cs                |  204 +++
 .../Binary/BinarySelfTest.cs                    |    2 +-
 .../Cache/Query/CacheLinqTest.cs                |   38 +-
 .../Cache/Query/CacheQueriesTest.cs             |   60 +-
 .../Apache.Ignite.Core.Tests/MarshallerTest.cs  |    2 +-
 .../Apache.Ignite.Core.csproj                   |    1 +
 .../Binary/BinaryReflectiveSerializer.cs        |   44 +-
 .../Binary/TimestampAttribute.cs                |   40 +
 .../Cache/Query/SqlFieldsQuery.cs               |   29 +-
 .../Apache.Ignite.Core/Cache/Query/SqlQuery.cs  |   31 +
 .../Impl/Binary/BinaryReflectiveActions.cs      |   89 +-
 .../BinaryReflectiveSerializerInternal.cs       |   10 +-
 .../Impl/Binary/BinaryUtils.cs                  |    4 +-
 .../Apache.Ignite.Core/Impl/Cache/CacheImpl.cs  |    3 +
 .../Apache.Ignite.Linq/CacheExtensions.cs       |   10 +
 .../Impl/CacheFieldsQueryExecutor.cs            |   42 +-
 .../Apache.Ignite.Linq/Impl/CacheQueryable.cs   |    3 +-
 .../dotnet/Apache.Ignite.Linq/QueryOptions.cs   |   23 +
 .../processors/schedule/ScheduleFutureImpl.java |    2 +-
 modules/spark/pom.xml                           |    6 -
 .../spring/SpringTransactionManager.java        |   13 +
 .../jdbc/CacheJdbcPojoStoreFactorySelfTest.java |    2 +-
 .../GridSpringBeanSerializationSelfTest.java    |   15 +-
 .../GridSpringTransactionManagerSelfTest.java   |   45 +
 modules/web-console/frontend/app/app.js         |    4 +-
 .../activities-user-dialog.tpl.pug              |    1 +
 .../app/components/ignite-icon/directive.js     |   67 +
 .../app/components/ignite-icon/index.js         |   25 +
 .../app/components/ignite-icon/style.scss       |   21 +
 .../list-of-registered-users.tpl.pug            |    6 +-
 .../components/web-console-header/component.js  |   19 +-
 .../components/web-console-header/style.scss    |   39 +-
 .../components/web-console-header/template.pug  |   17 +-
 .../frontend/app/helpers/jade/mixins.pug        |   10 +-
 .../states/configuration/igfs/secondary.pug     |    2 +-
 .../frontend/app/primitives/btn/index.scss      |   58 +-
 .../app/primitives/datepicker/index.pug         |    2 +-
 .../frontend/app/primitives/dropdown/index.pug  |    7 +-
 .../frontend/app/primitives/dropdown/index.scss |   88 +-
 .../frontend/app/primitives/modal/index.scss    |   18 +-
 .../app/primitives/ui-grid-settings/index.scss  |   30 +-
 .../frontend/app/primitives/ui-grid/index.scss  |    6 +-
 .../frontend/gulpfile.babel.js/paths.js         |    1 +
 .../gulpfile.babel.js/webpack/common.js         |   10 +-
 modules/web-console/frontend/package.json       |    1 +
 .../frontend/public/images/icons/clock.svg      |    1 +
 .../frontend/public/images/icons/cross.svg      |    2 +-
 .../frontend/public/images/icons/csv.svg        |    1 +
 .../frontend/public/images/icons/download.svg   |    2 +
 .../frontend/public/images/icons/export.svg     |    1 -
 .../frontend/public/images/icons/gear.svg       |    2 +-
 .../frontend/public/images/icons/index.js       |   23 +
 .../frontend/public/images/icons/manual.svg     |    1 +
 .../frontend/public/stylesheets/style.scss      |   10 +-
 .../frontend/public/stylesheets/variables.scss  |    1 +
 modules/web-console/frontend/views/index.pug    |    1 +
 .../webapp2/META-INF/ignite-webapp-config.xml   |   15 +-
 .../ignite-int-max-values-onheap-config.xml     |    4 +-
 modules/yardstick/config/ignite-jdbc-config.xml |    4 +-
 parent/pom.xml                                  |    2 +-
 353 files changed, 10554 insertions(+), 5707 deletions(-)
----------------------------------------------------------------------



[05/31] ignite git commit: IGNITE-5264: Improved schema-based handling for CREATE INDEX and DROP INDEX operations. This closes #1990.

Posted by sb...@apache.org.
IGNITE-5264: Improved schema-based handling for CREATE INDEX and DROP INDEX operations. This closes #1990.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/3ef78264
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/3ef78264
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/3ef78264

Branch: refs/heads/ignite-5075
Commit: 3ef78264a36171d064627741d8e340c236bc7d38
Parents: c5a04da
Author: devozerov <vo...@gridgain.com>
Authored: Tue May 23 14:22:29 2017 +0300
Committer: devozerov <vo...@gridgain.com>
Committed: Tue May 23 14:22:29 2017 +0300

----------------------------------------------------------------------
 .../processors/query/GridQueryProcessor.java    | 91 +++++++++++---------
 .../processors/query/schema/SchemaKey.java      | 59 -------------
 .../message/SchemaProposeDiscoveryMessage.java  |  7 +-
 .../operation/SchemaAbstractOperation.java      | 25 ++++--
 .../operation/SchemaIndexAbstractOperation.java |  7 +-
 .../operation/SchemaIndexCreateOperation.java   |  8 +-
 .../operation/SchemaIndexDropOperation.java     |  7 +-
 .../processors/query/h2/IgniteH2Indexing.java   | 31 ++++++-
 .../query/h2/database/H2PkHashIndex.java        |  2 +-
 .../query/h2/database/H2TreeIndex.java          |  2 +-
 .../query/h2/ddl/DdlStatementsProcessor.java    | 21 +++--
 .../query/h2/opt/GridH2CollocationModel.java    |  6 +-
 .../query/h2/opt/GridH2IndexBase.java           |  2 +-
 .../processors/query/h2/opt/GridH2Table.java    | 48 ++++++++---
 .../query/h2/opt/GridH2TreeIndex.java           |  2 +-
 .../query/h2/sql/GridSqlDropIndex.java          | 14 +--
 .../query/h2/sql/GridSqlQueryParser.java        |  2 +-
 .../DynamicIndexAbstractBasicSelfTest.java      |  8 +-
 .../DynamicIndexAbstractConcurrentSelfTest.java | 66 +++++++-------
 .../cache/index/SchemaExchangeSelfTest.java     |  2 +-
 .../query/h2/sql/GridQueryParsingTest.java      |  4 +-
 21 files changed, 222 insertions(+), 192 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
index 13525f6..1731edc 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryProcessor.java
@@ -52,7 +52,6 @@ import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheVisitor;
 import org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheVisitorImpl;
 import org.apache.ignite.internal.processors.query.schema.SchemaIndexOperationCancellationToken;
-import org.apache.ignite.internal.processors.query.schema.SchemaKey;
 import org.apache.ignite.internal.processors.query.schema.SchemaOperationClientFuture;
 import org.apache.ignite.internal.processors.query.schema.SchemaOperationException;
 import org.apache.ignite.internal.processors.query.schema.SchemaOperationManager;
@@ -155,7 +154,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     private final GridMessageListener ioLsnr;
 
     /** Schema operations. */
-    private final ConcurrentHashMap<SchemaKey, SchemaOperation> schemaOps = new ConcurrentHashMap<>();
+    private final ConcurrentHashMap<String, SchemaOperation> schemaOps = new ConcurrentHashMap<>();
 
     /** Active propose messages. */
     private final LinkedHashMap<UUID, SchemaProposeDiscoveryMessage> activeProposals = new LinkedHashMap<>();
@@ -339,19 +338,21 @@ public class GridQueryProcessor extends GridProcessorAdapter {
      * @return {@code True} if exchange should be triggered.
      */
     private boolean onSchemaProposeDiscovery(SchemaProposeDiscoveryMessage msg) {
-        UUID opId = msg.operation().id();
-        String space = msg.operation().space();
+        SchemaAbstractOperation op = msg.operation();
+
+        UUID opId = op.id();
+        String cacheName = op.cacheName();
 
         if (!msg.initialized()) {
             // Ensure cache exists on coordinator node.
-            DynamicCacheDescriptor cacheDesc = ctx.cache().cacheDescriptor(space);
+            DynamicCacheDescriptor cacheDesc = ctx.cache().cacheDescriptor(cacheName);
 
             if (cacheDesc == null) {
                 if (log.isDebugEnabled())
                     log.debug("Received schema propose discovery message, but cache doesn't exist " +
                         "(will report error) [opId=" + opId + ", msg=" + msg + ']');
 
-                msg.onError(new SchemaOperationException(SchemaOperationException.CODE_CACHE_NOT_FOUND, space));
+                msg.onError(new SchemaOperationException(SchemaOperationException.CODE_CACHE_NOT_FOUND, cacheName));
             }
             else {
                 CacheConfiguration ccfg = cacheDesc.cacheConfiguration();
@@ -417,9 +418,9 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             // running operation.
             SchemaOperation schemaOp = new SchemaOperation(msg);
 
-            SchemaKey key = msg.schemaKey();
+            String schemaName = msg.schemaName();
 
-            SchemaOperation prevSchemaOp = schemaOps.get(key);
+            SchemaOperation prevSchemaOp = schemaOps.get(schemaName);
 
             if (prevSchemaOp != null) {
                 prevSchemaOp = prevSchemaOp.unwind();
@@ -433,7 +434,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 return false;
             }
             else {
-                schemaOps.put(key, schemaOp);
+                schemaOps.put(schemaName, schemaOp);
 
                 return exchangeReady;
             }
@@ -456,7 +457,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             if (disconnected)
                 return;
 
-            SchemaOperation curOp = schemaOps.get(msg.schemaKey());
+            SchemaOperation curOp = schemaOps.get(msg.schemaName());
 
             assert curOp != null;
             assert F.eq(opId, curOp.id());
@@ -493,7 +494,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
             // Apply changes to public cache schema if operation is successful and original cache is still there.
             if (!msg.hasError()) {
-                DynamicCacheDescriptor cacheDesc = ctx.cache().cacheDescriptor(msg.operation().space());
+                DynamicCacheDescriptor cacheDesc = ctx.cache().cacheDescriptor(msg.operation().cacheName());
 
                 if (cacheDesc != null && F.eq(cacheDesc.deploymentId(), proposeMsg.deploymentId()))
                     cacheDesc.schemaChangeFinish(msg);
@@ -503,7 +504,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             msg.proposeMessage(proposeMsg);
 
             if (exchangeReady) {
-                SchemaOperation op = schemaOps.get(proposeMsg.schemaKey());
+                SchemaOperation op = schemaOps.get(proposeMsg.schemaName());
 
                 if (F.eq(op.id(), opId)) {
                     // Completed top operation.
@@ -529,9 +530,9 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             }
             else {
                 // Set next operation as top-level one.
-                SchemaKey schemaKey = proposeMsg.schemaKey();
+                String schemaName = proposeMsg.schemaName();
 
-                SchemaOperation op = schemaOps.remove(schemaKey);
+                SchemaOperation op = schemaOps.remove(schemaName);
 
                 assert op != null;
                 assert F.eq(op.id(), opId);
@@ -540,7 +541,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 SchemaOperation nextOp = op.next();
 
                 if (nextOp != null)
-                    schemaOps.put(schemaKey, nextOp);
+                    schemaOps.put(schemaName, nextOp);
             }
 
             // Clean stale IO messages from just-joined nodes.
@@ -571,13 +572,13 @@ public class GridQueryProcessor extends GridProcessorAdapter {
         // Get current cache state.
         SchemaProposeDiscoveryMessage msg = schemaOp.proposeMessage();
 
-        String space = msg.operation().space();
+        String cacheName = msg.operation().cacheName();
 
-        DynamicCacheDescriptor cacheDesc = ctx.cache().cacheDescriptor(space);
+        DynamicCacheDescriptor cacheDesc = ctx.cache().cacheDescriptor(cacheName);
 
         boolean cacheExists = cacheDesc != null && F.eq(msg.deploymentId(), cacheDesc.deploymentId());
 
-        boolean cacheRegistered = cacheExists && spaces.contains(CU.mask(space));
+        boolean cacheRegistered = cacheExists && spaces.contains(CU.mask(cacheName));
 
         // Validate schema state and decide whether we should proceed or not.
         SchemaAbstractOperation op = msg.operation();
@@ -612,7 +613,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             }
         }
         else
-            err = new SchemaOperationException(SchemaOperationException.CODE_CACHE_NOT_FOUND, op.space());
+            err = new SchemaOperationException(SchemaOperationException.CODE_CACHE_NOT_FOUND, cacheName);
 
         // Start operation.
         SchemaOperationWorker worker =
@@ -897,7 +898,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
         boolean nop = false;
         SchemaOperationException err = null;
 
-        String space = op.space();
+        String cacheName = op.cacheName();
 
         if (op instanceof SchemaIndexCreateOperation) {
             SchemaIndexCreateOperation op0 = (SchemaIndexCreateOperation) op;
@@ -907,7 +908,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             // Make sure table exists.
             String tblName = op0.tableName();
 
-            type = type(space, tblName);
+            type = type(cacheName, tblName);
 
             if (type == null)
                 err = new SchemaOperationException(SchemaOperationException.CODE_TABLE_NOT_FOUND, tblName);
@@ -927,7 +928,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             if (err == null) {
                 String idxName = op0.index().getName();
 
-                QueryIndexKey idxKey = new QueryIndexKey(space, idxName);
+                QueryIndexKey idxKey = new QueryIndexKey(cacheName, idxName);
 
                 if (idxs.get(idxKey) != null) {
                     if (op0.ifNotExists())
@@ -942,7 +943,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
             String idxName = op0.indexName();
 
-            QueryIndexDescriptorImpl oldIdx = idxs.get(new QueryIndexKey(space, idxName));
+            QueryIndexDescriptorImpl oldIdx = idxs.get(new QueryIndexKey(cacheName, idxName));
 
             if (oldIdx == null) {
                 if (op0.ifExists())
@@ -1153,6 +1154,8 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             if (log.isDebugEnabled())
                 log.debug("Local operation finished successfully [opId=" + op.id() + ']');
 
+            String cacheName = op.cacheName();
+
             try {
                 if (op instanceof SchemaIndexCreateOperation) {
                     SchemaIndexCreateOperation op0 = (SchemaIndexCreateOperation)op;
@@ -1161,7 +1164,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
                     QueryIndexDescriptorImpl idxDesc = type.index(op0.indexName());
 
-                    QueryIndexKey idxKey = new QueryIndexKey(op.space(), op0.indexName());
+                    QueryIndexKey idxKey = new QueryIndexKey(cacheName, op0.indexName());
 
                     idxs.put(idxKey, idxDesc);
                 }
@@ -1172,7 +1175,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
 
                     QueryUtils.processDynamicIndexChange(op0.indexName(), null, type);
 
-                    QueryIndexKey idxKey = new QueryIndexKey(op.space(), op0.indexName());
+                    QueryIndexKey idxKey = new QueryIndexKey(cacheName, op0.indexName());
 
                     idxs.remove(idxKey);
                 }
@@ -1227,12 +1230,12 @@ public class GridQueryProcessor extends GridProcessorAdapter {
         if (log.isDebugEnabled())
             log.debug("Started local index operation [opId=" + op.id() + ']');
 
-        String space = op.space();
+        String cacheName = op.cacheName();
 
-        GridCacheAdapter cache = ctx.cache().internalCache(op.space());
+        GridCacheAdapter cache = ctx.cache().internalCache(cacheName);
 
         if (cache == null || !F.eq(depId, cache.context().dynamicDeploymentId()))
-            throw new SchemaOperationException(SchemaOperationException.CODE_CACHE_NOT_FOUND, op.space());
+            throw new SchemaOperationException(SchemaOperationException.CODE_CACHE_NOT_FOUND, cacheName);
 
         try {
             if (op instanceof SchemaIndexCreateOperation) {
@@ -1241,14 +1244,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 QueryIndexDescriptorImpl idxDesc = QueryUtils.createIndexDescriptor(type, op0.index());
 
                 SchemaIndexCacheVisitor visitor =
-                    new SchemaIndexCacheVisitorImpl(this, cache.context(), space, op0.tableName(), cancelTok);
+                    new SchemaIndexCacheVisitorImpl(this, cache.context(), cacheName, op0.tableName(), cancelTok);
 
-                idx.dynamicIndexCreate(space, op0.tableName(), idxDesc, op0.ifNotExists(), visitor);
+                idx.dynamicIndexCreate(cacheName, op0.tableName(), idxDesc, op0.ifNotExists(), visitor);
             }
             else if (op instanceof SchemaIndexDropOperation) {
                 SchemaIndexDropOperation op0 = (SchemaIndexDropOperation) op;
 
-                idx.dynamicIndexDrop(space, op0.indexName(), op0.ifExists());
+                idx.dynamicIndexDrop(cacheName, op0.indexName(), op0.ifExists());
             }
             else
                 throw new SchemaOperationException("Unsupported operation: " + op);
@@ -1861,15 +1864,17 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     /**
      * Entry point for index procedure.
      *
-     * @param space Space name.
+     * @param cacheName Cache name.
+     * @param schemaName Schema name.
      * @param tblName Table name.
      * @param idx Index.
      * @param ifNotExists When set to {@code true} operation will fail if index already exists.
      * @return Future completed when index is created.
      */
-    public IgniteInternalFuture<?> dynamicIndexCreate(String space, String tblName, QueryIndex idx,
-        boolean ifNotExists) {
-        SchemaAbstractOperation op = new SchemaIndexCreateOperation(UUID.randomUUID(), space, tblName, idx, ifNotExists);
+    public IgniteInternalFuture<?> dynamicIndexCreate(String cacheName, String schemaName, String tblName,
+        QueryIndex idx, boolean ifNotExists) {
+        SchemaAbstractOperation op = new SchemaIndexCreateOperation(UUID.randomUUID(), cacheName, schemaName, tblName,
+            idx, ifNotExists);
 
         return startIndexOperationDistributed(op);
     }
@@ -1877,12 +1882,16 @@ public class GridQueryProcessor extends GridProcessorAdapter {
     /**
      * Entry point for index drop procedure
      *
+     * @param cacheName Cache name.
+     * @param schemaName Schema name.
      * @param idxName Index name.
      * @param ifExists When set to {@code true} operation fill fail if index doesn't exists.
      * @return Future completed when index is created.
      */
-    public IgniteInternalFuture<?> dynamicIndexDrop(String space, String idxName, boolean ifExists) {
-        SchemaAbstractOperation op = new SchemaIndexDropOperation(UUID.randomUUID(), space, idxName, ifExists);
+    public IgniteInternalFuture<?> dynamicIndexDrop(String cacheName, String schemaName, String idxName,
+        boolean ifExists) {
+        SchemaAbstractOperation op = new SchemaIndexDropOperation(UUID.randomUUID(), cacheName, schemaName, idxName,
+            ifExists);
 
         return startIndexOperationDistributed(op);
     }
@@ -2215,7 +2224,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
             SchemaProposeDiscoveryMessage proposeMsg = activeProposals.get(opId);
 
             if (proposeMsg != null) {
-                SchemaOperation op = schemaOps.get(proposeMsg.schemaKey());
+                SchemaOperation op = schemaOps.get(proposeMsg.schemaName());
 
                 if (op != null && F.eq(op.id(), opId) && op.started() && coordinator().isLocal()) {
                     if (log.isDebugEnabled())
@@ -2401,14 +2410,14 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                 return;
 
             final UUID opId = id();
-            final SchemaKey key = proposeMsg.schemaKey();
+            final String schemaName = proposeMsg.schemaName();
 
             // Operation might be still in progress on client nodes which are not tracked by coordinator,
             // so we chain to operation future instead of doing synchronous unwind.
             mgr.worker().future().listen(new IgniteInClosure<IgniteInternalFuture>() {
                 @Override public void apply(IgniteInternalFuture fut) {
                     synchronized (stateMux) {
-                        SchemaOperation op = schemaOps.remove(key);
+                        SchemaOperation op = schemaOps.remove(schemaName);
 
                         assert op != null;
                         assert F.eq(op.id(), opId);
@@ -2417,7 +2426,7 @@ public class GridQueryProcessor extends GridProcessorAdapter {
                         final SchemaOperation nextOp = op.next();
 
                         if (nextOp != null) {
-                            schemaOps.put(key, nextOp);
+                            schemaOps.put(schemaName, nextOp);
 
                             if (log.isDebugEnabled())
                                 log.debug("Next schema change operation started [opId=" + nextOp.id() + ']');

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaKey.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaKey.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaKey.java
deleted file mode 100644
index 3f12b77..0000000
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaKey.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.schema;
-
-import org.apache.ignite.internal.util.typedef.F;
-import org.apache.ignite.lang.IgniteUuid;
-
-/**
- * Schema key.
- */
-public class SchemaKey {
-    /** Space. */
-    private final String space;
-
-    /** Deployment ID. */
-    private final IgniteUuid depId;
-
-    /**
-     * Constructor.
-     *
-     * @param space Space.
-     * @param depId Deployment ID.
-     */
-    public SchemaKey(String space, IgniteUuid depId) {
-        this.space = space;
-        this.depId = depId;
-    }
-
-    /** {@inheritDoc} */
-    @Override public int hashCode() {
-        return 31 * (space != null ? space.hashCode() : 0) + depId.hashCode();
-    }
-
-    /** {@inheritDoc} */
-    @Override public boolean equals(Object obj) {
-        if (obj instanceof SchemaKey) {
-            SchemaKey other = (SchemaKey)obj;
-
-            return F.eq(space, other.space) && F.eq(depId, other.depId);
-        }
-
-        return false;
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/message/SchemaProposeDiscoveryMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/message/SchemaProposeDiscoveryMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/message/SchemaProposeDiscoveryMessage.java
index 664ee03..5fd2606 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/message/SchemaProposeDiscoveryMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/message/SchemaProposeDiscoveryMessage.java
@@ -18,7 +18,6 @@
 package org.apache.ignite.internal.processors.query.schema.message;
 
 import org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage;
-import org.apache.ignite.internal.processors.query.schema.SchemaKey;
 import org.apache.ignite.internal.processors.query.schema.SchemaOperationException;
 import org.apache.ignite.internal.processors.query.schema.operation.SchemaAbstractOperation;
 import org.apache.ignite.internal.util.typedef.internal.S;
@@ -120,10 +119,10 @@ public class SchemaProposeDiscoveryMessage extends SchemaAbstractDiscoveryMessag
     }
 
     /**
-     * @return Schema key.
+     * @return Schema name.
      */
-    public SchemaKey schemaKey() {
-        return new SchemaKey(operation().space(), depId);
+    public String schemaName() {
+        return operation().schemaName();
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
index 8418ece..726c90c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaAbstractOperation.java
@@ -32,18 +32,22 @@ public abstract class SchemaAbstractOperation implements Serializable {
     /** Operation ID. */
     private final UUID opId;
 
-    /** Space. */
-    private final String space;
+    /** Cache name. */
+    private final String cacheName;
+
+    /** Schema name. */
+    private final String schemaName;
 
     /**
      * Constructor.
      *
      * @param opId Operation ID.
-     * @param space Space.
+     * @param schemaName Schema name.
      */
-    public SchemaAbstractOperation(UUID opId, String space) {
+    public SchemaAbstractOperation(UUID opId, String cacheName, String schemaName) {
         this.opId = opId;
-        this.space = space;
+        this.cacheName = cacheName;
+        this.schemaName = schemaName;
     }
 
     /**
@@ -56,8 +60,15 @@ public abstract class SchemaAbstractOperation implements Serializable {
     /**
      * @return Space.
      */
-    public String space() {
-        return space;
+    public String cacheName() {
+        return cacheName;
+    }
+
+    /**
+     * @return Schema name.
+     */
+    public String schemaName() {
+        return schemaName;
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexAbstractOperation.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexAbstractOperation.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexAbstractOperation.java
index fc4a9ff..31badd0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexAbstractOperation.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexAbstractOperation.java
@@ -27,10 +27,11 @@ public abstract class SchemaIndexAbstractOperation extends SchemaAbstractOperati
      * Constructor.
      *
      * @param opId Operation ID.
-     * @param space Space.
+     * @param cacheName Cache name.
+     * @param schemaName Schema name.
      */
-    public SchemaIndexAbstractOperation(UUID opId, String space) {
-        super(opId, space);
+    public SchemaIndexAbstractOperation(UUID opId, String cacheName, String schemaName) {
+        super(opId, cacheName, schemaName);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexCreateOperation.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexCreateOperation.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexCreateOperation.java
index 9281f2a..7b4543f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexCreateOperation.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexCreateOperation.java
@@ -45,13 +45,15 @@ public class SchemaIndexCreateOperation extends SchemaIndexAbstractOperation {
      * Constructor.
      *
      * @param opId Operation id.
-     * @param space Space.
+     * @param cacheName Cache name.
+     * @param schemaName Schame name.
      * @param tblName Table name.
      * @param idx Index params.
      * @param ifNotExists Ignore operation if index exists.
      */
-    public SchemaIndexCreateOperation(UUID opId, String space, String tblName, QueryIndex idx, boolean ifNotExists) {
-        super(opId, space);
+    public SchemaIndexCreateOperation(UUID opId, String cacheName, String schemaName, String tblName, QueryIndex idx,
+        boolean ifNotExists) {
+        super(opId, cacheName, schemaName);
 
         this.tblName = tblName;
         this.idx = idx;

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexDropOperation.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexDropOperation.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexDropOperation.java
index da60560..406be66 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexDropOperation.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/operation/SchemaIndexDropOperation.java
@@ -38,12 +38,13 @@ public class SchemaIndexDropOperation extends SchemaIndexAbstractOperation {
      * Constructor.
      *
      * @param opId Operation id.
-     * @param space Space.
+     * @param cacheName Cache name.
+     * @param schemaName Schema name.
      * @param idxName Index name.
      * @param ifExists Ignore operation if index doesn't exist.
      */
-    public SchemaIndexDropOperation(UUID opId, String space, String idxName, boolean ifExists) {
-        super(opId, space);
+    public SchemaIndexDropOperation(UUID opId, String cacheName, String schemaName, String idxName, boolean ifExists) {
+        super(opId, cacheName, schemaName);
 
         this.idxName = idxName;
         this.ifExists = ifExists;

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
index 0874ddc..ce69bb1 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
@@ -1616,7 +1616,11 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                             break;
                         }
                         catch (SQLException e) {
-                            if (!cachesCreated && e.getErrorCode() == ErrorCode.SCHEMA_NOT_FOUND_1) {
+                            if (!cachesCreated && (
+                                e.getErrorCode() == ErrorCode.SCHEMA_NOT_FOUND_1 ||
+                                e.getErrorCode() == ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1 ||
+                                e.getErrorCode() == ErrorCode.INDEX_NOT_FOUND_1)
+                            ) {
                                 try {
                                     ctx.cache().createMissingQueryCaches();
                                 }
@@ -1632,7 +1636,6 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                         }
                     }
 
-
                     prepared = GridSqlQueryParser.prepared(stmt);
 
                     if (qry instanceof JdbcSqlFieldsQuery && ((JdbcSqlFieldsQuery) qry).isQuery() != prepared.isQuery())
@@ -1642,8 +1645,8 @@ public class IgniteH2Indexing implements GridQueryIndexing {
                     if (prepared.isQuery()) {
                         bindParameters(stmt, F.asList(qry.getArgs()));
 
-                        twoStepQry = GridSqlQuerySplitter.split((JdbcPreparedStatement)stmt, qry.getArgs(), grpByCollocated,
-                            distributedJoins, enforceJoinOrder, this);
+                        twoStepQry = GridSqlQuerySplitter.split((JdbcPreparedStatement)stmt, qry.getArgs(),
+                            grpByCollocated, distributedJoins, enforceJoinOrder, this);
 
                         assert twoStepQry != null;
                     }
@@ -2035,6 +2038,26 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     }
 
     /**
+     * Find table for index.
+     *
+     * @param schemaName Schema name.
+     * @param idxName Index name.
+     * @return Table or {@code null} if index is not found.
+     */
+    public GridH2Table dataTableForIndex(String schemaName, String idxName) {
+        for (Map.Entry<QueryTable, GridH2Table> dataTableEntry : dataTables.entrySet()) {
+            if (F.eq(dataTableEntry.getKey().schema(), schemaName)) {
+                GridH2Table h2Tbl = dataTableEntry.getValue();
+
+                if (h2Tbl.containsUserIndex(idxName))
+                    return h2Tbl;
+            }
+        }
+
+        return null;
+    }
+
+    /**
      * Gets corresponding DB type from java class.
      *
      * @param cls Java class.

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
index 149eda7..7579fa5 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2PkHashIndex.java
@@ -90,7 +90,7 @@ public class H2PkHashIndex extends GridH2IndexBase {
         IgniteBiPredicate<Object, Object> p = null;
 
         if (f != null) {
-            String spaceName = getTable().spaceName();
+            String spaceName = getTable().cacheName();
 
             p = f.forSpace(spaceName);
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
index 58ab32d..814df77 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/database/H2TreeIndex.java
@@ -167,7 +167,7 @@ public class H2TreeIndex extends GridH2IndexBase {
             IgniteBiPredicate<Object, Object> p = null;
 
             if (f != null) {
-                String spaceName = getTable().spaceName();
+                String spaceName = getTable().cacheName();
 
                 p = f.forSpace(spaceName);
             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
index 949ea6a..fe2bfdb 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/ddl/DdlStatementsProcessor.java
@@ -39,6 +39,7 @@ import org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropIndex;
 import org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser;
 import org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement;
 import org.apache.ignite.internal.processors.query.schema.SchemaOperationException;
+import org.apache.ignite.internal.util.future.GridFinishedFuture;
 import org.h2.command.Prepared;
 import org.h2.command.ddl.CreateIndex;
 import org.h2.command.ddl.DropIndex;
@@ -87,8 +88,6 @@ public class DdlStatementsProcessor {
             if (gridStmt instanceof GridSqlCreateIndex) {
                 GridSqlCreateIndex createIdx = (GridSqlCreateIndex)gridStmt;
 
-                String spaceName = idx.space(createIdx.schemaName());
-
                 QueryIndex newIdx = new QueryIndex();
 
                 newIdx.setName(createIdx.index().getName());
@@ -119,14 +118,24 @@ public class DdlStatementsProcessor {
 
                 newIdx.setFields(flds);
 
-                fut = ctx.query().dynamicIndexCreate(spaceName, typeDesc.tableName(), newIdx, createIdx.ifNotExists());
+                fut = ctx.query().dynamicIndexCreate(tbl.cacheName(), createIdx.schemaName(), typeDesc.tableName(),
+                    newIdx, createIdx.ifNotExists());
             }
             else if (gridStmt instanceof GridSqlDropIndex) {
                 GridSqlDropIndex dropIdx = (GridSqlDropIndex)gridStmt;
 
-                String spaceName = idx.space(dropIdx.schemaName());
-
-                fut = ctx.query().dynamicIndexDrop(spaceName, dropIdx.name(), dropIdx.ifExists());
+                GridH2Table tbl = idx.dataTableForIndex(dropIdx.schemaName(), dropIdx.indexName());
+
+                if (tbl != null)
+                    fut = ctx.query().dynamicIndexDrop(tbl.cacheName(), dropIdx.schemaName(), dropIdx.indexName(),
+                        dropIdx.ifExists());
+                else {
+                    if (dropIdx.ifExists())
+                        fut = new GridFinishedFuture();
+                    else
+                        throw new SchemaOperationException(SchemaOperationException.CODE_INDEX_NOT_FOUND,
+                            dropIdx.indexName());
+                }
             }
             else
                 throw new IgniteSQLException("Unsupported DDL operation: " + sql,

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2CollocationModel.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2CollocationModel.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2CollocationModel.java
index 037607b..5cb983c 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2CollocationModel.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2CollocationModel.java
@@ -387,11 +387,11 @@ public final class GridH2CollocationModel {
 
         if (validate) {
             if (tbl.rowDescriptor().context().customAffinityMapper())
-                throw customAffinityError(tbl.spaceName());
+                throw customAffinityError(tbl.cacheName());
 
             if (F.isEmpty(tf.getIndexConditions())) {
                 throw new CacheException("Failed to prepare distributed join query: " +
-                    "join condition does not use index [joinedCache=" + tbl.spaceName() +
+                    "join condition does not use index [joinedCache=" + tbl.cacheName() +
                     ", plan=" + tf.getSelect().getPlanSQL() + ']');
             }
         }
@@ -484,7 +484,7 @@ public final class GridH2CollocationModel {
 
         if (t instanceof GridH2Table) {
             if (validate && ((GridH2Table)t).rowDescriptor().context().customAffinityMapper())
-                throw customAffinityError(((GridH2Table)t).spaceName());
+                throw customAffinityError(((GridH2Table)t).cacheName());
 
             IndexColumn affCol = ((GridH2Table)t).getAffinityKeyColumn();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
index 12850f4..30fb612 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2IndexBase.java
@@ -342,7 +342,7 @@ public abstract class GridH2IndexBase extends BaseIndex {
      * @return Filtered iterator.
      */
     protected GridCursor<GridH2Row> filter(GridCursor<GridH2Row> cursor, IndexingQueryFilter filter) {
-        return new FilteringCursor(cursor, U.currentTimeMillis(), filter, getTable().spaceName());
+        return new FilteringCursor(cursor, U.currentTimeMillis(), filter, getTable().cacheName());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
index 37c03e3..41cf68b 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Table.java
@@ -65,7 +65,7 @@ import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType
  */
 public class GridH2Table extends TableBase {
     /** */
-    private final String spaceName;
+    private final String cacheName;
 
     /** */
     private final GridH2RowDescriptor desc;
@@ -116,16 +116,16 @@ public class GridH2Table extends TableBase {
      * @param desc Row descriptor.
      * @param rowFactory Row factory.
      * @param idxsFactory Indexes factory.
-     * @param spaceName Space name.
+     * @param cacheName Cache name.
      */
     public GridH2Table(CreateTableData createTblData, @Nullable GridH2RowDescriptor desc, H2RowFactory rowFactory,
-        GridH2SystemIndexFactory idxsFactory, @Nullable String spaceName) {
+        GridH2SystemIndexFactory idxsFactory, String cacheName) {
         super(createTblData);
 
         assert idxsFactory != null;
 
         this.desc = desc;
-        this.spaceName = spaceName;
+        this.cacheName = cacheName;
 
         if (desc != null && desc.context() != null && !desc.context().customAffinityMapper()) {
             boolean affinityColExists = true;
@@ -211,8 +211,8 @@ public class GridH2Table extends TableBase {
     /**
      * @return Space name.
      */
-    @Nullable public String spaceName() {
-        return spaceName;
+    @Nullable public String cacheName() {
+        return cacheName;
     }
 
     /** {@inheritDoc} */
@@ -759,12 +759,12 @@ public class GridH2Table extends TableBase {
 
             Index cloneIdx = createDuplicateIndexIfNeeded(idx);
 
-            ArrayList<Index> newIdxs = new ArrayList<>(
-                    idxs.size() + ((cloneIdx == null) ? 1 : 2));
+            ArrayList<Index> newIdxs = new ArrayList<>(idxs.size() + ((cloneIdx == null) ? 1 : 2));
 
             newIdxs.addAll(idxs);
 
             newIdxs.add(idx);
+
             if (cloneIdx != null)
                 newIdxs.add(cloneIdx);
 
@@ -804,6 +804,23 @@ public class GridH2Table extends TableBase {
         }
     }
 
+    /**
+     * Check whether user index with provided name exists.
+     *
+     * @param idxName Index name.
+     * @return {@code True} if exists.
+     */
+    public boolean containsUserIndex(String idxName) {
+        for (int i = 2; i < idxs.size(); i++) {
+            Index idx = idxs.get(i);
+
+            if (idx.getName().equalsIgnoreCase(idxName))
+                return true;
+        }
+
+        return false;
+    }
+
     /** {@inheritDoc} */
     @Override public void removeIndex(Index h2Idx) {
         throw DbException.getUnsupportedException("must use removeIndex(session, idx)");
@@ -823,7 +840,7 @@ public class GridH2Table extends TableBase {
             Index targetIdx = (h2Idx instanceof GridH2ProxyIndex)?
                     ((GridH2ProxyIndex)h2Idx).underlyingIndex(): h2Idx;
 
-            for (int i = 2; i < idxs.size(); ) {
+            for (int i = 2; i < idxs.size();) {
                 Index idx = idxs.get(i);
 
                 if (idx == targetIdx || (idx instanceof GridH2ProxyIndex &&
@@ -983,24 +1000,29 @@ public class GridH2Table extends TableBase {
      * @return Proxy index.
      */
     public Index createDuplicateIndexIfNeeded(Index target) {
-        if (!(target instanceof H2TreeIndex) &&
-            !(target instanceof SpatialIndex))
+        if (!(target instanceof H2TreeIndex) && !(target instanceof SpatialIndex))
             return null;
 
         IndexColumn[] cols = target.getIndexColumns();
+
         List<IndexColumn> proxyCols = new ArrayList<>(cols.length);
+
         boolean modified = false;
-        for (int i = 0; i < cols.length; i++) {
-            IndexColumn col = cols[i];
+
+        for (IndexColumn col : cols) {
             IndexColumn proxyCol = new IndexColumn();
+
             proxyCol.columnName = col.columnName;
             proxyCol.column = col.column;
             proxyCol.sortType = col.sortType;
 
             int altColId = desc.getAlternativeColumnId(proxyCol.column.getColumnId());
+
             if (altColId != proxyCol.column.getColumnId()) {
                 proxyCol.column = getColumn(altColId);
+
                 proxyCol.columnName = proxyCol.column.getName();
+
                 modified = true;
             }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
index 56f6667..39256d4 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2TreeIndex.java
@@ -206,7 +206,7 @@ public class GridH2TreeIndex extends GridH2IndexBase implements Comparator<GridS
         int seg = threadLocalSegment();
 
         // Fast path if we don't need to perform any filtering.
-        if (f == null || f.forSpace((getTable()).spaceName()) == null)
+        if (f == null || f.forSpace((getTable()).cacheName()) == null)
             try {
                 return treeForRead(seg).size();
             } catch (IgniteCheckedException e) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlDropIndex.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlDropIndex.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlDropIndex.java
index c844b49..f3250b0 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlDropIndex.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlDropIndex.java
@@ -24,7 +24,7 @@ import org.h2.command.Parser;
  */
 public class GridSqlDropIndex extends GridSqlStatement {
     /** Index name. */
-    private String name;
+    private String idxName;
 
     /** Schema name. */
     private String schemaName;
@@ -35,15 +35,15 @@ public class GridSqlDropIndex extends GridSqlStatement {
     /**
      * @return Index name.
      */
-    public String name() {
-        return name;
+    public String indexName() {
+        return idxName;
     }
 
     /**
-     * @param name Index name.
+     * @param idxName Index name.
      */
-    public void name(String name) {
-        this.name = name;
+    public void indexName(String idxName) {
+        this.idxName = idxName;
     }
 
     /**
@@ -77,6 +77,6 @@ public class GridSqlDropIndex extends GridSqlStatement {
     /** {@inheritDoc} */
     @Override public String getSQL() {
         return "DROP INDEX " + (ifExists ? "IF EXISTS " : "") + Parser.quoteIdentifier(schemaName) + '.' +
-            Parser.quoteIdentifier(name);
+            Parser.quoteIdentifier(idxName);
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQueryParser.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQueryParser.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQueryParser.java
index 13d4237..71c77ac 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQueryParser.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQueryParser.java
@@ -725,7 +725,7 @@ public class GridSqlQueryParser {
     private GridSqlDropIndex parseDropIndex(DropIndex dropIdx) {
         GridSqlDropIndex res = new GridSqlDropIndex();
 
-        res.name(DROP_INDEX_NAME.get(dropIdx));
+        res.indexName(DROP_INDEX_NAME.get(dropIdx));
         res.schemaName(SCHEMA_COMMAND_SCHEMA.get(dropIdx).getName());
         res.ifExists(DROP_INDEX_IF_EXISTS.get(dropIdx));
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
index 6621bb4..1241d0c 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractBasicSelfTest.java
@@ -351,7 +351,9 @@ public abstract class DynamicIndexAbstractBasicSelfTest extends DynamicIndexAbst
         final QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
         try {
-            queryProcessor(node()).dynamicIndexCreate(randomString(), TBL_NAME, idx, false).get();
+            String cacheName = randomString();
+
+            queryProcessor(node()).dynamicIndexCreate(cacheName, cacheName, TBL_NAME, idx, false).get();
         }
         catch (SchemaOperationException e) {
             assertEquals(SchemaOperationException.CODE_CACHE_NOT_FOUND, e.code());
@@ -844,7 +846,9 @@ public abstract class DynamicIndexAbstractBasicSelfTest extends DynamicIndexAbst
         initialize(mode, atomicityMode, near);
 
         try {
-            queryProcessor(node()).dynamicIndexDrop(randomString(), "my_idx", false).get();
+            String cacheName = randomString();
+
+            queryProcessor(node()).dynamicIndexDrop(cacheName, cacheName, "my_idx", false).get();
         }
         catch (SchemaOperationException e) {
             assertEquals(SchemaOperationException.CODE_CACHE_NOT_FOUND, e.code());

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
index ae86933..f9e2f75 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/DynamicIndexAbstractConcurrentSelfTest.java
@@ -39,10 +39,12 @@ import org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheVisito
 import org.apache.ignite.internal.processors.query.schema.SchemaOperationException;
 import org.apache.ignite.internal.util.typedef.T2;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import javax.cache.Cache;
-import java.util.*;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CountDownLatch;
@@ -148,7 +150,8 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
 
         QueryIndex idx1 = index(IDX_NAME_1, field(FIELD_NAME_1));
 
-        IgniteInternalFuture<?> idxFut1 = queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx1, false);
+        IgniteInternalFuture<?> idxFut1 = queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME,
+            idx1, false);
 
         Thread.sleep(100);
 
@@ -168,7 +171,8 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
 
         QueryIndex idx2 = index(IDX_NAME_2, field(alias(FIELD_NAME_2)));
 
-        IgniteInternalFuture<?> idxFut2 = queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx2, false);
+        IgniteInternalFuture<?> idxFut2 =
+            queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx2, false);
 
         Thread.sleep(100);
 
@@ -203,8 +207,11 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         QueryIndex idx1 = index(IDX_NAME_1, field(FIELD_NAME_1));
         QueryIndex idx2 = index(IDX_NAME_2, field(alias(FIELD_NAME_2)));
 
-        IgniteInternalFuture<?> idxFut1 = queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx1, false);
-        IgniteInternalFuture<?> idxFut2 = queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx2, false);
+        IgniteInternalFuture<?> idxFut1 =
+            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx1, false);
+
+        IgniteInternalFuture<?> idxFut2 =
+            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx2, false);
 
         // Start even more nodes of different flavors
         Ignition.start(serverConfiguration(5));
@@ -247,7 +254,8 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
 
         QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
-        IgniteInternalFuture<?> idxFut = queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false);
+        IgniteInternalFuture<?> idxFut =
+            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false);
 
         Ignition.start(serverConfiguration(2));
         Ignition.start(serverConfiguration(3, true));
@@ -317,7 +325,7 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         // Create index.
         QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
-        queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false).get();
+        queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false).get();
 
         // Stop updates once index is ready.
         stopped.set(true);
@@ -389,7 +397,7 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
         final IgniteInternalFuture<?> idxFut =
-            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false);
+            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false);
 
         Thread.sleep(100);
 
@@ -437,7 +445,7 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
         final IgniteInternalFuture<?> idxFut =
-            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false);
+            queryProcessor(srv1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false);
 
         Thread.sleep(100);
 
@@ -487,12 +495,12 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
                     IgniteInternalFuture fut;
 
                     if (exists) {
-                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true);
+                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true);
 
                         exists = false;
                     }
                     else {
-                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true);
+                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true);
 
                         exists = true;
                     }
@@ -519,8 +527,8 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         // Make sure nothing hanged.
         idxFut.get();
 
-        queryProcessor(cli).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true).get();
-        queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true).get();
+        queryProcessor(cli).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true).get();
+        queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true).get();
 
         assertIndex(CACHE_NAME, TBL_NAME, IDX_NAME_1, field(FIELD_NAME_1));
 
@@ -563,12 +571,12 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
                     IgniteInternalFuture fut;
 
                     if (exists) {
-                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true);
+                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true);
 
                         exists = false;
                     }
                     else {
-                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true);
+                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true);
 
                         exists = true;
                     }
@@ -649,7 +657,7 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
             @Override public void run() throws Exception {
                 final QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
-                queryProcessor(srv).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false).get();
+                queryProcessor(srv).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false).get();
             }
         });
 
@@ -660,7 +668,7 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         reconnectClientNode(srv, cli, restartCache, new RunnableX() {
             @Override public void run() throws Exception {
                 if (!restartCache)
-                    queryProcessor(srv).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, false).get();
+                    queryProcessor(srv).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, false).get();
             }
         });
 
@@ -670,7 +678,7 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         // Update existing index.
         QueryIndex idx = index(IDX_NAME_2, field(alias(FIELD_NAME_2)));
 
-        queryProcessor(srv).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false).get();
+        queryProcessor(srv).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false).get();
 
         assertIndex(cli, true, CACHE_NAME, TBL_NAME, IDX_NAME_2, field(alias(FIELD_NAME_2)));
         assertIndexUsed(IDX_NAME_2, SQL_SIMPLE_FIELD_2, SQL_ARG_2);
@@ -678,11 +686,11 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         reconnectClientNode(srv, cli, restartCache, new RunnableX() {
             @Override public void run() throws Exception {
                 if (!restartCache)
-                    queryProcessor(srv).dynamicIndexDrop(CACHE_NAME, IDX_NAME_2, false).get();
+                    queryProcessor(srv).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_2, false).get();
 
                 final QueryIndex idx = index(IDX_NAME_2, field(FIELD_NAME_1), field(alias(FIELD_NAME_2)));
 
-                queryProcessor(srv).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false);
+                queryProcessor(srv).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false);
             }
         });
 
@@ -800,12 +808,12 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
                     IgniteInternalFuture fut;
 
                     if (exists) {
-                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true);
+                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true);
 
                         exists = false;
                     }
                     else {
-                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true);
+                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true);
 
                         exists = true;
                     }
@@ -836,8 +844,8 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         // Make sure cache is operational at this point.
         cli.getOrCreateCache(cacheConfiguration());
 
-        queryProcessor(cli).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true).get();
-        queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true).get();
+        queryProcessor(cli).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true).get();
+        queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true).get();
 
         assertIndex(CACHE_NAME, TBL_NAME, IDX_NAME_1, field(FIELD_NAME_1));
 
@@ -901,12 +909,12 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
                     IgniteInternalFuture fut;
 
                     if (exists) {
-                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true);
+                        fut = queryProcessor(node).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true);
 
                         exists = false;
                     }
                     else {
-                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true);
+                        fut = queryProcessor(node).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true);
 
                         exists = true;
                     }
@@ -937,8 +945,8 @@ public abstract class DynamicIndexAbstractConcurrentSelfTest extends DynamicInde
         // Make sure cache is operational at this point.
         cli.getOrCreateCache(cacheConfiguration());
 
-        queryProcessor(cli).dynamicIndexDrop(CACHE_NAME, IDX_NAME_1, true).get();
-        queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, true).get();
+        queryProcessor(cli).dynamicIndexDrop(CACHE_NAME, CACHE_NAME, IDX_NAME_1, true).get();
+        queryProcessor(cli).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, true).get();
 
         assertIndex(CACHE_NAME, TBL_NAME, IDX_NAME_1, field(FIELD_NAME_1));
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/SchemaExchangeSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/SchemaExchangeSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/SchemaExchangeSelfTest.java
index 5a00345..71244bb 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/SchemaExchangeSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/index/SchemaExchangeSelfTest.java
@@ -469,7 +469,7 @@ public class SchemaExchangeSelfTest extends AbstractSchemaSelfTest {
                 final QueryIndex idx = index(IDX_NAME_1, field(FIELD_NAME_1));
 
                 try {
-                    queryProcessor(node1).dynamicIndexCreate(CACHE_NAME, TBL_NAME, idx, false).get();
+                    queryProcessor(node1).dynamicIndexCreate(CACHE_NAME, CACHE_NAME, TBL_NAME, idx, false).get();
                 }
                 catch (IgniteCheckedException e) {
                     throw new IgniteException(e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/3ef78264/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
index 6d0c6ac..21666d6 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/sql/GridQueryParsingTest.java
@@ -591,7 +591,7 @@ public class GridQueryParsingTest extends GridCommonAbstractTest {
      * Test two instances of {@link GridSqlDropIndex} for equality.
      */
     private static void assertDropIndexEquals(GridSqlDropIndex exp, GridSqlDropIndex actual) {
-        assertEqualsIgnoreCase(exp.name(), actual.name());
+        assertEqualsIgnoreCase(exp.indexName(), actual.indexName());
         assertEqualsIgnoreCase(exp.schemaName(), actual.schemaName());
         assertEquals(exp.ifExists(), actual.ifExists());
     }
@@ -602,7 +602,7 @@ public class GridQueryParsingTest extends GridCommonAbstractTest {
     private static GridSqlDropIndex buildDropIndex(String name, String schema, boolean ifExists) {
         GridSqlDropIndex res = new GridSqlDropIndex();
 
-        res.name(name);
+        res.indexName(name);
         res.schemaName(schema);
         res.ifExists(ifExists);
 


[19/31] ignite git commit: Fixed a misprint in the non collocated join example

Posted by sb...@apache.org.
Fixed a misprint in the non collocated join example


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/b8875870
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/b8875870
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/b8875870

Branch: refs/heads/ignite-5075
Commit: b8875870257b8dc867283368067eb4387d7d9859
Parents: 794e1d3
Author: Denis Magda <dm...@gridgain.com>
Authored: Tue May 23 13:45:34 2017 -0700
Committer: Denis Magda <dm...@gridgain.com>
Committed: Tue May 23 13:45:34 2017 -0700

----------------------------------------------------------------------
 .../org/apache/ignite/examples/datagrid/CacheQueryExample.java     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/b8875870/examples/src/main/java/org/apache/ignite/examples/datagrid/CacheQueryExample.java
----------------------------------------------------------------------
diff --git a/examples/src/main/java/org/apache/ignite/examples/datagrid/CacheQueryExample.java b/examples/src/main/java/org/apache/ignite/examples/datagrid/CacheQueryExample.java
index aa52cc1..4a6fc1b 100644
--- a/examples/src/main/java/org/apache/ignite/examples/datagrid/CacheQueryExample.java
+++ b/examples/src/main/java/org/apache/ignite/examples/datagrid/CacheQueryExample.java
@@ -222,7 +222,7 @@ public class CacheQueryExample {
             "where Person.orgId = org.id " +
             "and lower(org.name) = lower(?)";
 
-        SqlQuery qry = new SqlQuery<AffinityKey<Long>, Person>(Person.class, joinSql).
+        SqlQuery qry = new SqlQuery<Long, Person>(Person.class, joinSql).
             setArgs("ApacheIgnite");
 
         // Enable distributed joins for query.


[13/31] ignite git commit: IGNITE-5163: Implemented infrastructure for the new JDBC driver. This closes #1912.

Posted by sb...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/OdbcProcessorValidationSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/OdbcProcessorValidationSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/OdbcProcessorValidationSelfTest.java
deleted file mode 100644
index 3d21948..0000000
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/OdbcProcessorValidationSelfTest.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * 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.odbc;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.ignite.IgniteException;
-import org.apache.ignite.configuration.IgniteConfiguration;
-import org.apache.ignite.configuration.OdbcConfiguration;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
-import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
-import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
-import org.apache.ignite.testframework.GridTestUtils;
-import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
-
-/**
- * ODBC configuration validation tests.
- */
-public class OdbcProcessorValidationSelfTest extends GridCommonAbstractTest {
-    /** Node index generator. */
-    private static final AtomicInteger NODE_IDX_GEN = new AtomicInteger();
-
-    /** {@inheritDoc} */
-    @Override protected void afterTest() throws Exception {
-        stopAllGrids();
-    }
-
-    /**
-     * Ensure we can start with default configuration.
-     *
-     * @throws Exception If failed.
-     */
-    public void testAddressDefault() throws Exception {
-        check(new OdbcConfiguration(), true);
-    }
-
-    /**
-     * Test address where only host is provided.
-     *
-     * @throws Exception If failed.
-     */
-    public void testAddressHostOnly() throws Exception {
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1"), true);
-    }
-
-    /**
-     * Test address with both host and port.
-     *
-     * @throws Exception If failed.
-     */
-    public void testAddressHostAndPort() throws Exception {
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999"), true);
-
-        // Shouldn't fit into range.
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999"), false);
-    }
-
-    /**
-     * Test address with host and port range.
-     *
-     * @throws Exception If failed.
-     */
-    public void testAddressHostAndPortRange() throws Exception {
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..10000"), true);
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..10000"), true);
-
-        // Shouldn't fit into range.
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..10000"), false);
-    }
-
-    /**
-     * Test start with invalid host.
-     *
-     * @throws Exception If failed.
-     */
-    public void testAddressInvalidHost() throws Exception {
-        check(new OdbcConfiguration().setEndpointAddress("126.0.0.1"), false);
-    }
-
-    /**
-     * Test start with invalid address format.
-     *
-     * @throws Exception If failed.
-     */
-    public void testAddressInvalidFormat() throws Exception {
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:"), false);
-
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:0"), false);
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:-1"), false);
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:111111"), false);
-
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999.."), false);
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..9998"), false);
-
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:a"), false);
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:a.."), false);
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:a..b"), false);
-
-        check(new OdbcConfiguration().setEndpointAddress(":9999"), false);
-        check(new OdbcConfiguration().setEndpointAddress(":9999..10000"), false);
-    }
-
-    /**
-     * Test connection parameters: sendBufferSize, receiveBufferSize, connectionTimeout.
-     *
-     * @throws Exception If failed.
-     */
-    public void testConnectionParams() throws Exception {
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
-            .setSocketSendBufferSize(4 * 1024), true);
-
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
-            .setSocketReceiveBufferSize(4 * 1024), true);
-
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
-            .setSocketSendBufferSize(-64 * 1024), false);
-
-        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
-            .setSocketReceiveBufferSize(-64 * 1024), false);
-    }
-
-    /**
-     * Test thread pool size.
-     *
-     * @throws Exception If failed.
-     */
-    public void testThreadPoolSize() throws Exception {
-        check(new OdbcConfiguration().setThreadPoolSize(0), false);
-        check(new OdbcConfiguration().setThreadPoolSize(-1), false);
-
-        check(new OdbcConfiguration().setThreadPoolSize(4), true);
-    }
-
-    /**
-     * Perform check.
-     *
-     * @param odbcCfg ODBC configuration.
-     * @param success Success flag. * @throws Exception If failed.
-     */
-    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
-    private void check(OdbcConfiguration odbcCfg, boolean success) throws Exception {
-        final IgniteConfiguration cfg = super.getConfiguration();
-
-        cfg.setIgniteInstanceName(OdbcProcessorValidationSelfTest.class.getName() + "-" + NODE_IDX_GEN.incrementAndGet());
-        cfg.setLocalHost("127.0.0.1");
-        cfg.setOdbcConfiguration(odbcCfg);
-        cfg.setMarshaller(new BinaryMarshaller());
-
-        TcpDiscoverySpi spi = new TcpDiscoverySpi();
-        spi.setIpFinder(new TcpDiscoveryVmIpFinder(true));
-
-        cfg.setDiscoverySpi(spi);
-
-        if (success)
-            startGrid(cfg.getGridName(), cfg);
-        else {
-            GridTestUtils.assertThrows(log, new Callable<Void>() {
-                @Override public Void call() throws Exception {
-                    startGrid(cfg.getGridName(), cfg);
-
-                    return null;
-                }
-            }, IgniteException.class, null);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessorValidationSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessorValidationSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessorValidationSelfTest.java
new file mode 100644
index 0000000..e433b6c
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/odbc/SqlListenerProcessorValidationSelfTest.java
@@ -0,0 +1,184 @@
+/*
+ * 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.odbc;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.OdbcConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * ODBC configuration validation tests.
+ */
+public class SqlListenerProcessorValidationSelfTest extends GridCommonAbstractTest {
+    /** Node index generator. */
+    private static final AtomicInteger NODE_IDX_GEN = new AtomicInteger();
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * Ensure we can start with default configuration.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddressDefault() throws Exception {
+        check(new OdbcConfiguration(), true);
+    }
+
+    /**
+     * Test address where only host is provided.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddressHostOnly() throws Exception {
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1"), true);
+    }
+
+    /**
+     * Test address with both host and port.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddressHostAndPort() throws Exception {
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999"), true);
+
+        // Shouldn't fit into range.
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999"), false);
+    }
+
+    /**
+     * Test address with host and port range.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddressHostAndPortRange() throws Exception {
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..10000"), true);
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..10000"), true);
+
+        // Shouldn't fit into range.
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..10000"), false);
+    }
+
+    /**
+     * Test start with invalid host.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddressInvalidHost() throws Exception {
+        check(new OdbcConfiguration().setEndpointAddress("126.0.0.1"), false);
+    }
+
+    /**
+     * Test start with invalid address format.
+     *
+     * @throws Exception If failed.
+     */
+    public void testAddressInvalidFormat() throws Exception {
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:"), false);
+
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:0"), false);
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:-1"), false);
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:111111"), false);
+
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999.."), false);
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9999..9998"), false);
+
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:a"), false);
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:a.."), false);
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:a..b"), false);
+
+        check(new OdbcConfiguration().setEndpointAddress(":9999"), false);
+        check(new OdbcConfiguration().setEndpointAddress(":9999..10000"), false);
+    }
+
+    /**
+     * Test connection parameters: sendBufferSize, receiveBufferSize, connectionTimeout.
+     *
+     * @throws Exception If failed.
+     */
+    public void testConnectionParams() throws Exception {
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
+            .setSocketSendBufferSize(4 * 1024), true);
+
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
+            .setSocketReceiveBufferSize(4 * 1024), true);
+
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
+            .setSocketSendBufferSize(-64 * 1024), false);
+
+        check(new OdbcConfiguration().setEndpointAddress("127.0.0.1:9998..10000")
+            .setSocketReceiveBufferSize(-64 * 1024), false);
+    }
+
+    /**
+     * Test thread pool size.
+     *
+     * @throws Exception If failed.
+     */
+    public void testThreadPoolSize() throws Exception {
+        check(new OdbcConfiguration().setThreadPoolSize(0), false);
+        check(new OdbcConfiguration().setThreadPoolSize(-1), false);
+
+        check(new OdbcConfiguration().setThreadPoolSize(4), true);
+    }
+
+    /**
+     * Perform check.
+     *
+     * @param odbcCfg ODBC configuration.
+     * @param success Success flag. * @throws Exception If failed.
+     */
+    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
+    private void check(OdbcConfiguration odbcCfg, boolean success) throws Exception {
+        final IgniteConfiguration cfg = super.getConfiguration();
+
+        cfg.setIgniteInstanceName(SqlListenerProcessorValidationSelfTest.class.getName() + "-" +
+            NODE_IDX_GEN.incrementAndGet());
+
+        cfg.setLocalHost("127.0.0.1");
+        cfg.setOdbcConfiguration(odbcCfg);
+        cfg.setMarshaller(new BinaryMarshaller());
+
+        TcpDiscoverySpi spi = new TcpDiscoverySpi();
+        spi.setIpFinder(new TcpDiscoveryVmIpFinder(true));
+
+        cfg.setDiscoverySpi(spi);
+
+        if (success)
+            startGrid(cfg.getGridName(), cfg);
+        else {
+            GridTestUtils.assertThrows(log, new Callable<Void>() {
+                @Override public Void call() throws Exception {
+                    startGrid(cfg.getGridName(), cfg);
+
+                    return null;
+                }
+            }, IgniteException.class, null);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/test/java/org/apache/ignite/testframework/GridTestUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/GridTestUtils.java b/modules/core/src/test/java/org/apache/ignite/testframework/GridTestUtils.java
index 1a821a1..8559b97 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/GridTestUtils.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/GridTestUtils.java
@@ -344,7 +344,7 @@ public final class GridTestUtils {
             Throwable t = e;
 
             while (t != null) {
-                if (cls == t.getClass() && (msg == null || (t.getMessage() != null || t.getMessage().contains(msg)))) {
+                if (cls == t.getClass() && (msg == null || (t.getMessage() != null && t.getMessage().contains(msg)))) {
                     log.info("Caught expected exception: " + t.getMessage());
 
                     return t;

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
index 0ec0f0d..ee69f24 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
@@ -52,7 +52,7 @@ import org.apache.ignite.internal.processors.database.BPlusTreeSelfTest;
 import org.apache.ignite.internal.processors.database.FreeListImplSelfTest;
 import org.apache.ignite.internal.processors.database.MetadataStorageSelfTest;
 import org.apache.ignite.internal.processors.odbc.OdbcEscapeSequenceSelfTest;
-import org.apache.ignite.internal.processors.odbc.OdbcProcessorValidationSelfTest;
+import org.apache.ignite.internal.processors.odbc.SqlListenerProcessorValidationSelfTest;
 import org.apache.ignite.internal.processors.service.ClosureServiceClientsNodesTest;
 import org.apache.ignite.internal.product.GridProductVersionSelfTest;
 import org.apache.ignite.internal.util.nio.IgniteExceptionInNioWorkerSelfTest;
@@ -142,7 +142,7 @@ public class IgniteBasicTestSuite extends TestSuite {
 
         suite.addTestSuite(IgniteExceptionInNioWorkerSelfTest.class);
         suite.addTestSuite(IgniteLocalNodeMapBeforeStartTest.class);
-        suite.addTestSuite(OdbcProcessorValidationSelfTest.class);
+        suite.addTestSuite(SqlListenerProcessorValidationSelfTest.class);
         suite.addTestSuite(OdbcEscapeSequenceSelfTest.class);
 
         GridTestUtils.addTestIfNeeded(suite, DynamicProxySerializationMultiJvmSelfTest.class, ignoredTests);

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f1dc3ac/modules/platforms/cpp/odbc/include/ignite/odbc/message.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/odbc/include/ignite/odbc/message.h b/modules/platforms/cpp/odbc/include/ignite/odbc/message.h
index aca214a..54c00fd 100644
--- a/modules/platforms/cpp/odbc/include/ignite/odbc/message.h
+++ b/modules/platforms/cpp/odbc/include/ignite/odbc/message.h
@@ -34,6 +34,14 @@ namespace ignite
 {
     namespace odbc
     {
+        struct ClientType
+        {
+            enum Type
+            {
+                ODBC = 0
+            };
+        };
+
         struct RequestType
         {
             enum Type
@@ -104,6 +112,8 @@ namespace ignite
                 writer.WriteInt16(version.GetMajor());
                 writer.WriteInt16(version.GetMinor());
                 writer.WriteInt16(version.GetMaintenance());
+                
+                writer.WriteInt8(ClientType::ODBC);
 
                 writer.WriteBool(distributedJoins);
                 writer.WriteBool(enforceJoinOrder);