You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kylin.apache.org by xx...@apache.org on 2022/11/21 09:12:20 UTC
[kylin] branch kylin5 updated: KYLIN-5297 add jdbc for kylin5 (#2025)
This is an automated email from the ASF dual-hosted git repository.
xxyu pushed a commit to branch kylin5
in repository https://gitbox.apache.org/repos/asf/kylin.git
The following commit(s) were added to refs/heads/kylin5 by this push:
new ef3ccfa03d KYLIN-5297 add jdbc for kylin5 (#2025)
ef3ccfa03d is described below
commit ef3ccfa03dd11e41e74129a4834953dc0d965e2a
Author: Tengting Xu <34...@users.noreply.github.com>
AuthorDate: Mon Nov 21 17:12:14 2022 +0800
KYLIN-5297 add jdbc for kylin5 (#2025)
* KYLIN-5297 add jdbc for kylin5
* Minor remove useless codes
* Minor fix codes smell
* Minor fix codes smell
---
build/release/jdbc_package.sh | 42 ++
pom.xml | 1 +
src/jdbc/libs/log4j-api-2.18.0.jar | Bin 0 -> 315115 bytes
src/jdbc/libs/log4j-core-2.18.0.jar | Bin 0 -> 1861441 bytes
src/jdbc/libs/log4j-slf4j-impl-2.18.0.jar | Bin 0 -> 24801 bytes
src/jdbc/pom.xml | 239 ++++++++
.../calcite/avatica/util/KylinDateAccessor.java | 80 +++
.../calcite/avatica/util/KylinDelegateCursor.java | 122 ++++
.../main/java/org/apache/kylin/jdbc/Driver.java | 216 +++++++
.../java/org/apache/kylin/jdbc/IRemoteClient.java | 65 +++
.../java/org/apache/kylin/jdbc/KylinCheckSql.java | 43 ++
.../java/org/apache/kylin/jdbc/KylinClient.java | 647 +++++++++++++++++++++
.../org/apache/kylin/jdbc/KylinConnection.java | 190 ++++++
.../org/apache/kylin/jdbc/KylinJdbcFactory.java | 138 +++++
.../main/java/org/apache/kylin/jdbc/KylinMeta.java | 545 +++++++++++++++++
.../apache/kylin/jdbc/KylinPreparedStatement.java | 173 ++++++
.../java/org/apache/kylin/jdbc/KylinResultSet.java | 142 +++++
.../java/org/apache/kylin/jdbc/KylinStatement.java | 50 ++
.../java/org/apache/kylin/jdbc/LogInitializer.java | 110 ++++
.../java/org/apache/kylin/jdbc/LoggerUtils.java | 33 ++
.../main/java/org/apache/kylin/jdbc/QueryCLI.java | 232 ++++++++
.../apache/kylin/jdbc/json/GenericResponse.java | 50 ++
.../kylin/jdbc/json/PreparedQueryRequest.java | 33 ++
.../org/apache/kylin/jdbc/json/QueryRequest.java | 39 ++
.../apache/kylin/jdbc/json/SQLResponseStub.java | 350 +++++++++++
.../apache/kylin/jdbc/json/StatementParameter.java | 47 ++
.../org/apache/kylin/jdbc/json/TableMetaStub.java | 348 +++++++++++
.../apache/kylin/jdbc/json/TableWithComment.java | 613 +++++++++++++++++++
.../kylin/jdbc/json/TablesWithCommentResponse.java | 37 ++
.../resources/META-INF/services/java.sql.Driver | 1 +
src/jdbc/src/main/resources/kylin-jdbc.properties | 29 +
.../resources/org-apache-kylin-jdbc.properties | 28 +
.../java/org/apache/kylin/jdbc/DriverTest.java | 267 +++++++++
.../java/org/apache/kylin/jdbc/DummyClient.java | 129 ++++
.../java/org/apache/kylin/jdbc/DummyDriver.java | 30 +
.../org/apache/kylin/jdbc/DummyJdbcFactory.java | 34 ++
.../org/apache/kylin/jdbc/KylinChecekSQLTest.java | 42 ++
.../org/apache/kylin/jdbc/SQLResonseStubTest.java | 64 ++
38 files changed, 5209 insertions(+)
diff --git a/build/release/jdbc_package.sh b/build/release/jdbc_package.sh
new file mode 100755
index 0000000000..fe8c0f831a
--- /dev/null
+++ b/build/release/jdbc_package.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+#
+# 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.
+#
+
+dir=$(dirname ${0})
+cd ${dir}/../..
+
+mvn versions:set -DnewVersion=${RELEASE_VERSION}
+RELEASE_VERSION=$(mvn -q -Dexec.executable="echo" -Dexec.args='${project.version}' --non-recursive exec:exec)
+
+mvn clean install -e -DskipTests -pl src/jdbc
+
+if [[ -d jdbc_dist ]]; then
+ rm -rf jdbc_dist/*
+fi
+mkdir -p jdbc_dist
+
+cp src/jdbc/target/kylin-*.jar jdbc_dist/
+cp src/jdbc/target/kylin-jdbc.properties jdbc_dist/
+cp src/jdbc/libs/*.jar jdbc_dist/
+rm -f jdbc_dist/*-tests.jar
+cd jdbc_dist
+tar -zcvf kylin-jdbc-${RELEASE_VERSION}.tar.gz ./*
+rm *.jar
+rm *.properties
+
+echo "Packaging JDBC is done, please check the directory: `pwd`."
diff --git a/pom.xml b/pom.xml
index ea56e35536..485b7b4a4d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -357,6 +357,7 @@
<module>src/data-loading-booter</module>
<module>src/query-booter</module>
<module>src/common-booter</module>
+ <module>src/jdbc</module>
</modules>
<dependencyManagement>
diff --git a/src/jdbc/libs/log4j-api-2.18.0.jar b/src/jdbc/libs/log4j-api-2.18.0.jar
new file mode 100644
index 0000000000..b4e933f7ec
Binary files /dev/null and b/src/jdbc/libs/log4j-api-2.18.0.jar differ
diff --git a/src/jdbc/libs/log4j-core-2.18.0.jar b/src/jdbc/libs/log4j-core-2.18.0.jar
new file mode 100644
index 0000000000..d6486fdf3d
Binary files /dev/null and b/src/jdbc/libs/log4j-core-2.18.0.jar differ
diff --git a/src/jdbc/libs/log4j-slf4j-impl-2.18.0.jar b/src/jdbc/libs/log4j-slf4j-impl-2.18.0.jar
new file mode 100644
index 0000000000..cc41910c32
Binary files /dev/null and b/src/jdbc/libs/log4j-slf4j-impl-2.18.0.jar differ
diff --git a/src/jdbc/pom.xml b/src/jdbc/pom.xml
new file mode 100644
index 0000000000..f2a696c971
--- /dev/null
+++ b/src/jdbc/pom.xml
@@ -0,0 +1,239 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>kylin</artifactId>
+ <groupId>org.apache.kylin</groupId>
+ <version>5.0.0-SNAPSHOT</version>
+ <relativePath>../../pom.xml</relativePath>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>kylin-jdbc</artifactId>
+
+ <properties>
+ <shadeBase>org.apache.kylin.jdbc.shaded</shadeBase>
+ <javaVersion>1.8</javaVersion>
+ <apache-httpclient.version>4.5.13</apache-httpclient.version>
+ <jackson.version>2.13.1</jackson.version>
+ <avatica.version>1.16.0</avatica.version>
+ <jackson-databind.version>2.13.2.1</jackson-databind.version>
+ <junit.version>4.12</junit.version>
+ <commons-cli.version>1.3.1</commons-cli.version>
+ <commons-io.version>2.7</commons-io.version>
+ <lombok.version>1.18.2</lombok.version>
+ <commons-codec.version>1.13</commons-codec.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ <version>${apache-httpclient.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>${commons-codec.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>${jackson.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>${jackson-databind.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.calcite.avatica</groupId>
+ <artifactId>avatica</artifactId>
+ <version>${avatica.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.calcite.avatica</groupId>
+ <artifactId>avatica-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>${commons-cli.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>${commons-io.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.7.26</version>
+ </dependency>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <version>${lombok.version}</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.2.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.5.1</version>
+ <configuration>
+ <source>${javaVersion}</source>
+ <target>${javaVersion}</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <createDependencyReducedPom>false</createDependencyReducedPom>
+
+ <artifactSet>
+ <excludes>
+ <exclude>org.slf4j:jcl-over-slf4j:*</exclude>
+ </excludes>
+ </artifactSet>
+
+ <relocations>
+ <relocation>
+ <pattern>org.apache.calcite</pattern>
+ <shadedPattern>${shadeBase}.org.apache.calcite</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>lombok</pattern>
+ <shadedPattern>${shadeBase}.lombok</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.fasterxml.jackson</pattern>
+ <shadedPattern>${shadeBase}.com.fasterxml.jackson</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.google.protobuf</pattern>
+ <shadedPattern>${shadeBase}.com.google.protobuf</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>org.apache.http</pattern>
+ <shadedPattern>${shadeBase}.org.apache.http</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>org.apache.commons</pattern>
+ <shadedPattern>${shadeBase}.org.apache.commons</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.google.common</pattern>
+ <shadedPattern>${shadeBase}.com.google.common</shadedPattern>
+ </relocation>
+ </relocations>
+ <filters>
+ <filter>
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <fork>true</fork>
+ <meminitial>1024m</meminitial>
+ <maxmem>2048m</maxmem>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>compile</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <tasks>
+ <echo>Copy kylin-jdbc.properties</echo>
+ <copy file="${basedir}/src/main/resources/kylin-jdbc.properties" tofile="${basedir}/target/kylin-jdbc.properties"/>
+ </tasks>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.sonarsource.scanner.maven</groupId>
+ <artifactId>sonar-maven-plugin</artifactId>
+ <version>3.6.1.1688</version>
+ </plugin>
+ <plugin>
+ <groupId>org.owasp</groupId>
+ <artifactId>dependency-check-maven</artifactId>
+ <version>6.0.3</version>
+ <configuration>
+ <format>ALL</format>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <distributionManagement>
+ <repository>
+ <id>${repository.id}</id>
+ <url>${repository.url}</url>
+ <name>${repository.name}</name>
+ <layout>default</layout>
+ </repository>
+ <snapshotRepository>
+ <id>${repository.id.snapshots}</id>
+ <url>${repository.url.snapshots}</url>
+ <name>${repository.name.snapshots}</name>
+ <layout>default</layout>
+ </snapshotRepository>
+ </distributionManagement>
+
+</project>
diff --git a/src/jdbc/src/main/java/org/apache/calcite/avatica/util/KylinDateAccessor.java b/src/jdbc/src/main/java/org/apache/calcite/avatica/util/KylinDateAccessor.java
new file mode 100644
index 0000000000..d270766ca7
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/calcite/avatica/util/KylinDateAccessor.java
@@ -0,0 +1,80 @@
+/*
+ * 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.calcite.avatica.util;
+
+import java.sql.Date;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.Calendar;
+
+import org.apache.calcite.avatica.AvaticaUtils;
+
+/**
+ * a mirror of org.apache.calcite.avatica.util.AbstractCursor.DateAccessor with the getTimestamp method impl
+ * org.apache.calcite.avatica.util.KylinDateAccessor is for the compatibility of Oracle BIP which always use getTimestamp method to fetch Date typed data
+ */
+public class KylinDateAccessor extends AbstractCursor.AccessorImpl {
+
+ public KylinDateAccessor(AbstractCursor.Getter getter) {
+ super(getter);
+ }
+
+ @Override
+ public Date getDate(Calendar calendar) throws SQLException {
+ Date date = (Date) getObject();
+ if (date == null) {
+ return null;
+ }
+ if (calendar != null) {
+ long v = date.getTime();
+ v -= calendar.getTimeZone().getOffset(v);
+ date = new Date(v);
+ }
+ return date;
+ }
+
+ @Override
+ public Timestamp getTimestamp(Calendar calendar) throws SQLException {
+ Date date = getDate(calendar);
+ if (date == null) {
+ return null;
+ }
+ return new Timestamp(date.getTime());
+ }
+
+ @Override
+ public String getString() throws SQLException {
+ final int v = getInt();
+ if (v == 0 && wasNull()) {
+ return null;
+ }
+ return dateAsString(v, null);
+ }
+
+ @Override
+ public long getLong() throws SQLException {
+ Date date = getDate(null);
+ return date == null ? 0L : (date.getTime() / DateTimeUtils.MILLIS_PER_DAY);
+ }
+
+ private static String dateAsString(int v, Calendar calendar) {
+ AvaticaUtils.discard(calendar); // time zone shift doesn't make sense
+ return DateTimeUtils.unixDateToString(v);
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/calcite/avatica/util/KylinDelegateCursor.java b/src/jdbc/src/main/java/org/apache/calcite/avatica/util/KylinDelegateCursor.java
new file mode 100644
index 0000000000..a19af8c4f3
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/calcite/avatica/util/KylinDelegateCursor.java
@@ -0,0 +1,122 @@
+/*
+ * 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.calcite.avatica.util;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.calcite.avatica.AvaticaSite;
+import org.apache.calcite.avatica.ColumnMetaData;
+
+public class KylinDelegateCursor extends AbstractCursor {
+
+ private static final int FLOAT_TYPE_ID = 6;
+
+ private final AbstractCursor cursor;
+
+ public KylinDelegateCursor(AbstractCursor cursor) {
+ this.cursor = cursor;
+ }
+
+ @Override
+ protected Accessor createAccessor(ColumnMetaData columnMetaData, Getter getter, Calendar localCalendar, ArrayImpl.Factory factory) {
+ if (columnMetaData.type.id == Types.DATE && columnMetaData.type.rep == ColumnMetaData.Rep.JAVA_SQL_DATE) {
+ return new KylinDateAccessor(getter);
+ }
+ Set<Integer> NUMBER_META_TYPE_IDS = new HashSet<>(Arrays.asList(-6, -5, 2, 3, 4, 5, 6, 7, 8));
+ if (columnMetaData.type.rep == ColumnMetaData.Rep.NUMBER
+ && NUMBER_META_TYPE_IDS.contains(columnMetaData.type.id)) {
+ return new KylinNumberAccessor(getter, columnMetaData.scale);
+ } else {
+ if (columnMetaData.type.id == FLOAT_TYPE_ID) {
+ // java.lang.Float.TYPE
+ return new KylinFloatToDoubleAccessor(getter);
+ } else {
+ return cursor.createAccessor(columnMetaData, getter, localCalendar, factory);
+ }
+ }
+ }
+
+ private static class KylinFloatToDoubleAccessor extends AbstractCursor.AccessorImpl {
+ private KylinFloatToDoubleAccessor(AbstractCursor.Getter getter) {
+ super(getter);
+ }
+
+ @Override
+ public double getDouble() throws SQLException {
+ Object obj = this.getObject();
+ if (null == obj) {
+ return 0.0D;
+ } else {
+ if (obj instanceof Double) {
+ return (Double)obj;
+ } else if (obj instanceof BigDecimal) {
+ return ((BigDecimal)obj).doubleValue();
+ } else {
+ return Double.valueOf(obj.toString());
+ }
+ }
+ }
+ }
+
+ private class KylinNumberAccessor extends NumberAccessor {
+
+ KylinNumberAccessor(AbstractCursor.Getter getter, int scale) {
+ super(getter, scale);
+ }
+
+ @Override
+ public BigDecimal getBigDecimal(int scale) throws SQLException {
+ Number n = this.getNumber();
+ if (n == null) {
+ return null;
+ } else {
+ BigDecimal decimal = AvaticaSite.toBigDecimal(n);
+ return 0 != scale ? decimal.setScale(scale, RoundingMode.DOWN) : decimal;
+ }
+ }
+ }
+
+ @Override
+ public boolean wasNull() {
+ return cursor.wasNull();
+ }
+
+ @Override
+ protected Getter createGetter(int ordinal) {
+ return cursor.createGetter(ordinal);
+ }
+
+ @Override
+ public boolean next() {
+ return cursor.next();
+ }
+
+ @Override
+ public void close() {
+ cursor.close();
+ }
+
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/Driver.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/Driver.java
new file mode 100644
index 0000000000..65fa76db01
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/Driver.java
@@ -0,0 +1,216 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+import java.util.Scanner;
+
+import org.apache.calcite.avatica.AvaticaConnection;
+import org.apache.calcite.avatica.DriverVersion;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.avatica.UnregisteredDriver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>
+ * Kylin JDBC Driver based on Calcite Avatica and Kylin restful API.<br>
+ * Supported versions:
+ * </p>
+ * <ul>
+ * <li>jdbc 4.0</li>
+ * <li>jdbc 4.1</li>
+ * </ul>
+ *
+ * <p>
+ * Supported Statements:
+ * </p>
+ * <ul>
+ * <li>{@link KylinStatementImpl}</li>
+ * <li>{@link KylinPrepareStatementImpl}</li>
+ * </ul>
+ *
+ * <p>
+ * Supported properties:
+ * <ul>
+ * <li>user: username</li>
+ * <li>password: password</li>
+ * <li>ssl: true/false</li>
+ * </ul>
+ * </p>
+ *
+ * <p>
+ * Driver init code sample:<br>
+ *
+ * <pre>
+ * Driver driver = (Driver) Class.forName("org.apache.kylin.jdbc.Driver").newInstance();
+ * Properties info = new Properties();
+ * info.put("user", "user");
+ * info.put("password", "password");
+ * info.put("ssl", true);
+ * Connection conn = driver.connect("jdbc:kylin://{domain}/{project}", info);
+ * </pre>
+ *
+ * </p>
+ */
+public class Driver extends UnregisteredDriver {
+
+ private static final Logger logger = LoggerFactory.getLogger(Driver.class);
+ public static final String CONNECT_STRING_PREFIX = "jdbc:kylin:";
+ public static final String PARAM_SPLIT_REGEX = ";";
+
+ static {
+ LogInitializer.init();
+ entry(logger);
+ try {
+ DriverManager.registerDriver(new Driver());
+ } catch (SQLException e) {
+ throw new RuntimeException("Error occurred while registering JDBC driver "
+ + Driver.class.getName() + ": " + e);
+ }
+ exit(logger);
+ }
+
+ private static InputStream preprocessPropertiesFile(String myFile) throws IOException {
+ try (Scanner in = new Scanner(new FileReader(myFile))){
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ while(in.hasNext()) {
+ out.write(in.nextLine().replace("\\", "\\\\").getBytes());
+ out.write("\n".getBytes());
+ }
+ return new ByteArrayInputStream(out.toByteArray());
+ }
+ }
+
+ @Override
+ protected String getConnectStringPrefix() {
+ return CONNECT_STRING_PREFIX;
+ }
+
+ @Override
+ public Connection connect(String url, Properties info) throws SQLException {
+ if (!this.acceptsURL(url)) {
+ return null;
+ } else {
+ String prefix = this.getConnectStringPrefix();
+
+ if (!url.startsWith(prefix)) {
+ throw new AssertionError();
+ }
+
+ Properties info2 = connectStringParseProperties(url, info);
+ AvaticaConnection connection = this.factory.newConnection(this, this.factory, url, info2);
+ this.handler.onConnectionInit(connection);
+ return connection;
+ }
+ }
+
+ private Properties connectStringParseProperties(String url, Properties props) {
+ Properties newProps;
+ if (props == null) {
+ newProps = new Properties();
+ } else {
+ newProps = (Properties)props.clone();
+ }
+
+ String prefixParams = url.split("//")[0].substring(this.getConnectStringPrefix().length());
+ propertyParser(prefixParams, newProps);
+
+ URI uri = URI.create(url.substring(CONNECT_STRING_PREFIX.length()));
+ String propString = uri.getRawQuery();
+ propertyParser(propString, newProps);
+
+ return newProps;
+ }
+
+ private void propertyParser(String propString, Properties props) {
+ if (propString == null) {
+ return;
+ }
+
+ for (String propPair : propString.split(PARAM_SPLIT_REGEX)) {
+ if (!propPair.contains("=")) {
+ continue;
+ }
+
+ String[] splitted = propPair.split("=");
+ String key = urlDecoder(splitted[0]);
+ String val = "";
+ if (splitted.length > 2) {
+ IllegalArgumentException e = new IllegalArgumentException(
+ String.format("The paramter in connection string '%s' is in wrong format."
+ + " Please correct it and retry.", propPair));
+ logger.error(e.getMessage());
+ throw e;
+ }
+ if (splitted.length == 2) {
+ val = urlDecoder(splitted[1]);
+ }
+ props.put(key, val);
+ }
+ }
+
+ private String urlDecoder(String url) {
+ try {
+ url = java.net.URLDecoder.decode(url, "utf-8");
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Url decode fail: ", e);
+ }
+ return url;
+ }
+
+ @Override
+ protected DriverVersion createDriverVersion() {
+ return DriverVersion.load(Driver.class, "org-apache-kylin-jdbc.properties", "Kylin JDBC Driver", "unknown version", "Kylin", "unknown version");
+ }
+
+ @Override
+ protected String getFactoryClassName(JdbcVersion jdbcVersion) {
+ switch (jdbcVersion) {
+ case JDBC_30:
+ throw new UnsupportedOperationException();
+ case JDBC_40:
+ return KylinJdbcFactory.Version40.class.getName();
+ case JDBC_41:
+ default:
+ return KylinJdbcFactory.Version41.class.getName();
+ }
+ }
+
+ @Override
+ public Meta createMeta(AvaticaConnection connection) {
+ entry(logger);
+ Meta meta = new KylinMeta((KylinConnection) connection);
+ exit(logger);
+ return meta;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/IRemoteClient.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/IRemoteClient.java
new file mode 100644
index 0000000000..41c10c33d1
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/IRemoteClient.java
@@ -0,0 +1,65 @@
+/*
+ * 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.kylin.jdbc;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.calcite.avatica.AvaticaParameter;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.kylin.jdbc.KylinMeta.KMetaProject;
+
+public interface IRemoteClient extends Closeable {
+
+ public static class QueryResult {
+ public final List<ColumnMetaData> columnMeta;
+ public final Iterable<Object> iterable;
+ public final String queryId;
+ public final long duration;
+ public final long resultRowCount;
+
+ public QueryResult(List<ColumnMetaData> columnMeta, Iterable<Object> iterable,
+ String queryId, long duration, long resultRowCount) {
+ this.columnMeta = columnMeta;
+ this.iterable = iterable;
+ this.queryId = queryId;
+ this.duration = duration;
+ this.resultRowCount = resultRowCount;
+ }
+ }
+
+ /**
+ * Connect to Kylin restful service. IOException will be thrown if authentication failed.
+ */
+ public void connect() throws IOException;
+
+ /**
+ * Retrieve meta data of given project.
+ */
+ public KMetaProject retrieveMetaData(String project) throws IOException;
+
+ /**
+ * Execute query remotely and get back result.
+ */
+ public QueryResult executeQuery(String sql, List<AvaticaParameter> params, List<Object> paramValues,
+ Map<String, String> queryToggles, String queryId) throws IOException;
+
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinCheckSql.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinCheckSql.java
new file mode 100644
index 0000000000..13a6748eaf
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinCheckSql.java
@@ -0,0 +1,43 @@
+/*
+ * 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.kylin.jdbc;
+
+class KylinCheckSql {
+
+ private KylinCheckSql() {}
+
+ public static int countDynamicPlaceholder(String sql) {
+ int placeholderCount = 0;
+ boolean singleQuotes = true;
+ boolean doubleQuotes = true;
+ boolean backticks = true;
+ for (int i = 0; i < sql.length(); i++) {
+ if (sql.charAt(i) == '\'') {
+ singleQuotes = !singleQuotes;
+ } else if (sql.charAt(i) == '\"') {
+ doubleQuotes = !doubleQuotes;
+ } else if (sql.charAt(i) == '`') {
+ backticks = !backticks;
+ } else if (sql.charAt(i) == '?' && singleQuotes && doubleQuotes && backticks) {
+ placeholderCount++;
+ }
+ }
+ return placeholderCount;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinClient.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinClient.java
new file mode 100644
index 0000000000..f211d960f0
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinClient.java
@@ -0,0 +1,647 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import javax.net.ssl.SSLContext;
+import javax.xml.bind.DatatypeConverter;
+
+import org.apache.calcite.avatica.AvaticaParameter;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.ColumnMetaData.Rep;
+import org.apache.calcite.avatica.ColumnMetaData.ScalarType;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.ssl.SSLContexts;
+import org.apache.http.util.EntityUtils;
+import org.apache.kylin.jdbc.KylinMeta.KMetaCatalog;
+import org.apache.kylin.jdbc.KylinMeta.KMetaColumn;
+import org.apache.kylin.jdbc.KylinMeta.KMetaProject;
+import org.apache.kylin.jdbc.KylinMeta.KMetaSchema;
+import org.apache.kylin.jdbc.KylinMeta.KMetaTable;
+import org.apache.kylin.jdbc.json.GenericResponse;
+import org.apache.kylin.jdbc.json.PreparedQueryRequest;
+import org.apache.kylin.jdbc.json.SQLResponseStub;
+import org.apache.kylin.jdbc.json.StatementParameter;
+import org.apache.kylin.jdbc.json.TableMetaStub;
+import org.apache.kylin.jdbc.json.TableMetaStub.ColumnMetaStub;
+import org.apache.kylin.jdbc.json.TableWithComment;
+import org.apache.kylin.jdbc.json.TablesWithCommentResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class KylinClient implements IRemoteClient {
+
+ // TODO: cannot support tableau
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinClient.class);
+
+ private final KylinConnection conn;
+ private final Properties connProps;
+ private final CloseableHttpClient httpClient;
+ private final ObjectMapper jsonMapper;
+ private static final int POOL_MAX = 10;
+ private static final int POOL_MIN = 0;
+ private static final int RESPONSE_CODE_200 = 200;
+ private static final int RESPONSE_CODE_201 = 201;
+ private static final String APPLICATION = "application/json";
+ private static final String TIME_ZONE = "UTC";
+ private static final String AUTH_METHOD = "Basic ";
+
+ public KylinClient(KylinConnection conn) {
+ entry(logger);
+ this.conn = conn;
+ this.connProps = conn.getConnectionProperties();
+ this.httpClient = buildHttpClient();
+ this.jsonMapper = new ObjectMapper();
+ jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ exit(logger);
+ }
+
+ private CloseableHttpClient buildHttpClient() {
+ HttpClientBuilder builder = HttpClients.custom();
+
+ // network timeout
+ int timeout = Integer.parseInt(connProps.getProperty("timeout", "0"));
+ RequestConfig rconf = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();
+ builder.setDefaultRequestConfig(rconf);
+ logger.debug("use connection timeout " + timeout);
+
+ // SSL friendly
+ PoolingHttpClientConnectionManager cm;
+ if (isSSL()) {
+ try {
+ SSLContext sslContext = SSLContexts.custom()
+ .loadTrustMaterial((TrustStrategy) (x509Certificates, s) -> true).build();
+ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, (s, sslSession) -> true);
+ Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create()
+ .register("https", sslsf).build();
+ cm = new PoolingHttpClientConnectionManager(r);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ logger.debug("use SSL connection with optimistic trust");
+ } else {
+ cm = new PoolingHttpClientConnectionManager();
+ logger.debug("use non-SSL connection");
+ }
+
+ // connection pool
+ int pool = Integer.parseInt(connProps.getProperty("pool", "1"));
+ if (pool > POOL_MAX || pool < POOL_MIN) {
+ logger.debug("invalid 'pool', reset to default");
+ pool = 1;
+ }
+ if (pool == 0) {
+ logger.debug("use NO connection pool");
+ } else {
+ cm.setDefaultMaxPerRoute(pool);
+ cm.setMaxTotal(pool);
+ logger.debug("use connection pool size " + pool);
+ }
+
+ builder.setConnectionManager(cm);
+ return builder.build();
+ }
+
+ @SuppressWarnings("rawtypes")
+ public static Class convertType(int sqlType) {
+ Class result = Object.class;
+
+ switch (sqlType) {
+ case Types.CHAR:
+ case Types.VARCHAR:
+ case Types.LONGVARCHAR:
+ result = String.class;
+ break;
+ case Types.NUMERIC:
+ case Types.DECIMAL:
+ result = BigDecimal.class;
+ break;
+ case Types.BIT:
+ case Types.BOOLEAN:
+ result = Boolean.class;
+ break;
+ case Types.TINYINT:
+ result = Byte.class;
+ break;
+ case Types.SMALLINT:
+ result = Short.class;
+ break;
+ case Types.INTEGER:
+ result = Integer.class;
+ break;
+ case Types.BIGINT:
+ result = Long.class;
+ break;
+ case Types.REAL:
+ case Types.FLOAT:
+ case Types.DOUBLE:
+ result = Double.class;
+ break;
+ case Types.BINARY:
+ case Types.VARBINARY:
+ case Types.LONGVARBINARY:
+ result = Byte[].class;
+ break;
+ case Types.DATE:
+ result = Date.class;
+ break;
+ case Types.TIME:
+ result = Time.class;
+ break;
+ case Types.TIMESTAMP:
+ result = Timestamp.class;
+ break;
+ default:
+ //do nothing
+ break;
+ }
+
+ return result;
+ }
+
+ public Object wrapObject(String value, int sqlType) {
+ if (null == value) {
+ return null;
+ }
+
+ switch (sqlType) {
+ case Types.CHAR:
+ case Types.VARCHAR:
+ case Types.LONGVARCHAR:
+ return value;
+ case Types.NUMERIC:
+ case Types.DECIMAL:
+ return new BigDecimal(value);
+ case Types.BIT:
+ case Types.BOOLEAN:
+ return Boolean.parseBoolean(value);
+ case Types.TINYINT:
+ return Byte.valueOf(value);
+ case Types.SMALLINT:
+ return Short.valueOf(value);
+ case Types.INTEGER:
+ return Integer.parseInt(value);
+ case Types.BIGINT:
+ return Long.parseLong(value);
+ case Types.FLOAT:
+ return Float.parseFloat(value);
+ case Types.REAL:
+ case Types.DOUBLE:
+ return Double.parseDouble(value);
+ case Types.BINARY:
+ case Types.VARBINARY:
+ case Types.LONGVARBINARY:
+ return value.getBytes();
+ case Types.DATE:
+ return dateConverter(value);
+ case Types.TIME:
+ return timeConverter(value);
+ case Types.TIMESTAMP:
+ return timestampConverter(value);
+ default:
+ //do nothing
+ break;
+ }
+
+ return value;
+ }
+
+ private Date dateConverter(String value) {
+ try {
+ return new Date(parseDateTime(value, "yyyy-MM-dd"));
+ } catch (ParseException ex) {
+ logger.error("parse date failed!", ex);
+ return null;
+ }
+ }
+
+ private Time timeConverter(String value) {
+ try {
+ return new Time(parseDateTime(value, "HH:mm:ss"));
+ } catch (ParseException ex) {
+ logger.error("parse time failed!", ex);
+ return null;
+ }
+ }
+
+ private Timestamp timestampConverter(String value) {
+ String[] formats = new String[] { "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss" };
+ ParseException ex = null;
+ for (String format : formats) {
+ try {
+ return new Timestamp(parseDateTime(value, format));
+ } catch (ParseException e) {
+ ex = e;
+ }
+ }
+ logger.error("parse timestamp failed!", ex);
+ return null;
+ }
+
+ private long parseDateTime(String value, String format) throws ParseException {
+ SimpleDateFormat formatter = new SimpleDateFormat(format);
+ formatter.setTimeZone(TimeZone.getTimeZone(TIME_ZONE));
+ return formatter.parse(value).getTime();
+ }
+
+ private boolean isSSL() {
+ return Boolean.parseBoolean(connProps.getProperty("ssl", "false"));
+ }
+
+ private String baseUrl() {
+ return (isSSL() ? "https://" : "http://") + conn.getBaseUrl();
+ }
+
+ private void addHttpHeadersV2(HttpRequestBase method) {
+ String headerVal = "application/vnd.apache.kylin-v4-public+json, text/plain, */*";
+ method.addHeader("Accept", headerVal);
+ addCommonHttpHeaders(method);
+ }
+
+ private void addCommonHttpHeaders(HttpRequestBase method) {
+ method.addHeader("Content-Type", APPLICATION);
+ method.addHeader("User-Agent", "KylinJDBCDriver");
+ String authToken = connProps.getProperty("auth-token");
+ if (authToken == null || authToken.trim().isEmpty()) {
+ String username = connProps.getProperty("user");
+ String password = connProps.getProperty("password");
+ authToken = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes());
+ }
+ method.addHeader("Authorization", AUTH_METHOD + authToken);
+ method.addHeader("Auto", "true");
+ }
+
+ @Override
+ public void connect() throws IOException {
+ entry(logger);
+
+ // authorization post
+ HttpPost post = new HttpPost(baseUrl() + "/kylin/api/user/authentication");
+ addHttpHeadersV2(post);
+ StringEntity requestEntity = new StringEntity("{}", ContentType.create(APPLICATION, "UTF-8"));
+ post.setEntity(requestEntity);
+
+ try {
+ HttpResponse response = httpClient.execute(post);
+
+ if (response.getStatusLine().getStatusCode() != RESPONSE_CODE_200
+ && response.getStatusLine().getStatusCode() != RESPONSE_CODE_201) {
+ throw asIOException(post, response);
+ }
+ } finally {
+ post.releaseConnection();
+ }
+ exit(logger);
+ }
+
+ @Override
+ public KMetaProject retrieveMetaData(String project) throws IOException {
+ entry(logger);
+ if (!conn.getProject().equals(project)) {
+ throw new IllegalArgumentException(
+ "Project name [" + project + "] not fit current connection[" + conn.getProject() + "]");
+ }
+ String url = baseUrl() + "/kylin/api/query/tables_and_columns?project=" + project;
+ HttpGet get = new HttpGet(url);
+ addHttpHeadersV2(get);
+
+ List<TableMetaStub> tableMetaStubs;
+ try {
+ HttpResponse response = httpClient.execute(get);
+
+ if (response.getStatusLine().getStatusCode() != RESPONSE_CODE_200
+ && response.getStatusLine().getStatusCode() != RESPONSE_CODE_201) {
+ throw asIOException(get, response);
+ }
+
+ GenericResponse<List<TableMetaStub>> tableMetaStubVPlus = jsonMapper.readValue(
+ response.getEntity().getContent(), new TypeReference<GenericResponse<List<TableMetaStub>>>() {
+ });
+
+ if (tableMetaStubVPlus == null || tableMetaStubVPlus.getData() == null) {
+ throw new IOException("Response abnormal without data");
+ }
+
+ tableMetaStubs = tableMetaStubVPlus.getData();
+ } finally {
+ get.releaseConnection();
+ }
+
+ String urlWithComment = baseUrl() + "/kylin/api/tables?project=" + project + "&page_size=" + Integer.MAX_VALUE;
+ HttpGet getWithComment = new HttpGet(urlWithComment);
+ addHttpHeadersV2(getWithComment);
+ try {
+ HttpResponse responseWithComment = httpClient.execute(getWithComment);
+ GenericResponse<TablesWithCommentResponse> tablesWithCommentResponseVPlus = jsonMapper.readValue(
+ responseWithComment.getEntity().getContent(),
+ new TypeReference<GenericResponse<TablesWithCommentResponse>>() {
+ });
+ TablesWithCommentResponse tablesWithCommentResponse = tablesWithCommentResponseVPlus.getData();
+ List<TableWithComment> tableWithComments = tablesWithCommentResponse.getValue();
+ Map<String, String> columnWithCommentMap = new HashMap<>();
+ for (TableWithComment tableWithComment : tableWithComments) {
+ for (TableWithComment.ColumnWithComment columnWithComment : tableWithComment.getColumns()) {
+ String keyWithComment = tableWithComment.getDatabase() + "." + tableWithComment.getName() + "."
+ + columnWithComment.getName();
+ columnWithCommentMap.put(keyWithComment, columnWithComment.getComment());
+ }
+ }
+ for (TableMetaStub tableMetaStub : tableMetaStubs) {
+ for (ColumnMetaStub columnMetaStub : tableMetaStub.getColumns()) {
+ String keyMetaStub = tableMetaStub.getTABLE_SCHEM() + "." + tableMetaStub.getTABLE_NAME() + "."
+ + columnMetaStub.getCOLUMN_NAME();
+ if (columnWithCommentMap.containsKey(keyMetaStub)) {
+ columnMetaStub.setREMARKS(columnWithCommentMap.get(keyMetaStub));
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Get comment failed:" + e.getMessage(), e);
+ } finally {
+ getWithComment.releaseConnection();
+ }
+ List<KMetaTable> tables = convertMetaTables(tableMetaStubs);
+ List<KMetaSchema> schemas = convertMetaSchemas(tables);
+ List<KMetaCatalog> catalogs = convertMetaCatalogs(schemas);
+ KMetaProject metaProject = new KMetaProject(project, catalogs);
+ exit(logger);
+ return metaProject;
+ }
+
+ private List<KMetaCatalog> convertMetaCatalogs(List<KMetaSchema> schemas) {
+ Map<String, List<KMetaSchema>> catalogMap = new LinkedHashMap<>();
+ for (KMetaSchema schema : schemas) {
+ List<KMetaSchema> list = catalogMap.computeIfAbsent(schema.tableCatalog, k -> new ArrayList<>());
+ list.add(schema);
+ }
+
+ List<KMetaCatalog> result = new ArrayList<>();
+ for (List<KMetaSchema> catSchemas : catalogMap.values()) {
+ String catalog = catSchemas.get(0).tableCatalog;
+ result.add(new KMetaCatalog(catalog, catSchemas));
+ }
+ return result;
+ }
+
+ private List<KMetaSchema> convertMetaSchemas(List<KMetaTable> tables) {
+ Map<String, List<KMetaTable>> schemaMap = new LinkedHashMap<>();
+ for (KMetaTable table : tables) {
+ String key = table.tableCat + "!!" + table.tableSchem;
+ List<KMetaTable> list = schemaMap.computeIfAbsent(key, k -> new ArrayList<>());
+ list.add(table);
+ }
+
+ List<KMetaSchema> result = new ArrayList<>();
+ for (List<KMetaTable> schemaTables : schemaMap.values()) {
+ String catalog = schemaTables.get(0).tableCat;
+ String schema = schemaTables.get(0).tableSchem;
+ result.add(new KMetaSchema(catalog, schema, schemaTables));
+ }
+ return result;
+ }
+
+ private List<KMetaTable> convertMetaTables(List<TableMetaStub> tableMetaStubs) {
+ List<KMetaTable> result = new ArrayList<>(tableMetaStubs.size());
+ for (TableMetaStub tableStub : tableMetaStubs) {
+ result.add(convertMetaTable(tableStub));
+ }
+ return result;
+ }
+
+ private KMetaTable convertMetaTable(TableMetaStub tableStub) {
+ List<KMetaColumn> columns = new ArrayList<>(tableStub.getColumns().size());
+ for (ColumnMetaStub columnStub : tableStub.getColumns()) {
+ columns.add(convertMetaColumn(columnStub));
+ }
+ return new KMetaTable(tableStub.getTABLE_CAT(), tableStub.getTABLE_SCHEM(), tableStub.getTABLE_NAME(),
+ tableStub.getTABLE_TYPE(), columns);
+ }
+
+ private KMetaColumn convertMetaColumn(ColumnMetaStub columnStub) {
+ return new KMetaColumn(columnStub.getTABLE_CAT(), columnStub.getTABLE_SCHEM(), columnStub.getTABLE_NAME(),
+ columnStub.getCOLUMN_NAME(), columnStub.getDATA_TYPE(), columnStub.getTYPE_NAME(),
+ columnStub.getCOLUMN_SIZE(), columnStub.getDECIMAL_DIGITS(), columnStub.getNUM_PREC_RADIX(),
+ columnStub.getNULLABLE(), columnStub.getCHAR_OCTET_LENGTH(), columnStub.getORDINAL_POSITION(),
+ columnStub.getIS_NULLABLE(), columnStub.getREMARKS());
+ }
+
+ @Override
+ public QueryResult executeQuery(String sql, List<AvaticaParameter> params, List<Object> paramValues,
+ Map<String, String> queryToggles, String queryId) throws IOException {
+ entry(logger);
+ GenericResponse<SQLResponseStub> queryResp = executeKylinQuery(sql, convertParameters(params, paramValues),
+ queryToggles, queryId);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Response:\n {} ", jsonMapper.writeValueAsString(queryResp));
+ }
+ if (queryResp == null || queryResp.getData() == null) {
+ throw new IOException("Response abnormal without data");
+ }
+ SQLResponseStub resp = queryResp.getData();
+ if (resp.getIsException()) {
+ throw new IOException(resp.getExceptionMessage());
+ }
+
+ List<ColumnMetaData> metas = convertColumnMeta(resp);
+ List<Object> data = convertResultData(resp, metas);
+ QueryResult result = new QueryResult(metas, data, resp.getQueryId(), resp.getDuration(),
+ resp.getResultRowCount());
+ exit(logger);
+ return result;
+ }
+
+ private List<StatementParameter> convertParameters(List<AvaticaParameter> params, List<Object> paramValues) {
+ List<StatementParameter> result = new ArrayList<>();
+ if (params == null || params.isEmpty()) {
+ return result;
+ }
+
+ if (params.size() != paramValues.size()) {
+ throw new IllegalArgumentException(
+ "Param count:" + params.size() + "mismatch values count:" + paramValues.size());
+ }
+
+ for (Object v : paramValues) {
+ if (v == null) {
+ result.add(new StatementParameter(Object.class.getCanonicalName(), null));
+ } else {
+ result.add(new StatementParameter(v.getClass().getCanonicalName(), String.valueOf(v)));
+ }
+ }
+ return result;
+ }
+
+ public GenericResponse<SQLResponseStub> executeKylinQuery(String sql, List<StatementParameter> params,
+ Map<String, String> queryToggles, String queryId) throws IOException {
+ long start = System.currentTimeMillis();
+
+ String url = baseUrl() + "/kylin/api/query";
+ String project = conn.getProject();
+
+ PreparedQueryRequest request = new PreparedQueryRequest();
+ if (null != params) {
+ request.setParams(params);
+ }
+ request.setQueryId(queryId);
+ request.setSql(sql);
+ request.setProject(project);
+ request.setBackdoorToggles(queryToggles);
+ int maxRowsNum = Integer.parseInt(queryToggles.get("ATTR_STATEMENT_MAX_ROWS"));
+ if (maxRowsNum > 0) {
+ request.setLimit(maxRowsNum);
+ }
+
+ String executeAs = connProps.getProperty("EXECUTE_AS_USER_ID");
+ if (executeAs != null) {
+ request.setExecuteAs(executeAs);
+ String formatString = "Found the parameter EXECUTE_AS_USER_ID in the connection string. "
+ + "The query will be executed as the user defined in this connection string.\n"
+ + "EXECUTE_AS_USER_ID = {}";
+ logger.info(formatString, executeAs);
+ }
+
+ HttpPost post = new HttpPost(url);
+ addHttpHeadersV2(post);
+
+ String postBody = jsonMapper.writeValueAsString(request);
+ logger.info("Post body:\n {} ", postBody);
+ StringEntity requestEntity = new StringEntity(postBody, ContentType.create(APPLICATION, "UTF-8"));
+ post.setEntity(requestEntity);
+
+ try (CloseableHttpResponse response = httpClient.execute(post)) {
+
+ if (response.getStatusLine().getStatusCode() != RESPONSE_CODE_200
+ && response.getStatusLine().getStatusCode() != RESPONSE_CODE_201) {
+ throw asIOException(post, response);
+ }
+
+ GenericResponse<SQLResponseStub> r = jsonMapper.readValue(response.getEntity().getContent(),
+ new TypeReference<GenericResponse<SQLResponseStub>>() {
+ });
+
+ long dur = System.currentTimeMillis() - start;
+ SQLResponseStub rr = r.getData();
+ if (maxRowsNum > 0 && rr.getResults().size() > maxRowsNum) {
+ rr.setResults(rr.getResults().subList(0, maxRowsNum));
+ }
+ logger.info("Query " + rr.getQueryId() + " returned "
+ + (rr.getIsException() ? r.getCode() + "+ex" : r.getCode()) + " in " + dur + " millis at client, "
+ + rr.getDuration() + " millis at server");
+ return r;
+ }
+ }
+
+ private List<ColumnMetaData> convertColumnMeta(SQLResponseStub queryResp) {
+ List<ColumnMetaData> metas = new ArrayList<>();
+ for (int i = 0; i < queryResp.getColumnMetas().size(); i++) {
+ SQLResponseStub.ColumnMetaStub scm = queryResp.getColumnMetas().get(i);
+ Class<?> columnClass = convertType(scm.getColumnType());
+ int columnType = scm.getColumnType();
+ String columnTypeName = scm.getColumnTypeName();
+ if (columnClass == BigDecimal.class) {
+ columnClass = Number.class;
+ } else if (columnType == -1) {
+ columnType = 12;
+ }
+ ScalarType type = ColumnMetaData.scalar(columnType, columnTypeName, Rep.of(columnClass));
+
+ ColumnMetaData meta = new ColumnMetaData(i, scm.isAutoIncrement(), scm.isCaseSensitive(),
+ scm.isSearchable(), scm.isCurrency(), scm.getIsNullable(), scm.isSigned(), scm.getDisplaySize(),
+ scm.getLabel(), scm.getName(), scm.getSchemaName(), scm.getPrecision(), scm.getScale(),
+ scm.getTableName(), scm.getSchemaName(), type, scm.isReadOnly(), scm.isWritable(), scm.isWritable(),
+ columnClass.getCanonicalName());
+
+ metas.add(meta);
+ }
+
+ return metas;
+ }
+
+ private List<Object> convertResultData(SQLResponseStub queryResp, List<ColumnMetaData> metas) {
+ List<String[]> stringResults = queryResp.getResults();
+ List<Object> data = new ArrayList<>(stringResults.size());
+ for (String[] result : stringResults) {
+ Object[] row = new Object[result.length];
+
+ for (int i = 0; i < result.length; i++) {
+ ColumnMetaData meta = metas.get(i);
+ row[i] = wrapObject(result[i], meta.type.id);
+ }
+
+ data.add(row);
+ }
+ return data;
+ }
+
+ private IOException asIOException(HttpRequestBase request, HttpResponse response) throws IOException {
+ int statusCode = response.getStatusLine().getStatusCode();
+ String responseStr = EntityUtils.toString(response.getEntity());
+ if (responseStr.contains("Error occured while trying to proxy to")) {
+ return new IOException("FAILED!\n"
+ + "[Kyligence][JDBCDriver] Unsupported Apache Kylin instance, please contact Apache Kylin Community.");
+ } else {
+ return new IOException(
+ request.getMethod() + " failed, error code " + statusCode + " and response: " + responseStr);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ httpClient.close();
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinConnection.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinConnection.java
new file mode 100644
index 0000000000..f8cd35999b
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinConnection.java
@@ -0,0 +1,190 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.io.IOException;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.calcite.avatica.AvaticaConnection;
+import org.apache.calcite.avatica.AvaticaParameter;
+import org.apache.calcite.avatica.AvaticaPreparedStatement;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.ConnectionPropertiesImpl;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.avatica.Meta.CursorFactory;
+import org.apache.calcite.avatica.Meta.Signature;
+import org.apache.calcite.avatica.UnregisteredDriver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KylinConnection extends AvaticaConnection {
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinConnection.class);
+
+ private final String baseUrl;
+ private final String project;
+ private final IRemoteClient remoteClient;
+
+ protected KylinConnection(UnregisteredDriver driver, KylinJdbcFactory factory, String url, Properties info)
+ throws SQLException {
+ super(driver, factory, url, info);
+ entry(logger);
+ checkProperties();
+ String odbcUrl = url;
+ odbcUrl = odbcUrl.replaceAll(Driver.CONNECT_STRING_PREFIX + "([A-Za-z0-9\\_]+?=.*?;)*?//", "");
+
+ String[] temps0 = odbcUrl.split("\\?");
+ odbcUrl = temps0[0];
+
+ String[] temps = odbcUrl.split("/");
+ assert temps.length == 2;
+
+ this.baseUrl = temps[0];
+ this.project = temps[1];
+
+ logger.info("------------------------");
+ logger.info("Kylin Connection Info:");
+ logger.info("base url: {}", this.baseUrl);
+ logger.info("project name: {}", this.project);
+ info.entrySet().stream().filter(infoEntry -> !String.valueOf(infoEntry.getKey()).equalsIgnoreCase("password"))
+ .forEach(infoEntry -> logger.info("{}: {}", infoEntry.getKey(), infoEntry.getValue()));
+ logger.info("------------------------");
+
+ this.remoteClient = factory.newRemoteClient(this);
+
+ try {
+ this.remoteClient.connect();
+ } catch (IOException e) {
+ try {
+ this.remoteClient.close();
+ } catch (Exception eClose) {
+ // close quietly
+ }
+ logger.error("Connect Kylin failed: ", e);
+ throw new SQLException(e);
+ }
+ exit(logger);
+ }
+
+ String getBaseUrl() {
+ return baseUrl;
+ }
+
+ String getProject() {
+ return project;
+ }
+
+ Properties getConnectionProperties() {
+ return info;
+ }
+
+ private void checkProperties() {
+ String executeAs = info.getProperty("EXECUTE_AS_USER_ID");
+ if (executeAs != null) {
+ if (executeAs.isEmpty()) {
+ IllegalArgumentException e = new IllegalArgumentException("The parameter “EXECUTE_AS_USER_ID” can’t be empty. "
+ + "please contact your system admin and check its value in the connection string for Kylin.");
+ logger.error(e.getMessage());
+ throw e;
+ }
+
+ if (executeAs.length() > 1024) {
+ IllegalArgumentException e = new IllegalArgumentException("The value of parameter EXECUTE_AS_USER_ID can’t exceed 1024 characters. "
+ + "Please shorten your user id value.");
+ logger.error(e.getMessage());
+ throw e;
+ }
+ }
+ }
+
+ @Override
+ public boolean getAutoCommit() throws SQLException {
+ entry(logger);
+ if (meta.connectionSync(handle, new ConnectionPropertiesImpl()).isAutoCommit() == null)
+ setAutoCommit(true);
+ boolean isAutoCommit = super.getAutoCommit();
+ exit(logger);
+ return isAutoCommit;
+ }
+
+ @Override
+ public boolean isReadOnly() throws SQLException {
+ entry(logger);
+ if (meta.connectionSync(handle, new ConnectionPropertiesImpl()).isReadOnly() == null)
+ setReadOnly(true);
+ boolean isReadOnly = super.isReadOnly();
+ exit(logger);
+ return isReadOnly;
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
+ int resultSetHoldability) throws SQLException {
+ entry(logger);
+ Meta.Signature sig = mockPreparedSignature(sql);
+ AvaticaPreparedStatement preparedStatement = factory().newPreparedStatement(
+ this, null, sig, resultSetType, resultSetConcurrency, resultSetHoldability);
+ exit(logger);
+ return preparedStatement;
+ }
+
+ // TODO add restful API to prepare SQL, get back expected ResultSetMetaData
+ Signature mockPreparedSignature(String sql) {
+ List<AvaticaParameter> params = new ArrayList<>();
+ int placeholderCount = KylinCheckSql.countDynamicPlaceholder(sql);
+ for (int i = 1; i <= placeholderCount; i++) {
+ AvaticaParameter param = new AvaticaParameter(false, 0, 0, 0, null, null, null);
+ params.add(param);
+ }
+
+ ArrayList<ColumnMetaData> columns = new ArrayList<>();
+ Map<String, Object> internalParams = Collections.emptyMap();
+
+ return new Meta.Signature(columns, sql, params, internalParams, CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ }
+
+ private KylinJdbcFactory factory() {
+ return (KylinJdbcFactory) factory;
+ }
+
+ public IRemoteClient getRemoteClient() {
+ return remoteClient;
+ }
+
+ @Override
+ public void close() throws SQLException {
+ entry(logger);
+ super.close();
+ try {
+ remoteClient.close();
+ } catch (IOException e) {
+ throw new SQLException(e);
+ }
+ exit(logger);
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinJdbcFactory.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinJdbcFactory.java
new file mode 100644
index 0000000000..02d225ff44
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinJdbcFactory.java
@@ -0,0 +1,138 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import org.apache.calcite.avatica.AvaticaConnection;
+import org.apache.calcite.avatica.AvaticaDatabaseMetaData;
+import org.apache.calcite.avatica.AvaticaFactory;
+import org.apache.calcite.avatica.AvaticaPreparedStatement;
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.AvaticaStatement;
+import org.apache.calcite.avatica.Meta.Frame;
+import org.apache.calcite.avatica.Meta.Signature;
+import org.apache.calcite.avatica.Meta.StatementHandle;
+import org.apache.calcite.avatica.QueryState;
+import org.apache.calcite.avatica.UnregisteredDriver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Kylin JDBC factory.
+ */
+public class KylinJdbcFactory implements AvaticaFactory {
+
+ public static class Version40 extends KylinJdbcFactory {
+ public Version40() {
+ super(4, 0);
+ }
+ }
+
+ public static class Version41 extends KylinJdbcFactory {
+ public Version41() {
+ super(4, 1);
+ }
+ }
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinJdbcFactory.class);
+ final int major;
+ final int minor;
+
+ /** Creates a JDBC factory with given major/minor version number. */
+ protected KylinJdbcFactory(int major, int minor) {
+ entry(logger);
+ this.major = major;
+ this.minor = minor;
+ exit(logger);
+ }
+
+ @Override
+ public int getJdbcMajorVersion() {
+ return major;
+ }
+
+ @Override
+ public int getJdbcMinorVersion() {
+ return minor;
+ }
+
+ @Override
+ public AvaticaConnection newConnection(UnregisteredDriver driver, AvaticaFactory factory, String url, Properties info) throws SQLException {
+ entry(logger);
+ KylinConnection conn = new KylinConnection(driver, (KylinJdbcFactory) factory, url, info);
+ exit(logger);
+ return conn;
+ }
+
+ @Override
+ public AvaticaDatabaseMetaData newDatabaseMetaData(AvaticaConnection connection) {
+ entry(logger);
+ AvaticaDatabaseMetaData metaData = new AvaticaDatabaseMetaData(connection) {};
+ exit(logger);
+ return metaData;
+ }
+
+ @Override
+ public AvaticaStatement newStatement(AvaticaConnection connection, StatementHandle h, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ entry(logger);
+ KylinStatement statement = new KylinStatement(connection, h, resultSetType, resultSetConcurrency, resultSetHoldability);
+ exit(logger);
+ return statement;
+ }
+
+ @Override
+ public AvaticaPreparedStatement newPreparedStatement(AvaticaConnection connection, StatementHandle h, Signature signature, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ entry(logger);
+ KylinPreparedStatement preparedStatement = new KylinPreparedStatement(connection, h, signature, resultSetType, resultSetConcurrency, resultSetHoldability);
+ exit(logger);
+ return preparedStatement;
+ }
+
+ @Override
+ public AvaticaResultSet newResultSet(AvaticaStatement statement, QueryState state, Signature signature, TimeZone timeZone, Frame firstFrame) throws SQLException {
+ entry(logger);
+ AvaticaResultSetMetaData resultSetMetaData = new AvaticaResultSetMetaData(statement, null, signature);
+ KylinResultSet resultSet = new KylinResultSet(statement, state, signature, resultSetMetaData, timeZone, firstFrame);
+ exit(logger);
+ return resultSet;
+ }
+
+ @Override
+ public ResultSetMetaData newResultSetMetaData(AvaticaStatement statement, Signature signature) throws SQLException {
+ entry(logger);
+ AvaticaResultSetMetaData resultSetMetaData = new AvaticaResultSetMetaData(statement, null, signature);
+ exit(logger);
+ return resultSetMetaData;
+ }
+
+ public IRemoteClient newRemoteClient(KylinConnection conn) {
+ entry(logger);
+ KylinClient client = new KylinClient(conn);
+ exit(logger);
+ return client;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java
new file mode 100644
index 0000000000..516eb235d0
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java
@@ -0,0 +1,545 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.calcite.avatica.AvaticaUtils;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.MetaImpl;
+import org.apache.calcite.avatica.NoSuchStatementException;
+import org.apache.calcite.avatica.QueryState;
+import org.apache.calcite.avatica.remote.TypedValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation of Avatica interface
+ */
+public class KylinMeta extends MetaImpl {
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinMeta.class);
+ private KMetaProject metaProject;
+
+ public KylinMeta(KylinConnection connection) {
+ super(connection);
+ entry(logger);
+ exit(logger);
+ }
+
+ private KylinConnection connection() {
+ return (KylinConnection) connection;
+ }
+
+ // insert/update/delete go this path, ignorable for Kylin
+ @Override
+ public StatementHandle prepare(ConnectionHandle ch, String sql, long maxRowCount) {
+ entry(logger);
+ StatementHandle result = super.createStatement(ch);
+ result.signature = connection().mockPreparedSignature(sql);
+ exit(logger);
+ return result;
+ }
+
+ @Override
+ public ExecuteBatchResult prepareAndExecuteBatch(StatementHandle sh, List<String> sqlCommands) throws NoSuchStatementException {
+ entry(logger);
+ ExecuteBatchResult result = new ExecuteBatchResult(new long[] {});
+ exit(logger);
+ return result;
+ }
+
+ @Override
+ public ExecuteBatchResult executeBatch(StatementHandle sh, List<List<TypedValue>> parameterValues)
+ throws NoSuchStatementException {
+ entry(logger);
+ ExecuteBatchResult result = new ExecuteBatchResult(new long[] {});
+ exit(logger);
+ return result;
+ }
+
+ /**
+ * @deprecated (2022-11-20, real execution happens in KylinResultSet.execute())
+ */
+ @Override
+ @Deprecated
+ public ExecuteResult execute(StatementHandle sh, List<TypedValue> parameterValues, long maxRowCount)
+ throws NoSuchStatementException {
+ entry(logger);
+ final MetaResultSet metaResultSet = MetaResultSet.create(sh.connectionId, sh.id, false, sh.signature, null);
+ ExecuteResult result = new ExecuteResult(Collections.singletonList(metaResultSet));
+ exit(logger);
+ return result;
+ }
+
+ @Override
+ public ExecuteResult execute(StatementHandle sh, List<TypedValue> parameterValues, int maxRowsInFirstFrame)
+ throws NoSuchStatementException {
+ entry(logger);
+ final MetaResultSet metaResultSet = MetaResultSet.create(sh.connectionId, sh.id, false, sh.signature, null);
+ ExecuteResult result = new ExecuteResult(Collections.singletonList(metaResultSet));
+ exit(logger);
+ return result;
+ }
+
+ /**
+ * @deprecated (2022-11-20, mimic from CalciteMetaImpl, real execution happens via callback in KylinResultSet.execute())
+ */
+ @Override
+ @Deprecated
+ public ExecuteResult prepareAndExecute(StatementHandle sh, String sql, long maxRowCount, PrepareCallback callback) {
+ entry(logger);
+ try {
+ synchronized (callback.getMonitor()) {
+ callback.clear();
+ sh.signature = connection().mockPreparedSignature(sql);
+ callback.assign(sh.signature, null, -1);
+ }
+ callback.execute();
+ final MetaResultSet metaResultSet = MetaResultSet.create(sh.connectionId, sh.id, false, sh.signature, null);
+ ExecuteResult result = new ExecuteResult(Collections.singletonList(metaResultSet));
+ exit(logger);
+ return result;
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public ExecuteResult prepareAndExecute(StatementHandle sh, String sql, long maxRowCount, int maxRowsInFirstFrame,
+ PrepareCallback callback) throws NoSuchStatementException {
+ entry(logger);
+ try {
+ synchronized (callback.getMonitor()) {
+ callback.clear();
+ sh.signature = connection().mockPreparedSignature(sql);
+ callback.assign(sh.signature, null, -1);
+ }
+ callback.execute();
+ final MetaResultSet metaResultSet = MetaResultSet.create(sh.connectionId, sh.id, false, sh.signature, null);
+ ExecuteResult result = new ExecuteResult(Collections.singletonList(metaResultSet));
+ exit(logger);
+ return result;
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void closeStatement(StatementHandle h) {
+ entry(logger);
+ // nothing to do
+ exit(logger);
+ }
+
+ private KMetaProject getMetaProject() {
+ entry(logger);
+ try {
+ if (metaProject == null) {
+ KylinConnection conn = connection();
+ metaProject = conn.getRemoteClient().retrieveMetaData(conn.getProject());
+ }
+ exit(logger);
+ return metaProject;
+ } catch (IOException e) {
+ logger.error(e.getMessage(), e);
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public MetaResultSet getTableTypes(ConnectionHandle ch) {
+ entry(logger);
+ MetaResultSet resultSet = createResultSet(metaTableTypes, MetaTableType.class, "TABLE_TYPE");
+ exit(logger);
+ return resultSet;
+ }
+
+ @Override
+ public MetaResultSet getCatalogs(ConnectionHandle ch) {
+ entry(logger);
+ List<KMetaCatalog> catalogs = getMetaProject().catalogs;
+ MetaResultSet resultSet = createResultSet(catalogs, KMetaCatalog.class, "TABLE_CAT");
+ exit(logger);
+ return resultSet;
+ }
+
+ @Override
+ public MetaResultSet getSchemas(ConnectionHandle ch, String catalog, Pat schemaPattern) {
+ entry(logger);
+ List<KMetaSchema> schemas = getMetaProject().getSchemas(catalog, schemaPattern);
+ MetaResultSet resultSet = createResultSet(schemas, KMetaSchema.class, "TABLE_SCHEM", "TABLE_CATALOG");
+ entry(logger);
+ return resultSet;
+ }
+
+ @Override
+ public MetaResultSet getTables(ConnectionHandle ch, String catalog, Pat schemaPattern, Pat tableNamePattern,
+ List<String> typeList) {
+ entry(logger);
+ List<KMetaTable> tables = getMetaProject().getTables(catalog, schemaPattern, tableNamePattern, typeList);
+ MetaResultSet resultSet = createResultSet(tables, KMetaTable.class, //
+ "TABLE_CAT", //
+ "TABLE_SCHEM", //
+ "TABLE_NAME", //
+ "TABLE_TYPE", //
+ "REMARKS", //
+ "TYPE_CAT", //
+ "TYPE_SCHEM", //
+ "TYPE_NAME", //
+ "SELF_REFERENCING_COL_NAME", //
+ "REF_GENERATION");
+ exit(logger);
+ return resultSet;
+ }
+
+ @Override
+ public MetaResultSet getColumns(ConnectionHandle ch, String catalog, Pat schemaPattern, Pat tableNamePattern,
+ Pat columnNamePattern) {
+ entry(logger);
+ List<KMetaColumn> columns = getMetaProject().getColumns(catalog, schemaPattern, tableNamePattern,
+ columnNamePattern);
+ MetaResultSet resultSet = createResultSet(columns, KMetaColumn.class, //
+ "TABLE_CAT", //
+ "TABLE_SCHEM", //
+ "TABLE_NAME", //
+ "COLUMN_NAME", //
+ "DATA_TYPE", //
+ "TYPE_NAME", //
+ "COLUMN_SIZE", //
+ "BUFFER_LENGTH", //
+ "DECIMAL_DIGITS", //
+ "NUM_PREC_RADIX", //
+ "NULLABLE", //
+ "REMARKS", //
+ "COLUMN_DEF", //
+ "SQL_DATA_TYPE", //
+ "SQL_DATETIME_SUB", //
+ "CHAR_OCTET_LENGTH", //
+ "ORDINAL_POSITION", //
+ "IS_NULLABLE", //
+ "SCOPE_CATALOG", //
+ "SCOPE_TABLE", //
+ "SOURCE_DATA_TYPE", //
+ "IS_AUTOINCREMENT", //
+ "IS_GENERATEDCOLUMN");
+ exit(logger);
+ return resultSet;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private MetaResultSet createResultSet(List iterable, Class clazz, String... names) {
+ entry(logger);
+ final List<ColumnMetaData> columns = new ArrayList<>();
+ final List<Field> fields = new ArrayList<>();
+ final List<String> fieldNames = new ArrayList<>();
+ for (String name : names) {
+ final int index = fields.size();
+ final String fieldName = AvaticaUtils.toCamelCase(name);
+ final Field field;
+ try {
+ field = clazz.getField(fieldName);
+ } catch (NoSuchFieldException e) {
+
+ throw new RuntimeException(e);
+ }
+ columns.add(columnMetaData(name, index, field.getType(), true));
+ fields.add(field);
+ fieldNames.add(fieldName);
+ }
+
+ CursorFactory cursorFactory = CursorFactory.record(clazz, fields, fieldNames);
+ Signature signature = new Signature(columns, "", null, Collections.<String, Object> emptyMap(), cursorFactory,
+ StatementType.SELECT);
+ StatementHandle sh = this.createStatement(connection().handle);
+ Frame frame = new Frame(0, true, iterable);
+ MetaResultSet resultSet = MetaResultSet.create(connection().id, sh.id, true, signature, frame);
+ exit(logger);
+ return resultSet;
+ }
+
+ // ============================================================================
+
+ public static interface NamedWithChildren extends Named {
+ List<? extends NamedWithChildren> getChildren();
+ }
+
+ public static List<? extends NamedWithChildren> searchByPatterns(NamedWithChildren parent, Pat... patterns) {
+ if (patterns == null || patterns.length <= 0) {
+ throw new AssertionError();
+ }
+
+ List<? extends NamedWithChildren> children = findChildren(parent, patterns[0]);
+ if (patterns.length == 1) {
+ return children;
+ } else {
+ List<NamedWithChildren> result = new ArrayList<>();
+ Pat[] subPatterns = Arrays.copyOfRange(patterns, 1, patterns.length);
+ for (NamedWithChildren c : children) {
+ result.addAll(searchByPatterns(c, subPatterns));
+ }
+ return result;
+ }
+ }
+
+ private static List<? extends NamedWithChildren> findChildren(NamedWithChildren parent, Pat pattern) {
+ if (null == pattern.s || pattern.s.equals("%")) {
+ return parent.getChildren();
+ }
+
+ List<NamedWithChildren> result = new ArrayList<>();
+ Pattern regex = likeToRegex(pattern);
+
+ for (NamedWithChildren c : parent.getChildren()) {
+ if (regex.matcher(c.getName()).matches()) {
+ result.add(c);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Converts a LIKE-style pattern (where '%' represents a wild-card,
+ * escaped using '\') to a Java regex.
+ */
+ private static Pattern likeToRegex(Pat pattern) {
+ StringBuilder buf = new StringBuilder("^");
+ char[] charArray = pattern.s.toCharArray();
+ int slash = -2;
+ for (int i = 0; i < charArray.length; i++) {
+ char c = charArray[i];
+ if (slash == i - 1) {
+ buf.append('[').append(c).append(']');
+ } else {
+ switch (c) {
+ case '\\':
+ slash = i;
+ break;
+ case '%':
+ buf.append(".*");
+ break;
+ case '[':
+ buf.append("\\[");
+ break;
+ case ']':
+ buf.append("\\]");
+ break;
+ default:
+ buf.append('[').append(c).append(']');
+ }
+ }
+ }
+ buf.append("$");
+
+ return Pattern.compile(buf.toString());
+ }
+
+ // ============================================================================
+
+ private static final List<MetaTableType> metaTableTypes = new ArrayList<MetaTableType>();
+ static {
+ metaTableTypes.add(new MetaTableType("TABLE"));
+ }
+
+ public static class KMetaProject implements NamedWithChildren {
+ public final String projectName;
+ public final List<KMetaCatalog> catalogs;
+
+ public KMetaProject(String projectName, List<KMetaCatalog> catalogs) {
+ this.projectName = projectName;
+ this.catalogs = catalogs;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<KMetaSchema> getSchemas(String catalog, Pat schemaPattern) {
+ return (List<KMetaSchema>) searchByPatterns(this, Pat.of(catalog), schemaPattern);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<KMetaTable> getTables(String catalog, Pat schemaPattern, Pat tableNamePattern,
+ List<String> typeList) {
+ return (List<KMetaTable>) searchByPatterns(this, Pat.of(catalog), schemaPattern, tableNamePattern);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<KMetaColumn> getColumns(String catalog, Pat schemaPattern, Pat tableNamePattern,
+ Pat columnNamePattern) {
+ return (List<KMetaColumn>) searchByPatterns(this, Pat.of(catalog), schemaPattern, tableNamePattern,
+ columnNamePattern);
+ }
+
+ @Override
+ public String getName() {
+ return projectName;
+ }
+
+ @Override
+ public List<? extends NamedWithChildren> getChildren() {
+ return catalogs;
+ }
+ }
+
+ public static class KMetaCatalog implements NamedWithChildren {
+ public final String tableCat;
+ public final List<KMetaSchema> schemas;
+
+ public KMetaCatalog(String tableCatalog, List<KMetaSchema> schemas) {
+ this.tableCat = tableCatalog;
+ this.schemas = schemas;
+ }
+
+ @Override
+ public String getName() {
+ return tableCat;
+ }
+
+ @Override
+ public List<? extends NamedWithChildren> getChildren() {
+ return schemas;
+ }
+ }
+
+ public static class KMetaSchema extends MetaSchema implements NamedWithChildren {
+ public final List<KMetaTable> tables;
+
+ public KMetaSchema(String tableCatalog, String tableSchem, List<KMetaTable> tables) {
+ super(tableCatalog, tableSchem);
+ this.tables = tables;
+ }
+
+ @Override
+ public List<? extends NamedWithChildren> getChildren() {
+ return tables;
+ }
+ }
+
+ public static class KMetaTable extends MetaTable implements NamedWithChildren {
+ public final List<KMetaColumn> columns;
+
+ public KMetaTable(String tableCat, String tableSchem, String tableName, String tableType,
+ List<KMetaColumn> columns) {
+ super(tableCat, tableSchem, tableName, tableType);
+ this.columns = columns;
+ }
+
+ @Override
+ public List<? extends NamedWithChildren> getChildren() {
+ return columns;
+ }
+ }
+
+ public static class KMetaColumn implements NamedWithChildren {
+ public final String tableCat;
+ public final String tableSchem;
+ @MetaImpl.ColumnNoNulls
+ public final String tableName;
+ @MetaImpl.ColumnNoNulls
+ public final String columnName;
+ public final int dataType;
+ @MetaImpl.ColumnNoNulls
+ public final String typeName;
+ public final Integer columnSize;
+ @MetaImpl.ColumnNullableUnknown
+ public final Integer bufferLength = null;
+ public final Integer decimalDigits;
+ public final Integer numPrecRadix;
+ public final int nullable;
+ public final String remarks;
+ public final String columnDef = null;
+ @MetaImpl.ColumnNullableUnknown
+ public final Integer sqlDataType = null;
+ @MetaImpl.ColumnNullableUnknown
+ public final Integer sqlDatetimeSub = null;
+ public final Integer charOctetLength;
+ public final int ordinalPosition;
+ @MetaImpl.ColumnNoNulls
+ public final String isNullable;
+ public final String scopeCatalog = null;
+ public final String scopeSchema = null;
+ public final String scopeTable = null;
+ public final Short sourceDataType = null;
+ @MetaImpl.ColumnNoNulls
+ public final String isAutoincrement = "";
+ @MetaImpl.ColumnNoNulls
+ public final String isGeneratedcolumn = "";
+
+ public KMetaColumn(String tableCat, String tableSchem, String tableName, String columnName, int dataType,
+ String typeName, int columnSize, Integer decimalDigits, int numPrecRadix, int nullable,
+ int charOctetLength, int ordinalPosition, String isNullable, String remarks) {
+ this.tableCat = tableCat;
+ this.tableSchem = tableSchem;
+ this.tableName = tableName;
+ this.columnName = columnName;
+ this.dataType = dataType;
+ this.typeName = typeName;
+ this.columnSize = columnSize;
+ this.decimalDigits = decimalDigits;
+ this.numPrecRadix = numPrecRadix;
+ this.nullable = nullable;
+ this.charOctetLength = charOctetLength;
+ this.ordinalPosition = ordinalPosition;
+ this.isNullable = isNullable;
+ this.remarks = remarks;
+ }
+
+ @Override
+ public String getName() {
+ return this.columnName;
+ }
+
+ @Override
+ public List<NamedWithChildren> getChildren() {
+ return Collections.emptyList();
+ }
+ }
+
+ @Override
+ public Frame fetch(StatementHandle h, long offset, int fetchMaxRowCount) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean syncResults(StatementHandle sh, QueryState state, long offset) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void commit(ConnectionHandle ch) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void rollback(ConnectionHandle ch) {
+ // TODO Auto-generated method stub
+
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinPreparedStatement.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinPreparedStatement.java
new file mode 100644
index 0000000000..a4215bed7a
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinPreparedStatement.java
@@ -0,0 +1,173 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.io.InputStream;
+import java.io.Reader;
+import java.sql.NClob;
+import java.sql.RowId;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.calcite.avatica.AvaticaConnection;
+import org.apache.calcite.avatica.AvaticaPreparedStatement;
+import org.apache.calcite.avatica.Meta.Signature;
+import org.apache.calcite.avatica.Meta.StatementHandle;
+import org.apache.calcite.avatica.remote.TypedValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KylinPreparedStatement extends AvaticaPreparedStatement {
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinPreparedStatement.class);
+
+ private String queryId;
+
+ protected KylinPreparedStatement(AvaticaConnection connection, StatementHandle h, Signature signature, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ super(connection, h, signature, resultSetType, resultSetConcurrency, resultSetHoldability);
+ entry(logger);
+ if (this.handle.signature == null) {
+ this.handle.signature = signature;
+ }
+ exit(logger);
+ }
+
+ protected List<Object> getParameterJDBCValues() {
+ entry(logger);
+ List<TypedValue> typeValues = getParameterValues();
+ List<Object> jdbcValues = new ArrayList<>(typeValues.size());
+ for (TypedValue typeValue : typeValues) {
+ Object jdbcValue = typeValue == null ? null : typeValue.toJdbc(getCalendar());
+ jdbcValues.add(jdbcValue);
+ }
+ exit(logger);
+ return jdbcValues;
+ }
+
+ // ============================================================================
+
+ @Override
+ public void setRowId(int parameterIndex, RowId x) throws SQLException {
+ getSite(parameterIndex).setRowId(x);
+ }
+
+ @Override
+ public void setNString(int parameterIndex, String value) throws SQLException {
+ getSite(parameterIndex).setNString(value);
+ }
+
+ @Override
+ public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
+ getSite(parameterIndex).setNCharacterStream(value, length);
+ }
+
+ @Override
+ public void setNClob(int parameterIndex, NClob value) throws SQLException {
+ getSite(parameterIndex).setNClob(value);
+ }
+
+ @Override
+ public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
+ getSite(parameterIndex).setClob(reader, length);
+ }
+
+ @Override
+ public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
+ getSite(parameterIndex).setBlob(inputStream, length);
+ }
+
+ @Override
+ public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
+ getSite(parameterIndex).setNClob(reader, length);
+ }
+
+ @Override
+ public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
+ getSite(parameterIndex).setSQLXML(xmlObject);
+ }
+
+ @Override
+ public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
+ getSite(parameterIndex).setAsciiStream(x, length);
+ }
+
+ @Override
+ public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
+ getSite(parameterIndex).setBinaryStream(x, length);
+ }
+
+ @Override
+ public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
+ getSite(parameterIndex).setCharacterStream(reader, length);
+ }
+
+ @Override
+ public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
+ getSite(parameterIndex).setAsciiStream(x);
+ }
+
+ @Override
+ public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
+ getSite(parameterIndex).setBinaryStream(x);
+ }
+
+ @Override
+ public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
+ getSite(parameterIndex).setCharacterStream(reader);
+ }
+
+ @Override
+ public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
+ getSite(parameterIndex).setNCharacterStream(value);
+ }
+
+ @Override
+ public void setClob(int parameterIndex, Reader reader) throws SQLException {
+ getSite(parameterIndex).setClob(reader);
+ }
+
+ @Override
+ public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
+ getSite(parameterIndex).setBlob(inputStream);
+ }
+
+ @Override
+ public void setNClob(int parameterIndex, Reader reader) throws SQLException {
+ getSite(parameterIndex).setNClob(reader);
+ }
+
+ public String getQueryId() {
+ return queryId;
+ }
+
+ public void setQueryId(String queryId) {
+ logger.debug("Query id is set manually to {}", queryId);
+ this.queryId = queryId;
+ }
+
+ public void resetQueryId() {
+ logger.trace("Reset query id");
+ this.queryId = null;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinResultSet.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinResultSet.java
new file mode 100644
index 0000000000..a061de2ab7
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinResultSet.java
@@ -0,0 +1,142 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.apache.kylin.jdbc.LoggerUtils.entry;
+import static org.apache.kylin.jdbc.LoggerUtils.exit;
+
+import java.io.IOException;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+
+import org.apache.calcite.avatica.AvaticaParameter;
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaStatement;
+import org.apache.calcite.avatica.Meta.Frame;
+import org.apache.calcite.avatica.Meta.Signature;
+import org.apache.calcite.avatica.MetaImpl;
+import org.apache.calcite.avatica.QueryState;
+import org.apache.calcite.avatica.util.AbstractCursor;
+import org.apache.calcite.avatica.util.KylinDelegateCursor;
+import org.apache.kylin.jdbc.IRemoteClient.QueryResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KylinResultSet extends AvaticaResultSet {
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinResultSet.class);
+
+ private String queryId;
+ private long resultRowCount;
+ private long duration;
+
+ public KylinResultSet(AvaticaStatement statement, QueryState state, Signature signature, ResultSetMetaData resultSetMetaData, TimeZone timeZone, Frame firstFrame)
+ throws SQLException {
+ super(statement, state, signature, resultSetMetaData, timeZone, firstFrame);
+ entry(logger);
+ exit(logger);
+ }
+
+ public void setQueryId(String queryId) {
+ this.queryId = queryId;
+ }
+
+ public String getQueryId() {
+ return this.queryId;
+ }
+
+
+ public long getResultRowCount() {
+ return resultRowCount;
+ }
+
+ public void setResultRowCount(long resultRowCount) {
+ this.resultRowCount = resultRowCount;
+ }
+
+ public long getDuration() {
+ return duration;
+ }
+
+ public void setDuration(long duration) {
+ this.duration = duration;
+ }
+
+ @Override
+ protected AvaticaResultSet execute() throws SQLException {
+
+ entry(logger);
+ // skip execution if result is already there (case of meta data lookup)
+ if (this.firstFrame != null) {
+ return super.execute();
+ }
+
+ String sql = signature.sql;
+ List<AvaticaParameter> params = signature.parameters;
+ List<Object> paramValues = null;
+ if (!(statement instanceof KylinPreparedStatement)) {
+ params = null;
+ } else if (params != null && params.size() > 0) {
+ paramValues = ((KylinPreparedStatement) statement).getParameterJDBCValues();
+ }
+
+ String queryId = null;
+ if (statement instanceof KylinPreparedStatement) {
+ queryId = ((KylinPreparedStatement) statement).getQueryId();
+ ((KylinPreparedStatement) statement).resetQueryId();
+ } else if (statement instanceof KylinStatement) {
+ queryId = ((KylinStatement) statement).getQueryId();
+ ((KylinStatement) statement).resetQueryId();
+ }
+
+ IRemoteClient client = ((KylinConnection) statement.connection).getRemoteClient();
+
+ Map<String, String> queryToggles = new HashMap<>();
+ int maxRows = statement.getMaxRows();
+ queryToggles.put("ATTR_STATEMENT_MAX_ROWS", String.valueOf(maxRows));
+
+ QueryResult result;
+ try {
+ result = client.executeQuery(sql, params, paramValues, queryToggles, queryId);
+ } catch (IOException e) {
+ logger.error("Query KE failed: ", e);
+ throw new SQLException(e);
+ }
+
+ columnMetaDataList.clear();
+ columnMetaDataList.addAll(result.columnMeta);
+
+ cursor = MetaImpl.createCursor(signature.cursorFactory, result.iterable);
+ if (cursor instanceof AbstractCursor) {
+ cursor = new KylinDelegateCursor((AbstractCursor) cursor);
+ }
+ AvaticaResultSet resultSet = super.execute2(cursor, columnMetaDataList);
+ KylinResultSet kylinResultSet = (KylinResultSet)resultSet;
+ kylinResultSet.setQueryId(result.queryId);
+ kylinResultSet.setDuration(result.duration);
+ kylinResultSet.setResultRowCount(result.resultRowCount);
+ exit(logger);
+ return kylinResultSet;
+ }
+
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinStatement.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinStatement.java
new file mode 100644
index 0000000000..4e8e82a9dc
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/KylinStatement.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.kylin.jdbc;
+
+import org.apache.calcite.avatica.AvaticaConnection;
+import org.apache.calcite.avatica.AvaticaStatement;
+import org.apache.calcite.avatica.Meta.StatementHandle;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KylinStatement extends AvaticaStatement {
+
+ private static final Logger logger = LoggerFactory.getLogger(KylinStatement.class);
+
+ private String queryId;
+
+ protected KylinStatement(AvaticaConnection connection, StatementHandle h, int resultSetType, int resultSetConcurrency, int resultSetHoldability) {
+ super(connection, h, resultSetType, resultSetConcurrency, resultSetHoldability);
+ }
+
+ public String getQueryId() {
+ return queryId;
+ }
+
+ public void setQueryId(String queryId) {
+ logger.debug("Query id is set manually to {}", queryId);
+ this.queryId = queryId;
+ }
+
+ public void resetQueryId() {
+ logger.trace("Reset query id");
+ this.queryId = null;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/LogInitializer.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/LogInitializer.java
new file mode 100644
index 0000000000..b5e2da8f32
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/LogInitializer.java
@@ -0,0 +1,110 @@
+/*
+ * 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.kylin.jdbc;
+
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.util.Properties;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+
+
+public class LogInitializer {
+
+ public static final String SLASH_SEPARATOR = "/";
+
+ public static void init() {
+
+ File tmp = null;
+ try {
+ Class<?> logManagerClz = Class.forName("org.apache.logging.log4j.LogManager");
+ Class<?> logContextClz = Class.forName("org.apache.logging.log4j.core.LoggerContext");
+
+ String classPath = new File(KylinConnection.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath();
+ String separator = String.valueOf(File.separatorChar);
+ String configFileName = classPath.substring(0, classPath.lastIndexOf(separator)+1) + "kylin-jdbc.properties";
+ Properties properties = new Properties();
+ if (new File(configFileName).exists()) {
+ properties.load(preprocessPropertiesFile(configFileName));
+ String level = properties.getProperty("LogLevel");
+ String file = properties.getProperty("LogPath");
+ if (!SLASH_SEPARATOR.equals(separator)) {
+ file = file.replaceAll(Matcher.quoteReplacement(File.separator), "/");
+ }
+ String maxBackupIndex = properties.getProperty("MaxBackupIndex");
+ String maxFileSize = properties.getProperty("MaxFileSize");
+
+ tmp = File.createTempFile("KylinJDBCDRiver", "xml");
+ try(PrintStream out = new PrintStream(tmp)) {
+ out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+ out.println("<Configuration>");
+ out.println(" <Appenders>");
+ out.println(" <RollingFile name=\"RollingFile\" fileName=\"" + file + "\" filePattern=\"" + file + ".%i\">");
+ out.println(" <PatternLayout>");
+ out.println(" <pattern>%d{ISO8601} %-5p [%t] : %m%n</pattern>");
+ out.println(" </PatternLayout>");
+ out.println(" <Policies>");
+ out.println(" <SizeBasedTriggeringPolicy size=\"" + maxFileSize + "\"/>");
+ out.println(" </Policies>");
+ out.println(" <DefaultRolloverStrategy max=\"" + maxBackupIndex + "\"/>");
+ out.println(" </RollingFile>");
+ out.println(" </Appenders>");
+ out.println(" <Loggers>");
+ out.println(" <Logger name=\"org.apache.kylin.jdbc.shaded\" level=\"off\"/>");
+ out.println(" <Root level=\"" + level + "\">");
+ out.println(" <AppenderRef ref=\"RollingFile\"/>");
+ out.println(" </Root>");
+ out.println(" </Loggers>");
+ out.println("</Configuration>");
+ }
+
+ Object context = logManagerClz.getMethod("getContext", boolean.class).invoke(null, false);
+ logContextClz.getMethod("setConfigLocation", java.net.URI.class).invoke(context, tmp.toURI());
+ }
+ } catch (ClassNotFoundException | NoSuchMethodException e) {
+ System.out.println("Log4j class not found, fallback to sl4j");
+ } catch (Exception e) {
+ System.err.println("Failed to init logger");
+ e.printStackTrace(System.err);
+ } finally {
+ if (tmp != null && tmp.exists()) {
+ if (tmp.delete()) {
+ System.err.println("Failed to delete temp KylinJDBCDRiver.xml file.");
+ }
+ }
+ }
+ }
+
+ private static InputStream preprocessPropertiesFile(String myFile) throws IOException {
+ try(Scanner in = new Scanner(new FileReader(myFile))) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ while(in.hasNext()) {
+ out.write(in.nextLine().replace("\\", "\\\\").getBytes());
+ out.write("\n".getBytes());
+ }
+ return new ByteArrayInputStream(out.toByteArray());
+ }
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/LoggerUtils.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/LoggerUtils.java
new file mode 100644
index 0000000000..11ed98427e
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/LoggerUtils.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.kylin.jdbc;
+
+import org.slf4j.Logger;
+
+public class LoggerUtils {
+ public static void entry(Logger logger) {
+ StackTraceElement element = Thread.currentThread().getStackTrace()[2];
+ logger.trace("Enter: {}#{}()", element.getClassName(), element.getMethodName());
+ }
+
+ public static void exit(Logger logger) {
+ StackTraceElement element = Thread.currentThread().getStackTrace()[2];
+ logger.trace("Exit: {}#{}()", element.getClassName(), element.getMethodName());
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/QueryCLI.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/QueryCLI.java
new file mode 100644
index 0000000000..d49c1843c0
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/QueryCLI.java
@@ -0,0 +1,232 @@
+/*
+ * 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.kylin.jdbc;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+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.util.Properties;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.io.FileUtils;
+
+public class QueryCLI {
+
+ private static final String PROJECT_ARG_NAME = "project";
+
+ @SuppressWarnings("static-access")
+ private static final Option OPT_SERVICE = OptionBuilder.withArgName("host:port").hasArg().isRequired()
+ .withDescription("Service endpoint, e.g. -s localhost:7070").create("s");
+
+ @SuppressWarnings("static-access")
+ private static final Option OPT_PROJECT = OptionBuilder.withArgName(PROJECT_ARG_NAME).hasArg().isRequired()
+ .withDescription("Project name, e.g. -project learn_kylin").create(PROJECT_ARG_NAME);
+
+ @SuppressWarnings("static-access")
+ private static final Option OPT_USER = OptionBuilder.withArgName("username").hasArg().isRequired(false)
+ .withDescription("Login user name, by default -u ADMIN").create("u");
+
+ @SuppressWarnings("static-access")
+ private static final Option OPT_PWD = OptionBuilder.withArgName("password").hasArg().isRequired(false)
+ .withDescription("Login password, by default -p KYLIN").create("p");
+
+ private static final Options OPTIONS = new Options();
+ static {
+ OPTIONS.addOption(OPT_SERVICE);
+ OPTIONS.addOption(OPT_PROJECT);
+ OPTIONS.addOption(OPT_USER);
+ OPTIONS.addOption(OPT_PWD);
+ }
+
+ public static void main(String[] args) {
+ QueryCLI cli = new QueryCLI(args, System.in, System.out);
+ int exitCode = cli.run();
+ System.exit(exitCode);
+ }
+
+ // ============================================================================
+
+ final PrintWriter out;
+ final BufferedReader in;
+
+ ParseException parserException;
+ String inpService;
+ String inpProject;
+ String inpUser;
+ String inpPwd;
+ String[] inpSqls;
+
+ public QueryCLI(String[] args, InputStream in, OutputStream out) {
+ this.out = new PrintWriter(out, true);
+ this.in = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
+
+ try {
+ GnuParser parser = new GnuParser();
+ CommandLine line = parser.parse(OPTIONS, args);
+ this.inpService = line.getOptionValue("s");
+ this.inpProject = line.getOptionValue(PROJECT_ARG_NAME);
+ this.inpUser = line.getOptionValue("u", "ADMIN");
+ this.inpPwd = line.getOptionValue("p", "KYLIN");
+ this.inpSqls = line.getArgs();
+ } catch (ParseException e) {
+ parserException = e;
+ }
+ }
+
+ public int run() {
+ if (parserException != null) {
+ printHelp();
+ return -1;
+ }
+
+ try {
+ initDriver();
+ } catch (Exception e) {
+ out.println("[ERROR] Failed to init Driver" + e.getMessage());
+ e.printStackTrace(out);
+ return -2;
+ }
+
+ boolean hasError = false;
+ for (String sqlOrFile : inpSqls) {
+ try {
+
+ runSql(sqlOrFile);
+
+ } catch (Exception ex) {
+ out.println("[ERROR] Failed to run: " + sqlOrFile);
+ ex.printStackTrace(out);
+ hasError = true;
+ }
+
+ // spacing between queries
+ out.println();
+ }
+
+ return hasError ? -3 : 0;
+ }
+
+ private void initDriver() {
+ try {
+ Class.forName("org.apache.kylin.jdbc.Driver");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void runSql(String sqlOrFile) throws Exception {
+ String sql = getSql(sqlOrFile);
+ out.println("Running: " + sql);
+
+ Properties props = new Properties();
+ props.put("user", inpUser);
+ props.put("password", inpPwd);
+ int placeholderCount = KylinCheckSql.countDynamicPlaceholder(sql);
+ boolean isPreparedStatement = placeholderCount > 0;
+ ResultSet rs = null;
+ try (Connection conn = DriverManager.getConnection("jdbc:kylin://" + inpService + "/" + inpProject, props)) {
+ long start;
+ if (isPreparedStatement) {
+ try (PreparedStatement prep = conn.prepareStatement(sql)) {
+ start = System.currentTimeMillis();
+ rs = prep.executeQuery();
+ }
+ } else {
+ try (Statement stat = conn.createStatement()) {
+ // normal statement
+ start = System.currentTimeMillis();
+ rs = stat.executeQuery(sql);
+ }
+ }
+ int rows = printResultSet(rs);
+
+ double seconds = (System.currentTimeMillis() - start) / (double) 1000;
+ out.println("----");
+ out.println(rows + " rows, " + seconds + " seconds");
+ } finally {
+ if (rs != null) {
+ try {
+ rs.close();
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ private String getSql(String sqlOrFile) throws IOException {
+ File f = new File(sqlOrFile);
+ if (f.exists()) {
+ return FileUtils.readFileToString(f, StandardCharsets.UTF_8);
+ } else {
+ return sqlOrFile;
+ }
+ }
+
+ private int printResultSet(ResultSet rs) throws SQLException {
+ ResultSetMetaData meta = rs.getMetaData();
+ int nCols = meta.getColumnCount();
+ int nRows = 0;
+
+ for (int i = 1; i <= nCols; i++) {
+ if (i > 1) {
+ out.print("\t");
+ }
+ out.print(meta.getColumnName(i));
+ }
+ out.println();
+
+ while (rs.next()) {
+ for (int i = 1; i <= nCols; i++) {
+ if (i > 1)
+ out.print("\t");
+ out.print(rs.getString(i));
+ }
+ out.println();
+ nRows++;
+ }
+
+ return nRows;
+ }
+
+ private void printHelp() {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp(out, 100, "java org.apache.kylin.jdbc.QueryCLI [options] <sql-or-file>", "options:",
+ OPTIONS, 2, 2, "");
+ }
+
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/GenericResponse.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/GenericResponse.java
new file mode 100644
index 0000000000..e3ac299193
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/GenericResponse.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.kylin.jdbc.json;
+
+import java.io.Serializable;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class GenericResponse<T> implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String code;
+
+ private T data;
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public T getData() {
+ return data;
+ }
+
+ public void setData(T data) {
+ this.data = data;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/PreparedQueryRequest.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/PreparedQueryRequest.java
new file mode 100644
index 0000000000..f019319275
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/PreparedQueryRequest.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.kylin.jdbc.json;
+
+import java.util.List;
+
+public class PreparedQueryRequest extends QueryRequest {
+ private List<StatementParameter> params;
+
+ public List<StatementParameter> getParams() {
+ return params;
+ }
+
+ public void setParams(List<StatementParameter> params) {
+ this.params = params;
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/QueryRequest.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/QueryRequest.java
new file mode 100644
index 0000000000..fecb9f9c0a
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/QueryRequest.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.kylin.jdbc.json;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class QueryRequest implements Serializable {
+
+ private String queryId;
+ private String sql;
+ private String project;
+ private String executeAs;
+ private Integer limit;
+ private boolean acceptPartial = false;
+
+ private Map<String, String> backdoorToggles;
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/SQLResponseStub.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/SQLResponseStub.java
new file mode 100644
index 0000000000..4772ab06cc
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/SQLResponseStub.java
@@ -0,0 +1,350 @@
+/*
+ * 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.kylin.jdbc.json;
+
+import java.io.Serializable;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SQLResponseStub implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ // the data type for each column
+ private List<ColumnMetaStub> columnMetas;
+
+ // the results rows, each row contains several columns
+ private List<String[]> results;
+
+ private long resultRowCount;
+
+ private String queryId;
+
+ private String cube;
+
+ // if not select query, only return affected row count
+ private int affectedRowCount;
+
+ // if isException, the detailed exception message
+ private String exceptionMessage;
+
+ private boolean isException;
+
+ private long duration;
+
+ private boolean isPartial = false;
+
+ private long totalScanCount;
+
+ private boolean hitExceptionCache = false;
+
+ private boolean storageCacheUsed = false;
+
+ public SQLResponseStub() {
+ }
+
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+
+ public List<ColumnMetaStub> getColumnMetas() {
+ return columnMetas;
+ }
+
+ public void setColumnMetas(List<ColumnMetaStub> columnMetas) {
+ this.columnMetas = columnMetas;
+ }
+
+ public List<String[]> getResults() {
+ return results;
+ }
+
+ public void setResults(List<String[]> results) {
+ this.results = results;
+ }
+
+ public long getResultRowCount() {
+ return resultRowCount;
+ }
+
+ public void setResultRowCount(long resultRowCount) {
+ this.resultRowCount = resultRowCount;
+ }
+
+ public String getQueryId() {
+ return queryId;
+ }
+
+ public void setQueryId(String queryId) {
+ this.queryId = queryId;
+ }
+
+ public String getCube() {
+ return cube;
+ }
+
+ public void setCube(String cube) {
+ this.cube = cube;
+ }
+
+ public int getAffectedRowCount() {
+ return affectedRowCount;
+ }
+
+ public void setAffectedRowCount(int affectedRowCount) {
+ this.affectedRowCount = affectedRowCount;
+ }
+
+ public boolean getIsException() {
+ return isException;
+ }
+
+ public void setIsException(boolean isException) {
+ this.isException = isException;
+ }
+
+ public String getExceptionMessage() {
+ return exceptionMessage;
+ }
+
+ public void setExceptionMessage(String exceptionMessage) {
+ this.exceptionMessage = exceptionMessage;
+ }
+
+ public long getDuration() {
+ return duration;
+ }
+
+ public void setDuration(long duration) {
+ this.duration = duration;
+ }
+
+ public boolean isPartial() {
+ return isPartial;
+ }
+
+ public void setPartial(boolean isPartial) {
+ this.isPartial = isPartial;
+ }
+
+ public long getTotalScanCount() {
+ return totalScanCount;
+ }
+
+ public void setTotalScanCount(long totalScanCount) {
+ this.totalScanCount = totalScanCount;
+ }
+
+ public boolean isHitExceptionCache() {
+ return hitExceptionCache;
+ }
+
+ public void setHitExceptionCache(boolean hitExceptionCache) {
+ this.hitExceptionCache = hitExceptionCache;
+ }
+
+ public boolean isStorageCacheUsed() {
+ return storageCacheUsed;
+ }
+
+ public void setStorageCacheUsed(boolean storageCacheUsed) {
+ this.storageCacheUsed = storageCacheUsed;
+ }
+
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class ColumnMetaStub implements Serializable{
+
+ private boolean isAutoIncrement;
+ private boolean isCaseSensitive;
+ private boolean isSearchable;
+ private boolean isCurrency;
+ private int isNullable;// 0:nonull, 1:nullable, 2: nullableunknown
+ private boolean isSigned;
+ private int displaySize;
+ private String label;// AS keyword
+ private String name;
+ private String schemaName;
+ private String catelogName;
+ private String tableName;
+ private int precision;
+ private int scale;
+ private int columnType;// as defined in java.sql.Types
+ private String columnTypeName;
+ private boolean isReadOnly;
+ private boolean isWritable;
+ private boolean isDefinitelyWritable;
+
+ public ColumnMetaStub() {
+ }
+
+ public boolean isAutoIncrement() {
+ return isAutoIncrement;
+ }
+
+ public void setAutoIncrement(boolean isAutoIncrement) {
+ this.isAutoIncrement = isAutoIncrement;
+ }
+
+ public boolean isCaseSensitive() {
+ return isCaseSensitive;
+ }
+
+ public void setCaseSensitive(boolean isCaseSensitive) {
+ this.isCaseSensitive = isCaseSensitive;
+ }
+
+ public boolean isSearchable() {
+ return isSearchable;
+ }
+
+ public void setSearchable(boolean isSearchable) {
+ this.isSearchable = isSearchable;
+ }
+
+ public boolean isCurrency() {
+ return isCurrency;
+ }
+
+ public void setCurrency(boolean isCurrency) {
+ this.isCurrency = isCurrency;
+ }
+
+ public int getIsNullable() {
+ return isNullable;
+ }
+
+ public void setIsNullable(int isNullable) {
+ this.isNullable = isNullable;
+ }
+
+ public boolean isSigned() {
+ return isSigned;
+ }
+
+ public void setSigned(boolean isSigned) {
+ this.isSigned = isSigned;
+ }
+
+ public int getDisplaySize() {
+ return displaySize;
+ }
+
+ public void setDisplaySize(int displaySize) {
+ this.displaySize = displaySize;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getSchemaName() {
+ return schemaName;
+ }
+
+ public void setSchemaName(String schemaName) {
+ this.schemaName = schemaName;
+ }
+
+ public String getCatelogName() {
+ return catelogName;
+ }
+
+ public void setCatelogName(String catelogName) {
+ this.catelogName = catelogName;
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
+
+ public void setTableName(String tableName) {
+ this.tableName = tableName;
+ }
+
+ public int getPrecision() {
+ return precision;
+ }
+
+ public void setPrecision(int precision) {
+ this.precision = precision;
+ }
+
+ public int getScale() {
+ return scale;
+ }
+
+ public void setScale(int scale) {
+ this.scale = scale;
+ }
+
+ public int getColumnType() {
+ return columnType;
+ }
+
+ public void setColumnType(int columnType) {
+ this.columnType = columnType;
+ }
+
+ public String getColumnTypeName() {
+ return columnTypeName;
+ }
+
+ public void setColumnTypeName(String columnTypeName) {
+ this.columnTypeName = columnTypeName;
+ }
+
+ public boolean isReadOnly() {
+ return isReadOnly;
+ }
+
+ public void setReadOnly(boolean isReadOnly) {
+ this.isReadOnly = isReadOnly;
+ }
+
+ public boolean isWritable() {
+ return isWritable;
+ }
+
+ public void setWritable(boolean isWritable) {
+ this.isWritable = isWritable;
+ }
+
+ public boolean isDefinitelyWritable() {
+ return isDefinitelyWritable;
+ }
+
+ public void setDefinitelyWritable(boolean isDefinitelyWritable) {
+ this.isDefinitelyWritable = isDefinitelyWritable;
+ }
+
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/StatementParameter.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/StatementParameter.java
new file mode 100644
index 0000000000..766b02555a
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/StatementParameter.java
@@ -0,0 +1,47 @@
+/*
+ * 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.kylin.jdbc.json;
+
+public class StatementParameter {
+
+ private String className;
+ private String value;
+
+ public StatementParameter(String className, String value) {
+ this.className = className;
+ this.value = value;
+ }
+
+ public String getClassName() {
+ return className;
+ }
+
+ public void setClazz(String className) {
+ this.className = className;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TableMetaStub.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TableMetaStub.java
new file mode 100644
index 0000000000..22cf3fa04c
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TableMetaStub.java
@@ -0,0 +1,348 @@
+/*
+ * 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.kylin.jdbc.json;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TableMetaStub {
+
+ private static final long serialVersionUID = 1L;
+ private String TABLE_CAT;
+ private String TABLE_SCHEM;
+ private String TABLE_NAME;
+ private String TABLE_TYPE;
+ private String REMARKS;
+ private String TYPE_CAT;
+ private String TYPE_SCHEM;
+ private String TYPE_NAME;
+ private String SELF_REFERENCING_COL_NAME;
+ private String REF_GENERATION;
+ @JsonProperty("columns")
+ private List<ColumnMetaStub> columns = new ArrayList<ColumnMetaStub>();
+
+ public String getTABLE_CAT() {
+ return TABLE_CAT;
+ }
+
+ public void setTABLE_CAT(String tABLE_CAT) {
+ TABLE_CAT = tABLE_CAT;
+ }
+
+ public String getTABLE_SCHEM() {
+ return TABLE_SCHEM;
+ }
+
+ public void setTABLE_SCHEM(String tABLE_SCHEM) {
+ TABLE_SCHEM = tABLE_SCHEM;
+ }
+
+ public String getTABLE_NAME() {
+ return TABLE_NAME;
+ }
+
+ public void setTABLE_NAME(String tABLE_NAME) {
+ TABLE_NAME = tABLE_NAME;
+ }
+
+ public String getTABLE_TYPE() {
+ return TABLE_TYPE;
+ }
+
+ public void setTABLE_TYPE(String tABLE_TYPE) {
+ TABLE_TYPE = tABLE_TYPE;
+ }
+
+ public String getREMARKS() {
+ return REMARKS;
+ }
+
+ public void setREMARKS(String rEMARKS) {
+ REMARKS = rEMARKS;
+ }
+
+ public String getTYPE_CAT() {
+ return TYPE_CAT;
+ }
+
+ public void setTYPE_CAT(String tYPE_CAT) {
+ TYPE_CAT = tYPE_CAT;
+ }
+
+ public String getTYPE_SCHEM() {
+ return TYPE_SCHEM;
+ }
+
+ public void setTYPE_SCHEM(String tYPE_SCHEM) {
+ TYPE_SCHEM = tYPE_SCHEM;
+ }
+
+ public String getTYPE_NAME() {
+ return TYPE_NAME;
+ }
+
+ public void setTYPE_NAME(String tYPE_NAME) {
+ TYPE_NAME = tYPE_NAME;
+ }
+
+ public String getSELF_REFERENCING_COL_NAME() {
+ return SELF_REFERENCING_COL_NAME;
+ }
+
+ public void setSELF_REFERENCING_COL_NAME(String sELF_REFERENCING_COL_NAME) {
+ SELF_REFERENCING_COL_NAME = sELF_REFERENCING_COL_NAME;
+ }
+
+ public String getREF_GENERATION() {
+ return REF_GENERATION;
+ }
+
+ public void setREF_GENERATION(String rEF_GENERATION) {
+ REF_GENERATION = rEF_GENERATION;
+ }
+
+ public List<ColumnMetaStub> getColumns() {
+ return columns;
+ }
+
+ public void setColumns(List<ColumnMetaStub> columns) {
+ this.columns = columns;
+ }
+
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class ColumnMetaStub {
+ private String TABLE_CAT;
+ private String TABLE_SCHEM;
+ private String TABLE_NAME;
+ private String COLUMN_NAME;
+ private int DATA_TYPE;
+ private String TYPE_NAME;
+ private int COLUMN_SIZE;
+ private int BUFFER_LENGTH;
+ private int DECIMAL_DIGITS;
+ private int NUM_PREC_RADIX;
+ private int NULLABLE;
+ private String REMARKS;
+ private String COLUMN_DEF;
+ private int SQL_DATA_TYPE;
+ private int SQL_DATETIME_SUB;
+ private int CHAR_OCTET_LENGTH;
+ private int ORDINAL_POSITION;
+ private String IS_NULLABLE;
+ private String SCOPE_CATLOG;
+ private String SCOPE_SCHEMA;
+ private String SCOPE_TABLE;
+ private short SOURCE_DATA_TYPE;
+ private String IS_AUTOINCREMENT;
+
+ public String getTABLE_CAT() {
+ return TABLE_CAT;
+ }
+
+ public void setTABLE_CAT(String tABLE_CAT) {
+ TABLE_CAT = tABLE_CAT;
+ }
+
+ public String getTABLE_SCHEM() {
+ return TABLE_SCHEM;
+ }
+
+ public void setTABLE_SCHEM(String tABLE_SCHEM) {
+ TABLE_SCHEM = tABLE_SCHEM;
+ }
+
+ public String getTABLE_NAME() {
+ return TABLE_NAME;
+ }
+
+ public void setTABLE_NAME(String tABLE_NAME) {
+ TABLE_NAME = tABLE_NAME;
+ }
+
+ public String getCOLUMN_NAME() {
+ return COLUMN_NAME;
+ }
+
+ public void setCOLUMN_NAME(String cOLUMN_NAME) {
+ COLUMN_NAME = cOLUMN_NAME;
+ }
+
+ public int getDATA_TYPE() {
+ return DATA_TYPE;
+ }
+
+ public void setDATA_TYPE(int dATA_TYPE) {
+ DATA_TYPE = dATA_TYPE;
+ }
+
+ public String getTYPE_NAME() {
+ return TYPE_NAME;
+ }
+
+ public void setTYPE_NAME(String tYPE_NAME) {
+ TYPE_NAME = tYPE_NAME;
+ }
+
+ public int getCOLUMN_SIZE() {
+ return COLUMN_SIZE;
+ }
+
+ public void setCOLUMN_SIZE(int cOLUMN_SIZE) {
+ COLUMN_SIZE = cOLUMN_SIZE;
+ }
+
+ public int getBUFFER_LENGTH() {
+ return BUFFER_LENGTH;
+ }
+
+ public void setBUFFER_LENGTH(int bUFFER_LENGTH) {
+ BUFFER_LENGTH = bUFFER_LENGTH;
+ }
+
+ public int getDECIMAL_DIGITS() {
+ return DECIMAL_DIGITS;
+ }
+
+ public void setDECIMAL_DIGITS(int dECIMAL_DIGITS) {
+ DECIMAL_DIGITS = dECIMAL_DIGITS;
+ }
+
+ public int getNUM_PREC_RADIX() {
+ return NUM_PREC_RADIX;
+ }
+
+ public void setNUM_PREC_RADIX(int nUM_PREC_RADIX) {
+ NUM_PREC_RADIX = nUM_PREC_RADIX;
+ }
+
+ public int getNULLABLE() {
+ return NULLABLE;
+ }
+
+ public void setNULLABLE(int nULLABLE) {
+ NULLABLE = nULLABLE;
+ }
+
+ public String getREMARKS() {
+ return REMARKS;
+ }
+
+ public void setREMARKS(String rEMARKS) {
+ REMARKS = rEMARKS;
+ }
+
+ public String getCOLUMN_DEF() {
+ return COLUMN_DEF;
+ }
+
+ public void setCOLUMN_DEF(String cOLUMN_DEF) {
+ COLUMN_DEF = cOLUMN_DEF;
+ }
+
+ public int getSQL_DATA_TYPE() {
+ return SQL_DATA_TYPE;
+ }
+
+ public void setSQL_DATA_TYPE(int sQL_DATA_TYPE) {
+ SQL_DATA_TYPE = sQL_DATA_TYPE;
+ }
+
+ public int getSQL_DATETIME_SUB() {
+ return SQL_DATETIME_SUB;
+ }
+
+ public void setSQL_DATETIME_SUB(int sQL_DATETIME_SUB) {
+ SQL_DATETIME_SUB = sQL_DATETIME_SUB;
+ }
+
+ public int getCHAR_OCTET_LENGTH() {
+ return CHAR_OCTET_LENGTH;
+ }
+
+ public void setCHAR_OCTET_LENGTH(int cHAR_OCTET_LENGTH) {
+ CHAR_OCTET_LENGTH = cHAR_OCTET_LENGTH;
+ }
+
+ public int getORDINAL_POSITION() {
+ return ORDINAL_POSITION;
+ }
+
+ public void setORDINAL_POSITION(int oRDINAL_POSITION) {
+ ORDINAL_POSITION = oRDINAL_POSITION;
+ }
+
+ public String getIS_NULLABLE() {
+ return IS_NULLABLE;
+ }
+
+ public void setIS_NULLABLE(String iS_NULLABLE) {
+ IS_NULLABLE = iS_NULLABLE;
+ }
+
+ public String getSCOPE_CATLOG() {
+ return SCOPE_CATLOG;
+ }
+
+ public void setSCOPE_CATLOG(String sCOPE_CATLOG) {
+ SCOPE_CATLOG = sCOPE_CATLOG;
+ }
+
+ public String getSCOPE_SCHEMA() {
+ return SCOPE_SCHEMA;
+ }
+
+ public void setSCOPE_SCHEMA(String sCOPE_SCHEMA) {
+ SCOPE_SCHEMA = sCOPE_SCHEMA;
+ }
+
+ public String getSCOPE_TABLE() {
+ return SCOPE_TABLE;
+ }
+
+ public void setSCOPE_TABLE(String sCOPE_TABLE) {
+ SCOPE_TABLE = sCOPE_TABLE;
+ }
+
+ public short getSOURCE_DATA_TYPE() {
+ return SOURCE_DATA_TYPE;
+ }
+
+ public void setSOURCE_DATA_TYPE(short sOURCE_DATA_TYPE) {
+ SOURCE_DATA_TYPE = sOURCE_DATA_TYPE;
+ }
+
+ public String getIS_AUTOINCREMENT() {
+ return IS_AUTOINCREMENT;
+ }
+
+ public void setIS_AUTOINCREMENT(String iS_AUTOINCREMENT) {
+ this.IS_AUTOINCREMENT = iS_AUTOINCREMENT;
+ }
+ }
+}
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TableWithComment.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TableWithComment.java
new file mode 100644
index 0000000000..b20916f5cd
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TableWithComment.java
@@ -0,0 +1,613 @@
+/*
+ * 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.kylin.jdbc.json;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TableWithComment {
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("uuid")
+ protected String uuid;
+
+ @JsonProperty("last_modified")
+ protected long lastModified;
+
+ @JsonProperty("create_time")
+ protected long createTime;
+
+ @JsonProperty("version")
+ protected String version;
+
+ @JsonProperty("mvcc")
+ private long mvcc;
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("columns")
+ private List<ColumnWithComment> columns;
+
+ @JsonProperty("source_type")
+ private int sourceType;
+
+ @JsonProperty("kafka_bootstrap_servers")
+ private String kafkaBootstrapServers;
+
+ @JsonProperty("subscribe")
+ private String subscribe;
+
+ @JsonProperty("starting_offsets")
+ private String startingOffsets;
+
+ @JsonProperty("table_type")
+ private String tableType;
+
+ @JsonProperty("top")
+ private boolean isTop;
+
+ @JsonProperty("data_gen")
+ private String dataGen;
+
+ @JsonProperty("increment_loading")
+ private boolean incrementLoading;
+
+ @JsonProperty("last_snapshot_path")
+ private String lastSnapshotPath;
+
+ @JsonProperty("last_snapshot_size")
+ private long lastSnapshotSize;
+
+ @JsonProperty("snapshot_last_modified")
+ private long snapshotLastModified;
+
+ @JsonProperty("query_hit_count")
+ private int snapshotHitCount;
+
+ //first level partition col for this table
+ @JsonProperty("partition_column")
+ private String partitionColumn;
+
+ @JsonProperty("snapshot_partitions")
+ private Map<String, Long> snapshotPartitions;
+
+ //partition col of current built snapshot
+ @JsonProperty("snapshot_partition_col")
+ private String snapshotPartitionCol;
+
+ // user select partition for this snapshot table
+ @JsonProperty("selected_snapshot_partition_col")
+ private String selectedSnapshotPartitionCol;
+
+ @JsonProperty("temp_snapshot_path")
+ private String tempSnapshotPath;
+
+ @Setter
+ @Getter
+ protected String project;
+
+ @Setter
+ @Getter
+ private String identity;
+ private String database;
+ private boolean isBorrowedFromGlobal;
+
+ @JsonProperty("exd")
+ private Map<String, String> descExd;
+
+ @JsonProperty("root_fact")
+ private boolean rootFact;
+
+ @JsonProperty("lookup")
+ private boolean lookup;
+
+ @JsonProperty("primary_key")
+ private Set<String> primaryKey;
+
+ @JsonProperty("foreign_key")
+ private Set<String> foreignKey;
+
+ @JsonProperty("partitioned_column")
+ private String partitionedColumn;
+
+ @JsonProperty("partitioned_column_format")
+ private String partitionedColumnFormat;
+
+ @JsonProperty("storage_size")
+ private long storageSize;
+
+ @JsonProperty("total_records")
+ private long totalRecords;
+
+ @JsonProperty("sampling_rows")
+ private List<String[]> samplingRows;
+
+ @JsonProperty("last_build_job_id")
+ private String jodID;
+
+ public String getDatabase() {
+ return database;
+ }
+
+ public void setDatabase(String database) {
+ this.database = database;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public long getLastModified() {
+ return lastModified;
+ }
+
+ public void setLastModified(long lastModified) {
+ this.lastModified = lastModified;
+ }
+
+ public long getCreateTime() {
+ return createTime;
+ }
+
+ public void setCreateTime(long createTime) {
+ this.createTime = createTime;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public long getMvcc() {
+ return mvcc;
+ }
+
+ public void setMvcc(long mvcc) {
+ this.mvcc = mvcc;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List<ColumnWithComment> getColumns() {
+ return columns;
+ }
+
+ public void setColumns(List<ColumnWithComment> columns) {
+ this.columns = columns;
+ }
+
+ public int getSourceType() {
+ return sourceType;
+ }
+
+ public void setSourceType(int sourceType) {
+ this.sourceType = sourceType;
+ }
+
+ public String getKafkaBootstrapServers() {
+ return kafkaBootstrapServers;
+ }
+
+ public void setKafkaBootstrapServers(String kafkaBootstrapServers) {
+ this.kafkaBootstrapServers = kafkaBootstrapServers;
+ }
+
+ public String getSubscribe() {
+ return subscribe;
+ }
+
+ public void setSubscribe(String subscribe) {
+ this.subscribe = subscribe;
+ }
+
+ public String getStartingOffsets() {
+ return startingOffsets;
+ }
+
+ public void setStartingOffsets(String startingOffsets) {
+ this.startingOffsets = startingOffsets;
+ }
+
+ public String getTableType() {
+ return tableType;
+ }
+
+ public void setTableType(String tableType) {
+ this.tableType = tableType;
+ }
+
+ public boolean isTop() {
+ return isTop;
+ }
+
+ public void setTop(boolean top) {
+ isTop = top;
+ }
+
+ public String getDataGen() {
+ return dataGen;
+ }
+
+ public void setDataGen(String dataGen) {
+ this.dataGen = dataGen;
+ }
+
+ public boolean isIncrementLoading() {
+ return incrementLoading;
+ }
+
+ public void setIncrementLoading(boolean incrementLoading) {
+ this.incrementLoading = incrementLoading;
+ }
+
+ public String getLastSnapshotPath() {
+ return lastSnapshotPath;
+ }
+
+ public void setLastSnapshotPath(String lastSnapshotPath) {
+ this.lastSnapshotPath = lastSnapshotPath;
+ }
+
+ public long getLastSnapshotSize() {
+ return lastSnapshotSize;
+ }
+
+ public void setLastSnapshotSize(long lastSnapshotSize) {
+ this.lastSnapshotSize = lastSnapshotSize;
+ }
+
+ public long getSnapshotLastModified() {
+ return snapshotLastModified;
+ }
+
+ public void setSnapshotLastModified(long snapshotLastModified) {
+ this.snapshotLastModified = snapshotLastModified;
+ }
+
+ public int getSnapshotHitCount() {
+ return snapshotHitCount;
+ }
+
+ public void setSnapshotHitCount(int snapshotHitCount) {
+ this.snapshotHitCount = snapshotHitCount;
+ }
+
+ public String getPartitionColumn() {
+ return partitionColumn;
+ }
+
+ public void setPartitionColumn(String partitionColumn) {
+ this.partitionColumn = partitionColumn;
+ }
+
+ public Map<String, Long> getSnapshotPartitions() {
+ return snapshotPartitions;
+ }
+
+ public void setSnapshotPartitions(Map<String, Long> snapshotPartitions) {
+ this.snapshotPartitions = snapshotPartitions;
+ }
+
+ public String getSnapshotPartitionCol() {
+ return snapshotPartitionCol;
+ }
+
+ public void setSnapshotPartitionCol(String snapshotPartitionCol) {
+ this.snapshotPartitionCol = snapshotPartitionCol;
+ }
+
+ public String getSelectedSnapshotPartitionCol() {
+ return selectedSnapshotPartitionCol;
+ }
+
+ public void setSelectedSnapshotPartitionCol(String selectedSnapshotPartitionCol) {
+ this.selectedSnapshotPartitionCol = selectedSnapshotPartitionCol;
+ }
+
+ public String getTempSnapshotPath() {
+ return tempSnapshotPath;
+ }
+
+ public void setTempSnapshotPath(String tempSnapshotPath) {
+ this.tempSnapshotPath = tempSnapshotPath;
+ }
+
+ public String getProject() {
+ return project;
+ }
+
+ public void setProject(String project) {
+ this.project = project;
+ }
+
+ public String getIdentity() {
+ return identity;
+ }
+
+ public void setIdentity(String identity) {
+ this.identity = identity;
+ }
+
+ public boolean isBorrowedFromGlobal() {
+ return isBorrowedFromGlobal;
+ }
+
+ public void setBorrowedFromGlobal(boolean borrowedFromGlobal) {
+ isBorrowedFromGlobal = borrowedFromGlobal;
+ }
+
+ public Map<String, String> getDescExd() {
+ return descExd;
+ }
+
+ public void setDescExd(Map<String, String> descExd) {
+ this.descExd = descExd;
+ }
+
+ public boolean isRootFact() {
+ return rootFact;
+ }
+
+ public void setRootFact(boolean rootFact) {
+ this.rootFact = rootFact;
+ }
+
+ public boolean isLookup() {
+ return lookup;
+ }
+
+ public void setLookup(boolean lookup) {
+ this.lookup = lookup;
+ }
+
+ public Set<String> getPrimaryKey() {
+ return primaryKey;
+ }
+
+ public void setPrimaryKey(Set<String> primaryKey) {
+ this.primaryKey = primaryKey;
+ }
+
+ public Set<String> getForeignKey() {
+ return foreignKey;
+ }
+
+ public void setForeignKey(Set<String> foreignKey) {
+ this.foreignKey = foreignKey;
+ }
+
+ public String getPartitionedColumn() {
+ return partitionedColumn;
+ }
+
+ public void setPartitionedColumn(String partitionedColumn) {
+ this.partitionedColumn = partitionedColumn;
+ }
+
+ public String getPartitionedColumnFormat() {
+ return partitionedColumnFormat;
+ }
+
+ public void setPartitionedColumnFormat(String partitionedColumnFormat) {
+ this.partitionedColumnFormat = partitionedColumnFormat;
+ }
+
+ public long getStorageSize() {
+ return storageSize;
+ }
+
+ public void setStorageSize(long storageSize) {
+ this.storageSize = storageSize;
+ }
+
+ public long getTotalRecords() {
+ return totalRecords;
+ }
+
+ public void setTotalRecords(long totalRecords) {
+ this.totalRecords = totalRecords;
+ }
+
+ public List<String[]> getSamplingRows() {
+ return samplingRows;
+ }
+
+ public void setSamplingRows(List<String[]> samplingRows) {
+ this.samplingRows = samplingRows;
+ }
+
+ public String getJodID() {
+ return jodID;
+ }
+
+ public void setJodID(String jodID) {
+ this.jodID = jodID;
+ }
+
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class ColumnWithComment {
+
+ @JsonProperty("id")
+ private String id;
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("datatype")
+ private String datatype;
+
+ @JsonProperty("comment")
+ private String comment;
+
+ @JsonProperty("data_gen")
+ private String dataGen;
+
+ @JsonProperty("index")
+ private String index;
+
+ //if null, it's not a computed column
+ @JsonProperty("cc_expr")
+ private String computedColumnExpr;
+
+ @JsonProperty("case_sensitive_name")
+ public String caseSensitiveName;
+
+ @JsonProperty("is_partitioned")
+ public boolean isPartitioned;
+
+ @JsonProperty("cardinality")
+ private Long cardinality;
+
+ @JsonProperty("min_value")
+ private String minValue;
+
+ @JsonProperty("max_value")
+ private String maxValue;
+
+ @JsonProperty("null_count")
+ private Long nullCount;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDatatype() {
+ return datatype;
+ }
+
+ public void setDatatype(String datatype) {
+ this.datatype = datatype;
+ }
+
+ public String getComment() {
+ return comment;
+ }
+
+ public void setComment(String comment) {
+ this.comment = comment;
+ }
+
+ public String getDataGen() {
+ return dataGen;
+ }
+
+ public void setDataGen(String dataGen) {
+ this.dataGen = dataGen;
+ }
+
+ public String getIndex() {
+ return index;
+ }
+
+ public void setIndex(String index) {
+ this.index = index;
+ }
+
+ public String getComputedColumnExpr() {
+ return computedColumnExpr;
+ }
+
+ public void setComputedColumnExpr(String computedColumnExpr) {
+ this.computedColumnExpr = computedColumnExpr;
+ }
+
+ public String getCaseSensitiveName() {
+ return caseSensitiveName;
+ }
+
+ public void setCaseSensitiveName(String caseSensitiveName) {
+ this.caseSensitiveName = caseSensitiveName;
+ }
+
+ public boolean isPartitioned() {
+ return isPartitioned;
+ }
+
+ public void setPartitioned(boolean partitioned) {
+ isPartitioned = partitioned;
+ }
+
+ public Long getCardinality() {
+ return cardinality;
+ }
+
+ public void setCardinality(Long cardinality) {
+ this.cardinality = cardinality;
+ }
+
+ public String getMinValue() {
+ return minValue;
+ }
+
+ public void setMinValue(String minValue) {
+ this.minValue = minValue;
+ }
+
+ public String getMaxValue() {
+ return maxValue;
+ }
+
+ public void setMaxValue(String maxValue) {
+ this.maxValue = maxValue;
+ }
+
+ public Long getNullCount() {
+ return nullCount;
+ }
+
+ public void setNullCount(Long nullCount) {
+ this.nullCount = nullCount;
+ }
+ }
+}
+
diff --git a/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TablesWithCommentResponse.java b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TablesWithCommentResponse.java
new file mode 100644
index 0000000000..e3ad4a3814
--- /dev/null
+++ b/src/jdbc/src/main/java/org/apache/kylin/jdbc/json/TablesWithCommentResponse.java
@@ -0,0 +1,37 @@
+/*
+ * 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.kylin.jdbc.json;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TablesWithCommentResponse {
+
+ private List<TableWithComment> value;
+
+ public List<TableWithComment> getValue() {
+ return value;
+ }
+
+ public void setValue(List<TableWithComment> value) {
+ this.value = value;
+ }
+}
diff --git a/src/jdbc/src/main/resources/META-INF/services/java.sql.Driver b/src/jdbc/src/main/resources/META-INF/services/java.sql.Driver
new file mode 100644
index 0000000000..4f51333d50
--- /dev/null
+++ b/src/jdbc/src/main/resources/META-INF/services/java.sql.Driver
@@ -0,0 +1 @@
+org.apache.kylin.jdbc.Driver
\ No newline at end of file
diff --git a/src/jdbc/src/main/resources/kylin-jdbc.properties b/src/jdbc/src/main/resources/kylin-jdbc.properties
new file mode 100644
index 0000000000..006f204282
--- /dev/null
+++ b/src/jdbc/src/main/resources/kylin-jdbc.properties
@@ -0,0 +1,29 @@
+#
+# 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.
+#
+
+# Set level
+LogLevel=OFF
+
+# Set log path and file name
+LogPath=/usr/local/KylinJDBC.log
+
+# Set maximum number of log files to keep
+MaxBackupIndex=10
+
+# Set maximum size of each log file in bytes
+MaxFileSize=268435456
diff --git a/src/jdbc/src/main/resources/org-apache-kylin-jdbc.properties b/src/jdbc/src/main/resources/org-apache-kylin-jdbc.properties
new file mode 100644
index 0000000000..68918b146c
--- /dev/null
+++ b/src/jdbc/src/main/resources/org-apache-kylin-jdbc.properties
@@ -0,0 +1,28 @@
+#
+# 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.
+#
+
+driver.name=Kylin JDBC Driver
+driver.version=0.1
+product.name=Kylin
+product.version=0.1
+jdbc.compliant=true
+driver.version.major=0
+driver.version.minor=8
+database.version.major=0
+database.version.minor=8
+build.timestamp=20140918-2017
\ No newline at end of file
diff --git a/src/jdbc/src/test/java/org/apache/kylin/jdbc/DriverTest.java b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DriverTest.java
new file mode 100644
index 0000000000..2c6eab52a0
--- /dev/null
+++ b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DriverTest.java
@@ -0,0 +1,267 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import org.apache.calcite.avatica.DriverVersion;
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * Unit test for Driver.
+ */
+public class DriverTest {
+
+ @Test
+ public void testVersion() {
+ Driver driver = new DummyDriver();
+ DriverVersion version = driver.getDriverVersion();
+ Assert.assertNotEquals("unknown version", version.productVersion);
+ }
+
+ @Test
+ public void testStatementWithMockData() throws SQLException {
+ Driver driver = new DummyDriver();
+
+ Connection conn = driver.connect("jdbc:kylin://test_url/test_db", null);
+
+ ResultSet tables = conn.getMetaData().getTables(null, null, null, null);
+ while (tables.next()) {
+ for (int i = 0; i < 4; i++) {
+ assertEquals("dummy", tables.getString(i + 1));
+ }
+ for (int i = 4; i < 10; i++) {
+ assertNull(tables.getString(i + 1));
+ }
+ }
+
+ Statement state = conn.createStatement();
+ ResultSet resultSet = state.executeQuery("select * from test_table");
+
+ ResultSetMetaData metadata = resultSet.getMetaData();
+ assertEquals(12, metadata.getColumnType(1));
+ assertEquals("varchar", metadata.getColumnTypeName(1));
+ assertEquals(1, metadata.isNullable(1));
+
+ while (resultSet.next()) {
+ assertEquals("foo", resultSet.getString(1));
+ assertEquals("bar", resultSet.getString(2));
+ assertEquals("tool", resultSet.getString(3));
+ }
+
+ resultSet.close();
+ state.close();
+ conn.close();
+ }
+
+ @Test
+ public void testStatementWithQuestionMask() throws SQLException {
+ Driver driver = new DummyDriver();
+
+ Connection conn = driver.connect("jdbc:kylin://test_url/test_db", null);
+ Statement state = conn.createStatement();
+ ResultSet resultSet = state.executeQuery("select * from test_table where url not in ('http://a.b.com/?a=b')");
+ ResultSetMetaData metadata = resultSet.getMetaData();
+ assertEquals(12, metadata.getColumnType(1));
+ assertEquals("varchar", metadata.getColumnTypeName(1));
+ assertEquals(1, metadata.isNullable(1));
+
+ while (resultSet.next()) {
+ assertEquals("foo", resultSet.getString(1));
+ assertEquals("bar", resultSet.getString(2));
+ assertEquals("tool", resultSet.getString(3));
+ }
+
+ resultSet.close();
+ state.close();
+ conn.close();
+ }
+
+ @Test
+ public void testPreparedStatementWithMockData() throws SQLException {
+ Driver driver = new DummyDriver();
+
+ Connection conn = driver.connect("jdbc:kylin://test_url/test_db", null);
+ PreparedStatement state = conn.prepareStatement("select * from test_table where id=?");
+ state.setInt(1, 10);
+ ResultSet resultSet = state.executeQuery();
+
+ ResultSetMetaData metadata = resultSet.getMetaData();
+ assertEquals(12, metadata.getColumnType(1));
+ assertEquals("varchar", metadata.getColumnTypeName(1));
+ assertEquals(1, metadata.isNullable(1));
+
+ while (resultSet.next()) {
+ assertEquals("foo", resultSet.getString(1));
+ assertEquals("bar", resultSet.getString(2));
+ assertEquals("tool", resultSet.getString(3));
+ }
+
+ resultSet.close();
+ state.close();
+ conn.close();
+ }
+
+ @Test
+ public void testDateAndTimeStampWithMockData() throws Exception {
+ TimeZone timeZone = TimeZone.getDefault();
+ TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
+ Driver driver = new DummyDriver();
+
+ Connection conn = driver.connect("jdbc:kylin://test_url/test_db", null);
+ PreparedStatement state = conn.prepareStatement("select * from test_table where id=?");
+ state.setInt(1, 10);
+ ResultSet resultSet = state.executeQuery();
+
+ ResultSetMetaData metadata = resultSet.getMetaData();
+ assertEquals("date", metadata.getColumnTypeName(4));
+ assertEquals("time", metadata.getColumnTypeName(5));
+ assertEquals("timestamp", metadata.getColumnTypeName(6));
+
+ while (resultSet.next()) {
+ assertEquals("2019-04-27", resultSet.getString(4));
+ assertEquals("2019-04-27", resultSet.getDate(4).toString());
+ assertEquals("17:30:03", resultSet.getString(5));
+ assertEquals("17:30:03", resultSet.getTime(5).toString());
+ assertEquals("2019-04-27 17:30:03", resultSet.getString(6));
+ assertEquals("2019-04-27 17:30:03.123", resultSet.getTimestamp(6).toString());
+ }
+
+ resultSet.close();
+ state.close();
+ conn.close();
+ TimeZone.setDefault(timeZone);
+ }
+
+ @Ignore("require dev sandbox")
+ @Test
+ public void testWithCubeData() throws Exception {
+ Driver driver = new Driver();
+ Properties info = new Properties();
+ info.put("user", "ADMIN");
+ info.put("password", "KYLIN");
+ Connection conn = driver.connect("jdbc:kylin://localhost:7070/default", info);
+
+ ResultSet catalogs = conn.getMetaData().getCatalogs();
+ System.out.println("CATALOGS");
+ printResultSetMetaData(catalogs);
+ printResultSet(catalogs);
+
+ ResultSet schemas = conn.getMetaData().getSchemas();
+ System.out.println("SCHEMAS");
+ printResultSetMetaData(schemas);
+ printResultSet(schemas);
+
+ ResultSet tables = conn.getMetaData().getTables(null, null, null, null);
+ System.out.println("TABLES");
+ printResultSetMetaData(tables);
+ printResultSet(tables);
+
+ for (int j = 0; j < 3; j++) {
+ Statement state = conn.createStatement();
+ ResultSet resultSet = state.executeQuery("select * from test_kylin_fact");
+
+ printResultSetMetaData(resultSet);
+ printResultSet(resultSet);
+
+ resultSet.close();
+ }
+
+ catalogs.close();
+ schemas.close();
+ tables.close();
+ conn.close();
+ }
+
+ @Ignore("require dev sandbox")
+ @Test
+ public void testPreparedStatementWithCubeData() throws SQLException {
+ Driver driver = new Driver();
+ Properties info = new Properties();
+ info.put("user", "ADMIN");
+ info.put("password", "KYLIN");
+ Connection conn = driver.connect("jdbc:kylin://localhost:7070/default", info);
+
+ PreparedStatement state = conn
+ .prepareStatement("select cal_dt, count(*) from test_kylin_fact where seller_id=? group by cal_dt");
+ state.setLong(1, 10000001);
+ ResultSet resultSet = state.executeQuery();
+
+ printResultSetMetaData(resultSet);
+ printResultSet(resultSet);
+
+ resultSet.close();
+ state.close();
+ conn.close();
+ }
+
+ @Test
+ public void testSSLFromURL() throws SQLException {
+ Driver driver = new DummyDriver();
+ Connection conn = driver.connect("jdbc:kylin:ssl=True;//test_url/test_db", null);
+ assertEquals("test_url", ((KylinConnection) conn).getBaseUrl());
+ assertEquals("test_db", ((KylinConnection) conn).getProject());
+ assertTrue(Boolean.parseBoolean((String) ((KylinConnection) conn).getConnectionProperties().get("ssl")));
+ }
+
+ private void printResultSet(ResultSet rs) throws SQLException {
+ ResultSetMetaData meta = rs.getMetaData();
+ System.out.println("Data:");
+
+ while (rs.next()) {
+ StringBuilder buf = new StringBuilder();
+ buf.append("[");
+ for (int i = 0; i < meta.getColumnCount(); i++) {
+ if (i > 0)
+ buf.append(", ");
+ buf.append(rs.getString(i + 1));
+ }
+ buf.append("]");
+ System.out.println(buf);
+ }
+ }
+
+ private void printResultSetMetaData(ResultSet rs) throws SQLException {
+ ResultSetMetaData metadata = rs.getMetaData();
+ System.out.println("Metadata:");
+
+ for (int i = 0; i < metadata.getColumnCount(); i++) {
+ String metaStr = metadata.getCatalogName(i + 1) + " " + metadata.getColumnClassName(i + 1) + " "
+ + metadata.getColumnDisplaySize(i + 1) + " " + metadata.getColumnLabel(i + 1) + " "
+ + metadata.getColumnName(i + 1) + " " + metadata.getColumnType(i + 1) + " "
+ + metadata.getColumnTypeName(i + 1) + " " + metadata.getPrecision(i + 1) + " "
+ + metadata.getScale(i + 1) + " " + metadata.getSchemaName(i + 1) + " "
+ + metadata.getTableName(i + 1);
+ System.out.println(metaStr);
+ }
+ }
+}
diff --git a/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyClient.java b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyClient.java
new file mode 100644
index 0000000000..6427ed12bd
--- /dev/null
+++ b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyClient.java
@@ -0,0 +1,129 @@
+/*
+ * 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.kylin.jdbc;
+
+import java.io.IOException;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.kylin.jdbc.KylinMeta.KMetaCatalog;
+import org.apache.kylin.jdbc.KylinMeta.KMetaColumn;
+import org.apache.kylin.jdbc.KylinMeta.KMetaProject;
+import org.apache.kylin.jdbc.KylinMeta.KMetaSchema;
+import org.apache.kylin.jdbc.KylinMeta.KMetaTable;
+import org.apache.kylin.jdbc.json.GenericResponse;
+import org.apache.kylin.jdbc.json.SQLResponseStub;
+import org.apache.kylin.jdbc.json.StatementParameter;
+
+/**
+ */
+public class DummyClient extends KylinClient {
+
+ public DummyClient(KylinConnection conn) {
+ super(conn);
+ }
+
+ @Override
+ public void connect() throws IOException {
+ }
+
+ @Override
+ public KMetaProject retrieveMetaData(String project) throws IOException {
+ List<KMetaColumn> columns = new ArrayList<KMetaColumn>();
+
+ KMetaTable table = new KMetaTable("dummy", "dummy", "dummy", "dummy", columns);
+ List<KMetaTable> tables = new ArrayList<KMetaTable>();
+ tables.add(table);
+
+ KMetaSchema schema = new KMetaSchema("dummy", "dummy", tables);
+ List<KMetaSchema> schemas = new ArrayList<KMetaSchema>();
+ schemas.add(schema);
+
+ KMetaCatalog catalog = new KMetaCatalog("dummy", schemas);
+ List<KMetaCatalog> catalogs = new ArrayList<KMetaCatalog>();
+ catalogs.add(catalog);
+
+ return new KMetaProject(project, catalogs);
+ }
+
+ @Override
+ public GenericResponse<SQLResponseStub> executeKylinQuery(String sql, List<StatementParameter> params,
+ Map<String, String> queryToggles, String queryId) throws IOException {
+ SQLResponseStub sqlResponseStub = new SQLResponseStub();
+
+ List<SQLResponseStub.ColumnMetaStub> meta = new ArrayList<>();
+ SQLResponseStub.ColumnMetaStub column1 = new SQLResponseStub.ColumnMetaStub();
+ column1.setColumnType(Types.VARCHAR);
+ column1.setColumnTypeName("varchar");
+ column1.setIsNullable(1);
+ meta.add(column1);
+
+ SQLResponseStub.ColumnMetaStub column2 = new SQLResponseStub.ColumnMetaStub();
+ column2.setColumnType(Types.VARCHAR);
+ column2.setColumnTypeName("varchar");
+ column2.setIsNullable(1);
+ meta.add(column2);
+
+ SQLResponseStub.ColumnMetaStub column3 = new SQLResponseStub.ColumnMetaStub();
+ column3.setColumnType(Types.VARCHAR);
+ column3.setColumnTypeName("varchar");
+ column3.setIsNullable(1);
+ meta.add(column3);
+
+ SQLResponseStub.ColumnMetaStub column4 = new SQLResponseStub.ColumnMetaStub();
+ column4.setColumnType(Types.DATE);
+ column4.setColumnTypeName("date");
+ column4.setIsNullable(1);
+ meta.add(column4);
+
+ SQLResponseStub.ColumnMetaStub column5 = new SQLResponseStub.ColumnMetaStub();
+ column5.setColumnType(Types.TIME);
+ column5.setColumnTypeName("time");
+ column5.setIsNullable(1);
+ meta.add(column5);
+
+ SQLResponseStub.ColumnMetaStub column6 = new SQLResponseStub.ColumnMetaStub();
+ column6.setColumnType(Types.TIMESTAMP);
+ column6.setColumnTypeName("timestamp");
+ column6.setIsNullable(1);
+ meta.add(column6);
+
+ sqlResponseStub.setColumnMetas(meta);
+
+ List<String[]> data = new ArrayList<String[]>();
+
+ String[] row = new String[] { "foo", "bar", "tool", "2019-04-27", "17:30:03", "2019-04-27 17:30:03.123" };
+ data.add(row);
+
+ sqlResponseStub.setResults(data);
+
+ sqlResponseStub.setQueryId(queryId);
+
+ GenericResponse<SQLResponseStub> rslt = new GenericResponse<>();
+ rslt.setData(sqlResponseStub);
+ return rslt;
+ }
+
+ @Override
+ public void close() throws IOException {
+ }
+
+}
diff --git a/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyDriver.java b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyDriver.java
new file mode 100644
index 0000000000..18e4107b68
--- /dev/null
+++ b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyDriver.java
@@ -0,0 +1,30 @@
+/*
+ * 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.kylin.jdbc;
+
+/**
+ */
+public class DummyDriver extends Driver {
+
+ @Override
+ protected String getFactoryClassName(JdbcVersion jdbcVersion) {
+ return DummyJdbcFactory.class.getName();
+ }
+
+}
diff --git a/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyJdbcFactory.java b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyJdbcFactory.java
new file mode 100644
index 0000000000..7ee1884aad
--- /dev/null
+++ b/src/jdbc/src/test/java/org/apache/kylin/jdbc/DummyJdbcFactory.java
@@ -0,0 +1,34 @@
+/*
+ * 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.kylin.jdbc;
+
+/**
+ */
+public class DummyJdbcFactory extends KylinJdbcFactory {
+
+ public DummyJdbcFactory() {
+ super(4, 1);
+ }
+
+ @Override
+ public IRemoteClient newRemoteClient(KylinConnection conn) {
+ return new DummyClient(conn);
+ }
+
+}
diff --git a/src/jdbc/src/test/java/org/apache/kylin/jdbc/KylinChecekSQLTest.java b/src/jdbc/src/test/java/org/apache/kylin/jdbc/KylinChecekSQLTest.java
new file mode 100644
index 0000000000..113235fa6f
--- /dev/null
+++ b/src/jdbc/src/test/java/org/apache/kylin/jdbc/KylinChecekSQLTest.java
@@ -0,0 +1,42 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class KylinChecekSQLTest {
+
+ @Test
+ public void testQueryPlaceholder() {
+ String sql1 = "select SELLER_ID from KYLIN_SALES where SELLER_ID = 10000455";
+ String sql2 = "select SELLER_ID from KYLIN_SALES where SELLER_ID = ?";
+ String sql3 = "select SELLER_ID from KYLIN_SALES where SELLER_ID = ? or SELLER_ID = ? ";
+ String sql4 = "select SELLER_ID from KYLIN_SALES where SELLER_ID = ? and name = '?name' ";
+ String sql5 = "select SELLER_ID from KYLIN_SALES where SELLER_ID = ? and name = `?name` ";
+ String sql6 = "select SELLER_ID from KYLIN_SALES where SELLER_ID = ? and name = \"?name\" ";
+ assertEquals(0, KylinCheckSql.countDynamicPlaceholder(sql1));
+ assertEquals(1, KylinCheckSql.countDynamicPlaceholder(sql2));
+ assertEquals(2, KylinCheckSql.countDynamicPlaceholder(sql3));
+ assertEquals(1, KylinCheckSql.countDynamicPlaceholder(sql4));
+ assertEquals(1, KylinCheckSql.countDynamicPlaceholder(sql5));
+ assertEquals(1, KylinCheckSql.countDynamicPlaceholder(sql6));
+ }
+}
diff --git a/src/jdbc/src/test/java/org/apache/kylin/jdbc/SQLResonseStubTest.java b/src/jdbc/src/test/java/org/apache/kylin/jdbc/SQLResonseStubTest.java
new file mode 100644
index 0000000000..e090af6744
--- /dev/null
+++ b/src/jdbc/src/test/java/org/apache/kylin/jdbc/SQLResonseStubTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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.kylin.jdbc;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+
+import java.io.IOException;
+
+import org.apache.kylin.jdbc.json.SQLResponseStub;
+import org.junit.Test;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Created by dongli on 1/25/16.
+ */
+public class SQLResonseStubTest {
+
+ @Test
+ public void testReadValuePartRecognizedField() throws IOException {
+ final String payload = "{ \"columnMetas\":[ { \"isNullable\":1, \"displaySize\":0, \"schemaName\":null, \"catelogName\":null, \"tableName\":null, \"precision\":0, \"scale\":0, \"columnType\":91, \"columnTypeName\":\"DATE\", \"readOnly\":true, \"writable\":false, \"caseSensitive\":true, \"searchable\":false, \"currency\":false, \"signed\":true, \"autoIncrement\":false, \"definitelyWritable\":false }," + "{ \"isNullable\":1, \"displaySize\":10, \"label\":\"LEAF_CATEG_ID\", \"name\" [...]
+ + "\"schemaName\":null, \"catelogName\":null, \"tableName\":null, \"precision\":10, \"scale\":0, \"columnType\":4, \"columnTypeName\":\"INTEGER\", \"readOnly\":true, \"writable\":false, \"caseSensitive\":true, \"searchable\":false, \"currency\":false, \"signed\":true, \"autoIncrement\":false, \"definitelyWritable\":false } ], \"results\":[ [ \"2013-08-07\", \"32996\", \"15\", \"15\", \"Auction\", \"10000000\", \"49.048952730908745\", \"49.048952730908745\", \"49.048952730 [...]
+ final SQLResponseStub stub = new ObjectMapper().readValue(payload, SQLResponseStub.class);
+ assertEquals("test_kylin_cube_with_slr_desc", stub.getCube());
+ assertEquals(3451, stub.getDuration());
+ assertFalse(stub.getColumnMetas().isEmpty());
+ assertEquals(91, stub.getColumnMetas().get(0).getColumnType());
+ assertNull(stub.getColumnMetas().get(0).getLabel());
+ assertFalse(stub.getResults().isEmpty());
+ assertNull(stub.getExceptionMessage());
+ }
+
+ @Test
+ public void testReadValueWithUnrecognizedField() throws IOException {
+ final String payload = "{ \"columnMetas\":[ { \"Unrecognized\":0, \"isNullable\":1, \"displaySize\":0, " + "\"label\":\"CAL_DT\", \"name\":\"CAL_DT\", \"schemaName\":null, \"catelogName\":null, " + "\"tableName\":null, \"precision\":0, \"scale\":0, \"columnType\":91, \"columnTypeName\":\"DATE\", " + "\"readOnly\":true, \"writable\":false, \"caseSensitive\":true, \"searchable\":false, \"currency\":false, \"signed\":true, \"autoIncrement\":false, \"definitelyWritable\":false },"
+ + " { \"isNullable\":1, \"displaySize\":10, \"label\":\"LEAF_CATEG_ID\", \"name\":\"LEAF_CATEG_ID\", \"schemaName\":null, \"catelogName\":null, \"tableName\":null, \"precision\":10, \"scale\":0, \"columnType\":4, \"columnTypeName\":\"INTEGER\", \"readOnly\":true, \"writable\":false, \"caseSensitive\":true, \"searchable\":false, \"currency\":false, \"signed\":true, \"autoIncrement\":false, \"definitelyWritable\":false } ], \"results\":[ [ \"2013-08-07\", \"32996\", \"15\", [...]
+ final SQLResponseStub stub = new ObjectMapper().readValue(payload, SQLResponseStub.class);
+ assertEquals("test_kylin_cube_with_slr_desc", stub.getCube());
+ assertEquals(3451, stub.getDuration());
+ assertFalse(stub.getColumnMetas().isEmpty());
+ assertEquals(91, stub.getColumnMetas().get(0).getColumnType());
+ assertEquals("CAL_DT", stub.getColumnMetas().get(0).getLabel());
+ assertFalse(stub.getResults().isEmpty());
+ assertNull(stub.getExceptionMessage());
+ }
+}