未验证 提交 bc218577 编写于 作者: Z Zhiyu Yang 提交者: GitHub

Hotfix/td 4876 (#6656)

* fix warn mesage in jdbc

* change

* [TD-4876]<fix>: fix getNetworkTimeout and setNetworkTimeout in jdbc driver

* [TD-4117]<test>: remove System.out.println in all jdbc test cases

* change
上级 ea1777d5
......@@ -32,7 +32,7 @@ ELSEIF (TD_WINDOWS)
#INSTALL(TARGETS taos RUNTIME DESTINATION driver)
#INSTALL(TARGETS shell RUNTIME DESTINATION .)
IF (TD_MVN_INSTALLED)
INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.31.jar DESTINATION connector/jdbc)
INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.32-dist.jar DESTINATION connector/jdbc)
ENDIF ()
ELSEIF (TD_DARWIN)
SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh")
......
......@@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED)
ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME}
POST_BUILD
COMMAND mvn -Dmaven.test.skip=true install -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.31.jar ${LIBRARY_OUTPUT_PATH}
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.32-dist.jar ${LIBRARY_OUTPUT_PATH}
COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml
COMMENT "build jdbc driver")
ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME})
......
......@@ -5,7 +5,7 @@
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.31</version>
<version>2.0.32</version>
<packaging>jar</packaging>
<name>JDBCDriver</name>
......
......@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.31</version>
<version>2.0.32</version>
<packaging>jar</packaging>
<name>JDBCDriver</name>
<url>https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc</url>
......@@ -113,16 +113,16 @@
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/TSDBJNIConnectorTest.java</exclude>
<exclude>**/UnsignedNumberJniTest.java</exclude>
<exclude>**/DatetimeBefore1970Test.java</exclude>
<exclude>**/AppMemoryLeakTest.java</exclude>
<exclude>**/AuthenticationTest.java</exclude>
<exclude>**/TaosInfoMonitorTest.java</exclude>
<exclude>**/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java</exclude>
<exclude>**/DatetimeBefore1970Test.java</exclude>
<exclude>**/FailOverTest.java</exclude>
<exclude>**/InvalidResultSetPointerTest.java</exclude>
<exclude>**/RestfulConnectionTest.java</exclude>
<exclude>**/ConnectMultiTaosdByRestfulWithDifferentTokenTest.java</exclude>
<exclude>**/TSDBJNIConnectorTest.java</exclude>
<exclude>**/TaosInfoMonitorTest.java</exclude>
<exclude>**/UnsignedNumberJniTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
......
package com.taosdata.jdbc;
import com.taosdata.jdbc.rs.enums.TimestampFormat;
import com.taosdata.jdbc.enums.TimestampFormat;
import java.sql.*;
import java.util.Enumeration;
......@@ -306,9 +306,6 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED);
switch (resultSetHoldability) {
case ResultSet.HOLD_CURSORS_OVER_COMMIT:
break;
......@@ -322,11 +319,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED);
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
switch (resultSetHoldability) {
case ResultSet.HOLD_CURSORS_OVER_COMMIT:
break;
......@@ -425,7 +418,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
status = resultSet.getInt("server_status()");
resultSet.close();
}
return status == 1 ? true : false;
return status == 1;
});
boolean status = false;
......@@ -434,9 +427,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
status = future.get();
else
status = future.get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
future.cancel(true);
......@@ -452,8 +443,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
if (isClosed)
throw (SQLClientInfoException) TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED);
if (clientInfoProps != null)
clientInfoProps.setProperty(name, value);
clientInfoProps.setProperty(name, value);
}
@Override
......@@ -461,8 +451,8 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
if (isClosed)
throw (SQLClientInfoException) TSDBError.createSQLException(TSDBErrorNumbers.ERROR_SQLCLIENT_EXCEPTION_ON_CONNECTION_CLOSED);
for (Enumeration<Object> enumer = properties.keys(); enumer.hasMoreElements(); ) {
String name = (String) enumer.nextElement();
for (Enumeration<Object> enumeration = properties.keys(); enumeration.hasMoreElements(); ) {
String name = (String) enumeration.nextElement();
clientInfoProps.put(name, properties.getProperty(name));
}
}
......@@ -528,14 +518,13 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
if (milliseconds < 0)
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE);
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD);
// do nothing
}
@Override
public int getNetworkTimeout() throws SQLException {
if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED);
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD);
return 0;
}
}
......@@ -12,8 +12,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
private final static int DRIVER_MAJAR_VERSION = 2;
private final static int DRIVER_MINOR_VERSION = 0;
private String precision = "ms";
private String database;
private String precision = TSDBConstants.DEFAULT_PRECISION;
public boolean allProceduresAreCallable() throws SQLException {
return false;
......@@ -1223,7 +1222,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
ResultSet databases = stmt.executeQuery("show databases");
while (databases.next()) {
String dbname = databases.getString("name");
this.database = dbname;
this.precision = databases.getString("precision");
if (dbname.equalsIgnoreCase(catalog))
return true;
......
......@@ -58,7 +58,7 @@ public abstract class AbstractDriver implements Driver {
value = parameterValuePair.substring(indexOfEqual + 1);
}
}
if ((value != null && value.length() > 0) && (parameter != null && parameter.length() > 0)) {
if (value != null && value.length() > 0 && parameter.length() > 0) {
urlProps.setProperty(parameter, value);
}
}
......@@ -87,7 +87,7 @@ public abstract class AbstractDriver implements Driver {
url = url.substring(0, indexOfColon);
}
// parse host
if (url != null && url.length() > 0 && url.trim().length() > 0) {
if (url.length() > 0 && url.trim().length() > 0) {
urlProps.setProperty(TSDBDriver.PROPERTY_KEY_HOST, url);
}
return urlProps;
......
package com.taosdata.jdbc;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.sql.ParameterMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
......
......@@ -15,10 +15,12 @@
package com.taosdata.jdbc;
import java.math.BigDecimal;
import java.sql.*;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
/*
......@@ -130,7 +132,7 @@ public class DatabaseMetaDataResultSet extends AbstractResultSet {
public Timestamp getTimestamp(int columnIndex) throws SQLException {
int colType = columnMetaDataList.get(columnIndex - 1).getColType();
int nativeType = TSDBConstants.jdbcType2TaosType(colType);
return rowCursor.getTimestamp(columnIndex,nativeType);
return rowCursor.getTimestamp(columnIndex, nativeType);
}
@Override
......@@ -145,9 +147,7 @@ public class DatabaseMetaDataResultSet extends AbstractResultSet {
@Override
public int findColumn(String columnLabel) throws SQLException {
Iterator<ColumnMetaData> colMetaDataIt = this.columnMetaDataList.iterator();
while (colMetaDataIt.hasNext()) {
ColumnMetaData colMetaData = colMetaDataIt.next();
for (ColumnMetaData colMetaData : this.columnMetaDataList) {
if (colMetaData.getColName() != null && colMetaData.getColName().equals(columnLabel)) {
return colMetaData.getColIndex();
}
......
......@@ -23,7 +23,7 @@ import java.util.Calendar;
import java.util.Map;
/*
* TDengine only supports a subset of the standard SQL, thus this implemetation of the
* TDengine only supports a subset of the standard SQL, thus this implementation of the
* standard JDBC API contains more or less some adjustments customized for certain
* compatibility needs.
*/
......
......@@ -20,7 +20,7 @@ import java.util.Properties;
public class TSDBConnection extends AbstractConnection {
private TSDBJNIConnector connector;
private TSDBDatabaseMetaData databaseMetaData;
private final TSDBDatabaseMetaData databaseMetaData;
private boolean batchFetch;
public Boolean getBatchFetch() {
......
......@@ -54,10 +54,11 @@ public abstract class TSDBConstants {
public static final int TSDB_DATA_TYPE_USMALLINT = 12; //unsigned smallint
public static final int TSDB_DATA_TYPE_UINT = 13; //unsigned int
public static final int TSDB_DATA_TYPE_UBIGINT = 14; //unsigned bigint
// nchar column max length
public static final int maxFieldSize = 16 * 1024;
// precision for data types
// precision for data types, this is used for metadata
public static final int BOOLEAN_PRECISION = 1;
public static final int TINYINT_PRECISION = 4;
public static final int SMALLINT_PRECISION = 6;
......@@ -67,10 +68,12 @@ public abstract class TSDBConstants {
public static final int DOUBLE_PRECISION = 22;
public static final int TIMESTAMP_MS_PRECISION = 23;
public static final int TIMESTAMP_US_PRECISION = 26;
// scale for data types
// scale for data types, this is used for metadata
public static final int FLOAT_SCALE = 31;
public static final int DOUBLE_SCALE = 31;
public static final String DEFAULT_PRECISION = "ms";
public static int typeName2JdbcType(String type) {
switch (type.toUpperCase()) {
case "TIMESTAMP":
......
......@@ -20,8 +20,8 @@ import java.sql.SQLException;
public class TSDBDatabaseMetaData extends AbstractDatabaseMetaData {
private String url;
private String userName;
private final String url;
private final String userName;
private Connection conn;
public TSDBDatabaseMetaData(String url, String userName) {
......
......@@ -176,7 +176,7 @@ public class TSDBDriver extends AbstractDriver {
int beginningOfSlashes = url.indexOf("//");
int index = url.indexOf("?");
if (index != -1) {
String paramString = url.substring(index + 1, url.length());
String paramString = url.substring(index + 1);
url = url.substring(0, index);
StringTokenizer queryParams = new StringTokenizer(paramString, "&");
while (queryParams.hasMoreElements()) {
......@@ -213,7 +213,7 @@ public class TSDBDriver extends AbstractDriver {
url = url.substring(0, indexOfColon);
}
if (url != null && url.length() > 0 && url.trim().length() > 0) {
if (url.length() > 0 && url.trim().length() > 0) {
urlProps.setProperty(TSDBDriver.PROPERTY_KEY_HOST, url);
}
......@@ -233,7 +233,7 @@ public class TSDBDriver extends AbstractDriver {
return false;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
public Logger getParentLogger() {
return null;
}
......
......@@ -8,7 +8,7 @@ import java.util.HashMap;
import java.util.Map;
public class TSDBError {
private static Map<Integer, String> TSDBErrorMap = new HashMap<>();
private static final Map<Integer, String> TSDBErrorMap = new HashMap<>();
static {
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_CONNECTION_CLOSED, "connection already closed");
......@@ -34,9 +34,8 @@ public class TSDBError {
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_TAOS_TYPE_IN_TDENGINE, "unknown taos type in tdengine");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN_TIMESTAMP_PERCISION, "unknown timestamp precision");
/**************************************************/
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNKNOWN, "unknown error");
/**************************************************/
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_SUBSCRIBE_FAILED, "failed to create subscription");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING, "Unsupported encoding");
TSDBErrorMap.put(TSDBErrorNumbers.ERROR_JNI_TDENGINE_ERROR, "internal error of database");
......
package com.taosdata.jdbc;
import java.util.HashSet;
import java.util.Set;
public class TSDBErrorNumbers {
......@@ -39,10 +40,9 @@ public class TSDBErrorNumbers {
public static final int ERROR_JNI_FETCH_END = 0x2358; // fetch to the end of resultSet
public static final int ERROR_JNI_OUT_OF_MEMORY = 0x2359; // JNI alloc memory failed
private static final HashSet<Integer> errorNumbers;
private static final Set<Integer> errorNumbers = new HashSet();
static {
errorNumbers = new HashSet();
errorNumbers.add(ERROR_CONNECTION_CLOSED);
errorNumbers.add(ERROR_UNSUPPORTED_METHOD);
errorNumbers.add(ERROR_INVALID_VARIABLE);
......@@ -65,7 +65,6 @@ public class TSDBErrorNumbers {
errorNumbers.add(ERROR_UNKNOWN_TAOS_TYPE_IN_TDENGINE);
errorNumbers.add(ERROR_UNKNOWN_TIMESTAMP_PERCISION);
/*****************************************************/
errorNumbers.add(ERROR_SUBSCRIBE_FAILED);
errorNumbers.add(ERROR_UNSUPPORTED_ENCODING);
errorNumbers.add(ERROR_JNI_TDENGINE_ERROR);
......
......@@ -29,14 +29,9 @@ import java.util.List;
public class TSDBJNIConnector {
private static volatile Boolean isInitialized = false;
private TaosInfo taosInfo = TaosInfo.getInstance();
// Connection pointer used in C
private long taos = TSDBConstants.JNI_NULL_POINTER;
// result set status in current connection
private boolean isResultsetClosed;
private final TaosInfo taosInfo = TaosInfo.getInstance();
private long taos = TSDBConstants.JNI_NULL_POINTER; // Connection pointer used in C
private boolean isResultsetClosed; // result set status in current connection
private int affectedRows = -1;
static {
......@@ -96,11 +91,9 @@ public class TSDBJNIConnector {
/**
* Execute DML/DDL operation
*
* @throws SQLException
*/
public long executeQuery(String sql) throws SQLException {
Long pSql = 0l;
long pSql = 0L;
try {
pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos);
taosInfo.stmt_count_increment();
......@@ -161,7 +154,7 @@ public class TSDBJNIConnector {
private native long getResultSetImp(long connection, long pSql);
public boolean isUpdateQuery(long pSql) {
return isUpdateQueryImp(this.taos, pSql) == 1 ? true : false;
return isUpdateQueryImp(this.taos, pSql) == 1;
}
private native long isUpdateQueryImp(long connection, long pSql);
......@@ -195,7 +188,7 @@ public class TSDBJNIConnector {
*/
public int getSchemaMetaData(long resultSet, List<ColumnMetaData> columnMetaData) {
int ret = this.getSchemaMetaDataImp(this.taos, resultSet, columnMetaData);
columnMetaData.stream().forEach(column -> column.setColIndex(column.getColIndex() + 1));
columnMetaData.forEach(column -> column.setColIndex(column.getColIndex() + 1));
return ret;
}
......@@ -218,8 +211,9 @@ public class TSDBJNIConnector {
/**
* Get Result Time Precision.
*
* @return 0: ms, 1: us, 2: ns
*/
*/
public int getResultTimePrecision(long sqlObj) {
return this.getResultTimePrecisionImp(this.taos, sqlObj);
}
......@@ -228,8 +222,6 @@ public class TSDBJNIConnector {
/**
* Execute close operation from C to release connection pointer by JNI
*
* @throws SQLException
*/
public void closeConnection() throws SQLException {
int code = this.closeConnectionImp(this.taos);
......@@ -268,8 +260,6 @@ public class TSDBJNIConnector {
/**
* Unsubscribe, close a subscription
*
* @param subscription
*/
void unsubscribe(long subscription, boolean isKeep) {
unsubscribeImp(subscription, isKeep);
......@@ -282,13 +272,13 @@ public class TSDBJNIConnector {
*/
public boolean validateCreateTableSql(String sql) {
int res = validateCreateTableSqlImp(taos, sql.getBytes());
return res != 0 ? false : true;
return res == 0;
}
private native int validateCreateTableSqlImp(long connection, byte[] sqlBytes);
public long prepareStmt(String sql) throws SQLException {
Long stmt;
long stmt;
try {
stmt = prepareStmtImp(sql.getBytes(), this.taos);
} catch (Exception e) {
......
......@@ -62,8 +62,8 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
if (parameterCnt > 1) {
// the table name is also a parameter, so ignore it.
this.colData = new ArrayList<ColumnInfo>();
this.tableTags = new ArrayList<TableTagInfo>();
this.colData = new ArrayList<>();
this.tableTags = new ArrayList<>();
}
}
......@@ -73,12 +73,16 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
}
/*
*
*/
/**
* Some of the SQLs sent by other popular frameworks or tools like Spark, contains syntax that cannot be parsed by
* the TDengine client. Thus, some simple parsers/filters are intentionally added in this JDBC implementation in
* order to process those supported SQLs.
*/
private void preprocessSql() {
/***** For processing some of Spark SQLs*****/
/***For processing some of Spark SQLs*/
// should replace it first
this.rawSql = this.rawSql.replaceAll("or (.*) is null", "");
this.rawSql = this.rawSql.replaceAll(" where ", " WHERE ");
......@@ -125,7 +129,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
}
rawSql = rawSql.replace(matcher.group(1), tableFullName);
}
/***** for inner queries *****/
}
@Override
......@@ -519,12 +522,10 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
}
}
;
private static class TableTagInfo {
private boolean isNull;
private Object value;
private int type;
private final Object value;
private final int type;
public TableTagInfo(Object value, int type) {
this.value = value;
......@@ -538,8 +539,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
}
}
;
public void setTableName(String name) {
this.tableName = name;
}
......@@ -627,7 +626,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
this.colData.addAll(Collections.nCopies(this.parameters.length - 1 - this.tableTags.size(), null));
}
ColumnInfo col = (ColumnInfo) this.colData.get(columnIndex);
ColumnInfo col = this.colData.get(columnIndex);
if (col == null) {
ColumnInfo p = new ColumnInfo();
p.setType(type);
......@@ -718,8 +717,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
ByteBuffer isNullList = ByteBuffer.allocate(num * Integer.BYTES);
isNullList.order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < num; ++i) {
TableTagInfo tag = this.tableTags.get(i);
for (TableTagInfo tag : this.tableTags) {
if (tag.isNull) {
typeList.put((byte) tag.type);
isNullList.putInt(1);
......@@ -818,7 +816,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
typeList, lengthList, isNullList);
}
ColumnInfo colInfo = (ColumnInfo) this.colData.get(0);
ColumnInfo colInfo = this.colData.get(0);
if (colInfo == null) {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "column data not bind");
}
......@@ -954,7 +952,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "not support data types");
}
}
;
connector.bindColumnDataArray(this.nativeStmtHandle, colDataList, lengthList, isNullList, col1.type, col1.bytes, rows, i);
}
......
......@@ -339,11 +339,11 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet {
case TSDBConstants.TSDB_DATA_TYPE_SMALLINT:
case TSDBConstants.TSDB_DATA_TYPE_INT:
case TSDBConstants.TSDB_DATA_TYPE_BIGINT:
res = new BigDecimal(Long.valueOf(this.rowData.getObject(columnIndex).toString()));
res = new BigDecimal(Long.parseLong(this.rowData.getObject(columnIndex).toString()));
break;
case TSDBConstants.TSDB_DATA_TYPE_FLOAT:
case TSDBConstants.TSDB_DATA_TYPE_DOUBLE:
res = new BigDecimal(Double.valueOf(this.rowData.getObject(columnIndex).toString()));
res = BigDecimal.valueOf(Double.parseDouble(this.rowData.getObject(columnIndex).toString()));
break;
case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP:
return new BigDecimal(((Timestamp) this.rowData.getObject(columnIndex)).getTime());
......
......@@ -36,23 +36,20 @@ public class TSDBResultSetBlockData {
private int rowIndex = 0;
private List<ColumnMetaData> columnMetaDataList;
private ArrayList<Object> colData = null;
private ArrayList<Object> colData;
public TSDBResultSetBlockData(List<ColumnMetaData> colMeta, int numOfCols) {
this.columnMetaDataList = colMeta;
this.colData = new ArrayList<Object>(numOfCols);
this.colData = new ArrayList<>(numOfCols);
}
public TSDBResultSetBlockData() {
this.colData = new ArrayList<Object>();
this.colData = new ArrayList<>();
}
public void clear() {
int size = this.colData.size();
if (this.colData != null) {
this.colData.clear();
}
this.colData.clear();
setNumOfCols(size);
}
......@@ -69,7 +66,7 @@ public class TSDBResultSetBlockData {
}
public void setNumOfCols(int numOfCols) {
this.colData = new ArrayList<Object>(numOfCols);
this.colData = new ArrayList<>(numOfCols);
this.colData.addAll(Collections.nCopies(numOfCols, null));
}
......@@ -166,15 +163,10 @@ public class TSDBResultSetBlockData {
}
}
/**
* The original type may not be a string type, but will be converted to by
* calling this method
*
* @param col column index
* @return
* @throws SQLException
*/
public String getString(int col) throws SQLException {
Object obj = get(col);
......@@ -387,7 +379,7 @@ public class TSDBResultSetBlockData {
return null;
}
return (long) val;
return val;
}
case TSDBConstants.TSDB_DATA_TYPE_FLOAT: {
......
......@@ -41,10 +41,7 @@ public class TSDBResultSetMetaData extends WrapperImpl implements ResultSetMetaD
}
public boolean isSearchable(int column) throws SQLException {
if (column == 1) {
return true;
}
return false;
return column == 1;
}
public boolean isCurrency(int column) throws SQLException {
......
......@@ -19,14 +19,13 @@ import com.taosdata.jdbc.utils.NullType;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
public class TSDBResultSetRowData {
private ArrayList<Object> data;
private int colSize;
private final int colSize;
public TSDBResultSetRowData(int colSize) {
this.colSize = colSize;
......@@ -390,27 +389,27 @@ public class TSDBResultSetRowData {
switch (nativeType) {
case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: {
Byte value = new Byte(String.valueOf(obj));
byte value = new Byte(String.valueOf(obj));
if (value >= 0)
return value.toString();
return Byte.toString(value);
return Integer.toString(value & 0xff);
}
case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: {
Short value = new Short(String.valueOf(obj));
short value = new Short(String.valueOf(obj));
if (value >= 0)
return value.toString();
return Short.toString(value);
return Integer.toString(value & 0xffff);
}
case TSDBConstants.TSDB_DATA_TYPE_UINT: {
Integer value = new Integer(String.valueOf(obj));
int value = new Integer(String.valueOf(obj));
if (value >= 0)
return value.toString();
return Long.toString(value & 0xffffffffl);
return Integer.toString(value);
return Long.toString(value & 0xffffffffL);
}
case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: {
Long value = new Long(String.valueOf(obj));
long value = new Long(String.valueOf(obj));
if (value >= 0)
return value.toString();
return Long.toString(value);
long lowValue = value & 0x7fffffffffffffffL;
return BigDecimal.valueOf(lowValue).add(BigDecimal.valueOf(Long.MAX_VALUE)).add(BigDecimal.valueOf(1)).toString();
}
......@@ -432,25 +431,26 @@ public class TSDBResultSetRowData {
/**
* !!! this method is invoked by JNI method and the index start from 0 in C implementations
*
* @param precision 0 : ms, 1 : us, 2 : ns
*/
public void setTimestamp(int col, long ts, int precision) {
long milliseconds = 0;
int fracNanoseconds = 0;
long milliseconds;
int fracNanoseconds;
switch (precision) {
case 0: {
milliseconds = ts;
fracNanoseconds = (int)(ts*1_000_000%1_000_000_000);
fracNanoseconds = (int) (ts * 1_000_000 % 1_000_000_000);
break;
}
case 1: {
milliseconds = ts/1_000;
fracNanoseconds = (int)(ts*1_000%1_000_000_000);
milliseconds = ts / 1_000;
fracNanoseconds = (int) (ts * 1_000 % 1_000_000_000);
break;
}
case 2: {
milliseconds = ts/1_000_000;
fracNanoseconds = (int)(ts%1_000_000_000);
milliseconds = ts / 1_000_000;
fracNanoseconds = (int) (ts % 1_000_000_000);
break;
}
default: {
......@@ -467,12 +467,10 @@ public class TSDBResultSetRowData {
Object obj = data.get(col - 1);
if (obj == null)
return null;
switch (nativeType) {
case TSDBConstants.TSDB_DATA_TYPE_BIGINT:
return new Timestamp((Long) obj);
default:
return (Timestamp) obj;
if (nativeType == TSDBConstants.TSDB_DATA_TYPE_BIGINT) {
return new Timestamp((Long) obj);
}
return (Timestamp) obj;
}
public Object getObject(int col) {
......
......@@ -47,9 +47,6 @@ public class TSDBSubscribe {
/**
* close subscription
*
* @param keepProgress
* @throws SQLException
*/
public void close(boolean keepProgress) throws SQLException {
if (this.connecter.isClosed())
......
......@@ -16,7 +16,7 @@ public class RestfulConnection extends AbstractConnection {
private final String host;
private final int port;
private final String url;
private volatile String database;
private final String database;
private final String token;
/******************************************************/
private boolean isClosed;
......
......@@ -13,7 +13,7 @@ import java.util.Calendar;
public class RestfulPreparedStatement extends RestfulStatement implements PreparedStatement {
private ParameterMetaData parameterMetaData;
private final ParameterMetaData parameterMetaData;
private final String rawSql;
private Object[] parameters;
private boolean isPrepared;
......
......@@ -7,7 +7,7 @@ import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;
import com.taosdata.jdbc.*;
import com.taosdata.jdbc.enums.TimestampPrecision;
import com.taosdata.jdbc.rs.enums.TimestampFormat;
import com.taosdata.jdbc.enums.TimestampFormat;
import com.taosdata.jdbc.utils.Utils;
import java.math.BigDecimal;
......@@ -17,19 +17,20 @@ import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class RestfulResultSet extends AbstractResultSet implements ResultSet {
private volatile boolean isClosed;
private int pos = -1;
private final String database;
private final Statement statement;
// data
private final ArrayList<ArrayList<Object>> resultSet = new ArrayList<>();
private final List<List<Object>> resultSet = new ArrayList<>();
// meta
private ArrayList<String> columnNames = new ArrayList<>();
private ArrayList<Field> columns = new ArrayList<>();
private RestfulResultSetMetaData metaData;
private final List<String> columnNames = new ArrayList<>();
private final List<Field> columns = new ArrayList<>();
private final RestfulResultSetMetaData metaData;
private volatile boolean isClosed;
private int pos = -1;
/**
* 由一个result的Json构造结果集,对应执行show databases, show tables等这些语句,返回结果集,但无法获取结果集对应的meta,统一当成String处理
......@@ -37,35 +38,30 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
* @param resultJson: 包含data信息的结果集,有sql返回的结果集
***/
public RestfulResultSet(String database, Statement statement, JSONObject resultJson) throws SQLException {
this.database = database;
this.statement = statement;
// get head
JSONArray head = resultJson.getJSONArray("head");
// get column metadata
JSONArray columnMeta = resultJson.getJSONArray("column_meta");
// get row data
JSONArray data = resultJson.getJSONArray("data");
if (data == null || data.isEmpty()) {
columnNames.clear();
columns.clear();
this.resultSet.clear();
this.metaData = new RestfulResultSetMetaData(this.database, null, this);
return;
}
// get head
JSONArray head = resultJson.getJSONArray("head");
// get rows
Integer rows = resultJson.getInteger("rows");
// parse column_meta
if (columnMeta != null) {
parseColumnMeta_new(columnMeta);
} else {
parseColumnMeta_old(head, data, rows);
}
this.metaData = new RestfulResultSetMetaData(this.database, columns, this);
this.metaData = new RestfulResultSetMetaData(database, columns, this);
if (data == null || data.isEmpty())
return;
// parse row data
resultSet.clear();
for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
ArrayList row = new ArrayList();
List<Object> row = new ArrayList();
JSONArray jsonRow = data.getJSONArray(rowIndex);
for (int colIndex = 0; colIndex < this.metaData.getColumnCount(); colIndex++) {
row.add(parseColumnData(jsonRow, colIndex, columns.get(colIndex).taos_type));
......@@ -174,8 +170,8 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
//TODO: this implementation has bug if the timestamp bigger than 9999_9999_9999_9
if (value < 1_0000_0000_0000_0L)
return new Timestamp(value);
long epochSec = value / 1000_000l;
long nanoAdjustment = value % 1000_000l * 1000l;
long epochSec = value / 1000_000L;
long nanoAdjustment = value % 1000_000L * 1000L;
return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment));
}
case UTC: {
......@@ -244,10 +240,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED);
pos++;
if (pos <= resultSet.size() - 1) {
return true;
}
return false;
return pos <= resultSet.size() - 1;
}
@Override
......@@ -257,13 +250,6 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
}
}
// @Override
// public boolean wasNull() throws SQLException {
// if (isClosed())
// throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED);
// return resultSet.isEmpty();
// }
@Override
public String getString(int columnIndex) throws SQLException {
checkAvailability(columnIndex, resultSet.get(pos).size());
......@@ -288,7 +274,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
wasNull = false;
if (value instanceof Boolean)
return (boolean) value;
return Boolean.valueOf(value.toString());
return Boolean.parseBoolean(value.toString());
}
@Override
......@@ -443,9 +429,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
return null;
if (value instanceof Timestamp)
return new Date(((Timestamp) value).getTime());
Date date = null;
date = Utils.parseDate(value.toString());
return date;
return Utils.parseDate(value.toString());
}
@Override
......@@ -460,8 +444,7 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
Time time = null;
try {
time = Utils.parseTime(value.toString());
} catch (DateTimeParseException e) {
time = null;
} catch (DateTimeParseException ignored) {
}
return time;
}
......@@ -525,9 +508,9 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
return null;
if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte)
return new BigDecimal(Long.valueOf(value.toString()));
return new BigDecimal(Long.parseLong(value.toString()));
if (value instanceof Double || value instanceof Float)
return new BigDecimal(Double.valueOf(value.toString()));
return BigDecimal.valueOf(Double.parseDouble(value.toString()));
if (value instanceof Timestamp)
return new BigDecimal(((Timestamp) value).getTime());
BigDecimal ret;
......@@ -637,36 +620,6 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
if (isClosed())
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_RESULTSET_CLOSED);
// if (this.resultSet.size() == 0)
// return false;
//
// if (row == 0) {
// beforeFirst();
// return false;
// } else if (row == 1) {
// return first();
// } else if (row == -1) {
// return last();
// } else if (row > this.resultSet.size()) {
// afterLast();
// return false;
// } else {
// if (row < 0) {
// // adjust to reflect after end of result set
// int newRowPosition = this.resultSet.size() + row + 1;
// if (newRowPosition <= 0) {
// beforeFirst();
// return false;
// } else {
// return absolute(newRowPosition);
// }
// } else {
// row--; // adjust for index difference
// this.pos = row;
// return true;
// }
// }
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_METHOD);
}
......@@ -710,5 +663,4 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet {
return isClosed;
}
}
}
\ No newline at end of file
......@@ -7,20 +7,17 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RestfulResultSetMetaData extends WrapperImpl implements ResultSetMetaData {
private final String database;
private List<RestfulResultSet.Field> fields;
private final RestfulResultSet resultSet;
private final List<RestfulResultSet.Field> fields;
public RestfulResultSetMetaData(String database, ArrayList<RestfulResultSet.Field> fields, RestfulResultSet resultSet) {
public RestfulResultSetMetaData(String database, List<RestfulResultSet.Field> fields, RestfulResultSet resultSet) {
this.database = database;
this.fields = fields == null ? Collections.emptyList() : fields;
this.resultSet = resultSet;
}
public List<RestfulResultSet.Field> getFields() {
......@@ -141,8 +138,8 @@ public class RestfulResultSetMetaData extends WrapperImpl implements ResultSetMe
@Override
public String getColumnTypeName(int column) throws SQLException {
int taos_type = fields.get(column - 1).taos_type;
return TSDBConstants.taosType2JdbcTypeName(taos_type);
int taosType = fields.get(column - 1).taos_type;
return TSDBConstants.taosType2JdbcTypeName(taosType);
}
@Override
......
......@@ -35,10 +35,6 @@ public class RestfulStatement extends AbstractStatement {
if (!SqlSyntaxValidator.isValidForExecuteQuery(sql))
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE_QUERY, "not a valid sql for executeQuery: " + sql);
if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) {
return executeOneQuery(sql);
}
return executeOneQuery(sql);
}
......@@ -50,9 +46,6 @@ public class RestfulStatement extends AbstractStatement {
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_FOR_EXECUTE_UPDATE, "not a valid sql for executeUpdate: " + sql);
final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql";
if (SqlSyntaxValidator.isDatabaseUnspecifiedUpdate(sql)) {
return executeOneUpdate(url, sql);
}
return executeOneUpdate(url, sql);
}
......
......@@ -27,19 +27,18 @@ public class HttpClientPoolUtil {
private static final int DEFAULT_MAX_TOTAL = 1000;
private static final int DEFAULT_HTTP_KEEP_TIME = 15000;
private static PoolingHttpClientConnectionManager connectionManager;
private static CloseableHttpClient httpClient;
private static synchronized void initPools() {
if (httpClient == null) {
connectionManager = new PoolingHttpClientConnectionManager();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL);
httpClient = HttpClients.custom().setKeepAliveStrategy(DEFAULT_KEEP_ALIVE_STRATEGY).setConnectionManager(connectionManager).build();
}
}
private static ConnectionKeepAliveStrategy DEFAULT_KEEP_ALIVE_STRATEGY = (response, context) -> {
private static final ConnectionKeepAliveStrategy DEFAULT_KEEP_ALIVE_STRATEGY = (response, context) -> {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
int keepTime = DEFAULT_HTTP_KEEP_TIME * 1000;
while (it.hasNext()) {
......
......@@ -14,10 +14,6 @@
*****************************************************************************/
package com.taosdata.jdbc.utils;
import com.taosdata.jdbc.TSDBConnection;
import java.sql.Connection;
public class SqlSyntaxValidator {
private static final String[] SQL = {"select", "insert", "import", "create", "use", "alter", "drop", "set", "show", "describe"};
......@@ -26,12 +22,6 @@ public class SqlSyntaxValidator {
private static final String[] databaseUnspecifiedShow = {"databases", "dnodes", "mnodes", "variables"};
private TSDBConnection tsdbConnection;
public SqlSyntaxValidator(Connection connection) {
this.tsdbConnection = (TSDBConnection) connection;
}
public static boolean isValidForExecuteUpdate(String sql) {
for (String prefix : updateSQL) {
if (sql.trim().toLowerCase().startsWith(prefix))
......
......@@ -6,6 +6,7 @@ import com.google.common.collect.TreeRangeSet;
import com.taosdata.jdbc.enums.TimestampPrecision;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
......@@ -160,7 +161,7 @@ public class Utils {
String paraStr;
if (para != null) {
if (para instanceof byte[]) {
paraStr = new String((byte[]) para, Charset.forName("UTF-8"));
paraStr = new String((byte[]) para, StandardCharsets.UTF_8);
} else {
paraStr = para.toString();
}
......
package com.taosdata.jdbc;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.*;
import java.util.Properties;
public class StatementTest {
static Connection connection = null;
static Statement statement = null;
static String dbName = "test";
static String tName = "t0";
static String host = "localhost";
@BeforeClass
public static void createConnection() throws SQLException {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
} catch (ClassNotFoundException e) {
return;
}
}
@Test
public void testCase() {
try {
ResultSet rs = statement.executeQuery("show databases");
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= metaData.getColumnCount(); i++) {
System.out.print(metaData.getColumnLabel(i) + ":" + rs.getString(i) + "\t");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void createTableAndQuery() throws SQLException {
long ts = System.currentTimeMillis();
statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("create table if not exists " + dbName + "." + tName + "(ts timestamp, k1 int)");
statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", 1)");
statement.execute("select * from " + dbName + "." + tName);
ResultSet resultSet = statement.getResultSet();
Assert.assertNotNull(resultSet);
boolean isClosed = statement.isClosed();
Assert.assertEquals(false, isClosed);
}
@Test(expected = SQLException.class)
public void testUnsupport() throws SQLException {
Assert.assertNotNull(statement.unwrap(TSDBStatement.class));
Assert.assertTrue(statement.isWrapperFor(TSDBStatement.class));
statement.getMaxFieldSize();
statement.setMaxFieldSize(0);
statement.setEscapeProcessing(true);
statement.cancel();
statement.getWarnings();
statement.clearWarnings();
statement.setCursorName(null);
statement.getMoreResults();
statement.setFetchDirection(0);
statement.getFetchDirection();
statement.getResultSetConcurrency();
statement.getResultSetType();
statement.getConnection();
statement.getMoreResults();
statement.getGeneratedKeys();
statement.executeUpdate(null, 0);
statement.executeUpdate(null, new int[]{0});
statement.executeUpdate(null, new String[]{"str1", "str2"});
statement.getResultSetHoldability();
statement.setPoolable(true);
statement.isPoolable();
statement.closeOnCompletion();
statement.isCloseOnCompletion();
}
@AfterClass
public static void close() {
try {
statement.execute("drop database if exists " + dbName);
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
......@@ -380,14 +380,15 @@ public class TSDBConnectionTest {
conn.abort(null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
@Test
public void setNetworkTimeout() throws SQLException {
conn.setNetworkTimeout(null, 1000);
}
@Test(expected = SQLFeatureNotSupportedException.class)
@Test
public void getNetworkTimeout() throws SQLException {
conn.getNetworkTimeout();
int networkTimeout = conn.getNetworkTimeout();
Assert.assertEquals(0, networkTimeout);
}
@Test
......
......@@ -14,24 +14,6 @@ public class TSDBStatementTest {
private static Connection conn;
private static Statement stmt;
@Test
public void executeQuery() {
try {
ResultSet rs = stmt.executeQuery("show databases");
Assert.assertNotNull(rs);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t");
}
System.out.println();
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void executeUpdate() {
final String dbName = ("test_" + UUID.randomUUID()).replace("-", "_").substring(0, 32);
......@@ -173,10 +155,6 @@ public class TSDBStatementTest {
Assert.assertEquals(3, meta.getColumnCount());
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t");
}
System.out.println();
count++;
}
Assert.assertEquals(1, count);
......
package com.taosdata.jdbc.cases;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Connection;
......@@ -12,21 +13,19 @@ public class AppMemoryLeakTest {
@Test(expected = SQLException.class)
public void testCreateTooManyConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.taosdata.jdbc.TSDBDriver");
int conCnt = 0;
while (true) {
Connection conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata");
System.out.println(conCnt++ + " : " + conn);
Assert.assertNotNull(conn);
}
}
@Test(expected = Exception.class)
public void testCreateTooManyStatement() throws ClassNotFoundException, SQLException {
Class.forName("com.taosdata.jdbc.TSDBDriver");
int stmtCnt = 0;
Connection conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata");
while (true) {
Statement stmt = conn.createStatement();
System.out.println(++stmtCnt + " : " + stmt);
Assert.assertNotNull(stmt);
}
}
......
......@@ -60,7 +60,6 @@ public class BatchInsertTest {
final int index = i;
executorService.execute(() -> {
try {
long startTime = System.currentTimeMillis();
Statement statement = connection.createStatement(); // get statement
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO " + tablePrefix + index + " VALUES");
......@@ -73,8 +72,6 @@ public class BatchInsertTest {
}
statement.addBatch(sb.toString());
statement.executeBatch();
long endTime = System.currentTimeMillis();
System.out.println("Thread " + index + " takes " + (endTime - startTime) + " microseconds");
connection.commit();
statement.close();
} catch (Exception e) {
......
......@@ -31,9 +31,6 @@ public class ConnectMultiTaosdByRestfulWithDifferentTokenTest {
ResultSet rs = stmt.executeQuery("select server_status()");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.println(meta.getColumnLabel(i) + ": " + rs.getString(i));
}
}
} catch (SQLException e) {
e.printStackTrace();
......
package com.taosdata.jdbc.cases;
import com.taosdata.jdbc.utils.TimestampUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.*;
import java.sql.*;
public class DatetimeBefore1970Test {
private static Connection conn;
private static final String host = "127.0.0.1";
private Connection conn;
@Test
public void test() {
try (Statement stmt = conn.createStatement()) {
// given
stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')");
stmt.executeUpdate("insert into weather(ts) values('1970-01-01 00:00:00.000')");
stmt.executeUpdate("insert into weather(ts) values('1970-01-01 08:00:00.000')");
stmt.executeUpdate("insert into weather(ts) values('1970-01-01 07:59:59.999')");
ResultSet rs = stmt.executeQuery("select * from weather order by ts asc");
ResultSetMetaData metaData = rs.getMetaData();
Assert.assertEquals(2, metaData.getColumnCount());
// when
rs.next();
// then
Timestamp ts = rs.getTimestamp("ts");
Assert.assertEquals("1969-12-31 23:59:59.999", TimestampUtil.longToDatetime(ts.getTime()));
// when
rs.next();
// then
ts = rs.getTimestamp("ts");
Assert.assertEquals("1970-01-01 00:00:00.000", TimestampUtil.longToDatetime(ts.getTime()));
// when
rs.next();
// then
ts = rs.getTimestamp("ts");
Assert.assertEquals("1970-01-01 08:00:00.000", TimestampUtil.longToDatetime(ts.getTime()));
// when
rs.next();
// then
ts = rs.getTimestamp("ts");
Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime()));
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
Timestamp ts = rs.getTimestamp("ts");
System.out.println("long: " + ts.getTime() + ", string: " + TimestampUtil.longToDatetime(ts.getTime()));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("timestamp: " + Long.MAX_VALUE + ", string: " + TimestampUtil.longToDatetime(Long.MAX_VALUE));
System.out.println("timestamp: " + Long.MIN_VALUE + ", string: " + TimestampUtil.longToDatetime(Long.MIN_VALUE));
System.out.println("timestamp: " + 0 + ", string: " + TimestampUtil.longToDatetime(0));
System.out.println("timestamp: " + -1 + ", string: " + TimestampUtil.longToDatetime(-1));
String datetime = "1970-01-01 00:00:00.000";
System.out.println("timestamp: " + TimestampUtil.datetimeToLong(datetime) + ", string: " + datetime);
datetime = "1969-12-31 23:59:59.999";
System.out.println("timestamp: " + TimestampUtil.datetimeToLong(datetime) + ", string: " + datetime);
}
@BeforeClass
public static void beforeClass() {
@Before
public void before() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
conn = DriverManager.getConnection("jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata");
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test_timestamp");
stmt.execute("create database if not exists test_timestamp keep 36500");
stmt.execute("use test_timestamp");
stmt.execute("create table weather(ts timestamp,f1 float)");
stmt.close();
} catch (ClassNotFoundException | SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
@After
public void after() {
try {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test_timestamp");
if (conn != null)
conn.close();
} catch (SQLException e) {
......
......@@ -20,7 +20,6 @@ public class ImportTest {
@BeforeClass
public static void before() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
......@@ -33,8 +32,6 @@ public class ImportTest {
stmt.close();
ts = System.currentTimeMillis();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
......@@ -47,7 +44,6 @@ public class ImportTest {
for (int i = 0; i < 50; i++) {
ts++;
int row = stmt.executeUpdate("import into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")");
System.out.println("import into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")\t" + row);
assertEquals(1, row);
}
}
......@@ -84,7 +80,6 @@ public class ImportTest {
long t = (++ts) + a;
sqlBuilder.append("(").append(t).append(",").append((100 + i)).append(",").append(i).append(") ");
}
System.out.println(sqlBuilder.toString());
int rows = stmt.executeUpdate(sqlBuilder.toString());
assertEquals(50, rows);
} catch (SQLException e) {
......
......@@ -41,7 +41,6 @@ public class MicroSecondPrecisionJNITest {
rs.next();
Timestamp timestamp = rs.getTimestamp(1);
System.out.println(timestamp);
long ts = timestamp.getTime();
Assert.assertEquals(timestamp1, ts);
int nanos = timestamp.getNanos();
......
......@@ -7,7 +7,7 @@ import org.junit.Test;
import java.sql.*;
import java.util.concurrent.TimeUnit;
public class MultiThreadsWithSameStatmentTest {
public class MultiThreadsWithSameStatementTest {
private class Service {
......@@ -16,12 +16,11 @@ public class MultiThreadsWithSameStatmentTest {
public Service() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata");
stmt = conn.createStatement();
stmt.execute("create database if not exists jdbctest");
stmt.executeUpdate("create table if not exists jdbctest.weather (ts timestamp, f1 int)");
} catch (ClassNotFoundException | SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
......@@ -48,10 +47,6 @@ public class MultiThreadsWithSameStatmentTest {
ResultSet resultSet = service.stmt.executeQuery("select * from jdbctest.weather");
while (resultSet.next()) {
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
System.out.print(metaData.getColumnLabel(i) + ": " + resultSet.getString(i));
}
System.out.println();
}
resultSet.close();
service.release();
......
......@@ -17,11 +17,6 @@ public class NullValueInResultSetJNITest {
ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
Object value = rs.getObject(i);
System.out.print(meta.getColumnLabel(i) + ": " + value + "\t");
}
System.out.println();
}
} catch (SQLException e) {
......
......@@ -19,9 +19,7 @@ public class NullValueInResultSetRestfulTest {
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
Object value = rs.getObject(i);
System.out.print(meta.getColumnLabel(i) + ": " + value + "\t");
}
System.out.println();
}
} catch (SQLException e) {
......
......@@ -21,7 +21,6 @@ public class QueryDataTest {
@Before
public void createDatabase() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
......@@ -36,7 +35,7 @@ public class QueryDataTest {
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))";
statement.executeUpdate(createTableSql);
} catch (ClassNotFoundException | SQLException e) {
} catch (SQLException e) {
return;
}
}
......@@ -44,7 +43,6 @@ public class QueryDataTest {
@Test
public void testQueryBinaryData() throws SQLException {
String insertSql = "insert into " + stbName + " values(now, 'taosdata')";
System.out.println(insertSql);
statement.executeUpdate(insertSql);
String querySql = "select * from " + stbName;
......@@ -52,7 +50,6 @@ public class QueryDataTest {
while (rs.next()) {
String name = rs.getString(2);
System.out.println("name = " + name);
assertEquals("taosdata", name);
}
rs.close();
......
......@@ -31,7 +31,7 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
// then
Assert.assertNotNull(metaData);
Assert.assertEquals(0, columnCount);
Assert.assertEquals(2, columnCount);
}
@Test
......@@ -53,7 +53,7 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
// then
Assert.assertEquals(true, execute);
Assert.assertNotNull(metaData);
Assert.assertEquals(0, columnCount);
Assert.assertEquals(2, columnCount);
}
@Before
......
......@@ -19,7 +19,6 @@ public class SelectTest {
@Before
public void createDatabaseAndTable() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
......@@ -31,8 +30,6 @@ public class SelectTest {
stmt.execute("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
} catch (ClassNotFoundException e) {
return;
} catch (SQLException e) {
e.printStackTrace();
}
......@@ -47,7 +44,6 @@ public class SelectTest {
for (int i = 0; i < 50; i++) {
ts++;
int row = stmt.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")");
System.out.println("insert into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")\t" + row);
assertEquals(1, row);
}
......
......@@ -23,7 +23,6 @@ public class StableTest {
@BeforeClass
public static void createDatabase() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
......@@ -34,8 +33,6 @@ public class StableTest {
statement.execute("create database if not exists " + dbName);
statement.execute("use " + dbName);
statement.close();
} catch (ClassNotFoundException e) {
return;
} catch (SQLException e) {
e.printStackTrace();
}
......@@ -68,9 +65,6 @@ public class StableTest {
String sql = "describe " + stbName;
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
System.out.println(i + ":" + rs.getString(i));
}
num++;
}
rs.close();
......@@ -86,9 +80,6 @@ public class StableTest {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("describe t1");
while (rs.next()) {
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
System.out.printf("%d: %s\n", i, rs.getString(i));
}
num++;
}
rs.close();
......
......@@ -8,11 +8,6 @@ import java.sql.*;
public class RestfulDriverTest {
private static final String host = "127.0.0.1";
@Test
public void connect() {
}
@Test
public void acceptsURL() throws SQLException {
Driver driver = new RestfulDriver();
......@@ -27,9 +22,7 @@ public class RestfulDriverTest {
Driver driver = new RestfulDriver();
final String url = "";
DriverPropertyInfo[] propertyInfo = driver.getPropertyInfo(url, null);
for (DriverPropertyInfo prop : propertyInfo) {
System.out.println(prop);
}
Assert.assertNotNull(propertyInfo);
}
@Test
......
......@@ -10,132 +10,151 @@ import java.util.Random;
public class RestfulJDBCTest {
private static final String host = "127.0.0.1";
private static Connection connection;
private Random random = new Random(System.currentTimeMillis());
private final Random random = new Random(System.currentTimeMillis());
private Connection connection;
/**
* select * from log.log
**/
@Test
public void testCase001() {
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from log.log");
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String column = metaData.getColumnLabel(i);
String value = resultSet.getString(i);
System.out.print(column + ":" + value + "\t");
}
System.out.println();
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
// given
String sql = "drop database if exists restful_test";
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
// given
sql = "create database if not exists restful_test";
// when
execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
// given
sql = "use restful_test";
// when
execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
/**
* create database
*/
@Test
public void testCase002() {
try (Statement stmt = connection.createStatement()) {
stmt.execute("drop database if exists restful_test");
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
} catch (SQLException e) {
e.printStackTrace();
}
// given
String sql = "create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)";
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
/**
* create super table
***/
@Test
public void testCase003() {
try (Statement stmt = connection.createStatement()) {
stmt.execute("create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)");
} catch (SQLException e) {
e.printStackTrace();
public void testCase004() {
for (int i = 1; i <= 100; i++) {
// given
String sql = "create table t" + i + " using weather tags('beijing', '" + i + "')";
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
}
@Test
public void testCase004() {
try (Statement stmt = connection.createStatement()) {
for (int i = 1; i <= 100; i++) {
stmt.execute("create table t" + i + " using weather tags('beijing', '" + i + "')");
public void testCase005() {
int rows = 0;
for (int i = 0; i < 10; i++) {
for (int j = 1; j <= 100; j++) {
// given
long currentTimeMillis = System.currentTimeMillis();
String sql = "insert into t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")";
// when
int affectRows = executeUpdate(connection, sql);
// then
Assert.assertEquals(1, affectRows);
rows += affectRows;
}
} catch (SQLException e) {
e.printStackTrace();
}
Assert.assertEquals(1000, rows);
}
@Test
public void testCase006() throws SQLException {
// given
String sql = "select * from weather";
// when
ResultSet rs = executeQuery(connection, sql);
ResultSetMetaData meta = rs.getMetaData();
// then
Assert.assertEquals(5, meta.getColumnCount());
while (rs.next()) {
Assert.assertNotNull(rs.getTimestamp("ts"));
Assert.assertNotNull(rs.getFloat("temperature"));
Assert.assertNotNull(rs.getInt("humidity"));
Assert.assertNotNull(rs.getString("location"));
}
}
@Test
public void testCase005() {
public void testCase007() {
// given
String sql = "drop database restful_test";
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
private int executeUpdate(Connection connection, String sql) {
try (Statement stmt = connection.createStatement()) {
int rows = 0;
for (int i = 0; i < 10; i++) {
for (int j = 1; j <= 100; j++) {
long currentTimeMillis = System.currentTimeMillis();
int affectRows = stmt.executeUpdate("insert into t" + j + " values(" + currentTimeMillis + "," + (random.nextFloat() * 50) + "," + random.nextInt(100) + ")");
Assert.assertEquals(1, affectRows);
rows += affectRows;
}
}
Assert.assertEquals(1000, rows);
return stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Test
public void testCase006() {
private boolean execute(Connection connection, String sql) {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
System.out.print("ts: " + rs.getTimestamp("ts"));
System.out.print(", temperature: " + rs.getString("temperature"));
System.out.print(", humidity: " + rs.getString("humidity"));
System.out.println(", location: " + rs.getString("location"));
}
return stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Test
public void testCase007() {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnLabel = meta.getColumnLabel(i);
String value = rs.getString(i);
System.out.print(columnLabel + ": " + value + "\t");
}
System.out.println();
}
private ResultSet executeQuery(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
return statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@BeforeClass
public static void before() throws ClassNotFoundException, SQLException {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
@Before
public void before() {
try {
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
} catch (SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void after() throws SQLException {
if (connection != null)
connection.close();
@After
public void after() {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
......@@ -27,12 +27,9 @@ public class RestfulPreparedStatementTest {
ResultSet rs = pstmt_select.executeQuery();
Assert.assertNotNull(rs);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t");
}
System.out.println();
}
int columnCount = meta.getColumnCount();
Assert.assertEquals(10, columnCount);
Assert.assertNotNull(rs);
}
@Test
......@@ -373,18 +370,19 @@ public class RestfulPreparedStatementTest {
@BeforeClass
public static void beforeClass() {
try {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
try (Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test_pstmt");
stmt.execute("create database if not exists test_pstmt");
stmt.execute("use test_pstmt");
stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))");
stmt.execute("create table t1 using weather tags('beijing')");
}
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test_pstmt");
stmt.execute("create database if not exists test_pstmt");
stmt.execute("use test_pstmt");
stmt.execute("create table weather(ts timestamp, f1 int, f2 bigint, f3 float, f4 double, f5 smallint, f6 tinyint, f7 bool, f8 binary(64), f9 nchar(64)) tags(loc nchar(64))");
stmt.execute("create table t1 using weather tags('beijing')");
stmt.close();
pstmt_insert = conn.prepareStatement(sql_insert);
pstmt_select = conn.prepareStatement(sql_select);
} catch (ClassNotFoundException | SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
......
......@@ -12,6 +12,7 @@ import java.util.UUID;
public class RestfulStatementTest {
private static final String host = "127.0.0.1";
private static Connection conn;
private static Statement stmt;
......@@ -21,11 +22,11 @@ public class RestfulStatementTest {
ResultSet rs = stmt.executeQuery("show databases");
Assert.assertNotNull(rs);
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
Assert.assertTrue(columnCount > 1);
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t");
}
System.out.println();
Assert.assertEquals("name", meta.getColumnLabel(1));
Assert.assertNotNull(rs.getString("name"));
}
rs.close();
} catch (SQLException e) {
......@@ -174,10 +175,10 @@ public class RestfulStatementTest {
Assert.assertEquals(3, meta.getColumnCount());
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t");
}
System.out.println();
Assert.assertEquals("ts", meta.getColumnLabel(1));
Assert.assertNotNull(rs.getTimestamp(1));
Assert.assertEquals("temperature", meta.getColumnLabel(2));
Assert.assertEquals(22.33, rs.getFloat(2), 0.001f);
count++;
}
Assert.assertEquals(1, count);
......@@ -388,15 +389,12 @@ public class RestfulStatementTest {
@BeforeClass
public static void beforeClass() {
try {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata", properties);
stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
......
package com.taosdata.jdbc.rs;
import com.taosdata.jdbc.utils.SQLExecutor;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.*;
import org.junit.runners.MethodSorters;
import java.sql.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SQLTest {
private static final String host = "127.0.0.1";
private static Connection connection;
@Test
public void testCase001() {
// given
String sql = "create database if not exists restful_test";
SQLExecutor.execute(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase002() {
// given
String sql = "use restful_test";
SQLExecutor.execute(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase003() {
// given
String sql = "show databases";
SQLExecutor.executeWithResult(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase004() {
// given
String sql = "show tables";
SQLExecutor.executeWithResult(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase005() {
// given
String sql = "show stables";
SQLExecutor.executeWithResult(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase006() {
// given
String sql = "show dnodes";
SQLExecutor.executeWithResult(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase007() {
// given
String sql = "show vgroups";
SQLExecutor.executeWithResult(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase008() {
// given
String sql = "drop table if exists restful_test.weather";
SQLExecutor.execute(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase009() {
// given
String sql = "create table if not exists restful_test.weather(ts timestamp, temperature float) tags(location nchar(64))";
SQLExecutor.execute(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase010() {
// given
String sql = "create table t1 using restful_test.weather tags('北京')";
SQLExecutor.execute(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase011() {
// given
String sql = "insert into restful_test.t1 values(now, 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase012() {
// given
String sql = "insert into restful_test.t1 values('2020-01-01 00:00:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase013() {
// given
String sql = "insert into restful_test.t1 values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase014() {
// given
String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:03:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase015() {
// given
String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase016() {
// given
String sql = "insert into t1 values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t2 values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase017() {
// given
String sql = "Insert into t3 using weather tags('广东') values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t4 using weather tags('天津') values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)";
SQLExecutor.executeUpdate(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertFalse(execute);
}
@Test
public void testCase018() {
// given
String sql = "select * from restful_test.t1";
SQLExecutor.executeQuery(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase019() {
// given
String sql = "select * from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase020() {
// given
String sql = "select ts, temperature from restful_test.t1";
SQLExecutor.executeQuery(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase021() {
// given
String sql = "select ts, temperature from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase022() {
// given
String sql = "select temperature, ts from restful_test.t1";
SQLExecutor.executeQuery(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase023() {
// given
String sql = "select temperature, ts from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
boolean execute = execute(connection, sql);
// then
Assert.assertTrue(execute);
}
@Test
public void testCase024() {
// given
String sql = "import into restful_test.t5 using weather tags('石家庄') values('2020-01-01 00:01:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
int affectedRows = executeUpdate(connection, sql);
// then
Assert.assertEquals(1, affectedRows);
}
@Test
public void testCase025() {
// given
String sql = "import into restful_test.t6 using weather tags('沈阳') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
int affectedRows = executeUpdate(connection, sql);
// then
Assert.assertEquals(2, affectedRows);
}
@Test
public void testCase026() {
// given
String sql = "import into restful_test.t7 using weather tags('长沙') values('2020-01-01 00:01:00.000', 22.22) restful_test.t8 using weather tags('吉林') values('2020-01-01 00:01:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
int affectedRows = executeUpdate(connection, sql);
// then
Assert.assertEquals(2, affectedRows);
}
@Test
public void testCase027() {
// given
String sql = "import into restful_test.t9 using weather tags('武汉') values('2020-01-01 00:01:00.000', 22.22) ,('2020-01-02 00:01:00.000', 22.22) restful_test.t10 using weather tags('哈尔滨') values('2020-01-01 00:01:00.000', 22.22),('2020-01-02 00:01:00.000', 22.22)";
SQLExecutor.executeUpdate(connection, sql);
// when
int affectedRows = executeUpdate(connection, sql);
// then
Assert.assertEquals(4, affectedRows);
}
@Test
public void testCase028() {
// given
String sql = "select location, temperature, ts from restful_test.weather where temperature > 1";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase029() {
String sql = "select location, temperature, ts from restful_test.weather where temperature < 1";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase030() {
String sql = "select location, temperature, ts from restful_test.weather where ts > now";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase031() {
String sql = "select location, temperature, ts from restful_test.weather where ts < now";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase032() {
String sql = "select count(*) from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase033() {
String sql = "select first(*) from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase034() {
String sql = "select last(*) from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase035() {
String sql = "select last_row(*) from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase036() {
String sql = "select ts, ts as primary_key from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase037() {
String sql = "select database()";
SQLExecutor.execute(connection, "use restful_test");
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase038() {
String sql = "select client_version()";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase039() {
String sql = "select server_status()";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase040() {
String sql = "select server_status() as status";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase041() {
String sql = "select tbname, location from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase042() {
String sql = "select count(tbname) from restful_test.weather";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase043() {
String sql = "select * from restful_test.weather where ts < now - 1h";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase044() {
String sql = "select * from restful_test.weather where ts < now - 1h and location like '%'";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase045() {
String sql = "select * from restful_test.weather where ts < now - 1h order by ts";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase046() {
String sql = "select last(*) from restful_test.weather where ts < now - 1h group by tbname order by tbname";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase047() {
String sql = "select * from restful_test.weather limit 2";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase048() {
String sql = "select * from restful_test.weather limit 2 offset 5";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase049() {
String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts ";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase050() {
String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts and t1.location = t3.location";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase051() {
String sql = "select * from restful_test.t1 tt, restful_test.t3 yy where tt.ts = yy.ts";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase052() {
String sql = "select server_status()";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
@Test
public void testCase053() {
String sql = "select avg(cpu_taosd), avg(cpu_system), max(cpu_cores), avg(mem_taosd), avg(mem_system), max(mem_total), avg(disk_used), max(disk_total), avg(band_speed), avg(io_read), avg(io_write), sum(req_http), sum(req_select), sum(req_insert) from log.dn1 where ts> now - 60m and ts<= now interval(1m) fill(value, 0)";
SQLExecutor.executeQuery(connection, sql);
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
private boolean execute(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
return statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private ResultSet executeQuery(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
return statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private int executeUpdate(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
return statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@BeforeClass
public static void before() throws ClassNotFoundException, SQLException {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
public static void before() throws SQLException {
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
}
......
package com.taosdata.jdbc.utils;
import java.sql.*;
public class SQLExecutor {
// insert, import
public static void executeUpdate(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
int affectedRows = statement.executeUpdate(sql);
long end = System.currentTimeMillis();
System.out.println("[ affected rows : " + affectedRows + " ] time cost: " + (end - start) + " ms, execute statement ====> " + sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// show databases, show tables, show stables
public static void executeWithResult(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
ResultSet resultSet = statement.getResultSet();
printResult(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
}
// use database, create database, create table, drop table...
public static void execute(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
boolean execute = statement.execute(sql);
long end = System.currentTimeMillis();
printSql(sql, execute, (end - start));
} catch (SQLException e) {
System.out.println("ERROR execute SQL ===> " + sql);
e.printStackTrace();
}
}
// select
public static void executeQuery(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
ResultSet resultSet = statement.executeQuery(sql);
long end = System.currentTimeMillis();
printSql(sql, true, (end - start));
printResult(resultSet);
} catch (SQLException e) {
System.out.println("ERROR execute SQL ===> " + sql);
e.printStackTrace();
}
}
private static void printSql(String sql, boolean succeed, long cost) {
System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql);
}
private static void printResult(ResultSet resultSet) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String columnLabel = metaData.getColumnLabel(i);
String value = resultSet.getString(i);
sb.append(columnLabel + ": " + value + "\t");
}
System.out.println(sb.toString());
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册