提交 925f2d4b 编写于 作者: S Shuaiqiang Chang

Merge branch 'develop' into hotfix/taos-tools

* develop: (41 commits)
  [TD-519] fix execute sql return
  fix crash caused by double free when fail to initQInfo
  fix: jdbc resultset
  [TD-314] modify python connector to adapt C API
  [td-225] add query cost statistics.
  [TD-314] modify python connector to adapt the taos API change
  test: importOneRow
  [td-225] update script
  [td-225] update script
  [td-225] update script
  [td-225] update the slow query buffer
  feat: taosdemo, taosdump
  [td-225] fix memory leaks.
  [td-225] add query cost summary right before the qinfo is destoried.
  [td-225] fix memory leaks
  [td-225] update the output log format
  [td-225] fix bugs found by script
  [td-225] handle super table missing error
  [td-225] fix invalid write
  [td-225] fix memory leaks
  ...
...@@ -132,10 +132,7 @@ bool tscIsSelectivityWithTagQuery(SSqlCmd* pCmd); ...@@ -132,10 +132,7 @@ bool tscIsSelectivityWithTagQuery(SSqlCmd* pCmd);
void tscAddSpecialColumnForSelect(SQueryInfo* pQueryInfo, int32_t outputColIndex, int16_t functionId, SColumnIndex* pIndex, void tscAddSpecialColumnForSelect(SQueryInfo* pQueryInfo, int32_t outputColIndex, int16_t functionId, SColumnIndex* pIndex,
SSchema* pColSchema, int16_t isTag); SSchema* pColSchema, int16_t isTag);
//void addRequiredTagColumn(SQueryInfo* pQueryInfo, int32_t tagColIndex, int32_t tableIndex); int32_t tscSetTableFullName(STableMetaInfo* pTableMetaInfo, SSQLToken* pzTableName, SSqlObj* pSql);
void addRequiredTagColumn(STableMetaInfo* pTableMetaInfo, SColumnIndex* index);
int32_t tscSetTableId(STableMetaInfo* pTableMetaInfo, SSQLToken* pzTableName, SSqlObj* pSql);
void tscClearInterpInfo(SQueryInfo* pQueryInfo); void tscClearInterpInfo(SQueryInfo* pQueryInfo);
bool tscIsInsertData(char* sqlstr); bool tscIsInsertData(char* sqlstr);
......
...@@ -294,7 +294,6 @@ typedef struct STscObj { ...@@ -294,7 +294,6 @@ typedef struct STscObj {
char sversion[TSDB_VERSION_LEN]; char sversion[TSDB_VERSION_LEN];
char writeAuth : 1; char writeAuth : 1;
char superAuth : 1; char superAuth : 1;
struct SSqlObj * pSql;
struct SSqlObj * pHb; struct SSqlObj * pHb;
struct SSqlObj * sqlList; struct SSqlObj * sqlList;
struct SSqlStream *streamList; struct SSqlStream *streamList;
...@@ -411,7 +410,7 @@ void doAsyncQuery(STscObj *pObj, SSqlObj *pSql, void (*fp)(), void *param, const ...@@ -411,7 +410,7 @@ void doAsyncQuery(STscObj *pObj, SSqlObj *pSql, void (*fp)(), void *param, const
void tscProcessMultiVnodesInsertFromFile(SSqlObj *pSql); void tscProcessMultiVnodesInsertFromFile(SSqlObj *pSql);
void tscKillSTableQuery(SSqlObj *pSql); void tscKillSTableQuery(SSqlObj *pSql);
void tscInitResObjForLocalQuery(SSqlObj *pObj, int32_t numOfRes, int32_t rowLen); void tscInitResObjForLocalQuery(SSqlObj *pObj, int32_t numOfRes, int32_t rowLen);
bool tscIsUpdateQuery(STscObj *pObj); bool tscIsUpdateQuery(SSqlObj* pSql);
bool tscHasReachLimitation(SQueryInfo *pQueryInfo, SSqlRes *pRes); bool tscHasReachLimitation(SQueryInfo *pQueryInfo, SSqlRes *pRes);
char *tscGetErrorMsgPayload(SSqlCmd *pCmd); char *tscGetErrorMsgPayload(SSqlCmd *pCmd);
......
...@@ -62,7 +62,7 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp ...@@ -62,7 +62,7 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp
* Method: executeQueryImp * Method: executeQueryImp
* Signature: ([BJ)I * Signature: ([BJ)I
*/ */
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp
(JNIEnv *, jobject, jbyteArray, jlong); (JNIEnv *, jobject, jbyteArray, jlong);
/* /*
...@@ -71,7 +71,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp ...@@ -71,7 +71,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp
* Signature: (J)I * Signature: (J)I
*/ */
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrCodeImp JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrCodeImp
(JNIEnv *, jobject, jlong); (JNIEnv *, jobject, jlong, jlong);
/* /*
* Class: com_taosdata_jdbc_TSDBJNIConnector * Class: com_taosdata_jdbc_TSDBJNIConnector
...@@ -87,7 +87,7 @@ JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrMsgImp ...@@ -87,7 +87,7 @@ JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrMsgImp
* Signature: (J)J * Signature: (J)J
*/ */
JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getResultSetImp JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getResultSetImp
(JNIEnv *, jobject, jlong); (JNIEnv *env, jobject jobj, jlong con, jlong tres);
/* /*
* Class: com_taosdata_jdbc_TSDBJNIConnector * Class: com_taosdata_jdbc_TSDBJNIConnector
...@@ -103,7 +103,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp ...@@ -103,7 +103,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp
* Signature: (J)I * Signature: (J)I
*/ */
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getAffectedRowsImp JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getAffectedRowsImp
(JNIEnv *, jobject, jlong); (JNIEnv *env, jobject jobj, jlong con, jlong res);
/* /*
* Class: com_taosdata_jdbc_TSDBJNIConnector * Class: com_taosdata_jdbc_TSDBJNIConnector
...@@ -142,7 +142,7 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_subscribeImp ...@@ -142,7 +142,7 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_subscribeImp
* Method: consumeImp * Method: consumeImp
* Signature: (J)Lcom/taosdata/jdbc/TSDBResultSetRowData; * Signature: (J)Lcom/taosdata/jdbc/TSDBResultSetRowData;
*/ */
JNIEXPORT jobject JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_consumeImp JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_consumeImp
(JNIEnv *, jobject, jlong); (JNIEnv *, jobject, jlong);
/* /*
......
...@@ -13,19 +13,35 @@ ...@@ -13,19 +13,35 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "com_taosdata_jdbc_TSDBJNIConnector.h"
#include "os.h" #include "os.h"
#include "taos.h" #include "taos.h"
#include "tscSubquery.h" #include "tlog.h"
#include "tscUtil.h" #include "tscUtil.h"
#include "tsclient.h" #include "tsclient.h"
#include "tlog.h"
#include "ttime.h" #include "ttime.h"
#define jniError(...) { if (jniDebugFlag & DEBUG_ERROR) { taosPrintLog("ERROR JNI ", jniDebugFlag, __VA_ARGS__); }} #include "com_taosdata_jdbc_TSDBJNIConnector.h"
#define jniWarn(...) { if (jniDebugFlag & DEBUG_WARN) { taosPrintLog("WARN JNI ", jniDebugFlag, __VA_ARGS__); }}
#define jniTrace(...) { if (jniDebugFlag & DEBUG_TRACE) { taosPrintLog("JNI ", jniDebugFlag, __VA_ARGS__); }} #define jniError(...) \
#define jniPrint(...) { taosPrintLog("JNI ", tscEmbedded ? 255 : uDebugFlag, __VA_ARGS__); } { \
if (jniDebugFlag & DEBUG_ERROR) { \
taosPrintLog("ERROR JNI ", jniDebugFlag, __VA_ARGS__); \
} \
}
#define jniWarn(...) \
{ \
if (jniDebugFlag & DEBUG_WARN) { \
taosPrintLog("WARN JNI ", jniDebugFlag, __VA_ARGS__); \
} \
}
#define jniTrace(...) \
{ \
if (jniDebugFlag & DEBUG_TRACE) { \
taosPrintLog("JNI ", jniDebugFlag, __VA_ARGS__); \
} \
}
#define jniPrint(...) \
{ taosPrintLog("JNI ", tscEmbedded ? 255 : uDebugFlag, __VA_ARGS__); }
int __init = 0; int __init = 0;
...@@ -117,7 +133,8 @@ void jniGetGlobalMethod(JNIEnv *env) { ...@@ -117,7 +133,8 @@ void jniGetGlobalMethod(JNIEnv *env) {
jniTrace("native method register finished"); jniTrace("native method register finished");
} }
JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setAllocModeImp(JNIEnv *env, jobject jobj, jint jMode, jstring jPath, jboolean jAutoDump) { JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setAllocModeImp(JNIEnv *env, jobject jobj, jint jMode,
jstring jPath, jboolean jAutoDump) {
if (jPath != NULL) { if (jPath != NULL) {
const char *path = (*env)->GetStringUTFChars(env, jPath, NULL); const char *path = (*env)->GetStringUTFChars(env, jPath, NULL);
taosSetAllocMode(jMode, path, !!jAutoDump); taosSetAllocMode(jMode, path, !!jAutoDump);
...@@ -172,14 +189,14 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions(JNIEnv ...@@ -172,14 +189,14 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions(JNIEnv
} }
(*env)->ReleaseStringUTFChars(env, optionValue, charset); (*env)->ReleaseStringUTFChars(env, optionValue, charset);
} else if (optionIndex == TSDB_OPTION_TIMEZONE) { } else if (optionIndex == TSDB_OPTION_TIMEZONE) {
const char *timezone = (*env)->GetStringUTFChars(env, optionValue, NULL); const char *tz1 = (*env)->GetStringUTFChars(env, optionValue, NULL);
if (timezone && strlen(timezone) != 0) { if (tz1 && strlen(tz1) != 0) {
res = taos_options(TSDB_OPTION_TIMEZONE, timezone); res = taos_options(TSDB_OPTION_TIMEZONE, tz1);
jniTrace("set timezone to %s, result:%d", timezone, res); jniTrace("set timezone to %s, result:%d", timezone, res);
} else { } else {
jniTrace("input timezone is empty"); jniTrace("input timezone is empty");
} }
(*env)->ReleaseStringUTFChars(env, optionValue, timezone); (*env)->ReleaseStringUTFChars(env, optionValue, tz1);
} else { } else {
jniError("option index:%d is not found", optionIndex); jniError("option index:%d is not found", optionIndex);
} }
...@@ -219,9 +236,9 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp(JNIEn ...@@ -219,9 +236,9 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp(JNIEn
} }
/* /*
* set numOfThreadsPerCore = 0 * set numOfThreadsPerCore = 0
* means only one thread for client side scheduler * means only one thread for client side scheduler
*/ */
tsNumOfThreadsPerCore = 0.0; tsNumOfThreadsPerCore = 0.0;
ret = (jlong)taos_connect((char *)host, (char *)user, (char *)pass, (char *)dbname, jport); ret = (jlong)taos_connect((char *)host, (char *)user, (char *)pass, (char *)dbname, jport);
...@@ -241,8 +258,8 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp(JNIEn ...@@ -241,8 +258,8 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp(JNIEn
return ret; return ret;
} }
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp(JNIEnv *env, jobject jobj, JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp(JNIEnv *env, jobject jobj,
jbyteArray jsql, jlong con) { jbyteArray jsql, jlong con) {
TAOS *tscon = (TAOS *)con; TAOS *tscon = (TAOS *)con;
if (tscon == NULL) { if (tscon == NULL) {
jniError("jobj:%p, connection is already closed", jobj); jniError("jobj:%p, connection is already closed", jobj);
...@@ -264,65 +281,76 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp(J ...@@ -264,65 +281,76 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp(J
(*env)->GetByteArrayRegion(env, jsql, 0, len, (jbyte *)dst); (*env)->GetByteArrayRegion(env, jsql, 0, len, (jbyte *)dst);
if ((*env)->ExceptionCheck(env)) { if ((*env)->ExceptionCheck(env)) {
//todo handle error // todo handle error
} }
jniTrace("jobj:%p, conn:%p, sql:%s", jobj, tscon, dst); jniTrace("jobj:%p, conn:%p, sql:%s", jobj, tscon, dst);
int code = taos_query(tscon, dst); SSqlObj *pSql = taos_query(tscon, dst);
if (code != 0) { int32_t code = taos_errno(pSql);
jniError("jobj:%p, conn:%p, code:%s, msg:%s", jobj, tscon, tstrerror(code), taos_errstr(tscon));
free(dst);
return JNI_TDENGINE_ERROR;
} else {
int32_t affectRows = 0;
SSqlObj *pSql = ((STscObj *)tscon)->pSql;
if (code != TSDB_CODE_SUCCESS) {
jniError("jobj:%p, conn:%p, code:%s, msg:%s", jobj, tscon, tstrerror(code), taos_errstr(pSql));
} else {
int32_t affectRows = 0;
if (pSql->cmd.command == TSDB_SQL_INSERT) { if (pSql->cmd.command == TSDB_SQL_INSERT) {
affectRows = taos_affected_rows(tscon); affectRows = taos_affected_rows(pSql);
jniTrace("jobj:%p, conn:%p, code:%s, affect rows:%d", jobj, tscon, tstrerror(code), affectRows); jniTrace("jobj:%p, conn:%p, code:%s, affect rows:%d", jobj, tscon, tstrerror(code), affectRows);
} else { } else {
jniTrace("jobj:%p, conn:%p, code:%s", jobj, tscon, tstrerror(code)); jniTrace("jobj:%p, conn:%p, code:%s", jobj, tscon, tstrerror(code));
} }
free(dst);
return affectRows;
} }
free(dst);
return (jlong)pSql;
} }
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrCodeImp(JNIEnv *env, jobject jobj, jlong con) { JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrCodeImp(JNIEnv *env, jobject jobj, jlong con, jlong tres) {
TAOS *tscon = (TAOS *)con; TAOS *tscon = (TAOS *)con;
if (tscon == NULL) { if (tscon == NULL) {
jniError("jobj:%p, connection is closed", jobj); jniError("jobj:%p, connection is closed", jobj);
return (jint)-TSDB_CODE_INVALID_CONNECTION; return (jint)TSDB_CODE_INVALID_CONNECTION;
}
if ((void *)tres == NULL) {
jniError("jobj:%p, conn:%p, resultset is null", jobj, tscon);
return JNI_RESULT_SET_NULL;
} }
return (jint)-taos_errno(tscon); TAOS_RES *pSql = (TAOS_RES *)tres;
return (jint)taos_errno(pSql);
} }
JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrMsgImp(JNIEnv *env, jobject jobj, jlong con) { JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrMsgImp(JNIEnv *env, jobject jobj, jlong tres) {
TAOS *tscon = (TAOS *)con; TAOS_RES *pSql = (TAOS_RES *)tres;
return (*env)->NewStringUTF(env, (const char *)taos_errstr(tscon)); return (*env)->NewStringUTF(env, (const char *)taos_errstr(pSql));
} }
JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getResultSetImp(JNIEnv *env, jobject jobj, jlong con) { JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getResultSetImp(JNIEnv *env, jobject jobj, jlong con,
jlong tres) {
TAOS *tscon = (TAOS *)con; TAOS *tscon = (TAOS *)con;
if (tscon == NULL) { if (tscon == NULL) {
jniError("jobj:%p, connection is closed", jobj); jniError("jobj:%p, connection is closed", jobj);
return JNI_CONNECTION_NULL; return JNI_CONNECTION_NULL;
} }
jlong ret = 0; if ((void *)tres == NULL) {
jniError("jobj:%p, conn:%p, resultset is null", jobj, tscon);
return JNI_RESULT_SET_NULL;
}
SSqlObj *pSql = (TAOS_RES *)tres;
STscObj *pObj = pSql->pTscObj;
if (tscIsUpdateQuery(tscon)) { if (tscIsUpdateQuery(pSql)) {
ret = 0; // for update query, no result pointer taos_free_result(pSql); // free result here
jniTrace("jobj:%p, conn:%p, no resultset", jobj, tscon); jniTrace("jobj:%p, conn:%p, no resultset, %p", jobj, pObj, (void *)tres);
return 0;
} else { } else {
ret = (jlong) taos_use_result(tscon); jniTrace("jobj:%p, conn:%p, get resultset, %p", jobj, pObj, (void *)tres);
jniTrace("jobj:%p, conn:%p, get resultset:%p", jobj, tscon, (void *) ret); return tres;
} }
return ret;
} }
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp(JNIEnv *env, jobject jobj, jlong con, JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp(JNIEnv *env, jobject jobj, jlong con,
...@@ -343,17 +371,21 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp( ...@@ -343,17 +371,21 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp(
return JNI_SUCCESS; return JNI_SUCCESS;
} }
JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getAffectedRowsImp(JNIEnv *env, jobject jobj, JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getAffectedRowsImp(JNIEnv *env, jobject jobj, jlong con,
jlong con) { jlong res) {
TAOS *tscon = (TAOS *)con; TAOS *tscon = (TAOS *)con;
if (tscon == NULL) { if (tscon == NULL) {
jniError("jobj:%p, connection is closed", jobj); jniError("jobj:%p, connection is closed", jobj);
return JNI_CONNECTION_NULL; return JNI_CONNECTION_NULL;
} }
jint ret = taos_affected_rows(tscon); if ((void *)res == NULL) {
jniError("jobj:%p, conn:%p, resultset is null", jobj, tscon);
return JNI_RESULT_SET_NULL;
}
jniTrace("jobj:%p, conn:%p, affect rows:%d", jobj, tscon, (void *)con, ret); jint ret = taos_affected_rows((SSqlObj *)res);
jniTrace("jobj:%p, conn:%p, sql:%p, affect rows:%d", jobj, tscon, (void *)con, res, ret);
return ret; return ret;
} }
...@@ -405,7 +437,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getSchemaMetaData ...@@ -405,7 +437,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getSchemaMetaData
* @return * @return
*/ */
jstring jniFromNCharToByteArray(JNIEnv *env, char *nchar, int32_t maxBytes) { jstring jniFromNCharToByteArray(JNIEnv *env, char *nchar, int32_t maxBytes) {
int len = (int)strlen(nchar); int len = (int)strlen(nchar);
if (len > maxBytes) { // no terminated symbol exists '\0' if (len > maxBytes) { // no terminated symbol exists '\0'
len = maxBytes; len = maxBytes;
} }
...@@ -439,7 +471,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchRowImp(JNIEn ...@@ -439,7 +471,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchRowImp(JNIEn
TAOS_ROW row = taos_fetch_row(result); TAOS_ROW row = taos_fetch_row(result);
if (row == NULL) { if (row == NULL) {
int tserrno = taos_errno(tscon); int tserrno = taos_errno(result);
if (tserrno == 0) { if (tserrno == 0) {
jniTrace("jobj:%p, conn:%p, resultset:%p, fields size is %d, fetch row to the end", jobj, tscon, res, num_fields); jniTrace("jobj:%p, conn:%p, resultset:%p, fields size is %d, fetch row to the end", jobj, tscon, res, num_fields);
return JNI_FETCH_END; return JNI_FETCH_END;
...@@ -476,24 +508,22 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchRowImp(JNIEn ...@@ -476,24 +508,22 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchRowImp(JNIEn
float fv = 0; float fv = 0;
fv = GET_FLOAT_VAL(row[i]); fv = GET_FLOAT_VAL(row[i]);
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetFloatFp, i, (jfloat)fv); (*env)->CallVoidMethod(env, rowobj, g_rowdataSetFloatFp, i, (jfloat)fv);
} } break;
break;
case TSDB_DATA_TYPE_DOUBLE: { case TSDB_DATA_TYPE_DOUBLE: {
double dv = 0; double dv = 0;
dv = GET_DOUBLE_VAL(row[i]); dv = GET_DOUBLE_VAL(row[i]);
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetDoubleFp, i, (jdouble)dv); (*env)->CallVoidMethod(env, rowobj, g_rowdataSetDoubleFp, i, (jdouble)dv);
} } break;
break;
case TSDB_DATA_TYPE_BINARY: { case TSDB_DATA_TYPE_BINARY: {
strncpy(tmp, row[i], (size_t) fields[i].bytes); // handle the case that terminated does not exist strncpy(tmp, row[i], (size_t)fields[i].bytes); // handle the case that terminated does not exist
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetStringFp, i, (*env)->NewStringUTF(env, tmp)); (*env)->CallVoidMethod(env, rowobj, g_rowdataSetStringFp, i, (*env)->NewStringUTF(env, tmp));
memset(tmp, 0, (size_t) fields[i].bytes); memset(tmp, 0, (size_t)fields[i].bytes);
break; break;
} }
case TSDB_DATA_TYPE_NCHAR: { case TSDB_DATA_TYPE_NCHAR: {
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetByteArrayFp, i, (*env)->CallVoidMethod(env, rowobj, g_rowdataSetByteArrayFp, i,
jniFromNCharToByteArray(env, (char*)row[i], fields[i].bytes)); jniFromNCharToByteArray(env, (char *)row[i], fields[i].bytes));
break; break;
} }
case TSDB_DATA_TYPE_TIMESTAMP: case TSDB_DATA_TYPE_TIMESTAMP:
...@@ -552,23 +582,84 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_subscribeImp(JNI ...@@ -552,23 +582,84 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_subscribeImp(JNI
return sub; return sub;
} }
JNIEXPORT jobject JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_consumeImp(JNIEnv *env, jobject jobj, jlong sub) { static jobject convert_one_row(JNIEnv *env, TAOS_ROW row, TAOS_FIELD *fields, int num_fields) {
jobject rowobj = (*env)->NewObject(env, g_rowdataClass, g_rowdataConstructor, num_fields);
jniTrace("created a rowdata object, rowobj:%p", rowobj);
for (int i = 0; i < num_fields; i++) {
if (row[i] == NULL) {
continue;
}
switch (fields[i].type) {
case TSDB_DATA_TYPE_BOOL:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetBooleanFp, i, (jboolean)(*((char *)row[i]) == 1));
break;
case TSDB_DATA_TYPE_TINYINT:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetByteFp, i, (jbyte) * ((char *)row[i]));
break;
case TSDB_DATA_TYPE_SMALLINT:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetShortFp, i, (jshort) * ((short *)row[i]));
break;
case TSDB_DATA_TYPE_INT:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetIntFp, i, (jint) * (int *)row[i]);
break;
case TSDB_DATA_TYPE_BIGINT:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetLongFp, i, (jlong) * ((int64_t *)row[i]));
break;
case TSDB_DATA_TYPE_FLOAT: {
float fv = 0;
fv = GET_FLOAT_VAL(row[i]);
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetFloatFp, i, (jfloat)fv);
} break;
case TSDB_DATA_TYPE_DOUBLE: {
double dv = 0;
dv = GET_DOUBLE_VAL(row[i]);
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetDoubleFp, i, (jdouble)dv);
} break;
case TSDB_DATA_TYPE_BINARY: {
char tmp[TSDB_MAX_BYTES_PER_ROW] = {0};
strncpy(tmp, row[i], (size_t)fields[i].bytes); // handle the case that terminated does not exist
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetStringFp, i, (*env)->NewStringUTF(env, tmp));
memset(tmp, 0, (size_t)fields[i].bytes);
break;
}
case TSDB_DATA_TYPE_NCHAR:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetByteArrayFp, i,
jniFromNCharToByteArray(env, (char *)row[i], fields[i].bytes));
break;
case TSDB_DATA_TYPE_TIMESTAMP:
(*env)->CallVoidMethod(env, rowobj, g_rowdataSetTimestampFp, i, (jlong) * ((int64_t *)row[i]));
break;
default:
break;
}
}
return rowobj;
}
JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_consumeImp(JNIEnv *env, jobject jobj, jlong sub) {
jniTrace("jobj:%p, in TSDBJNIConnector_consumeImp, sub:%ld", jobj, sub); jniTrace("jobj:%p, in TSDBJNIConnector_consumeImp, sub:%ld", jobj, sub);
jniGetGlobalMethod(env); jniGetGlobalMethod(env);
TAOS_SUB *tsub = (TAOS_SUB *)sub; TAOS_SUB *tsub = (TAOS_SUB *)sub;
int64_t start = taosGetTimestampMs();
int count = 0;
TAOS_RES *res = taos_consume(tsub); TAOS_RES *res = taos_consume(tsub);
if (res == NULL) { if (res == NULL) {
jniError("jobj:%p, tsub:%p, taos_consume returns NULL", jobj, tsub); jniError("jobj:%p, tsub:%p, taos_consume returns NULL", jobj, tsub);
return 0l; return NULL;
} }
return res; return res;
} }
JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_unsubscribeImp(JNIEnv *env, jobject jobj, jlong sub, jboolean keepProgress) { JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_unsubscribeImp(JNIEnv *env, jobject jobj, jlong sub,
jboolean keepProgress) {
TAOS_SUB *tsub = (TAOS_SUB *)sub; TAOS_SUB *tsub = (TAOS_SUB *)sub;
taos_unsubscribe(tsub, keepProgress); taos_unsubscribe(tsub, keepProgress);
} }
...@@ -591,7 +682,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_validateCreateTab ...@@ -591,7 +682,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_validateCreateTab
char *dst = (char *)calloc(1, sizeof(char) * (len + 1)); char *dst = (char *)calloc(1, sizeof(char) * (len + 1));
(*env)->GetByteArrayRegion(env, jsql, 0, len, (jbyte *)dst); (*env)->GetByteArrayRegion(env, jsql, 0, len, (jbyte *)dst);
if ((*env)->ExceptionCheck(env)) { if ((*env)->ExceptionCheck(env)) {
//todo handle error // todo handle error
} }
int code = taos_validate_sql(tscon, dst); int code = taos_validate_sql(tscon, dst);
......
...@@ -50,14 +50,15 @@ void doAsyncQuery(STscObj* pObj, SSqlObj* pSql, void (*fp)(), void* param, const ...@@ -50,14 +50,15 @@ void doAsyncQuery(STscObj* pObj, SSqlObj* pSql, void (*fp)(), void* param, const
pSql->maxRetry = TSDB_MAX_REPLICA_NUM; pSql->maxRetry = TSDB_MAX_REPLICA_NUM;
pSql->fp = fp; pSql->fp = fp;
sem_init(&pSql->rspSem, 0, 0);
if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, TSDB_DEFAULT_PAYLOAD_SIZE)) { if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, TSDB_DEFAULT_PAYLOAD_SIZE)) {
tscError("failed to malloc payload"); tscError("failed to malloc payload");
tscQueueAsyncError(fp, param, TSDB_CODE_CLI_OUT_OF_MEMORY); tscQueueAsyncError(fp, param, TSDB_CODE_CLI_OUT_OF_MEMORY);
return; return;
} }
pSql->sqlstr = realloc(pSql->sqlstr, sqlLen + 1); // todo check for OOM problem
pSql->sqlstr = calloc(1, sqlLen + 1);
if (pSql->sqlstr == NULL) { if (pSql->sqlstr == NULL) {
tscError("%p failed to malloc sql string buffer", pSql); tscError("%p failed to malloc sql string buffer", pSql);
tscQueueAsyncError(fp, param, TSDB_CODE_CLI_OUT_OF_MEMORY); tscQueueAsyncError(fp, param, TSDB_CODE_CLI_OUT_OF_MEMORY);
...@@ -95,7 +96,7 @@ void taos_query_a(TAOS *taos, const char *sqlstr, __async_cb_func_t fp, void *pa ...@@ -95,7 +96,7 @@ void taos_query_a(TAOS *taos, const char *sqlstr, __async_cb_func_t fp, void *pa
int32_t sqlLen = strlen(sqlstr); int32_t sqlLen = strlen(sqlstr);
if (sqlLen > tsMaxSQLStringLen) { if (sqlLen > tsMaxSQLStringLen) {
tscError("sql string too long"); tscError("sql string exceeds max length:%d", tsMaxSQLStringLen);
terrno = TSDB_CODE_INVALID_SQL; terrno = TSDB_CODE_INVALID_SQL;
tscQueueAsyncError(fp, param, TSDB_CODE_INVALID_SQL); tscQueueAsyncError(fp, param, TSDB_CODE_INVALID_SQL);
return; return;
......
...@@ -793,7 +793,7 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) { ...@@ -793,7 +793,7 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
} }
STableMetaInfo *pSTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, STABLE_INDEX); STableMetaInfo *pSTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, STABLE_INDEX);
tscSetTableId(pSTableMeterMetaInfo, &sToken, pSql); tscSetTableFullName(pSTableMeterMetaInfo, &sToken, pSql);
strncpy(pTag->name, pSTableMeterMetaInfo->name, TSDB_TABLE_ID_LEN); strncpy(pTag->name, pSTableMeterMetaInfo->name, TSDB_TABLE_ID_LEN);
code = tscGetTableMeta(pSql, pSTableMeterMetaInfo); code = tscGetTableMeta(pSql, pSTableMeterMetaInfo);
...@@ -834,9 +834,8 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) { ...@@ -834,9 +834,8 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
sql += index; sql += index;
if (TK_STRING == sToken.type) { if (TK_STRING == sToken.type) {
sToken.n = strdequote(sToken.z); strdequote(sToken.z);
strtrim(sToken.z); sToken.n = strtrim(sToken.z);
sToken.n = (uint32_t)strlen(sToken.z);
} }
if (sToken.type == TK_RP) { if (sToken.type == TK_RP) {
...@@ -925,7 +924,11 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) { ...@@ -925,7 +924,11 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
for (int32_t i = 0; i < spd.numOfCols; ++i) { for (int32_t i = 0; i < spd.numOfCols; ++i) {
if (!spd.hasVal[i]) { // current tag column do not have any value to insert, set it to null if (!spd.hasVal[i]) { // current tag column do not have any value to insert, set it to null
setNull(ptr, pTagSchema[i].type, pTagSchema[i].bytes); if (pTagSchema[i].type == TSDB_DATA_TYPE_BINARY || pTagSchema[i].type == TSDB_DATA_TYPE_NCHAR) {
setVardataNull(ptr, pTagSchema[i].type);
} else {
setNull(ptr, pTagSchema[i].type, pTagSchema[i].bytes);
}
} }
ptr += pTagSchema[i].bytes; ptr += pTagSchema[i].bytes;
...@@ -944,7 +947,7 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) { ...@@ -944,7 +947,7 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
return tscInvalidSQLErrMsg(pCmd->payload, "invalid table name", *sqlstr); return tscInvalidSQLErrMsg(pCmd->payload, "invalid table name", *sqlstr);
} }
int32_t ret = tscSetTableId(pTableMetaInfo, &tableToken, pSql); int32_t ret = tscSetTableFullName(pTableMetaInfo, &tableToken, pSql);
if (ret != TSDB_CODE_SUCCESS) { if (ret != TSDB_CODE_SUCCESS) {
return ret; return ret;
} }
...@@ -1087,7 +1090,7 @@ int doParseInsertSql(SSqlObj *pSql, char *str) { ...@@ -1087,7 +1090,7 @@ int doParseInsertSql(SSqlObj *pSql, char *str) {
goto _error_clean; goto _error_clean;
} }
if ((code = tscSetTableId(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) { if ((code = tscSetTableFullName(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) {
goto _error_clean; goto _error_clean;
} }
...@@ -1205,9 +1208,8 @@ int doParseInsertSql(SSqlObj *pSql, char *str) { ...@@ -1205,9 +1208,8 @@ int doParseInsertSql(SSqlObj *pSql, char *str) {
str += index; str += index;
if (TK_STRING == sToken.type) { if (TK_STRING == sToken.type) {
sToken.n = strdequote(sToken.z); strdequote(sToken.z);
strtrim(sToken.z); sToken.n = strtrim(sToken.z);
sToken.n = (uint32_t)strlen(sToken.z);
} }
if (sToken.type == TK_RP) { if (sToken.type == TK_RP) {
......
...@@ -88,13 +88,23 @@ void tscSaveSlowQueryFp(void *handle, void *tmrId) { ...@@ -88,13 +88,23 @@ void tscSaveSlowQueryFp(void *handle, void *tmrId) {
} }
void tscSaveSlowQuery(SSqlObj *pSql) { void tscSaveSlowQuery(SSqlObj *pSql) {
const static int64_t SLOW_QUERY_INTERVAL = 3000000L; const static int64_t SLOW_QUERY_INTERVAL = 3000000L; // todo configurable
if (pSql->res.useconds < SLOW_QUERY_INTERVAL) return; size_t size = 200; // other part of sql string, expect the main sql str
if (pSql->res.useconds < SLOW_QUERY_INTERVAL) {
return;
}
tscTrace("%p query time:%" PRId64 " sql:%s", pSql, pSql->res.useconds, pSql->sqlstr); tscTrace("%p query time:%" PRId64 " sql:%s", pSql, pSql->res.useconds, pSql->sqlstr);
int32_t sqlSize = TSDB_SHOW_SQL_LEN + size;
char *sql = malloc(200);
int len = snprintf(sql, 200, "insert into %s.slowquery values(now, '%s', %" PRId64 ", %" PRId64 ", '", tsMonitorDbName, char *sql = malloc(sqlSize);
if (sql == NULL) {
tscError("%p failed to allocate memory to sent slow query to dnode", pSql);
return;
}
int len = snprintf(sql, size, "insert into %s.slowquery values(now, '%s', %" PRId64 ", %" PRId64 ", '", tsMonitorDbName,
pSql->pTscObj->user, pSql->stime, pSql->res.useconds); pSql->pTscObj->user, pSql->stime, pSql->res.useconds);
int sqlLen = snprintf(sql + len, TSDB_SHOW_SQL_LEN, "%s", pSql->sqlstr); int sqlLen = snprintf(sql + len, TSDB_SHOW_SQL_LEN, "%s", pSql->sqlstr);
if (sqlLen > TSDB_SHOW_SQL_LEN - 1) { if (sqlLen > TSDB_SHOW_SQL_LEN - 1) {
...@@ -102,8 +112,8 @@ void tscSaveSlowQuery(SSqlObj *pSql) { ...@@ -102,8 +112,8 @@ void tscSaveSlowQuery(SSqlObj *pSql) {
} else { } else {
sqlLen += len; sqlLen += len;
} }
strcpy(sql + sqlLen, "')"); strcpy(sql + sqlLen, "')");
taosTmrStart(tscSaveSlowQueryFp, 200, sql, tscTmr); taosTmrStart(tscSaveSlowQueryFp, 200, sql, tscTmr);
} }
......
...@@ -163,8 +163,7 @@ static int32_t handlePassword(SSqlCmd* pCmd, SSQLToken* pPwd) { ...@@ -163,8 +163,7 @@ static int32_t handlePassword(SSqlCmd* pCmd, SSQLToken* pPwd) {
} }
strdequote(pPwd->z); strdequote(pPwd->z);
strtrim(pPwd->z); // trim space before and after passwords pPwd->n = strtrim(pPwd->z); // trim space before and after passwords
pPwd->n = strlen(pPwd->z);
if (pPwd->n <= 0) { if (pPwd->n <= 0) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
...@@ -226,7 +225,7 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) { ...@@ -226,7 +225,7 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) {
} else if (pInfo->type == TSDB_SQL_DROP_TABLE) { } else if (pInfo->type == TSDB_SQL_DROP_TABLE) {
assert(pInfo->pDCLInfo->nTokens == 1); assert(pInfo->pDCLInfo->nTokens == 1);
if (tscSetTableId(pTableMetaInfo, pzName, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pTableMetaInfo, pzName, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
} }
} else if (pInfo->type == TSDB_SQL_DROP_DNODE) { } else if (pInfo->type == TSDB_SQL_DROP_DNODE) {
...@@ -353,7 +352,7 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) { ...@@ -353,7 +352,7 @@ int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
} }
if (tscSetTableId(pTableMetaInfo, pToken, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pTableMetaInfo, pToken, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
} }
...@@ -686,7 +685,7 @@ int32_t parseSlidingClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql) { ...@@ -686,7 +685,7 @@ int32_t parseSlidingClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql) {
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
} }
int32_t tscSetTableId(STableMetaInfo* pTableMetaInfo, SSQLToken* pzTableName, SSqlObj* pSql) { int32_t tscSetTableFullName(STableMetaInfo* pTableMetaInfo, SSQLToken* pzTableName, SSqlObj* pSql) {
const char* msg = "name too long"; const char* msg = "name too long";
SSqlCmd* pCmd = &pSql->cmd; SSqlCmd* pCmd = &pSql->cmd;
...@@ -1465,7 +1464,6 @@ static int32_t setExprInfoForFunctions(SQueryInfo* pQueryInfo, SSchema* pSchema, ...@@ -1465,7 +1464,6 @@ static int32_t setExprInfoForFunctions(SQueryInfo* pQueryInfo, SSchema* pSchema,
int32_t addExprAndResultField(SQueryInfo* pQueryInfo, int32_t colIndex, tSQLExprItem* pItem, bool finalResult) { int32_t addExprAndResultField(SQueryInfo* pQueryInfo, int32_t colIndex, tSQLExprItem* pItem, bool finalResult) {
STableMetaInfo* pTableMetaInfo = NULL; STableMetaInfo* pTableMetaInfo = NULL;
int32_t optr = pItem->pNode->nSQLOptr; int32_t optr = pItem->pNode->nSQLOptr;
const char* msg1 = "not support column types"; const char* msg1 = "not support column types";
...@@ -4294,7 +4292,7 @@ int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) { ...@@ -4294,7 +4292,7 @@ int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
return invalidSqlErrMsg(pQueryInfo->msg, msg1); return invalidSqlErrMsg(pQueryInfo->msg, msg1);
} }
if (tscSetTableId(pTableMetaInfo, &(pAlterSQL->name), pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pTableMetaInfo, &(pAlterSQL->name), pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(pQueryInfo->msg, msg2); return invalidSqlErrMsg(pQueryInfo->msg, msg2);
} }
...@@ -4671,8 +4669,7 @@ int32_t validateColumnName(char* name) { ...@@ -4671,8 +4669,7 @@ int32_t validateColumnName(char* name) {
if (token.type == TK_STRING) { if (token.type == TK_STRING) {
strdequote(token.z); strdequote(token.z);
strtrim(token.z); token.n = strtrim(token.z);
token.n = (uint32_t)strlen(token.z);
int32_t k = tSQLGetToken(token.z, &token.type); int32_t k = tSQLGetToken(token.z, &token.type);
if (k != token.n) { if (k != token.n) {
...@@ -5516,7 +5513,7 @@ int32_t doCheckForCreateTable(SSqlObj* pSql, int32_t subClauseIndex, SSqlInfo* p ...@@ -5516,7 +5513,7 @@ int32_t doCheckForCreateTable(SSqlObj* pSql, int32_t subClauseIndex, SSqlInfo* p
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
if (tscSetTableId(pTableMetaInfo, pzTableName, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pTableMetaInfo, pzTableName, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
} }
...@@ -5571,7 +5568,7 @@ int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo) { ...@@ -5571,7 +5568,7 @@ int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
if (tscSetTableId(pStableMeterMetaInfo, pToken, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pStableMeterMetaInfo, pToken, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
...@@ -5617,7 +5614,7 @@ int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo) { ...@@ -5617,7 +5614,7 @@ int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo) {
} }
STableMetaInfo* pTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, TABLE_INDEX); STableMetaInfo* pTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, TABLE_INDEX);
ret = tscSetTableId(pTableMeterMetaInfo, &pInfo->pCreateTableInfo->name, pSql); ret = tscSetTableFullName(pTableMeterMetaInfo, &pInfo->pCreateTableInfo->name, pSql);
if (ret != TSDB_CODE_SUCCESS) { if (ret != TSDB_CODE_SUCCESS) {
return ret; return ret;
} }
...@@ -5660,7 +5657,7 @@ int32_t doCheckForStream(SSqlObj* pSql, SSqlInfo* pInfo) { ...@@ -5660,7 +5657,7 @@ int32_t doCheckForStream(SSqlObj* pSql, SSqlInfo* pInfo) {
return invalidSqlErrMsg(pQueryInfo->msg, msg1); return invalidSqlErrMsg(pQueryInfo->msg, msg1);
} }
if (tscSetTableId(pTableMetaInfo, &srcToken, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pTableMetaInfo, &srcToken, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(pQueryInfo->msg, msg2); return invalidSqlErrMsg(pQueryInfo->msg, msg2);
} }
...@@ -5691,7 +5688,7 @@ int32_t doCheckForStream(SSqlObj* pSql, SSqlInfo* pInfo) { ...@@ -5691,7 +5688,7 @@ int32_t doCheckForStream(SSqlObj* pSql, SSqlInfo* pInfo) {
} }
// set the created table[stream] name // set the created table[stream] name
if (tscSetTableId(pTableMetaInfo, pzTableName, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pTableMetaInfo, pzTableName, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(pQueryInfo->msg, msg1); return invalidSqlErrMsg(pQueryInfo->msg, msg1);
} }
...@@ -5800,7 +5797,7 @@ int32_t doCheckForQuery(SSqlObj* pSql, SQuerySQL* pQuerySql, int32_t index) { ...@@ -5800,7 +5797,7 @@ int32_t doCheckForQuery(SSqlObj* pSql, SQuerySQL* pQuerySql, int32_t index) {
STableMetaInfo* pMeterInfo1 = tscGetMetaInfo(pQueryInfo, i); STableMetaInfo* pMeterInfo1 = tscGetMetaInfo(pQueryInfo, i);
SSQLToken t = {.type = TSDB_DATA_TYPE_BINARY, .n = pTableItem->nLen, .z = pTableItem->pz}; SSQLToken t = {.type = TSDB_DATA_TYPE_BINARY, .n = pTableItem->nLen, .z = pTableItem->pz};
if (tscSetTableId(pMeterInfo1, &t, pSql) != TSDB_CODE_SUCCESS) { if (tscSetTableFullName(pMeterInfo1, &t, pSql) != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
......
...@@ -220,9 +220,7 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) { ...@@ -220,9 +220,7 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) {
if (pObj->signature != pObj) { if (pObj->signature != pObj) {
tscTrace("%p sql is already released or DB connection is closed, freed:%d pObj:%p signature:%p", pSql, pSql->freed, tscTrace("%p sql is already released or DB connection is closed, freed:%d pObj:%p signature:%p", pSql, pSql->freed,
pObj, pObj->signature); pObj, pObj->signature);
if (pSql != pObj->pSql) { tscFreeSqlObj(pSql);
tscFreeSqlObj(pSql);
}
rpcFreeCont(rpcMsg->pCont); rpcFreeCont(rpcMsg->pCont);
return; return;
} }
...@@ -257,6 +255,9 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) { ...@@ -257,6 +255,9 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) {
rpcMsg->code = TSDB_CODE_NOT_READY; rpcMsg->code = TSDB_CODE_NOT_READY;
rpcFreeCont(rpcMsg->pCont); rpcFreeCont(rpcMsg->pCont);
return; return;
} else if (pCmd->command == TSDB_SQL_META) {
// rpcFreeCont(rpcMsg->pCont);
// return;
} else { } else {
tscWarn("%p it shall renew table meta, code:%s, retry:%d", pSql, tstrerror(rpcMsg->code), ++pSql->retry); tscWarn("%p it shall renew table meta, code:%s, retry:%d", pSql, tstrerror(rpcMsg->code), ++pSql->retry);
...@@ -331,21 +332,11 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) { ...@@ -331,21 +332,11 @@ void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) {
rpcMsg->code = (*tscProcessMsgRsp[pCmd->command])(pSql); rpcMsg->code = (*tscProcessMsgRsp[pCmd->command])(pSql);
if (rpcMsg->code != TSDB_CODE_ACTION_IN_PROGRESS) { if (rpcMsg->code != TSDB_CODE_ACTION_IN_PROGRESS) {
void *taosres = tscKeepConn[pCmd->command] ? pSql : NULL;
rpcMsg->code = pRes->code ? pRes->code : pRes->numOfRows; rpcMsg->code = pRes->code ? pRes->code : pRes->numOfRows;
tscTrace("%p SQL result:%s res:%p", pSql, tstrerror(pRes->code), pSql); tscTrace("%p SQL result:%s res:%p", pSql, tstrerror(pRes->code), pSql);
/*
* Whether to free sqlObj or not should be decided before call the user defined function, since this SqlObj
* may be freed in UDF, and reused by other threads before tscShouldBeFreed called, in which case
* tscShouldBeFreed checks an object which is actually allocated by other threads.
*
* If this block of memory is re-allocated for an insert thread, in which tscKeepConn[command] equals to 0,
* the tscShouldBeFreed will success and tscFreeSqlObj free it immediately.
*/
bool shouldFree = tscShouldBeFreed(pSql); bool shouldFree = tscShouldBeFreed(pSql);
(*pSql->fp)(pSql->param, taosres, rpcMsg->code); (*pSql->fp)(pSql->param, pSql, rpcMsg->code);
if (shouldFree) { if (shouldFree) {
tscTrace("%p sqlObj is automatically freed", pSql); tscTrace("%p sqlObj is automatically freed", pSql);
......
...@@ -52,7 +52,7 @@ static bool validPassword(const char* passwd) { ...@@ -52,7 +52,7 @@ static bool validPassword(const char* passwd) {
return validImpl(passwd, TSDB_PASSWORD_LEN); return validImpl(passwd, TSDB_PASSWORD_LEN);
} }
STscObj *taosConnectImpl(const char *ip, const char *user, const char *pass, const char *db, uint16_t port, SSqlObj *taosConnectImpl(const char *ip, const char *user, const char *pass, const char *db, uint16_t port,
void (*fp)(void *, TAOS_RES *, int), void *param, void **taos) { void (*fp)(void *, TAOS_RES *, int), void *param, void **taos) {
taos_init(); taos_init();
...@@ -120,10 +120,8 @@ STscObj *taosConnectImpl(const char *ip, const char *user, const char *pass, con ...@@ -120,10 +120,8 @@ STscObj *taosConnectImpl(const char *ip, const char *user, const char *pass, con
pSql->pTscObj = pObj; pSql->pTscObj = pObj;
pSql->signature = pSql; pSql->signature = pSql;
pSql->maxRetry = TSDB_MAX_REPLICA_NUM; pSql->maxRetry = TSDB_MAX_REPLICA_NUM;
tsem_init(&pSql->rspSem, 0, 0); tsem_init(&pSql->rspSem, 0, 0);
pObj->pSql = pSql;
pObj->pDnodeConn = pDnodeConn; pObj->pDnodeConn = pDnodeConn;
pSql->fp = fp; pSql->fp = fp;
...@@ -143,42 +141,38 @@ STscObj *taosConnectImpl(const char *ip, const char *user, const char *pass, con ...@@ -143,42 +141,38 @@ STscObj *taosConnectImpl(const char *ip, const char *user, const char *pass, con
// tsRpcHeaderSize will be updated during RPC initialization, so only after it initialization, this value is valid // tsRpcHeaderSize will be updated during RPC initialization, so only after it initialization, this value is valid
tsInsertHeadSize = tsRpcHeadSize + sizeof(SMsgDesc) + sizeof(SSubmitMsg); tsInsertHeadSize = tsRpcHeadSize + sizeof(SMsgDesc) + sizeof(SSubmitMsg);
return pObj; return pSql;
} }
static void syncConnCallback(void *param, TAOS_RES *tres, int code) { static void syncConnCallback(void *param, TAOS_RES *tres, int code) {
STscObj *pObj = (STscObj *)param; SSqlObj *pSql = (SSqlObj *) tres;
assert(pObj != NULL && pObj->pSql != NULL); assert(pSql != NULL);
if (code < 0) { sem_post(&pSql->rspSem);
pObj->pSql->res.code = code;
}
sem_post(&pObj->pSql->rspSem);
} }
TAOS *taos_connect(const char *ip, const char *user, const char *pass, const char *db, uint16_t port) { TAOS *taos_connect(const char *ip, const char *user, const char *pass, const char *db, uint16_t port) {
tscTrace("try to create a connection to %s:%u, user:%s db:%s", ip, port, user, db); tscTrace("try to create a connection to %s:%u, user:%s db:%s", ip, port, user, db);
STscObj *pObj = taosConnectImpl(ip, user, pass, db, port, NULL, NULL, NULL); STscObj* pObj = NULL;
if (pObj != NULL) { SSqlObj *pSql = taosConnectImpl(ip, user, pass, db, port, syncConnCallback, NULL, (void**) &pObj);
SSqlObj* pSql = pObj->pSql; if (pSql != NULL) {
assert(pSql != NULL);
pSql->fp = syncConnCallback; pSql->fp = syncConnCallback;
pSql->param = pObj; pSql->param = pSql;
tscProcessSql(pSql); tscProcessSql(pSql);
sem_wait(&pSql->rspSem); sem_wait(&pSql->rspSem);
if (pSql->res.code != TSDB_CODE_SUCCESS) { if (pSql->res.code != TSDB_CODE_SUCCESS) {
terrno = pSql->res.code; terrno = pSql->res.code;
taos_free_result(pSql);
taos_close(pObj); taos_close(pObj);
return NULL; return NULL;
} }
tscTrace("%p DB connection is opening, dnodeConn:%p", pObj, pObj->pDnodeConn); tscTrace("%p DB connection is opening, dnodeConn:%p", pObj, pObj->pDnodeConn);
taos_free_result(pSql);
// version compare only requires the first 3 segments of the version string // version compare only requires the first 3 segments of the version string
int code = taosCheckVersion(version, taos_get_server_info(pObj), 3); int code = taosCheckVersion(version, taos_get_server_info(pObj), 3);
if (code != 0) { if (code != 0) {
...@@ -195,17 +189,14 @@ TAOS *taos_connect(const char *ip, const char *user, const char *pass, const cha ...@@ -195,17 +189,14 @@ TAOS *taos_connect(const char *ip, const char *user, const char *pass, const cha
TAOS *taos_connect_a(char *ip, char *user, char *pass, char *db, uint16_t port, void (*fp)(void *, TAOS_RES *, int), TAOS *taos_connect_a(char *ip, char *user, char *pass, char *db, uint16_t port, void (*fp)(void *, TAOS_RES *, int),
void *param, void **taos) { void *param, void **taos) {
STscObj* pObj = taosConnectImpl(ip, user, pass, db, port, fp, param, taos); SSqlObj* pSql = taosConnectImpl(ip, user, pass, db, port, fp, param, taos);
if (pObj == NULL) { if (pSql == NULL) {
return NULL; return NULL;
} }
SSqlObj* pSql = pObj->pSql;
pSql->res.code = tscProcessSql(pSql); pSql->res.code = tscProcessSql(pSql);
tscTrace("%p DB async connection is opening", pObj); tscTrace("%p DB async connection is opening", taos);
return taos;
return pObj;
} }
void taos_close(TAOS *taos) { void taos_close(TAOS *taos) {
...@@ -273,33 +264,38 @@ void waitForQueryRsp(void *param, TAOS_RES *tres, int code) { ...@@ -273,33 +264,38 @@ void waitForQueryRsp(void *param, TAOS_RES *tres, int code) {
pSql->res.code = code; pSql->res.code = code;
} }
SSqlObj *pSql = (SSqlObj *) tres;
sem_post(&pSql->rspSem); sem_post(&pSql->rspSem);
} }
int taos_query(TAOS *taos, const char *sqlstr) { TAOS_RES* taos_query(TAOS *taos, const char *sqlstr) {
STscObj *pObj = (STscObj *)taos; STscObj *pObj = (STscObj *)taos;
if (pObj == NULL || pObj->signature != pObj) { if (pObj == NULL || pObj->signature != pObj) {
terrno = TSDB_CODE_DISCONNECTED; terrno = TSDB_CODE_DISCONNECTED;
return TSDB_CODE_DISCONNECTED; return NULL;
}
int32_t sqlLen = strlen(sqlstr);
if (sqlLen > tsMaxSQLStringLen) {
tscError("sql string exceeds max length:%d", tsMaxSQLStringLen);
terrno = TSDB_CODE_INVALID_SQL;
return NULL;
}
taosNotePrintTsc(sqlstr);
SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
if (pSql == NULL) {
tscError("failed to malloc sqlObj");
terrno = TSDB_CODE_CLI_OUT_OF_MEMORY;
return NULL;
} }
SSqlObj* pSql = pObj->pSql;
size_t sqlLen = strlen(sqlstr);
doAsyncQuery(pObj, pSql, waitForQueryRsp, taos, sqlstr, sqlLen); doAsyncQuery(pObj, pSql, waitForQueryRsp, taos, sqlstr, sqlLen);
// wait for the callback function to post the semaphore // wait for the callback function to post the semaphore
tsem_wait(&pSql->rspSem); tsem_wait(&pSql->rspSem);
return pSql->res.code; return pSql;
}
TAOS_RES *taos_use_result(TAOS *taos) {
STscObj *pObj = (STscObj *)taos;
if (pObj == NULL || pObj->signature != pObj) {
terrno = TSDB_CODE_DISCONNECTED;
return NULL;
}
return pObj->pSql;
} }
int taos_result_precision(TAOS_RES *res) { int taos_result_precision(TAOS_RES *res) {
...@@ -332,18 +328,18 @@ int taos_num_fields(TAOS_RES *res) { ...@@ -332,18 +328,18 @@ int taos_num_fields(TAOS_RES *res) {
return num; return num;
} }
int taos_field_count(TAOS *taos) { int taos_field_count(TAOS_RES *tres) {
STscObj *pObj = (STscObj *)taos; SSqlObj* pSql = (SSqlObj*) tres;
if (pObj == NULL || pObj->signature != pObj) return 0; if (pSql == NULL || pSql->signature != pSql) return 0;
return taos_num_fields(pObj->pSql); return taos_num_fields(pSql);
} }
int taos_affected_rows(TAOS *taos) { int taos_affected_rows(TAOS_RES *tres) {
STscObj *pObj = (STscObj *)taos; SSqlObj* pSql = (SSqlObj*) tres;
if (pObj == NULL || pObj->signature != pObj) return 0; if (pSql == NULL || pSql->signature != pSql) return 0;
return (pObj->pSql->res.numOfRows); return (pSql->res.numOfRows);
} }
TAOS_FIELD *taos_fetch_fields(TAOS_RES *res) { TAOS_FIELD *taos_fetch_fields(TAOS_RES *res) {
...@@ -385,9 +381,8 @@ int taos_fetch_block_impl(TAOS_RES *res, TAOS_ROW *rows) { ...@@ -385,9 +381,8 @@ int taos_fetch_block_impl(TAOS_RES *res, TAOS_ROW *rows) {
SSqlObj *pSql = (SSqlObj *)res; SSqlObj *pSql = (SSqlObj *)res;
SSqlCmd *pCmd = &pSql->cmd; SSqlCmd *pCmd = &pSql->cmd;
SSqlRes *pRes = &pSql->res; SSqlRes *pRes = &pSql->res;
STscObj *pObj = pSql->pTscObj;
if (pRes->qhandle == 0 || pObj->pSql != pSql) { if (pRes->qhandle == 0 || pSql->signature != pSql) {
*rows = NULL; *rows = NULL;
return 0; return 0;
} }
...@@ -521,95 +516,76 @@ int taos_select_db(TAOS *taos, const char *db) { ...@@ -521,95 +516,76 @@ int taos_select_db(TAOS *taos, const char *db) {
} }
snprintf(sql, tListLen(sql), "use %s", db); snprintf(sql, tListLen(sql), "use %s", db);
return taos_query(taos, sql); SSqlObj* pSql = taos_query(taos, sql);
int32_t code = pSql->res.code;
taos_free_result(pSql);
return code;
} }
void taos_free_result(TAOS_RES *res) { void taos_free_result(TAOS_RES *res) {
if (res == NULL) return;
SSqlObj *pSql = (SSqlObj *)res; SSqlObj *pSql = (SSqlObj *)res;
tscTrace("%p start to free result", res);
if (pSql == NULL || pSql->signature != pSql) {
tscTrace("%p result has been freed", pSql);
return;
}
SSqlRes *pRes = &pSql->res; SSqlRes *pRes = &pSql->res;
SSqlCmd *pCmd = &pSql->cmd; SSqlCmd *pCmd = &pSql->cmd;
tscTrace("%p start to free result", pSql); // The semaphore can not be changed while freeing async sub query objects.
if (pSql->signature != pSql) return;
STscObj* pObj = pSql->pTscObj;
if (pRes == NULL || pRes->qhandle == 0) { if (pRes == NULL || pRes->qhandle == 0) {
/* Query rsp is not received from vnode, so the qhandle is NULL */ tscTrace("%p SqlObj is freed by app, qhandle is null", pSql);
tscTrace("%p qhandle is null, abort free, fp:%p", pSql, pSql->fp); tscFreeSqlObj(pSql);
// The semaphore can not be changed while freeing async sub query objects.
if (pObj->pSql != pSql) {
tscTrace("%p SqlObj is freed by app", pSql);
tscFreeSqlObj(pSql);
} else {
tscPartiallyFreeSqlObj(pSql);
}
return; return;
} }
// set freeFlag to 1 in retrieve message if there are un-retrieved results data in node // set freeFlag to 1 in retrieve message if there are un-retrieved results data in node
SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0); SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
if (pQueryInfo == NULL) { if (pQueryInfo == NULL) {
tscPartiallyFreeSqlObj(pSql); tscFreeSqlObj(pSql);
return; return;
} }
pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE; pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
STscObj* pTscObj = pSql->pTscObj;
STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0); STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
/* /*
* case 1. Partial data have been retrieved from vnodes, but not all data has been retrieved yet. * If the query process is cancelled by user in stable query, tscProcessSql should not be called
* We need to recycle the connection by noticing the vnode return 0 results. * for each subquery. Because the failure of execution tsProcessSql may trigger the callback function
* case 2. When the query response is received from vnodes and the numOfRows is set to 0, the user calls * be executed, and the retry efforts may result in double free the resources, e.g.,SRetrieveSupport
* taos_free_result before the taos_fetch_row is called in non-stream computing,
* we need to recycle the connection.
* case 3. If the query process is cancelled by user in stable query, tscProcessSql should not be called
* for each subquery. Because the failure of execution tsProcessSql may trigger the callback function
* be executed, and the retry efforts may result in double free the resources, e.g.,SRetrieveSupport
*/ */
if ((pCmd->command == TSDB_SQL_SELECT || if (pRes->code == TSDB_CODE_SUCCESS && pRes->completed == false &&
pCmd->command == TSDB_SQL_SHOW || (pCmd->command == TSDB_SQL_SELECT || pCmd->command == TSDB_SQL_SHOW ||
pCmd->command == TSDB_SQL_RETRIEVE || pCmd->command == TSDB_SQL_RETRIEVE || pCmd->command == TSDB_SQL_FETCH) &&
pCmd->command == TSDB_SQL_FETCH) && pRes->code == TSDB_CODE_SUCCESS && pRes->completed == false &&
(pCmd->command == TSDB_SQL_SELECT && pSql->pStream == NULL && pTableMetaInfo->pTableMeta != NULL)) { (pCmd->command == TSDB_SQL_SELECT && pSql->pStream == NULL && pTableMetaInfo->pTableMeta != NULL)) {
pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH; pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;
tscTrace("%p send msg to free qhandle in vnode, code:%d, numOfRows:%d, command:%s", pSql, pRes->code, pRes->numOfRows, tscTrace("%p start to send msg to free qhandle in dnode, command:%s", pSql, sqlCmd[pCmd->command]);
sqlCmd[pCmd->command]);
pSql->freed = 1; pSql->freed = 1;
tscProcessSql(pSql); tscProcessSql(pSql);
// waits for response and then goes on // in case of sync model query, waits for response and then goes on
if (pTscObj->pSql == pSql) { if (pSql->fp == waitForQueryRsp || pSql->fp == waitForRetrieveRsp) {
sem_wait(&pSql->rspSem); sem_wait(&pSql->rspSem);
} }
} else { // if no free resource msg is sent to vnode, we free this object immediately.
if (pTscObj->pSql != pSql) {
tscFreeSqlObj(pSql);
tscTrace("%p sql result is freed by app", pSql);
} else {
tscPartiallyFreeSqlObj(pSql);
tscTrace("%p sql result is freed by app", pSql);
}
} }
tscFreeSqlObj(pSql);
tscTrace("%p sql result is freed by app", pSql);
} }
// todo should not be used in async query // todo should not be used in async query
int taos_errno(TAOS *taos) { int taos_errno(TAOS_RES *tres) {
STscObj *pObj = (STscObj *)taos; SSqlObj *pSql = (SSqlObj *) tres;
if (pObj == NULL || pObj->signature != pObj) { if (pSql == NULL || pSql->signature != pSql) {
return terrno; return terrno;
} }
return pObj->pSql->res.code; return pSql->res.code;
} }
/* /*
...@@ -632,14 +608,13 @@ static bool hasAdditionalErrorInfo(int32_t code, SSqlCmd *pCmd) { ...@@ -632,14 +608,13 @@ static bool hasAdditionalErrorInfo(int32_t code, SSqlCmd *pCmd) {
} }
// todo should not be used in async model // todo should not be used in async model
char *taos_errstr(TAOS *taos) { char *taos_errstr(TAOS_RES *tres) {
STscObj *pObj = (STscObj *)taos; SSqlObj *pSql = (SSqlObj *) tres;
if (pObj == NULL || pObj->signature != pObj) if (pSql == NULL || pSql->signature != pSql) {
return (char*)tstrerror(terrno); return (char*) tstrerror(terrno);
}
SSqlObj* pSql = pObj->pSql;
if (hasAdditionalErrorInfo(pSql->res.code, &pSql->cmd)) { if (hasAdditionalErrorInfo(pSql->res.code, &pSql->cmd)) {
return pSql->cmd.payload; return pSql->cmd.payload;
} else { } else {
...@@ -769,7 +744,8 @@ int taos_validate_sql(TAOS *taos, const char *sql) { ...@@ -769,7 +744,8 @@ int taos_validate_sql(TAOS *taos, const char *sql) {
return TSDB_CODE_DISCONNECTED; return TSDB_CODE_DISCONNECTED;
} }
SSqlObj *pSql = pObj->pSql; SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
SSqlRes *pRes = &pSql->res; SSqlRes *pRes = &pSql->res;
SSqlCmd *pCmd = &pSql->cmd; SSqlCmd *pCmd = &pSql->cmd;
...@@ -847,9 +823,7 @@ static int tscParseTblNameList(SSqlObj *pSql, const char *tblNameList, int32_t t ...@@ -847,9 +823,7 @@ static int tscParseTblNameList(SSqlObj *pSql, const char *tblNameList, int32_t t
tblName[len] = '\0'; tblName[len] = '\0';
str = nextStr + 1; str = nextStr + 1;
len = strtrim(tblName);
strtrim(tblName);
len = (uint32_t)strlen(tblName);
SSQLToken sToken = {.n = len, .type = TK_ID, .z = tblName}; SSQLToken sToken = {.n = len, .type = TK_ID, .z = tblName};
tSQLGetToken(tblName, &sToken.type); tSQLGetToken(tblName, &sToken.type);
...@@ -861,7 +835,7 @@ static int tscParseTblNameList(SSqlObj *pSql, const char *tblNameList, int32_t t ...@@ -861,7 +835,7 @@ static int tscParseTblNameList(SSqlObj *pSql, const char *tblNameList, int32_t t
return code; return code;
} }
if ((code = tscSetTableId(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) { if ((code = tscSetTableFullName(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) {
return code; return code;
} }
...@@ -902,7 +876,7 @@ int taos_load_table_info(TAOS *taos, const char *tableNameList) { ...@@ -902,7 +876,7 @@ int taos_load_table_info(TAOS *taos, const char *tableNameList) {
return TSDB_CODE_DISCONNECTED; return TSDB_CODE_DISCONNECTED;
} }
SSqlObj *pSql = pObj->pSql; SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
SSqlRes *pRes = &pSql->res; SSqlRes *pRes = &pSql->res;
pRes->numOfTotal = 0; // the number of getting table meta from server pRes->numOfTotal = 0; // the number of getting table meta from server
......
...@@ -459,14 +459,14 @@ static int64_t tscGetLaunchTimestamp(const SSqlStream *pStream) { ...@@ -459,14 +459,14 @@ static int64_t tscGetLaunchTimestamp(const SSqlStream *pStream) {
return (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? timer / 1000L : timer; return (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? timer / 1000L : timer;
} }
static void setErrorInfo(STscObj* pObj, int32_t code, char* info) { static void setErrorInfo(SSqlObj* pSql, int32_t code, char* info) {
if (pObj == NULL) { if (pSql == NULL) {
return; return;
} }
SSqlCmd* pCmd = &pObj->pSql->cmd; SSqlCmd* pCmd = &pSql->cmd;
pObj->pSql->res.code = code; pSql->res.code = code;
if (info != NULL) { if (info != NULL) {
strncpy(pCmd->payload, info, pCmd->payloadLen); strncpy(pCmd->payload, info, pCmd->payloadLen);
...@@ -480,7 +480,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p ...@@ -480,7 +480,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p
SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj)); SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj));
if (pSql == NULL) { if (pSql == NULL) {
setErrorInfo(pObj, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL); setErrorInfo(pSql, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL);
return NULL; return NULL;
} }
...@@ -490,14 +490,14 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p ...@@ -490,14 +490,14 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p
SSqlRes *pRes = &pSql->res; SSqlRes *pRes = &pSql->res;
int ret = tscAllocPayload(pCmd, TSDB_DEFAULT_PAYLOAD_SIZE); int ret = tscAllocPayload(pCmd, TSDB_DEFAULT_PAYLOAD_SIZE);
if (TSDB_CODE_SUCCESS != ret) { if (TSDB_CODE_SUCCESS != ret) {
setErrorInfo(pObj, ret, NULL); setErrorInfo(pSql, ret, NULL);
free(pSql); free(pSql);
return NULL; return NULL;
} }
pSql->sqlstr = strdup(sqlstr); pSql->sqlstr = strdup(sqlstr);
if (pSql->sqlstr == NULL) { if (pSql->sqlstr == NULL) {
setErrorInfo(pObj, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL); setErrorInfo(pSql, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL);
tfree(pSql); tfree(pSql);
return NULL; return NULL;
...@@ -511,7 +511,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p ...@@ -511,7 +511,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p
tscResetSqlCmdObj(&pSql->cmd); tscResetSqlCmdObj(&pSql->cmd);
ret = tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE); ret = tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE);
if (TSDB_CODE_SUCCESS != ret) { if (TSDB_CODE_SUCCESS != ret) {
setErrorInfo(pObj, ret, NULL); setErrorInfo(pSql, ret, NULL);
tscError("%p open stream failed, sql:%s, code:%d", pSql, sqlstr, TSDB_CODE_CLI_OUT_OF_MEMORY); tscError("%p open stream failed, sql:%s, code:%d", pSql, sqlstr, TSDB_CODE_CLI_OUT_OF_MEMORY);
tscFreeSqlObj(pSql); tscFreeSqlObj(pSql);
return NULL; return NULL;
...@@ -521,7 +521,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p ...@@ -521,7 +521,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p
SQLInfoDestroy(&SQLInfo); SQLInfoDestroy(&SQLInfo);
if (pRes->code != TSDB_CODE_SUCCESS) { if (pRes->code != TSDB_CODE_SUCCESS) {
setErrorInfo(pObj, pRes->code, pCmd->payload); setErrorInfo(pSql, pRes->code, pCmd->payload);
tscError("%p open stream failed, sql:%s, reason:%s, code:%d", pSql, sqlstr, pCmd->payload, pRes->code); tscError("%p open stream failed, sql:%s, reason:%s, code:%d", pSql, sqlstr, pCmd->payload, pRes->code);
tscFreeSqlObj(pSql); tscFreeSqlObj(pSql);
...@@ -530,7 +530,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p ...@@ -530,7 +530,7 @@ TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *p
SSqlStream *pStream = (SSqlStream *)calloc(1, sizeof(SSqlStream)); SSqlStream *pStream = (SSqlStream *)calloc(1, sizeof(SSqlStream));
if (pStream == NULL) { if (pStream == NULL) {
setErrorInfo(pObj, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL); setErrorInfo(pSql, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL);
tscError("%p open stream failed, sql:%s, reason:%s, code:%d", pSql, sqlstr, pCmd->payload, pRes->code); tscError("%p open stream failed, sql:%s, reason:%s, code:%d", pSql, sqlstr, pCmd->payload, pRes->code);
tscFreeSqlObj(pSql); tscFreeSqlObj(pSql);
......
...@@ -181,21 +181,23 @@ static SArray* getTableList( SSqlObj* pSql ) { ...@@ -181,21 +181,23 @@ static SArray* getTableList( SSqlObj* pSql ) {
const char* p = strstr( pSql->sqlstr, " from " ); const char* p = strstr( pSql->sqlstr, " from " );
char* sql = alloca(strlen(p) + 32); char* sql = alloca(strlen(p) + 32);
sprintf(sql, "select tbid(tbname)%s", p); sprintf(sql, "select tbid(tbname)%s", p);
int code = taos_query( pSql->pTscObj, sql );
if (code != TSDB_CODE_SUCCESS) { SSqlObj* pSql1 = taos_query(pSql->pTscObj, sql);
tscError("failed to retrieve table id: %s", tstrerror(code)); if (terrno != TSDB_CODE_SUCCESS) {
tscError("failed to retrieve table id: %s", tstrerror(terrno));
return NULL; return NULL;
} }
TAOS_RES* res = taos_use_result( pSql->pTscObj );
TAOS_ROW row; TAOS_ROW row;
SArray* result = taosArrayInit( 128, sizeof(STidTags) ); SArray* result = taosArrayInit( 128, sizeof(STidTags) );
while ((row = taos_fetch_row(res))) { while ((row = taos_fetch_row(pSql1))) {
STidTags tags; STidTags tags;
memcpy(&tags, row[0], sizeof(tags)); memcpy(&tags, row[0], sizeof(tags));
taosArrayPush(result, &tags); taosArrayPush(result, &tags);
} }
taos_free_result(pSql1);
return result; return result;
} }
......
...@@ -1715,6 +1715,7 @@ static void multiVnodeInsertMerge(void* param, TAOS_RES* tres, int numOfRows) { ...@@ -1715,6 +1715,7 @@ static void multiVnodeInsertMerge(void* param, TAOS_RES* tres, int numOfRows) {
pParentObj->res.numOfRows += numOfRows; pParentObj->res.numOfRows += numOfRows;
} }
taos_free_result(tres);
int32_t completed = atomic_add_fetch_32(&pState->numOfCompleted, 1); int32_t completed = atomic_add_fetch_32(&pState->numOfCompleted, 1);
if (completed < total) { if (completed < total) {
return; return;
...@@ -1732,7 +1733,7 @@ static void multiVnodeInsertMerge(void* param, TAOS_RES* tres, int numOfRows) { ...@@ -1732,7 +1733,7 @@ static void multiVnodeInsertMerge(void* param, TAOS_RES* tres, int numOfRows) {
pParentObj->fp = pParentObj->fetchFp; pParentObj->fp = pParentObj->fetchFp;
// all data has been sent to vnode, call user function // all data has been sent to vnode, call user function
(*pParentObj->fp)(pParentObj->param, tres, numOfRows); (*pParentObj->fp)(pParentObj->param, pParentObj, numOfRows);
} }
int32_t tscHandleMultivnodeInsert(SSqlObj *pSql) { int32_t tscHandleMultivnodeInsert(SSqlObj *pSql) {
......
...@@ -409,8 +409,10 @@ void tscPartiallyFreeSqlObj(SSqlObj* pSql) { ...@@ -409,8 +409,10 @@ void tscPartiallyFreeSqlObj(SSqlObj* pSql) {
} }
void tscFreeSqlObj(SSqlObj* pSql) { void tscFreeSqlObj(SSqlObj* pSql) {
if (pSql == NULL || pSql->signature != pSql) return; if (pSql == NULL || pSql->signature != pSql) {
return;
}
tscTrace("%p start to free sql object", pSql); tscTrace("%p start to free sql object", pSql);
tscPartiallyFreeSqlObj(pSql); tscPartiallyFreeSqlObj(pSql);
...@@ -424,6 +426,7 @@ void tscFreeSqlObj(SSqlObj* pSql) { ...@@ -424,6 +426,7 @@ void tscFreeSqlObj(SSqlObj* pSql) {
pCmd->allocSize = 0; pCmd->allocSize = 0;
tfree(pSql->sqlstr); tfree(pSql->sqlstr);
sem_destroy(&pSql->rspSem);
free(pSql); free(pSql);
} }
...@@ -750,16 +753,7 @@ void tscCloseTscObj(STscObj* pObj) { ...@@ -750,16 +753,7 @@ void tscCloseTscObj(STscObj* pObj) {
assert(pObj != NULL); assert(pObj != NULL);
pObj->signature = NULL; pObj->signature = NULL;
SSqlObj* pSql = pObj->pSql;
if (pSql) {
terrno = pSql->res.code;
sem_destroy(&pSql->rspSem);
}
taosTmrStopA(&(pObj->pTimer)); taosTmrStopA(&(pObj->pTimer));
tscFreeSqlObj(pSql);
pthread_mutex_destroy(&pObj->mutex); pthread_mutex_destroy(&pObj->mutex);
if (pObj->pDnodeConn != NULL) { if (pObj->pDnodeConn != NULL) {
...@@ -1238,9 +1232,8 @@ void tscColumnListDestroy(SArray* pColumnList) { ...@@ -1238,9 +1232,8 @@ void tscColumnListDestroy(SArray* pColumnList) {
* *
*/ */
static int32_t validateQuoteToken(SSQLToken* pToken) { static int32_t validateQuoteToken(SSQLToken* pToken) {
pToken->n = strdequote(pToken->z); strdequote(pToken->z);
strtrim(pToken->z); pToken->n = strtrim(pToken->z);
pToken->n = (uint32_t)strlen(pToken->z);
int32_t k = tSQLGetToken(pToken->z, &pToken->type); int32_t k = tSQLGetToken(pToken->z, &pToken->type);
...@@ -1262,9 +1255,8 @@ int32_t tscValidateName(SSQLToken* pToken) { ...@@ -1262,9 +1255,8 @@ int32_t tscValidateName(SSQLToken* pToken) {
char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true); char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
if (sep == NULL) { // single part if (sep == NULL) { // single part
if (pToken->type == TK_STRING) { if (pToken->type == TK_STRING) {
pToken->n = strdequote(pToken->z); strdequote(pToken->z);
strtrim(pToken->z); pToken->n = strtrim(pToken->z);
pToken->n = (uint32_t)strlen(pToken->z);
int len = tSQLGetToken(pToken->z, &pToken->type); int len = tSQLGetToken(pToken->z, &pToken->type);
...@@ -1289,8 +1281,7 @@ int32_t tscValidateName(SSQLToken* pToken) { ...@@ -1289,8 +1281,7 @@ int32_t tscValidateName(SSQLToken* pToken) {
char* pStr = pToken->z; char* pStr = pToken->z;
if (pToken->type == TK_SPACE) { if (pToken->type == TK_SPACE) {
strtrim(pToken->z); pToken->n = strtrim(pToken->z);
pToken->n = (uint32_t)strlen(pToken->z);
} }
pToken->n = tSQLGetToken(pToken->z, &pToken->type); pToken->n = tSQLGetToken(pToken->z, &pToken->type);
...@@ -1471,22 +1462,24 @@ bool tscShouldFreeHeatBeat(SSqlObj* pHb) { ...@@ -1471,22 +1462,24 @@ bool tscShouldFreeHeatBeat(SSqlObj* pHb) {
* If connection need to be recycled, the SqlObj also should be freed. * If connection need to be recycled, the SqlObj also should be freed.
*/ */
bool tscShouldBeFreed(SSqlObj* pSql) { bool tscShouldBeFreed(SSqlObj* pSql) {
if (pSql == NULL || pSql->signature != pSql || pSql->fp == NULL) { if (pSql == NULL || pSql->signature != pSql) {
return false; return false;
} }
assert(pSql->fp != NULL);
STscObj* pTscObj = pSql->pTscObj; STscObj* pTscObj = pSql->pTscObj;
if (pSql->pStream != NULL || pTscObj->pHb == pSql || pTscObj->pSql == pSql || pSql->pSubscription != NULL) { if (pSql->pStream != NULL || pTscObj->pHb == pSql || pSql->pSubscription != NULL) {
return false; return false;
} }
// only the table meta and super table vgroup query will free resource automatically
int32_t command = pSql->cmd.command; int32_t command = pSql->cmd.command;
if (command == TSDB_SQL_CONNECT || command == TSDB_SQL_INSERT) { if (command == TSDB_SQL_META || command == TSDB_SQL_STABLEVGROUP) {
return true; return true;
} else {
return tscKeepConn[command] == 0 ||
(pSql->res.code != TSDB_CODE_ACTION_IN_PROGRESS && pSql->res.code != TSDB_CODE_SUCCESS);
} }
return false;
} }
/** /**
...@@ -1949,15 +1942,14 @@ int16_t tscGetJoinTagColIndexByUid(STagCond* pTagCond, uint64_t uid) { ...@@ -1949,15 +1942,14 @@ int16_t tscGetJoinTagColIndexByUid(STagCond* pTagCond, uint64_t uid) {
} }
} }
bool tscIsUpdateQuery(STscObj* pObj) { bool tscIsUpdateQuery(SSqlObj* pSql) {
if (pObj == NULL || pObj->signature != pObj) { if (pSql == NULL || pSql->signature != pSql) {
terrno = TSDB_CODE_DISCONNECTED; terrno = TSDB_CODE_DISCONNECTED;
return TSDB_CODE_DISCONNECTED; return TSDB_CODE_DISCONNECTED;
} }
SSqlCmd* pCmd = &pObj->pSql->cmd; SSqlCmd* pCmd = &pSql->cmd;
return ((pCmd->command >= TSDB_SQL_INSERT && pCmd->command <= TSDB_SQL_DROP_DNODE) || return ((pCmd->command >= TSDB_SQL_INSERT && pCmd->command <= TSDB_SQL_DROP_DNODE) || TSDB_SQL_USE_DB == pCmd->command);
TSDB_SQL_USE_DB == pCmd->command);
} }
int32_t tscInvalidSQLErrMsg(char* msg, const char* additionalInfo, const char* sql) { int32_t tscInvalidSQLErrMsg(char* msg, const char* additionalInfo, const char* sql) {
......
...@@ -18,8 +18,8 @@ import java.io.InputStream; ...@@ -18,8 +18,8 @@ import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.net.URL; import java.net.URL;
import java.sql.*;
import java.sql.Date; import java.sql.Date;
import java.sql.*;
import java.util.*; import java.util.*;
/* /*
......
...@@ -99,7 +99,7 @@ public class TSDBJNIConnector { ...@@ -99,7 +99,7 @@ public class TSDBJNIConnector {
this.taos = this.connectImp(host, port, dbName, user, password); this.taos = this.connectImp(host, port, dbName, user, password);
if (this.taos == TSDBConstants.JNI_NULL_POINTER) { if (this.taos == TSDBConstants.JNI_NULL_POINTER) {
throw new SQLException(TSDBConstants.WrapErrMsg(this.getErrMsg()), "", this.getErrCode()); throw new SQLException(TSDBConstants.WrapErrMsg(this.getErrMsg(null)), "", this.getErrCode(null));
} }
return true; return true;
...@@ -117,52 +117,57 @@ public class TSDBJNIConnector { ...@@ -117,52 +117,57 @@ public class TSDBJNIConnector {
freeResultSet(taosResultSetPointer); freeResultSet(taosResultSetPointer);
} }
int code; long pSql = 0l;
try { try {
code = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos); pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
this.freeResultSet(pSql);
throw new SQLException(TSDBConstants.WrapErrMsg("Unsupported encoding")); throw new SQLException(TSDBConstants.WrapErrMsg("Unsupported encoding"));
} }
int code = this.getErrCode(pSql);
affectedRows = code; affectedRows = code;
if (code < 0) { if (code < 0) {
affectedRows = -1; affectedRows = -1;
if (code == TSDBConstants.JNI_TDENGINE_ERROR) { if (code == TSDBConstants.JNI_TDENGINE_ERROR) {
throw new SQLException(TSDBConstants.WrapErrMsg(this.getErrMsg()), "", this.getErrCode()); this.freeResultSet(pSql);
throw new SQLException(TSDBConstants.WrapErrMsg(this.getErrMsg(pSql)), "", this.getErrCode(pSql));
} else { } else {
throw new SQLException(TSDBConstants.FixErrMsg(code), "", this.getErrCode()); this.freeResultSet(pSql);
throw new SQLException(TSDBConstants.FixErrMsg(code), "", this.getErrCode(pSql));
} }
} }
// Try retrieving result set for the executed SQL using the current connection pointer. If the executed // Try retrieving result set for the executed SQL using the current connection pointer. If the executed
// SQL is a DML/DDL which doesn't return a result set, then taosResultSetPointer should be 0L. Otherwise, // SQL is a DML/DDL which doesn't return a result set, then taosResultSetPointer should be 0L. Otherwise,
// taosResultSetPointer should be a non-zero value. // taosResultSetPointer should be a non-zero value.
taosResultSetPointer = this.getResultSetImp(this.taos); taosResultSetPointer = this.getResultSetImp(this.taos, pSql);
if (taosResultSetPointer != TSDBConstants.JNI_NULL_POINTER) { if (taosResultSetPointer != TSDBConstants.JNI_NULL_POINTER) {
isResultsetClosed = false; isResultsetClosed = false;
} }
return code; return code;
} }
private native int executeQueryImp(byte[] sqlBytes, long connection); private native long executeQueryImp(byte[] sqlBytes, long connection);
/** /**
* Get recent error code by connection * Get recent error code by connection
*/ */
public int getErrCode() { public int getErrCode(Long pSql) {
return Math.abs(this.getErrCodeImp(this.taos)); return Math.abs(this.getErrCodeImp(this.taos, pSql));
} }
private native int getErrCodeImp(long connection); private native int getErrCodeImp(long connection, Long pSql);
/** /**
* Get recent error message by connection * Get recent error message by connection
*/ */
public String getErrMsg() { public String getErrMsg(Long pSql) {
return this.getErrMsgImp(this.taos); return this.getErrMsgImp(this.taos, pSql);
} }
private native String getErrMsgImp(long connection); private native String getErrMsgImp(long connection, Long pSql);
/** /**
* Get resultset pointer * Get resultset pointer
...@@ -172,7 +177,7 @@ public class TSDBJNIConnector { ...@@ -172,7 +177,7 @@ public class TSDBJNIConnector {
return taosResultSetPointer; return taosResultSetPointer;
} }
private native long getResultSetImp(long connection); private native long getResultSetImp(long connection, long pSql);
/** /**
* Free resultset operation from C to release resultset pointer by JNI * Free resultset operation from C to release resultset pointer by JNI
...@@ -212,15 +217,15 @@ public class TSDBJNIConnector { ...@@ -212,15 +217,15 @@ public class TSDBJNIConnector {
/** /**
* Get affected rows count * Get affected rows count
*/ */
public int getAffectedRows() { public int getAffectedRows(Long pSql) {
int affectedRows = this.affectedRows; int affectedRows = this.affectedRows;
if (affectedRows < 0) { if (affectedRows < 0) {
affectedRows = this.getAffectedRowsImp(this.taos); affectedRows = this.getAffectedRowsImp(this.taos, pSql);
} }
return affectedRows; return affectedRows;
} }
private native int getAffectedRowsImp(long connection); private native int getAffectedRowsImp(long connection, Long pSql);
/** /**
* Get schema metadata * Get schema metadata
...@@ -248,7 +253,7 @@ public class TSDBJNIConnector { ...@@ -248,7 +253,7 @@ public class TSDBJNIConnector {
public void closeConnection() throws SQLException { public void closeConnection() throws SQLException {
int code = this.closeConnectionImp(this.taos); int code = this.closeConnectionImp(this.taos);
if (code < 0) { if (code < 0) {
throw new SQLException(TSDBConstants.FixErrMsg(code), "", this.getErrCode()); throw new SQLException(TSDBConstants.FixErrMsg(code), "", this.getErrCode(null));
} else if (code == 0) { } else if (code == 0) {
this.taos = TSDBConstants.JNI_NULL_POINTER; this.taos = TSDBConstants.JNI_NULL_POINTER;
} else { } else {
......
...@@ -27,6 +27,8 @@ public class TSDBStatement implements Statement { ...@@ -27,6 +27,8 @@ public class TSDBStatement implements Statement {
/** Timeout for a query */ /** Timeout for a query */
protected int queryTimeout = 0; protected int queryTimeout = 0;
private Long pSql = 0l;
/** /**
* Status of current statement * Status of current statement
*/ */
...@@ -66,21 +68,23 @@ public class TSDBStatement implements Statement { ...@@ -66,21 +68,23 @@ public class TSDBStatement implements Statement {
if (isClosed) { if (isClosed) {
throw new SQLException("Invalid method call on a closed statement."); throw new SQLException("Invalid method call on a closed statement.");
} }
int res = this.connecter.executeQuery(sql); long res = this.connecter.executeQuery(sql);
long resultSetPointer = this.connecter.getResultSet(); long resultSetPointer = this.connecter.getResultSet();
if (resultSetPointer == TSDBConstants.JNI_CONNECTION_NULL) { if (resultSetPointer == TSDBConstants.JNI_CONNECTION_NULL) {
this.connecter.freeResultSet(res);
throw new SQLException(TSDBConstants.FixErrMsg(TSDBConstants.JNI_CONNECTION_NULL)); throw new SQLException(TSDBConstants.FixErrMsg(TSDBConstants.JNI_CONNECTION_NULL));
} else if (resultSetPointer != TSDBConstants.JNI_NULL_POINTER) { } else if (resultSetPointer != TSDBConstants.JNI_NULL_POINTER) {
this.connecter.freeResultSet(); this.connecter.freeResultSet();
throw new SQLException("The executed SQL is not a DML or a DDL"); throw new SQLException("The executed SQL is not a DML or a DDL");
} else { } else {
return res; int num = this.connecter.getAffectedRows(res);
return num;
} }
} }
public String getErrorMsg() { public String getErrorMsg(long pSql) {
return this.connecter.getErrMsg(); return this.connecter.getErrMsg(pSql);
} }
public void close() throws SQLException { public void close() throws SQLException {
...@@ -170,7 +174,7 @@ public class TSDBStatement implements Statement { ...@@ -170,7 +174,7 @@ public class TSDBStatement implements Statement {
if (isClosed) { if (isClosed) {
throw new SQLException("Invalid method call on a closed statement."); throw new SQLException("Invalid method call on a closed statement.");
} }
return this.connecter.getAffectedRows(); return this.connecter.getAffectedRows(this.pSql);
} }
public boolean getMoreResults() throws SQLException { public boolean getMoreResults() throws SQLException {
......
...@@ -142,12 +142,14 @@ class CTaosInterface(object): ...@@ -142,12 +142,14 @@ class CTaosInterface(object):
libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField) libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
libtaos.taos_init.restype = None libtaos.taos_init.restype = None
libtaos.taos_connect.restype = ctypes.c_void_p libtaos.taos_connect.restype = ctypes.c_void_p
libtaos.taos_use_result.restype = ctypes.c_void_p #libtaos.taos_use_result.restype = ctypes.c_void_p
libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p) libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p)
libtaos.taos_errstr.restype = ctypes.c_char_p libtaos.taos_errstr.restype = ctypes.c_char_p
libtaos.taos_subscribe.restype = ctypes.c_void_p libtaos.taos_subscribe.restype = ctypes.c_void_p
libtaos.taos_consume.restype = ctypes.c_void_p libtaos.taos_consume.restype = ctypes.c_void_p
libtaos.taos_fetch_lengths.restype = ctypes.c_void_p libtaos.taos_fetch_lengths.restype = ctypes.c_void_p
libtaos.taos_free_result.restype = None
libtaos.taos_errno.restype = ctypes.c_int
def __init__(self, config=None): def __init__(self, config=None):
''' '''
...@@ -249,12 +251,12 @@ class CTaosInterface(object): ...@@ -249,12 +251,12 @@ class CTaosInterface(object):
raise AttributeError("sql is expected as a string") raise AttributeError("sql is expected as a string")
# finally: # finally:
# CTaosInterface.libtaos.close(connection) # CTaosInterface.libtaos.close(connection)
@staticmethod @staticmethod
def affectedRows(connection): def affectedRows(result):
"""The affected rows after runing query """The affected rows after runing query
""" """
return CTaosInterface.libtaos.taos_affected_rows(connection) return CTaosInterface.libtaos.taos_affected_rows(result)
@staticmethod @staticmethod
def subscribe(connection, restart, topic, sql, interval): def subscribe(connection, restart, topic, sql, interval):
...@@ -292,18 +294,17 @@ class CTaosInterface(object): ...@@ -292,18 +294,17 @@ class CTaosInterface(object):
CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0) CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0)
@staticmethod @staticmethod
def useResult(connection): def useResult(result):
'''Use result after calling self.query '''Use result after calling self.query
''' '''
result = ctypes.c_void_p(CTaosInterface.libtaos.taos_use_result(connection))
fields = [] fields = []
pfields = CTaosInterface.fetchFields(result) pfields = CTaosInterface.fetchFields(result)
for i in range(CTaosInterface.fieldsCount(connection)): for i in range(CTaosInterface.fieldsCount(result)):
fields.append({'name': pfields[i].name.decode('utf-8'), fields.append({'name': pfields[i].name.decode('utf-8'),
'bytes': pfields[i].bytes, 'bytes': pfields[i].bytes,
'type': ord(pfields[i].type)}) 'type': ord(pfields[i].type)})
return result, fields return fields
@staticmethod @staticmethod
def fetchBlock(result, fields): def fetchBlock(result, fields):
...@@ -337,8 +338,8 @@ class CTaosInterface(object): ...@@ -337,8 +338,8 @@ class CTaosInterface(object):
result.value = None result.value = None
@staticmethod @staticmethod
def fieldsCount(connection): def fieldsCount(result):
return CTaosInterface.libtaos.taos_field_count(connection) return CTaosInterface.libtaos.taos_field_count(result)
@staticmethod @staticmethod
def fetchFields(result): def fetchFields(result):
...@@ -386,29 +387,30 @@ class CTaosInterface(object): ...@@ -386,29 +387,30 @@ class CTaosInterface(object):
# return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00') # return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00')
@staticmethod @staticmethod
def errno(connection): def errno(result):
"""Return the error number. """Return the error number.
""" """
return CTaosInterface.libtaos.taos_errno(connection) return CTaosInterface.libtaos.taos_errno(result)
@staticmethod @staticmethod
def errStr(connection): def errStr(result):
"""Return the error styring """Return the error styring
""" """
return CTaosInterface.libtaos.taos_errstr(connection) return CTaosInterface.libtaos.taos_errstr(result)
if __name__ == '__main__': if __name__ == '__main__':
cinter = CTaosInterface() cinter = CTaosInterface()
conn = cinter.connect() conn = cinter.connect()
result = cinter.query(conn, 'show databases')
print('Query return value: {}'.format(cinter.query(conn, 'show databases'))) print('Query Affected rows: {}'.format(cinter.affectedRows(result)))
print('Affected rows: {}'.format(cinter.affectedRows(conn)))
result, des = CTaosInterface.useResult(conn) fields = CTaosInterface.useResult(result)
data, num_of_rows = CTaosInterface.fetchBlock(result, des) data, num_of_rows = CTaosInterface.fetchBlock(result, fields)
print(data) print(data)
cinter.freeresult(result)
cinter.close(conn) cinter.close(conn)
\ No newline at end of file
...@@ -78,9 +78,7 @@ class TDengineConnection(object): ...@@ -78,9 +78,7 @@ class TDengineConnection(object):
def clear_result_set(self): def clear_result_set(self):
"""Clear unused result set on this connection. """Clear unused result set on this connection.
""" """
result = self._chandle.useResult(self._conn)[0] pass
if result:
self._chandle.freeResult(result)
if __name__ == "__main__": if __name__ == "__main__":
conn = TDengineConnection(host='192.168.1.107') conn = TDengineConnection(host='192.168.1.107')
......
...@@ -28,6 +28,6 @@ class FieldType(object): ...@@ -28,6 +28,6 @@ class FieldType(object):
C_FLOAT_NULL = float('nan') C_FLOAT_NULL = float('nan')
C_DOUBLE_NULL = float('nan') C_DOUBLE_NULL = float('nan')
C_BINARY_NULL = bytearray([int('0xff', 16)]) C_BINARY_NULL = bytearray([int('0xff', 16)])
# Time precision definition # Timestamp precision definition
C_TIMESTAMP_MILLI = 0 C_TIMESTAMP_MILLI = 0
C_TIMESTAMP_MICRO = 1 C_TIMESTAMP_MICRO = 1
...@@ -116,25 +116,30 @@ class TDengineCursor(object): ...@@ -116,25 +116,30 @@ class TDengineCursor(object):
if params is not None: if params is not None:
pass pass
res = CTaosInterface.query(self._connection._conn, stmt) # global querySeqNum
# querySeqNum += 1
# localSeqNum = querySeqNum # avoid raice condition
# print(" >> Exec Query ({}): {}".format(localSeqNum, str(stmt)))
self._result = CTaosInterface.query(self._connection._conn, stmt)
# print(" << Query ({}) Exec Done".format(localSeqNum))
if (self._logfile): if (self._logfile):
with open(self._logfile, "a") as logfile: with open(self._logfile, "a") as logfile:
logfile.write("%s;\n" % operation) logfile.write("%s;\n" % operation)
if res == 0: errno = CTaosInterface.libtaos.taos_errno(self._result)
if CTaosInterface.fieldsCount(self._connection._conn) == 0: if errno == 0:
if CTaosInterface.fieldsCount(self._result) == 0:
self._affected_rows += CTaosInterface.affectedRows( self._affected_rows += CTaosInterface.affectedRows(
self._connection._conn) self._result )
return CTaosInterface.affectedRows(self._connection._conn) return CTaosInterface.affectedRows(self._result )
else: else:
self._result, self._fields = CTaosInterface.useResult( self._fields = CTaosInterface.useResult(
self._connection._conn) self._result)
return self._handle_result() return self._handle_result()
else: else:
raise ProgrammingError( raise ProgrammingError(
CTaosInterface.errStr( CTaosInterface.errStr(
self._connection._conn)) self._result ))
def executemany(self, operation, seq_of_parameters): def executemany(self, operation, seq_of_parameters):
"""Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. """Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
......
...@@ -142,12 +142,14 @@ class CTaosInterface(object): ...@@ -142,12 +142,14 @@ class CTaosInterface(object):
libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField) libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
libtaos.taos_init.restype = None libtaos.taos_init.restype = None
libtaos.taos_connect.restype = ctypes.c_void_p libtaos.taos_connect.restype = ctypes.c_void_p
libtaos.taos_use_result.restype = ctypes.c_void_p #libtaos.taos_use_result.restype = ctypes.c_void_p
libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p) libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p)
libtaos.taos_errstr.restype = ctypes.c_char_p libtaos.taos_errstr.restype = ctypes.c_char_p
libtaos.taos_subscribe.restype = ctypes.c_void_p libtaos.taos_subscribe.restype = ctypes.c_void_p
libtaos.taos_consume.restype = ctypes.c_void_p libtaos.taos_consume.restype = ctypes.c_void_p
libtaos.taos_fetch_lengths.restype = ctypes.c_void_p libtaos.taos_fetch_lengths.restype = ctypes.c_void_p
libtaos.taos_free_result.restype = None
libtaos.taos_errno.restype = ctypes.c_int
def __init__(self, config=None): def __init__(self, config=None):
''' '''
...@@ -249,12 +251,12 @@ class CTaosInterface(object): ...@@ -249,12 +251,12 @@ class CTaosInterface(object):
raise AttributeError("sql is expected as a string") raise AttributeError("sql is expected as a string")
# finally: # finally:
# CTaosInterface.libtaos.close(connection) # CTaosInterface.libtaos.close(connection)
@staticmethod @staticmethod
def affectedRows(connection): def affectedRows(result):
"""The affected rows after runing query """The affected rows after runing query
""" """
return CTaosInterface.libtaos.taos_affected_rows(connection) return CTaosInterface.libtaos.taos_affected_rows(result)
@staticmethod @staticmethod
def subscribe(connection, restart, topic, sql, interval): def subscribe(connection, restart, topic, sql, interval):
...@@ -292,18 +294,17 @@ class CTaosInterface(object): ...@@ -292,18 +294,17 @@ class CTaosInterface(object):
CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0) CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0)
@staticmethod @staticmethod
def useResult(connection): def useResult(result):
'''Use result after calling self.query '''Use result after calling self.query
''' '''
result = ctypes.c_void_p(CTaosInterface.libtaos.taos_use_result(connection))
fields = [] fields = []
pfields = CTaosInterface.fetchFields(result) pfields = CTaosInterface.fetchFields(result)
for i in range(CTaosInterface.fieldsCount(connection)): for i in range(CTaosInterface.fieldsCount(result)):
fields.append({'name': pfields[i].name.decode('utf-8'), fields.append({'name': pfields[i].name.decode('utf-8'),
'bytes': pfields[i].bytes, 'bytes': pfields[i].bytes,
'type': ord(pfields[i].type)}) 'type': ord(pfields[i].type)})
return result, fields return fields
@staticmethod @staticmethod
def fetchBlock(result, fields): def fetchBlock(result, fields):
...@@ -337,8 +338,8 @@ class CTaosInterface(object): ...@@ -337,8 +338,8 @@ class CTaosInterface(object):
result.value = None result.value = None
@staticmethod @staticmethod
def fieldsCount(connection): def fieldsCount(result):
return CTaosInterface.libtaos.taos_field_count(connection) return CTaosInterface.libtaos.taos_field_count(result)
@staticmethod @staticmethod
def fetchFields(result): def fetchFields(result):
...@@ -386,29 +387,30 @@ class CTaosInterface(object): ...@@ -386,29 +387,30 @@ class CTaosInterface(object):
# return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00') # return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00')
@staticmethod @staticmethod
def errno(connection): def errno(result):
"""Return the error number. """Return the error number.
""" """
return CTaosInterface.libtaos.taos_errno(connection) return CTaosInterface.libtaos.taos_errno(result)
@staticmethod @staticmethod
def errStr(connection): def errStr(result):
"""Return the error styring """Return the error styring
""" """
return CTaosInterface.libtaos.taos_errstr(connection).decode('utf-8') return CTaosInterface.libtaos.taos_errstr(result).decode('utf-8')
if __name__ == '__main__': if __name__ == '__main__':
cinter = CTaosInterface() cinter = CTaosInterface()
conn = cinter.connect() conn = cinter.connect()
result = cinter.query(conn, 'show databases')
print('Query return value: {}'.format(cinter.query(conn, 'show databases'))) print('Query Affected rows: {}'.format(cinter.affectedRows(result)))
print('Affected rows: {}'.format(cinter.affectedRows(conn)))
result, des = CTaosInterface.useResult(conn) fields = CTaosInterface.useResult(result)
data, num_of_rows = CTaosInterface.fetchBlock(result, des) data, num_of_rows = CTaosInterface.fetchBlock(result, fields)
print(data) print(data)
cinter.freeresult(result)
cinter.close(conn) cinter.close(conn)
\ No newline at end of file
...@@ -78,9 +78,7 @@ class TDengineConnection(object): ...@@ -78,9 +78,7 @@ class TDengineConnection(object):
def clear_result_set(self): def clear_result_set(self):
"""Clear unused result set on this connection. """Clear unused result set on this connection.
""" """
result = self._chandle.useResult(self._conn)[0] pass
if result:
self._chandle.freeResult(result)
if __name__ == "__main__": if __name__ == "__main__":
conn = TDengineConnection(host='192.168.1.107') conn = TDengineConnection(host='192.168.1.107')
......
...@@ -122,26 +122,26 @@ class TDengineCursor(object): ...@@ -122,26 +122,26 @@ class TDengineCursor(object):
# querySeqNum += 1 # querySeqNum += 1
# localSeqNum = querySeqNum # avoid raice condition # localSeqNum = querySeqNum # avoid raice condition
# print(" >> Exec Query ({}): {}".format(localSeqNum, str(stmt))) # print(" >> Exec Query ({}): {}".format(localSeqNum, str(stmt)))
res = CTaosInterface.query(self._connection._conn, stmt) self._result = CTaosInterface.query(self._connection._conn, stmt)
# print(" << Query ({}) Exec Done".format(localSeqNum)) # print(" << Query ({}) Exec Done".format(localSeqNum))
if (self._logfile): if (self._logfile):
with open(self._logfile, "a") as logfile: with open(self._logfile, "a") as logfile:
logfile.write("%s;\n" % operation) logfile.write("%s;\n" % operation)
if res == 0: errno = CTaosInterface.libtaos.taos_errno(self._result)
if CTaosInterface.fieldsCount(self._connection._conn) == 0: if errno == 0:
if CTaosInterface.fieldsCount(self._result) == 0:
self._affected_rows += CTaosInterface.affectedRows( self._affected_rows += CTaosInterface.affectedRows(
self._connection._conn) self._result )
return CTaosInterface.affectedRows(self._connection._conn) return CTaosInterface.affectedRows(self._result )
else: else:
self._result, self._fields = CTaosInterface.useResult( self._fields = CTaosInterface.useResult(
self._connection._conn) self._result)
return self._handle_result() return self._handle_result()
else: else:
raise ProgrammingError( raise ProgrammingError(
CTaosInterface.errStr( CTaosInterface.errStr(
self._connection._conn)) self._result ))
def executemany(self, operation, seq_of_parameters): def executemany(self, operation, seq_of_parameters):
"""Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. """Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
......
from taos.cinterface import CTaosInterface
from taos.error import *
from taos.subscription import TDengineSubscription
from taos.connection import TDengineConnection
if __name__ == '__main__':
conn = TDengineConnection(
host="127.0.0.1", user="root", password="taosdata", database="test")
# Generate a cursor object to run SQL commands
sub = conn.subscribe(False, "test", "select * from log0601;", 1000)
for i in range(100):
print(i)
data = sub.consume()
for d in data:
print(d)
sub.close()
conn.close()
...@@ -142,12 +142,14 @@ class CTaosInterface(object): ...@@ -142,12 +142,14 @@ class CTaosInterface(object):
libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField) libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
libtaos.taos_init.restype = None libtaos.taos_init.restype = None
libtaos.taos_connect.restype = ctypes.c_void_p libtaos.taos_connect.restype = ctypes.c_void_p
libtaos.taos_use_result.restype = ctypes.c_void_p #libtaos.taos_use_result.restype = ctypes.c_void_p
libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p) libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p)
libtaos.taos_errstr.restype = ctypes.c_char_p libtaos.taos_errstr.restype = ctypes.c_char_p
libtaos.taos_subscribe.restype = ctypes.c_void_p libtaos.taos_subscribe.restype = ctypes.c_void_p
libtaos.taos_consume.restype = ctypes.c_void_p libtaos.taos_consume.restype = ctypes.c_void_p
libtaos.taos_fetch_lengths.restype = ctypes.c_void_p libtaos.taos_fetch_lengths.restype = ctypes.c_void_p
libtaos.taos_free_result.restype = None
libtaos.taos_errno.restype = ctypes.c_int
def __init__(self, config=None): def __init__(self, config=None):
''' '''
...@@ -251,10 +253,10 @@ class CTaosInterface(object): ...@@ -251,10 +253,10 @@ class CTaosInterface(object):
# CTaosInterface.libtaos.close(connection) # CTaosInterface.libtaos.close(connection)
@staticmethod @staticmethod
def affectedRows(connection): def affectedRows(result):
"""The affected rows after runing query """The affected rows after runing query
""" """
return CTaosInterface.libtaos.taos_affected_rows(connection) return CTaosInterface.libtaos.taos_affected_rows(result)
@staticmethod @staticmethod
def subscribe(connection, restart, topic, sql, interval): def subscribe(connection, restart, topic, sql, interval):
...@@ -292,18 +294,17 @@ class CTaosInterface(object): ...@@ -292,18 +294,17 @@ class CTaosInterface(object):
CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0) CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0)
@staticmethod @staticmethod
def useResult(connection): def useResult(result):
'''Use result after calling self.query '''Use result after calling self.query
''' '''
result = ctypes.c_void_p(CTaosInterface.libtaos.taos_use_result(connection))
fields = [] fields = []
pfields = CTaosInterface.fetchFields(result) pfields = CTaosInterface.fetchFields(result)
for i in range(CTaosInterface.fieldsCount(connection)): for i in range(CTaosInterface.fieldsCount(result)):
fields.append({'name': pfields[i].name.decode('utf-8'), fields.append({'name': pfields[i].name.decode('utf-8'),
'bytes': pfields[i].bytes, 'bytes': pfields[i].bytes,
'type': ord(pfields[i].type)}) 'type': ord(pfields[i].type)})
return result, fields return fields
@staticmethod @staticmethod
def fetchBlock(result, fields): def fetchBlock(result, fields):
...@@ -337,8 +338,8 @@ class CTaosInterface(object): ...@@ -337,8 +338,8 @@ class CTaosInterface(object):
result.value = None result.value = None
@staticmethod @staticmethod
def fieldsCount(connection): def fieldsCount(result):
return CTaosInterface.libtaos.taos_field_count(connection) return CTaosInterface.libtaos.taos_field_count(result)
@staticmethod @staticmethod
def fetchFields(result): def fetchFields(result):
...@@ -386,29 +387,30 @@ class CTaosInterface(object): ...@@ -386,29 +387,30 @@ class CTaosInterface(object):
# return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00') # return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00')
@staticmethod @staticmethod
def errno(connection): def errno(result):
"""Return the error number. """Return the error number.
""" """
return CTaosInterface.libtaos.taos_errno(connection) return CTaosInterface.libtaos.taos_errno(result)
@staticmethod @staticmethod
def errStr(connection): def errStr(result):
"""Return the error styring """Return the error styring
""" """
return CTaosInterface.libtaos.taos_errstr(connection) return CTaosInterface.libtaos.taos_errstr(result)
if __name__ == '__main__': if __name__ == '__main__':
cinter = CTaosInterface() cinter = CTaosInterface()
conn = cinter.connect() conn = cinter.connect()
result = cinter.query(conn, 'show databases')
print('Query return value: {}'.format(cinter.query(conn, 'show databases'))) print('Query Affected rows: {}'.format(cinter.affectedRows(result)))
print('Affected rows: {}'.format(cinter.affectedRows(conn)))
result, des = CTaosInterface.useResult(conn) fields = CTaosInterface.useResult(result)
data, num_of_rows = CTaosInterface.fetchBlock(result, des) data, num_of_rows = CTaosInterface.fetchBlock(result, fields)
print(data) print(data)
cinter.freeresult(result)
cinter.close(conn) cinter.close(conn)
\ No newline at end of file
...@@ -79,9 +79,7 @@ class TDengineConnection(object): ...@@ -79,9 +79,7 @@ class TDengineConnection(object):
def clear_result_set(self): def clear_result_set(self):
"""Clear unused result set on this connection. """Clear unused result set on this connection.
""" """
result = self._chandle.useResult(self._conn)[0] pass
if result:
self._chandle.freeResult(result)
if __name__ == "__main__": if __name__ == "__main__":
conn = TDengineConnection(host='192.168.1.107') conn = TDengineConnection(host='192.168.1.107')
......
...@@ -109,16 +109,17 @@ class TDengineCursor(object): ...@@ -109,16 +109,17 @@ class TDengineCursor(object):
if params is not None: if params is not None:
pass pass
res = CTaosInterface.query(self._connection._conn, stmt) self._result = CTaosInterface.query(self._connection._conn, stmt)
if res == 0: errno = CTaosInterface.libtaos.taos_errno(self._result)
if CTaosInterface.fieldsCount(self._connection._conn) == 0: if errno == 0:
self._affected_rows += CTaosInterface.affectedRows(self._connection._conn) if CTaosInterface.fieldsCount(self._result) == 0:
return CTaosInterface.affectedRows(self._connection._conn) self._affected_rows += CTaosInterface.affectedRows(self._result)
return CTaosInterface.affectedRows(self._result )
else: else:
self._result, self._fields = CTaosInterface.useResult(self._connection._conn) self._fields = CTaosInterface.useResult(self._result)
return self._handle_result() return self._handle_result()
else: else:
raise ProgrammingError(CTaosInterface.errStr(self._connection._conn)) raise ProgrammingError(CTaosInterface.errStr(self._result))
def executemany(self, operation, seq_of_parameters): def executemany(self, operation, seq_of_parameters):
"""Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. """Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
......
...@@ -142,12 +142,14 @@ class CTaosInterface(object): ...@@ -142,12 +142,14 @@ class CTaosInterface(object):
libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField) libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField)
libtaos.taos_init.restype = None libtaos.taos_init.restype = None
libtaos.taos_connect.restype = ctypes.c_void_p libtaos.taos_connect.restype = ctypes.c_void_p
libtaos.taos_use_result.restype = ctypes.c_void_p #libtaos.taos_use_result.restype = ctypes.c_void_p
libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p) libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p)
libtaos.taos_errstr.restype = ctypes.c_char_p libtaos.taos_errstr.restype = ctypes.c_char_p
libtaos.taos_subscribe.restype = ctypes.c_void_p libtaos.taos_subscribe.restype = ctypes.c_void_p
libtaos.taos_consume.restype = ctypes.c_void_p libtaos.taos_consume.restype = ctypes.c_void_p
libtaos.taos_fetch_lengths.restype = ctypes.c_void_p libtaos.taos_fetch_lengths.restype = ctypes.c_void_p
libtaos.taos_free_result.restype = None
libtaos.taos_errno.restype = ctypes.c_int
def __init__(self, config=None): def __init__(self, config=None):
''' '''
...@@ -251,10 +253,10 @@ class CTaosInterface(object): ...@@ -251,10 +253,10 @@ class CTaosInterface(object):
# CTaosInterface.libtaos.close(connection) # CTaosInterface.libtaos.close(connection)
@staticmethod @staticmethod
def affectedRows(connection): def affectedRows(result):
"""The affected rows after runing query """The affected rows after runing query
""" """
return CTaosInterface.libtaos.taos_affected_rows(connection) return CTaosInterface.libtaos.taos_affected_rows(result)
@staticmethod @staticmethod
def subscribe(connection, restart, topic, sql, interval): def subscribe(connection, restart, topic, sql, interval):
...@@ -292,18 +294,17 @@ class CTaosInterface(object): ...@@ -292,18 +294,17 @@ class CTaosInterface(object):
CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0) CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0)
@staticmethod @staticmethod
def useResult(connection): def useResult(result):
'''Use result after calling self.query '''Use result after calling self.query
''' '''
result = ctypes.c_void_p(CTaosInterface.libtaos.taos_use_result(connection))
fields = [] fields = []
pfields = CTaosInterface.fetchFields(result) pfields = CTaosInterface.fetchFields(result)
for i in range(CTaosInterface.fieldsCount(connection)): for i in range(CTaosInterface.fieldsCount(result)):
fields.append({'name': pfields[i].name.decode('utf-8'), fields.append({'name': pfields[i].name.decode('utf-8'),
'bytes': pfields[i].bytes, 'bytes': pfields[i].bytes,
'type': ord(pfields[i].type)}) 'type': ord(pfields[i].type)})
return result, fields return fields
@staticmethod @staticmethod
def fetchBlock(result, fields): def fetchBlock(result, fields):
...@@ -337,8 +338,8 @@ class CTaosInterface(object): ...@@ -337,8 +338,8 @@ class CTaosInterface(object):
result.value = None result.value = None
@staticmethod @staticmethod
def fieldsCount(connection): def fieldsCount(result):
return CTaosInterface.libtaos.taos_field_count(connection) return CTaosInterface.libtaos.taos_field_count(result)
@staticmethod @staticmethod
def fetchFields(result): def fetchFields(result):
...@@ -386,29 +387,30 @@ class CTaosInterface(object): ...@@ -386,29 +387,30 @@ class CTaosInterface(object):
# return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00') # return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00')
@staticmethod @staticmethod
def errno(connection): def errno(result):
"""Return the error number. """Return the error number.
""" """
return CTaosInterface.libtaos.taos_errno(connection) return CTaosInterface.libtaos.taos_errno(result)
@staticmethod @staticmethod
def errStr(connection): def errStr(result):
"""Return the error styring """Return the error styring
""" """
return CTaosInterface.libtaos.taos_errstr(connection).decode('utf-8') return CTaosInterface.libtaos.taos_errstr(result).decode('utf-8')
if __name__ == '__main__': if __name__ == '__main__':
cinter = CTaosInterface() cinter = CTaosInterface()
conn = cinter.connect() conn = cinter.connect()
result = cinter.query(conn, 'show databases')
print('Query return value: {}'.format(cinter.query(conn, 'show databases'))) print('Query Affected rows: {}'.format(cinter.affectedRows(result)))
print('Affected rows: {}'.format(cinter.affectedRows(conn)))
result, des = CTaosInterface.useResult(conn) fields = CTaosInterface.useResult(result)
data, num_of_rows = CTaosInterface.fetchBlock(result, des) data, num_of_rows = CTaosInterface.fetchBlock(result, fields)
print(data) print(data)
cinter.freeresult(result)
cinter.close(conn) cinter.close(conn)
\ No newline at end of file
...@@ -79,9 +79,7 @@ class TDengineConnection(object): ...@@ -79,9 +79,7 @@ class TDengineConnection(object):
def clear_result_set(self): def clear_result_set(self):
"""Clear unused result set on this connection. """Clear unused result set on this connection.
""" """
result = self._chandle.useResult(self._conn)[0] pass
if result:
self._chandle.freeResult(result)
if __name__ == "__main__": if __name__ == "__main__":
conn = TDengineConnection(host='192.168.1.107') conn = TDengineConnection(host='192.168.1.107')
......
...@@ -109,16 +109,17 @@ class TDengineCursor(object): ...@@ -109,16 +109,17 @@ class TDengineCursor(object):
if params is not None: if params is not None:
pass pass
res = CTaosInterface.query(self._connection._conn, stmt) self._result = CTaosInterface.query(self._connection._conn, stmt)
if res == 0: errno = CTaosInterface.libtaos.taos_errno(self._result)
if CTaosInterface.fieldsCount(self._connection._conn) == 0: if errno == 0:
self._affected_rows += CTaosInterface.affectedRows(self._connection._conn) if CTaosInterface.fieldsCount(self._result) == 0:
return CTaosInterface.affectedRows(self._connection._conn) self._affected_rows += CTaosInterface.affectedRows(self._result )
return CTaosInterface.affectedRows(self._result )
else: else:
self._result, self._fields = CTaosInterface.useResult(self._connection._conn) self._fields = CTaosInterface.useResult(self._result )
return self._handle_result() return self._handle_result()
else: else:
raise ProgrammingError(CTaosInterface.errStr(self._connection._conn)) raise ProgrammingError(CTaosInterface.errStr(self._result ))
def executemany(self, operation, seq_of_parameters): def executemany(self, operation, seq_of_parameters):
"""Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. """Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
......
...@@ -88,14 +88,13 @@ int taos_stmt_execute(TAOS_STMT *stmt); ...@@ -88,14 +88,13 @@ int taos_stmt_execute(TAOS_STMT *stmt);
TAOS_RES * taos_stmt_use_result(TAOS_STMT *stmt); TAOS_RES * taos_stmt_use_result(TAOS_STMT *stmt);
int taos_stmt_close(TAOS_STMT *stmt); int taos_stmt_close(TAOS_STMT *stmt);
DLL_EXPORT int taos_query(TAOS *taos, const char *sql); DLL_EXPORT TAOS_RES *taos_query(TAOS *taos, const char *sql);
DLL_EXPORT TAOS_RES *taos_use_result(TAOS *taos);
DLL_EXPORT TAOS_ROW taos_fetch_row(TAOS_RES *res); DLL_EXPORT TAOS_ROW taos_fetch_row(TAOS_RES *res);
DLL_EXPORT int taos_result_precision(TAOS_RES *res); // get the time precision of result DLL_EXPORT int taos_result_precision(TAOS_RES *res); // get the time precision of result
DLL_EXPORT void taos_free_result(TAOS_RES *res); DLL_EXPORT void taos_free_result(TAOS_RES *res);
DLL_EXPORT int taos_field_count(TAOS *taos); DLL_EXPORT int taos_field_count(TAOS_RES *tres);
DLL_EXPORT int taos_num_fields(TAOS_RES *res); DLL_EXPORT int taos_num_fields(TAOS_RES *res);
DLL_EXPORT int taos_affected_rows(TAOS *taos); DLL_EXPORT int taos_affected_rows(TAOS_RES *taos);
DLL_EXPORT TAOS_FIELD *taos_fetch_fields(TAOS_RES *res); DLL_EXPORT TAOS_FIELD *taos_fetch_fields(TAOS_RES *res);
DLL_EXPORT int taos_select_db(TAOS *taos, const char *db); DLL_EXPORT int taos_select_db(TAOS *taos, const char *db);
DLL_EXPORT int taos_print_row(char *str, TAOS_ROW row, TAOS_FIELD *fields, int num_fields); DLL_EXPORT int taos_print_row(char *str, TAOS_ROW row, TAOS_FIELD *fields, int num_fields);
...@@ -112,9 +111,9 @@ int* taos_fetch_lengths(TAOS_RES *res); ...@@ -112,9 +111,9 @@ int* taos_fetch_lengths(TAOS_RES *res);
// TODO: the return value should be `const` // TODO: the return value should be `const`
DLL_EXPORT char *taos_get_server_info(TAOS *taos); DLL_EXPORT char *taos_get_server_info(TAOS *taos);
DLL_EXPORT char *taos_get_client_info(); DLL_EXPORT char *taos_get_client_info();
DLL_EXPORT char *taos_errstr(TAOS *taos); DLL_EXPORT char *taos_errstr(TAOS_RES *tres);
DLL_EXPORT int taos_errno(TAOS *taos); DLL_EXPORT int taos_errno(TAOS_RES *tres);
DLL_EXPORT void taos_query_a(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, int code), void *param); DLL_EXPORT void taos_query_a(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, int code), void *param);
DLL_EXPORT void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param); DLL_EXPORT void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);
......
...@@ -322,7 +322,7 @@ void tsDataSwap(void *pLeft, void *pRight, int32_t type, int32_t size); ...@@ -322,7 +322,7 @@ void tsDataSwap(void *pLeft, void *pRight, int32_t type, int32_t size);
#define TSDB_QUERY_TYPE_SUBQUERY 0x02u #define TSDB_QUERY_TYPE_SUBQUERY 0x02u
#define TSDB_QUERY_TYPE_STABLE_SUBQUERY 0x04u // two-stage subquery for super table #define TSDB_QUERY_TYPE_STABLE_SUBQUERY 0x04u // two-stage subquery for super table
#define TSDB_QUERY_TYPE_TABLE_QUERY 0x08u // query ordinary table; below only apply to client side #define TSDB_QUERY_TYPE_TABLE_QUERY 0x08u // query ordinary table; below only apply to client side
#define TSDB_QUERY_TYPE_STABLE_QUERY 0x10u // query on super table #define TSDB_QUERY_TYPE_STABLE_QUERY 0x10u // query on super table
#define TSDB_QUERY_TYPE_JOIN_QUERY 0x20u // join query #define TSDB_QUERY_TYPE_JOIN_QUERY 0x20u // join query
#define TSDB_QUERY_TYPE_PROJECTION_QUERY 0x40u // select *,columns... query #define TSDB_QUERY_TYPE_PROJECTION_QUERY 0x40u // select *,columns... query
......
...@@ -92,16 +92,15 @@ TAOS_DEFINE_ERROR(TSDB_CODE_NO_USER_FROM_CONN, 0, 0x0185, "can not get ...@@ -92,16 +92,15 @@ TAOS_DEFINE_ERROR(TSDB_CODE_NO_USER_FROM_CONN, 0, 0x0185, "can not get
// table // table
TAOS_DEFINE_ERROR(TSDB_CODE_TABLE_ALREADY_EXIST, 0, 0x0200, "table already exist") TAOS_DEFINE_ERROR(TSDB_CODE_TABLE_ALREADY_EXIST, 0, 0x0200, "table already exist")
TAOS_DEFINE_ERROR(TSDB_CODE_INVALID_TABLE_ID, 0, 0x0201, "invalid table id") TAOS_DEFINE_ERROR(TSDB_CODE_INVALID_TABLE_ID, 0, 0x0201, "invalid table id")
TAOS_DEFINE_ERROR(TSDB_CODE_INVALID_TABLE_TYPE, 0, 0x0202, "invalid table typee") TAOS_DEFINE_ERROR(TSDB_CODE_INVALID_TABLE_TYPE, 0, 0x0202, "invalid table type")
TAOS_DEFINE_ERROR(TSDB_CODE_NOT_SUPER_TABLE, 0, 0x0203, "no super table") // operation only available for super table TAOS_DEFINE_ERROR(TSDB_CODE_NOT_SUPER_TABLE, 0, 0x0203, "no super table") // operation only available for super table
TAOS_DEFINE_ERROR(TSDB_CODE_TAG_ALREAY_EXIST, 0, 0x0204, "tag already exist") TAOS_DEFINE_ERROR(TSDB_CODE_TAG_ALREAY_EXIST, 0, 0x0204, "tag already exist")
TAOS_DEFINE_ERROR(TSDB_CODE_TAG_NOT_EXIST, 0, 0x0205, "tag not exist") TAOS_DEFINE_ERROR(TSDB_CODE_TAG_NOT_EXIST, 0, 0x0205, "tag not exist")
TAOS_DEFINE_ERROR(TSDB_CODE_FIELD_ALREAY_EXIST, 0, 0x0206, "field already exist") TAOS_DEFINE_ERROR(TSDB_CODE_FIELD_ALREAY_EXIST, 0, 0x0206, "field already exist")
TAOS_DEFINE_ERROR(TSDB_CODE_FIELD_NOT_EXIST, 0, 0x0207, "field not exist") TAOS_DEFINE_ERROR(TSDB_CODE_FIELD_NOT_EXIST, 0, 0x0207, "field not exist")
TAOS_DEFINE_ERROR(TSDB_CODE_COL_NAME_TOO_LONG, 0, 0x0209, "column name too long") TAOS_DEFINE_ERROR(TSDB_CODE_COL_NAME_TOO_LONG, 0, 0x0208, "column name too long")
TAOS_DEFINE_ERROR(TSDB_CODE_TOO_MANY_TAGS, 0, 0x0209, "too many tags") TAOS_DEFINE_ERROR(TSDB_CODE_TOO_MANY_TAGS, 0, 0x0209, "too many tags")
// dnode & mnode // dnode & mnode
TAOS_DEFINE_ERROR(TSDB_CODE_NO_ENOUGH_DNODES, 0, 0x0280, "no enough dnodes") TAOS_DEFINE_ERROR(TSDB_CODE_NO_ENOUGH_DNODES, 0, 0x0280, "no enough dnodes")
TAOS_DEFINE_ERROR(TSDB_CODE_DNODE_ALREADY_EXIST, 0, 0x0281, "dnode already exist") TAOS_DEFINE_ERROR(TSDB_CODE_DNODE_ALREADY_EXIST, 0, 0x0281, "dnode already exist")
......
...@@ -275,22 +275,28 @@ void shellRunCommandOnServer(TAOS *con, char command[]) { ...@@ -275,22 +275,28 @@ void shellRunCommandOnServer(TAOS *con, char command[]) {
st = taosGetTimestampUs(); st = taosGetTimestampUs();
if (taos_query(con, command)) { TAOS_RES* pSql = taos_query(con, command);
taos_error(con); if (taos_errno(pSql)) {
taos_error(pSql);
return; return;
} }
if (regex_match(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) { if (regex_match(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
fprintf(stdout, "Database changed.\n\n"); fprintf(stdout, "Database changed.\n\n");
fflush(stdout); fflush(stdout);
taos_free_result(pSql);
return; return;
} }
int num_fields = taos_field_count(con); int num_fields = taos_field_count(pSql);
if (num_fields != 0) { // select and show kinds of commands if (num_fields != 0) { // select and show kinds of commands
int error_no = 0; int error_no = 0;
int numOfRows = shellDumpResult(con, fname, &error_no, printMode); int numOfRows = shellDumpResult(pSql, fname, &error_no, printMode);
if (numOfRows < 0) return; if (numOfRows < 0) {
taos_free_result(pSql);
return;
}
et = taosGetTimestampUs(); et = taosGetTimestampUs();
if (error_no == 0) { if (error_no == 0) {
...@@ -299,7 +305,7 @@ void shellRunCommandOnServer(TAOS *con, char command[]) { ...@@ -299,7 +305,7 @@ void shellRunCommandOnServer(TAOS *con, char command[]) {
printf("Query interrupted (%s), %d row(s) in set (%.6fs)\n", taos_errstr(con), numOfRows, (et - st) / 1E6); printf("Query interrupted (%s), %d row(s) in set (%.6fs)\n", taos_errstr(con), numOfRows, (et - st) / 1E6);
} }
} else { } else {
int num_rows_affacted = taos_affected_rows(con); int num_rows_affacted = taos_affected_rows(pSql);
et = taosGetTimestampUs(); et = taosGetTimestampUs();
printf("Query OK, %d row(s) affected (%.6fs)\n", num_rows_affacted, (et - st) / 1E6); printf("Query OK, %d row(s) affected (%.6fs)\n", num_rows_affacted, (et - st) / 1E6);
} }
...@@ -309,6 +315,8 @@ void shellRunCommandOnServer(TAOS *con, char command[]) { ...@@ -309,6 +315,8 @@ void shellRunCommandOnServer(TAOS *con, char command[]) {
if (fname != NULL) { if (fname != NULL) {
wordfree(&full_path); wordfree(&full_path);
} }
taos_free_result(pSql);
} }
/* Function to do regular expression check */ /* Function to do regular expression check */
...@@ -461,6 +469,7 @@ static int dumpResultToFile(const char* fname, TAOS_RES* result) { ...@@ -461,6 +469,7 @@ static int dumpResultToFile(const char* fname, TAOS_RES* result) {
} while( row != NULL); } while( row != NULL);
fclose(fp); fclose(fp);
taos_free_result(result);
return numOfRows; return numOfRows;
} }
...@@ -548,15 +557,15 @@ static void printField(const char* val, TAOS_FIELD* field, int width, int32_t le ...@@ -548,15 +557,15 @@ static void printField(const char* val, TAOS_FIELD* field, int width, int32_t le
} }
static int verticalPrintResult(TAOS_RES* result) { static int verticalPrintResult(TAOS_RES* tres) {
TAOS_ROW row = taos_fetch_row(result); TAOS_ROW row = taos_fetch_row(tres);
if (row == NULL) { if (row == NULL) {
return 0; return 0;
} }
int num_fields = taos_num_fields(result); int num_fields = taos_num_fields(tres);
TAOS_FIELD *fields = taos_fetch_fields(result); TAOS_FIELD *fields = taos_fetch_fields(tres);
int precision = taos_result_precision(result); int precision = taos_result_precision(tres);
int maxColNameLen = 0; int maxColNameLen = 0;
for (int col = 0; col < num_fields; col++) { for (int col = 0; col < num_fields; col++) {
...@@ -569,7 +578,7 @@ static int verticalPrintResult(TAOS_RES* result) { ...@@ -569,7 +578,7 @@ static int verticalPrintResult(TAOS_RES* result) {
int numOfRows = 0; int numOfRows = 0;
do { do {
printf("*************************** %d.row ***************************\n", numOfRows + 1); printf("*************************** %d.row ***************************\n", numOfRows + 1);
int32_t* length = taos_fetch_lengths(result); int32_t* length = taos_fetch_lengths(tres);
for (int i = 0; i < num_fields; i++) { for (int i = 0; i < num_fields; i++) {
TAOS_FIELD* field = fields + i; TAOS_FIELD* field = fields + i;
...@@ -581,7 +590,7 @@ static int verticalPrintResult(TAOS_RES* result) { ...@@ -581,7 +590,7 @@ static int verticalPrintResult(TAOS_RES* result) {
} }
numOfRows++; numOfRows++;
row = taos_fetch_row(result); row = taos_fetch_row(tres);
} while(row != NULL); } while(row != NULL);
return numOfRows; return numOfRows;
...@@ -656,15 +665,15 @@ static void printHeader(TAOS_FIELD* fields, int* width, int num_fields) { ...@@ -656,15 +665,15 @@ static void printHeader(TAOS_FIELD* fields, int* width, int num_fields) {
} }
static int horizontalPrintResult(TAOS_RES* result) { static int horizontalPrintResult(TAOS_RES* tres) {
TAOS_ROW row = taos_fetch_row(result); TAOS_ROW row = taos_fetch_row(tres);
if (row == NULL) { if (row == NULL) {
return 0; return 0;
} }
int num_fields = taos_num_fields(result); int num_fields = taos_num_fields(tres);
TAOS_FIELD *fields = taos_fetch_fields(result); TAOS_FIELD *fields = taos_fetch_fields(tres);
int precision = taos_result_precision(result); int precision = taos_result_precision(tres);
int width[TSDB_MAX_COLUMNS]; int width[TSDB_MAX_COLUMNS];
for (int col = 0; col < num_fields; col++) { for (int col = 0; col < num_fields; col++) {
...@@ -675,7 +684,7 @@ static int horizontalPrintResult(TAOS_RES* result) { ...@@ -675,7 +684,7 @@ static int horizontalPrintResult(TAOS_RES* result) {
int numOfRows = 0; int numOfRows = 0;
do { do {
int32_t* length = taos_fetch_lengths(result); int32_t* length = taos_fetch_lengths(tres);
for (int i = 0; i < num_fields; i++) { for (int i = 0; i < num_fields; i++) {
putchar(' '); putchar(' ');
printField(row[i], fields + i, width[i], length[i], precision); printField(row[i], fields + i, width[i], length[i], precision);
...@@ -684,32 +693,24 @@ static int horizontalPrintResult(TAOS_RES* result) { ...@@ -684,32 +693,24 @@ static int horizontalPrintResult(TAOS_RES* result) {
} }
putchar('\n'); putchar('\n');
numOfRows++; numOfRows++;
row = taos_fetch_row(result); row = taos_fetch_row(tres);
} while(row != NULL); } while(row != NULL);
return numOfRows; return numOfRows;
} }
int shellDumpResult(TAOS *con, char *fname, int *error_no, bool vertical) { int shellDumpResult(TAOS_RES *tres, char *fname, int *error_no, bool vertical) {
int numOfRows = 0; int numOfRows = 0;
TAOS_RES* result = taos_use_result(con);
if (result == NULL) {
taos_error(con);
return -1;
}
if (fname != NULL) { if (fname != NULL) {
numOfRows = dumpResultToFile(fname, result); numOfRows = dumpResultToFile(fname, tres);
} else if(vertical) { } else if(vertical) {
numOfRows = verticalPrintResult(result); numOfRows = verticalPrintResult(tres);
} else { } else {
numOfRows = horizontalPrintResult(result); numOfRows = horizontalPrintResult(tres);
} }
*error_no = taos_errno(con); *error_no = taos_errno(tres);
taos_free_result(result);
return numOfRows; return numOfRows;
} }
...@@ -771,12 +772,11 @@ void write_history() { ...@@ -771,12 +772,11 @@ void write_history() {
fclose(f); fclose(f);
} }
void taos_error(TAOS *con) { void taos_error(TAOS_RES *tres) {
fprintf(stderr, "\nDB error: %s\n", taos_errstr(con)); fprintf(stderr, "\nDB error: %s\n", taos_errstr(tres));
/* free local resouce: allocated memory/metric-meta refcnt */ /* free local resouce: allocated memory/metric-meta refcnt */
TAOS_RES *pRes = taos_use_result(con); taos_free_result(tres);
taos_free_result(pRes);
} }
int isCommentLine(char *line) { int isCommentLine(char *line) {
...@@ -858,8 +858,9 @@ void shellGetGrantInfo(void *con) { ...@@ -858,8 +858,9 @@ void shellGetGrantInfo(void *con) {
char sql[] = "show grants"; char sql[] = "show grants";
int code = taos_query(con, sql); TAOS_RES* pSql = taos_query(con, sql);
int code = taos_errno(pSql);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
if (code == TSDB_CODE_OPS_NOT_SUPPORT) { if (code == TSDB_CODE_OPS_NOT_SUPPORT) {
fprintf(stdout, "Server is Community Edition, version is %s\n\n", taos_get_server_info(con)); fprintf(stdout, "Server is Community Edition, version is %s\n\n", taos_get_server_info(con));
...@@ -869,12 +870,11 @@ void shellGetGrantInfo(void *con) { ...@@ -869,12 +870,11 @@ void shellGetGrantInfo(void *con) {
return; return;
} }
int num_fields = taos_field_count(con); int num_fields = taos_field_count(result);
if (num_fields == 0) { if (num_fields == 0) {
fprintf(stderr, "\nInvalid grant information.\n"); fprintf(stderr, "\nInvalid grant information.\n");
exit(0); exit(0);
} else { } else {
result = taos_use_result(con);
if (result == NULL) { if (result == NULL) {
fprintf(stderr, "\nGrant information is null.\n"); fprintf(stderr, "\nGrant information is null.\n");
exit(0); exit(0);
......
...@@ -192,11 +192,14 @@ static void shellSourceFile(TAOS *con, char *fptr) { ...@@ -192,11 +192,14 @@ static void shellSourceFile(TAOS *con, char *fptr) {
} }
memcpy(cmd + cmd_len, line, read_len); memcpy(cmd + cmd_len, line, read_len);
if (taos_query(con, cmd)) {
TAOS_RES* pSql = taos_query(con, cmd);
int32_t code = taos_errno(pSql);
if (code != 0) {
fprintf(stderr, "DB error: %s: %s (%d)\n", taos_errstr(con), fname, lineNo); fprintf(stderr, "DB error: %s: %s (%d)\n", taos_errstr(con), fname, lineNo);
/* free local resouce: allocated memory/metric-meta refcnt */ /* free local resouce: allocated memory/metric-meta refcnt */
TAOS_RES *pRes = taos_use_result(con); taos_free_result(pSql);
taos_free_result(pRes);
} }
memset(cmd, 0, MAX_COMMAND_SIZE); memset(cmd, 0, MAX_COMMAND_SIZE);
......
...@@ -18,21 +18,21 @@ ...@@ -18,21 +18,21 @@
#include "tsclient.h" #include "tsclient.h"
#include "tutil.h" #include "tutil.h"
TAOS* con; TAOS_RES* con;
pthread_t pid; pthread_t pid;
// TODO: IMPLEMENT INTERRUPT HANDLER. // TODO: IMPLEMENT INTERRUPT HANDLER.
void interruptHandler(int signum) { void interruptHandler(int signum) {
#ifdef LINUX #ifdef LINUX
TAOS_RES* res = taos_use_result(con); taos_stop_query(con);
taos_stop_query(res); if (con != NULL) {
if (res != NULL) {
/* /*
* we need to free result in async model, in order to avoid free * we need to free result in async model, in order to avoid free
* results while the master thread is waiting for server response. * results while the master thread is waiting for server response.
*/ */
tscQueueAsyncFreeResult(res); tscQueueAsyncFreeResult(con);
} }
result = NULL; result = NULL;
#else #else
printf("\nReceive ctrl+c or other signal, quit shell.\n"); printf("\nReceive ctrl+c or other signal, quit shell.\n");
...@@ -90,7 +90,6 @@ int main(int argc, char* argv[]) { ...@@ -90,7 +90,6 @@ int main(int argc, char* argv[]) {
/* Initialize the shell */ /* Initialize the shell */
con = shellInit(&args); con = shellInit(&args);
if (con == NULL) { if (con == NULL) {
taos_error(con);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
......
...@@ -461,8 +461,7 @@ int main(int argc, char *argv[]) { ...@@ -461,8 +461,7 @@ int main(int argc, char *argv[]) {
taos_init(); taos_init();
TAOS *taos = taos_connect(ip_addr, user, pass, NULL, port); TAOS *taos = taos_connect(ip_addr, user, pass, NULL, port);
if (taos == NULL) { if (taos == NULL) {
fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(taos)); fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
taos_close(taos);
return 1; return 1;
} }
char command[BUFFER_SIZE] = "\0"; char command[BUFFER_SIZE] = "\0";
...@@ -708,27 +707,24 @@ void *readTable(void *sarg) { ...@@ -708,27 +707,24 @@ void *readTable(void *sarg) {
sprintf(command, "select %s from %s%d where ts>= %" PRId64, aggreFunc[j], tb_prefix, i, sTime); sprintf(command, "select %s from %s%d where ts>= %" PRId64, aggreFunc[j], tb_prefix, i, sTime);
double t = getCurrentTime(); double t = getCurrentTime();
if (taos_query(taos, command) != 0) { TAOS_RES *pSql = taos_query(taos, command);
fprintf(stderr, "Failed to query\n"); int32_t code = taos_errno(pSql);
taos_close(taos);
exit(EXIT_FAILURE);
}
TAOS_RES *result = taos_use_result(taos); if (code != 0) {
if (result == NULL) { fprintf(stderr, "Failed to query:%s\n", taos_errstr(taos));
fprintf(stderr, "Failed to retreive results:%s\n", taos_errstr(taos)); taos_free_result(pSql);
taos_close(taos); taos_close(taos);
exit(1); exit(EXIT_FAILURE);
} }
while (taos_fetch_row(result) != NULL) { while (taos_fetch_row(pSql) != NULL) {
count++; count++;
} }
t = getCurrentTime() - t; t = getCurrentTime() - t;
totalT += t; totalT += t;
taos_free_result(result); taos_free_result(pSql);
} }
fprintf(fp, "|%10s | %10d | %12.2f | %10.2f |\n", fprintf(fp, "|%10s | %10d | %12.2f | %10.2f |\n",
...@@ -779,20 +775,18 @@ void *readMetric(void *sarg) { ...@@ -779,20 +775,18 @@ void *readMetric(void *sarg) {
fprintf(fp, "%s\n", command); fprintf(fp, "%s\n", command);
double t = getCurrentTime(); double t = getCurrentTime();
if (taos_query(taos, command) != 0) {
fprintf(stderr, "Failed to query\n");
taos_close(taos);
exit(EXIT_FAILURE);
}
TAOS_RES *result = taos_use_result(taos); TAOS_RES *pSql = taos_query(taos, command);
if (result == NULL) { int32_t code = taos_errno(pSql);
fprintf(stderr, "Failed to retreive results:%s\n", taos_errstr(taos));
if (code != 0) {
fprintf(stderr, "Failed to query:%s\n", taos_errstr(taos));
taos_free_result(pSql);
taos_close(taos); taos_close(taos);
exit(1); exit(1);
} }
int count = 0; int count = 0;
while (taos_fetch_row(result) != NULL) { while (taos_fetch_row(pSql) != NULL) {
count++; count++;
} }
t = getCurrentTime() - t; t = getCurrentTime() - t;
...@@ -800,7 +794,7 @@ void *readMetric(void *sarg) { ...@@ -800,7 +794,7 @@ void *readMetric(void *sarg) {
fprintf(fp, "| Speed: %12.2f(per s) | Latency: %.4f(ms) |\n", num_of_tables * num_of_DPT / t, t * 1000); fprintf(fp, "| Speed: %12.2f(per s) | Latency: %.4f(ms) |\n", num_of_tables * num_of_DPT / t, t * 1000);
printf("select %10s took %.6f second(s)\n\n", aggreFunc[j], t); printf("select %10s took %.6f second(s)\n\n", aggreFunc[j], t);
taos_free_result(result); taos_free_result(pSql);
} }
fprintf(fp, "\n"); fprintf(fp, "\n");
} }
...@@ -811,10 +805,19 @@ void *readMetric(void *sarg) { ...@@ -811,10 +805,19 @@ void *readMetric(void *sarg) {
void queryDB(TAOS *taos, char *command) { void queryDB(TAOS *taos, char *command) {
int i = 5; int i = 5;
while (i > 0) { TAOS_RES *pSql = NULL;
if (taos_query(taos, command) == 0) break; int32_t code = -1;
while (i > 0 && code != 0) {
pSql = taos_query(taos, command);
code = taos_errno(pSql);
taos_free_result(pSql);
pSql = NULL;
if (code == 0) {
break;
}
i--; i--;
} }
if (i == 0) { if (i == 0) {
fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(taos)); fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(taos));
taos_close(taos); taos_close(taos);
...@@ -947,6 +950,7 @@ void callBack(void *param, TAOS_RES *res, int code) { ...@@ -947,6 +950,7 @@ void callBack(void *param, TAOS_RES *res, int code) {
break; break;
} }
} }
tb_info->timestamp = tmp_time;
taos_query_a(tb_info->taos, buffer, callBack, tb_info); taos_query_a(tb_info->taos, buffer, callBack, tb_info);
......
...@@ -372,14 +372,12 @@ int taosGetTableRecordInfo(char *table, STableRecordInfo *pTableRecordInfo) { ...@@ -372,14 +372,12 @@ int taosGetTableRecordInfo(char *table, STableRecordInfo *pTableRecordInfo) {
memset(pTableRecordInfo, 0, sizeof(STableRecordInfo)); memset(pTableRecordInfo, 0, sizeof(STableRecordInfo));
sprintf(command, "show tables like %s", table); sprintf(command, "show tables like %s", table);
if (taos_query(taos, command) != 0) { TAOS_RES *result = taos_query(taos, command);\
fprintf(stderr, "failed to run command %s\n", command); int32_t code = taos_errno(result);
return -1;
}
result = taos_use_result(taos); if (code != 0) {
if (result == NULL) { fprintf(stderr, "failed to run command %s, error: %s\n", command, taos_errstr(result));
fprintf(stderr, "failed to use result\n"); taos_free_result(result);
return -1; return -1;
} }
...@@ -400,14 +398,12 @@ int taosGetTableRecordInfo(char *table, STableRecordInfo *pTableRecordInfo) { ...@@ -400,14 +398,12 @@ int taosGetTableRecordInfo(char *table, STableRecordInfo *pTableRecordInfo) {
if (isSet) return 0; if (isSet) return 0;
sprintf(command, "show stables like %s", table); sprintf(command, "show stables like %s", table);
if (taos_query(taos, command) != 0) {
fprintf(stderr, "failed to run command %s\n", command);
return -1;
}
result = taos_use_result(taos); result = taos_query(taos, command);
if (result == NULL) { code = taos_errno(result);
fprintf(stderr, "failed to use result\n"); if (code != 0) {
fprintf(stderr, "failed to run command %s, error: %s\n", command, taos_errstr(result));
taos_free_result(result);
return -1; return -1;
} }
...@@ -467,14 +463,11 @@ int taosDumpOut(SDumpArguments *arguments) { ...@@ -467,14 +463,11 @@ int taosDumpOut(SDumpArguments *arguments) {
taosDumpCharset(fp); taosDumpCharset(fp);
sprintf(command, "show databases"); sprintf(command, "show databases");
if (taos_query(taos, command) != 0) { result = taos_query(taos, command);
int32_t code = taos_errno(result);
if (code != 0) {
fprintf(stderr, "failed to run command: %s, reason: %s\n", command, taos_errstr(taos)); fprintf(stderr, "failed to run command: %s, reason: %s\n", command, taos_errstr(taos));
goto _exit_failure; taos_free_result(result);
}
result = taos_use_result(taos);
if (result == NULL) {
fprintf(stderr, "failed to use result\n");
goto _exit_failure; goto _exit_failure;
} }
...@@ -551,7 +544,7 @@ int taosDumpOut(SDumpArguments *arguments) { ...@@ -551,7 +544,7 @@ int taosDumpOut(SDumpArguments *arguments) {
taosDumpCreateDbClause(dbInfos[0], arguments->with_property, fp); taosDumpCreateDbClause(dbInfos[0], arguments->with_property, fp);
sprintf(command, "use %s", dbInfos[0]->name); sprintf(command, "use %s", dbInfos[0]->name);
if (taos_query(taos, command) != 0) { if (taos_query(taos, command) == NULL ) {
fprintf(stderr, "invalid database %s\n", dbInfos[0]->name); fprintf(stderr, "invalid database %s\n", dbInfos[0]->name);
goto _exit_failure; goto _exit_failure;
} }
...@@ -612,7 +605,7 @@ int taosDumpDb(SDbInfo *dbInfo, SDumpArguments *arguments, FILE *fp) { ...@@ -612,7 +605,7 @@ int taosDumpDb(SDbInfo *dbInfo, SDumpArguments *arguments, FILE *fp) {
taosDumpCreateDbClause(dbInfo, arguments->with_property, fp); taosDumpCreateDbClause(dbInfo, arguments->with_property, fp);
sprintf(command, "use %s", dbInfo->name); sprintf(command, "use %s", dbInfo->name);
if (taos_query(taos, command) != 0) { if (taos_errno(taos_query(taos, command)) != 0) {
fprintf(stderr, "invalid database %s\n", dbInfo->name); fprintf(stderr, "invalid database %s\n", dbInfo->name);
return -1; return -1;
} }
...@@ -620,14 +613,11 @@ int taosDumpDb(SDbInfo *dbInfo, SDumpArguments *arguments, FILE *fp) { ...@@ -620,14 +613,11 @@ int taosDumpDb(SDbInfo *dbInfo, SDumpArguments *arguments, FILE *fp) {
fprintf(fp, "USE %s\n\n", dbInfo->name); fprintf(fp, "USE %s\n\n", dbInfo->name);
sprintf(command, "show tables"); sprintf(command, "show tables");
if (taos_query(taos, command) != 0) { result = taos_query(taos,command);
fprintf(stderr, "failed to run command %s\n", command); int32_t code = taos_errno(result);
return -1; if (code != 0) {
} fprintf(stderr, "failed to run command %s, error: %s\n", command, taos_errstr(result));
taos_free_result(result);
result = taos_use_result(taos);
if (result == NULL) {
fprintf(stderr, "failed to use result\n");
return -1; return -1;
} }
...@@ -725,14 +715,11 @@ void taosDumpCreateMTableClause(STableDef *tableDes, char *metric, int numOfCols ...@@ -725,14 +715,11 @@ void taosDumpCreateMTableClause(STableDef *tableDes, char *metric, int numOfCols
TAOS_ROW row = NULL; TAOS_ROW row = NULL;
sprintf(command, "select %s from %s limit 1", tableDes->cols[counter].field, tableDes->name); sprintf(command, "select %s from %s limit 1", tableDes->cols[counter].field, tableDes->name);
if (taos_query(taos, command) != 0) {
fprintf(stderr, "failed to run command %s\n", command);
return;
}
result = taos_use_result(taos); result = taos_query(taos, command);
if (result == NULL) { int32_t code = taos_errno(result);
fprintf(stderr, "failed to use result\n"); if (code != 0) {
fprintf(stderr, "failed to run command %s, error: %s\n", command, taos_errstr(result));
return; return;
} }
...@@ -806,14 +793,12 @@ int taosGetTableDes(char *table, STableDef *tableDes) { ...@@ -806,14 +793,12 @@ int taosGetTableDes(char *table, STableDef *tableDes) {
int count = 0; int count = 0;
sprintf(command, "describe %s", table); sprintf(command, "describe %s", table);
if (taos_query(taos, command) != 0) {
fprintf(stderr, "failed to run command %s\n", command);
return -1;
}
result = taos_use_result(taos); result = taos_query(taos, command);
if (result == NULL) { int32_t code = taos_errno(result);
fprintf(stderr, "failed to use result\n"); if (code != 0) {
fprintf(stderr, "failed to run command %s, error: %s\n", command, taos_errstr(result));
taos_free_result(result);
return -1; return -1;
} }
...@@ -889,14 +874,11 @@ int32_t taosDumpMetric(char *metric, SDumpArguments *arguments, FILE *fp) { ...@@ -889,14 +874,11 @@ int32_t taosDumpMetric(char *metric, SDumpArguments *arguments, FILE *fp) {
strcpy(tableRecord.metric, metric); strcpy(tableRecord.metric, metric);
sprintf(command, "select tbname from %s", metric); sprintf(command, "select tbname from %s", metric);
if (taos_query(taos, command) != 0) { result = taos_query(taos, command);
fprintf(stderr, "failed to run command %s\n", command); int32_t code = taos_errno(result);
return -1; if (code != 0) {
} fprintf(stderr, "failed to run command %s, error: %s\n", command, taos_errstr(result));
taos_free_result(result);
result = taos_use_result(taos);
if (result == NULL) {
fprintf(stderr, "failed to use result\n");
return -1; return -1;
} }
...@@ -942,18 +924,16 @@ int taosDumpTableData(FILE *fp, char *tbname, SDumpArguments *arguments) { ...@@ -942,18 +924,16 @@ int taosDumpTableData(FILE *fp, char *tbname, SDumpArguments *arguments) {
sprintf(command, "select * from %s where _c0 >= %" PRId64 " and _c0 <= %" PRId64 " order by _c0 asc", tbname, arguments->start_time, sprintf(command, "select * from %s where _c0 >= %" PRId64 " and _c0 <= %" PRId64 " order by _c0 asc", tbname, arguments->start_time,
arguments->end_time); arguments->end_time);
if (taos_query(taos, command) != 0) {
fprintf(stderr, "failed to run command %s, reason: %s\n", command, taos_errstr(taos)); result = taos_query(taos, command);
return -1; int32_t code = taos_errno(result);
} if (code != 0) {
fprintf(stderr, "failed to run command %s, reason: %s\n", command, taos_errstr(result));
result = taos_use_result(taos); taos_free_result(result);
if (result == NULL) {
fprintf(stderr, "failed to use result\n");
return -1; return -1;
} }
numFields = taos_field_count(taos); numFields = taos_field_count(result);
assert(numFields > 0); assert(numFields > 0);
TAOS_FIELD *fields = taos_fetch_fields(result); TAOS_FIELD *fields = taos_fetch_fields(result);
tbuf = (char *)malloc(COMMAND_SIZE); tbuf = (char *)malloc(COMMAND_SIZE);
...@@ -1194,7 +1174,7 @@ int taosDumpIn(SDumpArguments *arguments) { ...@@ -1194,7 +1174,7 @@ int taosDumpIn(SDumpArguments *arguments) {
tcommand = command; tcommand = command;
} }
taosReplaceCtrlChar(tcommand); taosReplaceCtrlChar(tcommand);
if (taos_query(taos, tcommand) != 0) if (taos_query(taos, tcommand) == NULL)
fprintf(stderr, "linenu: %" PRId64 " failed to run command %s reason:%s \ncontinue...\n", linenu, command, fprintf(stderr, "linenu: %" PRId64 " failed to run command %s reason:%s \ncontinue...\n", linenu, command,
taos_errstr(taos)); taos_errstr(taos));
...@@ -1242,9 +1222,14 @@ int taosDumpIn(SDumpArguments *arguments) { ...@@ -1242,9 +1222,14 @@ int taosDumpIn(SDumpArguments *arguments) {
tcommand = command; tcommand = command;
} }
taosReplaceCtrlChar(tcommand); taosReplaceCtrlChar(tcommand);
if (taos_query(taos, tcommand) != 0) result = taos_query(taos, tcommand);
int32_t code = taos_errno(result);
if (code != 0)
{
fprintf(stderr, "linenu:%" PRId64 " failed to run command %s reason: %s \ncontinue...\n", linenu, command, fprintf(stderr, "linenu:%" PRId64 " failed to run command %s reason: %s \ncontinue...\n", linenu, command,
taos_errstr(taos)); taos_errstr(taos));
}
taos_free_result(result);
} }
pstr = command; pstr = command;
...@@ -1265,7 +1250,7 @@ int taosDumpIn(SDumpArguments *arguments) { ...@@ -1265,7 +1250,7 @@ int taosDumpIn(SDumpArguments *arguments) {
tcommand = command; tcommand = command;
} }
taosReplaceCtrlChar(lcommand); taosReplaceCtrlChar(lcommand);
if (taos_query(taos, tcommand) != 0) if (taos_query(taos, tcommand) == NULL)
fprintf(stderr, "linenu:%" PRId64 " failed to run command %s reason:%s \ncontinue...\n", linenu, command, fprintf(stderr, "linenu:%" PRId64 " failed to run command %s reason:%s \ncontinue...\n", linenu, command,
taos_errstr(taos)); taos_errstr(taos));
} }
......
...@@ -245,10 +245,10 @@ static void taosGetSystemLocale() { // get and set default locale ...@@ -245,10 +245,10 @@ static void taosGetSystemLocale() { // get and set default locale
strncpy(tsCharset, revisedCharset, tListLen(tsCharset)); strncpy(tsCharset, revisedCharset, tListLen(tsCharset));
free(revisedCharset); free(revisedCharset);
uError("charset not configured, set to system default:%s", tsCharset); uWarn("charset not configured, set to system default:%s", tsCharset);
} else { } else {
strcpy(tsCharset, "UTF-8"); strcpy(tsCharset, "UTF-8");
uError("can't get locale and charset from system, set it to UTF-8"); uWarn("can't get locale and charset from system, set it to UTF-8");
} }
} }
} }
......
...@@ -58,10 +58,10 @@ void httpProcessMultiSqlRetrieveCallBack(void *param, TAOS_RES *result, int numO ...@@ -58,10 +58,10 @@ void httpProcessMultiSqlRetrieveCallBack(void *param, TAOS_RES *result, int numO
if (numOfRows < 0) { if (numOfRows < 0) {
httpError("context:%p, fd:%d, ip:%s, user:%s, process pos:%d, retrieve failed code:%s, sql:%s", httpError("context:%p, fd:%d, ip:%s, user:%s, process pos:%d, retrieve failed code:%s, sql:%s",
pContext, pContext->fd, pContext->ipstr, pContext->user, multiCmds->pos, tstrerror(numOfRows), sql); pContext, pContext->fd, pContext->ipstr, pContext->user, multiCmds->pos, tstrerror(numOfRows), sql);
} else { }
taos_free_result(result);
} taos_free_result(result);
if (singleCmd->cmdReturnType == HTTP_CMD_RETURN_TYPE_WITH_RETURN && encode->stopJsonFp) { if (singleCmd->cmdReturnType == HTTP_CMD_RETURN_TYPE_WITH_RETURN && encode->stopJsonFp) {
(encode->stopJsonFp)(pContext, singleCmd); (encode->stopJsonFp)(pContext, singleCmd);
} }
...@@ -103,12 +103,15 @@ void httpProcessMultiSqlCallBack(void *param, TAOS_RES *result, int code) { ...@@ -103,12 +103,15 @@ void httpProcessMultiSqlCallBack(void *param, TAOS_RES *result, int code) {
} }
multiCmds->pos++; multiCmds->pos++;
httpProcessMultiSql(pContext); httpProcessMultiSql(pContext);
taos_free_result(result);
return; return;
} }
if (result == NULL) { int num_fields = taos_field_count(result);
if (num_fields == 0) {
// not select or show commands // not select or show commands
int affectRows = code; int affectRows = taos_affected_rows(result);
httpTrace("context:%p, fd:%d, ip:%s, user:%s, process pos:%d, affect rows:%d, sql:%s", httpTrace("context:%p, fd:%d, ip:%s, user:%s, process pos:%d, affect rows:%d, sql:%s",
pContext, pContext->fd, pContext->ipstr, pContext->user, multiCmds->pos, affectRows, sql); pContext, pContext->fd, pContext->ipstr, pContext->user, multiCmds->pos, affectRows, sql);
...@@ -132,6 +135,7 @@ void httpProcessMultiSqlCallBack(void *param, TAOS_RES *result, int code) { ...@@ -132,6 +135,7 @@ void httpProcessMultiSqlCallBack(void *param, TAOS_RES *result, int code) {
multiCmds->pos++; multiCmds->pos++;
} }
taos_free_result(result);
httpProcessMultiSql(pContext); httpProcessMultiSql(pContext);
} else { } else {
httpTrace("context:%p, fd:%d, ip:%s, user:%s, process pos:%d, start retrieve, sql:%s", httpTrace("context:%p, fd:%d, ip:%s, user:%s, process pos:%d, start retrieve, sql:%s",
...@@ -212,9 +216,9 @@ void httpProcessSingleSqlRetrieveCallBack(void *param, TAOS_RES *result, int num ...@@ -212,9 +216,9 @@ void httpProcessSingleSqlRetrieveCallBack(void *param, TAOS_RES *result, int num
if (numOfRows < 0) { if (numOfRows < 0) {
httpError("context:%p, fd:%d, ip:%s, user:%s, retrieve failed, code:%s", pContext, pContext->fd, pContext->ipstr, httpError("context:%p, fd:%d, ip:%s, user:%s, retrieve failed, code:%s", pContext, pContext->fd, pContext->ipstr,
pContext->user, tstrerror(numOfRows)); pContext->user, tstrerror(numOfRows));
} else { }
taos_free_result(result);
} taos_free_result(result);
if (encode->stopJsonFp) { if (encode->stopJsonFp) {
(encode->stopJsonFp)(pContext, &pContext->singleCmd); (encode->stopJsonFp)(pContext, &pContext->singleCmd);
...@@ -247,12 +251,14 @@ void httpProcessSingleSqlCallBack(void *param, TAOS_RES *result, int code) { ...@@ -247,12 +251,14 @@ void httpProcessSingleSqlCallBack(void *param, TAOS_RES *result, int code) {
pContext, pContext->fd, pContext->ipstr, pContext->user, pContext->session->taos, tstrerror(code), pObj); pContext, pContext->fd, pContext->ipstr, pContext->user, pContext->session->taos, tstrerror(code), pObj);
httpSendTaosdErrorResp(pContext, code); httpSendTaosdErrorResp(pContext, code);
} }
taos_free_result(result);
return; return;
} }
if (result == NULL) { int num_fields = taos_field_count(result);
if (num_fields == 0) {
// not select or show commands // not select or show commands
int affectRows = code; int affectRows = taos_affected_rows(result);
httpTrace("context:%p, fd:%d, ip:%s, user:%s, affect rows:%d, stop query, sqlObj:%p", httpTrace("context:%p, fd:%d, ip:%s, user:%s, affect rows:%d, stop query, sqlObj:%p",
pContext, pContext->fd, pContext->ipstr, pContext->user, affectRows, result); pContext, pContext->fd, pContext->ipstr, pContext->user, affectRows, result);
...@@ -269,6 +275,7 @@ void httpProcessSingleSqlCallBack(void *param, TAOS_RES *result, int code) { ...@@ -269,6 +275,7 @@ void httpProcessSingleSqlCallBack(void *param, TAOS_RES *result, int code) {
(encode->stopJsonFp)(pContext, &pContext->singleCmd); (encode->stopJsonFp)(pContext, &pContext->singleCmd);
} }
taos_free_result(result);
httpCloseContextByApp(pContext); httpCloseContextByApp(pContext);
} else { } else {
httpTrace("context:%p, fd:%d, ip:%s, user:%s, start retrieve", pContext, pContext->fd, pContext->ipstr, httpTrace("context:%p, fd:%d, ip:%s, user:%s, start retrieve", pContext, pContext->fd, pContext->ipstr,
......
...@@ -116,11 +116,14 @@ typedef struct SQueryCostInfo { ...@@ -116,11 +116,14 @@ typedef struct SQueryCostInfo {
uint64_t loadDataInCacheSize; uint64_t loadDataInCacheSize;
uint64_t loadDataTime; uint64_t loadDataTime;
uint64_t dataInRows; uint64_t totalRows;
uint64_t checkRows; uint64_t totalCheckedRows;
uint32_t dataBlocks; uint32_t totalBlocks;
uint32_t loadBlocks;
uint32_t loadBlockStatis; uint32_t loadBlockStatis;
uint32_t discardBlocks; uint32_t discardBlocks;
uint64_t elapsedTime;
uint64_t computTime;
} SQueryCostInfo; } SQueryCostInfo;
typedef struct SGroupItem { typedef struct SGroupItem {
...@@ -168,7 +171,7 @@ typedef struct SQueryRuntimeEnv { ...@@ -168,7 +171,7 @@ typedef struct SQueryRuntimeEnv {
SWindowResInfo windowResInfo; SWindowResInfo windowResInfo;
STSBuf* pTSBuf; STSBuf* pTSBuf;
STSCursor cur; STSCursor cur;
SQueryCostInfo summary; SQueryCostInfo summary;
bool stableQuery; // super table query or not bool stableQuery; // super table query or not
void* pQueryHandle; void* pQueryHandle;
void* pSecQueryHandle; // another thread for void* pSecQueryHandle; // another thread for
...@@ -177,8 +180,6 @@ typedef struct SQueryRuntimeEnv { ...@@ -177,8 +180,6 @@ typedef struct SQueryRuntimeEnv {
typedef struct SQInfo { typedef struct SQInfo {
void* signature; void* signature;
TSKEY startTime;
TSKEY elapsedTime;
int32_t pointsInterpo; int32_t pointsInterpo;
int32_t code; // error code to returned to client int32_t code; // error code to returned to client
sem_t dataReady; sem_t dataReady;
......
...@@ -1183,6 +1183,7 @@ static int32_t tableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBl ...@@ -1183,6 +1183,7 @@ static int32_t tableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBl
STableQueryInfo* pTableQInfo = pQuery->current; STableQueryInfo* pTableQInfo = pQuery->current;
SWindowResInfo* pWindowResInfo = &pRuntimeEnv->windowResInfo; SWindowResInfo* pWindowResInfo = &pRuntimeEnv->windowResInfo;
pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : pDataBlockInfo->rows - 1;
if (pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || isGroupbyNormalCol(pQuery->pGroupbyExpr)) { if (pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
rowwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, pDataBlock); rowwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, pDataBlock);
...@@ -1190,10 +1191,10 @@ static int32_t tableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBl ...@@ -1190,10 +1191,10 @@ static int32_t tableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBl
blockwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, searchFn, pDataBlock); blockwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, searchFn, pDataBlock);
} }
// update the lastkey of current table
TSKEY lastKey = QUERY_IS_ASC_QUERY(pQuery) ? pDataBlockInfo->window.ekey : pDataBlockInfo->window.skey; TSKEY lastKey = QUERY_IS_ASC_QUERY(pQuery) ? pDataBlockInfo->window.ekey : pDataBlockInfo->window.skey;
pTableQInfo->lastKey = lastKey + GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order); pTableQInfo->lastKey = lastKey + GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
// interval query with limit applied // interval query with limit applied
int32_t numOfRes = 0; int32_t numOfRes = 0;
...@@ -2013,7 +2014,7 @@ SArray *loadDataBlockOnDemand(SQueryRuntimeEnv *pRuntimeEnv, void* pQueryHandle, ...@@ -2013,7 +2014,7 @@ SArray *loadDataBlockOnDemand(SQueryRuntimeEnv *pRuntimeEnv, void* pQueryHandle,
if (*pStatis == NULL) { // data block statistics does not exist, load data block if (*pStatis == NULL) { // data block statistics does not exist, load data block
pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL); pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL);
pRuntimeEnv->summary.checkRows += pBlockInfo->rows; pRuntimeEnv->summary.totalCheckedRows += pBlockInfo->rows;
} }
} else { } else {
assert(r == BLK_DATA_ALL_NEEDED); assert(r == BLK_DATA_ALL_NEEDED);
...@@ -2032,7 +2033,7 @@ SArray *loadDataBlockOnDemand(SQueryRuntimeEnv *pRuntimeEnv, void* pQueryHandle, ...@@ -2032,7 +2033,7 @@ SArray *loadDataBlockOnDemand(SQueryRuntimeEnv *pRuntimeEnv, void* pQueryHandle,
// return DISK_DATA_DISCARDED; // return DISK_DATA_DISCARDED;
} }
pRuntimeEnv->summary.checkRows += pBlockInfo->rows; pRuntimeEnv->summary.totalCheckedRows += pBlockInfo->rows;
pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL); pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL);
} }
...@@ -2149,7 +2150,7 @@ static int64_t doScanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv) { ...@@ -2149,7 +2150,7 @@ static int64_t doScanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv) {
TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle; TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle;
while (tsdbNextDataBlock(pQueryHandle)) { while (tsdbNextDataBlock(pQueryHandle)) {
pRuntimeEnv->summary.dataBlocks += 1; pRuntimeEnv->summary.totalBlocks += 1;
if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) { if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
return 0; return 0;
} }
...@@ -2185,12 +2186,10 @@ static int64_t doScanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv) { ...@@ -2185,12 +2186,10 @@ static int64_t doScanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv) {
ensureOutputBuffer(pRuntimeEnv, &blockInfo); ensureOutputBuffer(pRuntimeEnv, &blockInfo);
SDataStatis *pStatis = NULL; SDataStatis *pStatis = NULL;
pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : blockInfo.rows - 1;
SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis); SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis);
int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, pStatis, binarySearchForKey, pDataBlock); int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, pStatis, binarySearchForKey, pDataBlock);
pRuntimeEnv->summary.dataInRows += blockInfo.rows; pRuntimeEnv->summary.totalRows += blockInfo.rows;
qTrace("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d, lastKey:%"PRId64, GET_QINFO_ADDR(pRuntimeEnv), qTrace("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d, lastKey:%"PRId64, GET_QINFO_ADDR(pRuntimeEnv),
blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, numOfRes, pQuery->current->lastKey); blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, numOfRes, pQuery->current->lastKey);
...@@ -3253,7 +3252,7 @@ void destroyTableQueryInfo(STableQueryInfo *pTableQueryInfo, int32_t numOfCols) ...@@ -3253,7 +3252,7 @@ void destroyTableQueryInfo(STableQueryInfo *pTableQueryInfo, int32_t numOfCols)
free(pTableQueryInfo); free(pTableQueryInfo);
} }
void restoreIntervalQueryRange(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo) { void setCurrentQueryTable(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo) {
SQuery *pQuery = pRuntimeEnv->pQuery; SQuery *pQuery = pRuntimeEnv->pQuery;
pQuery->current = pTableQueryInfo; pQuery->current = pTableQueryInfo;
...@@ -3322,7 +3321,7 @@ static void setWindowResOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult * ...@@ -3322,7 +3321,7 @@ static void setWindowResOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *
int32_t setAdditionalInfo(SQInfo *pQInfo, STableId* pTableId, STableQueryInfo *pTableQueryInfo) { int32_t setAdditionalInfo(SQInfo *pQInfo, STableId* pTableId, STableQueryInfo *pTableQueryInfo) {
SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv; SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
assert(pTableQueryInfo->lastKey >= 0); assert(pTableQueryInfo->lastKey >= TSKEY_INITIAL_VAL);
setTagVal(pRuntimeEnv, pTableId, pQInfo->tsdb); setTagVal(pRuntimeEnv, pTableId, pQInfo->tsdb);
...@@ -3534,10 +3533,11 @@ static void updateWindowResNumOfRes(SQueryRuntimeEnv *pRuntimeEnv, STableQueryIn ...@@ -3534,10 +3533,11 @@ static void updateWindowResNumOfRes(SQueryRuntimeEnv *pRuntimeEnv, STableQueryIn
} }
} }
void stableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo, void stableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pDataBlockInfo, SDataStatis *pStatis,
SDataBlockInfo *pDataBlockInfo, SDataStatis *pStatis, SArray *pDataBlock, SArray *pDataBlock, __block_search_fn_t searchFn) {
__block_search_fn_t searchFn) {
SQuery * pQuery = pRuntimeEnv->pQuery; SQuery * pQuery = pRuntimeEnv->pQuery;
STableQueryInfo* pTableQueryInfo = pQuery->current;
SWindowResInfo * pWindowResInfo = &pTableQueryInfo->windowResInfo; SWindowResInfo * pWindowResInfo = &pTableQueryInfo->windowResInfo;
pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : pDataBlockInfo->rows - 1; pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : pDataBlockInfo->rows - 1;
...@@ -3670,10 +3670,8 @@ int32_t doFillGapsInResults(SQueryRuntimeEnv* pRuntimeEnv, tFilePage **pDst, int ...@@ -3670,10 +3670,8 @@ int32_t doFillGapsInResults(SQueryRuntimeEnv* pRuntimeEnv, tFilePage **pDst, int
} }
} }
void queryCostStatis(SQInfo *pQInfo) { static void queryCostStatis(SQInfo *pQInfo) {
SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv; SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
// SQuery *pQuery = pRuntimeEnv->pQuery;
SQueryCostInfo *pSummary = &pRuntimeEnv->summary; SQueryCostInfo *pSummary = &pRuntimeEnv->summary;
// if (pRuntimeEnv->pResultBuf == NULL) { // if (pRuntimeEnv->pResultBuf == NULL) {
//// pSummary->tmpBufferInDisk = 0; //// pSummary->tmpBufferInDisk = 0;
...@@ -3693,8 +3691,9 @@ void queryCostStatis(SQInfo *pQInfo) { ...@@ -3693,8 +3691,9 @@ void queryCostStatis(SQInfo *pQInfo) {
// pQInfo, pSummary->readDiskBlocks, pSummary->totalBlockSize, pSummary->loadBlocksUs / 1000.0, // pQInfo, pSummary->readDiskBlocks, pSummary->totalBlockSize, pSummary->loadBlocksUs / 1000.0,
// pSummary->skippedFileBlocks, pSummary->totalGenData); // pSummary->skippedFileBlocks, pSummary->totalGenData);
qTrace("QInfo:%p cost: check blocks:%d, statis:%d, rows:%"PRId64", check rows:%"PRId64, pQInfo, pSummary->dataBlocks, qTrace("QInfo:%p :cost summary: elpased time:%"PRId64" us, total blocks:%d, use block statis:%d, use block data:%d, "
pSummary->loadBlockStatis, pSummary->dataInRows, pSummary->checkRows); "total rows:%"PRId64 ", check rows:%"PRId64, pQInfo, pSummary->elapsedTime, pSummary->totalBlocks,
pSummary->loadBlockStatis, pSummary->loadBlocks, pSummary->totalRows, pSummary->totalCheckedRows);
// qTrace("QInfo:%p cost: temp file:%d Bytes", pQInfo, pSummary->tmpBufferInDisk); // qTrace("QInfo:%p cost: temp file:%d Bytes", pQInfo, pSummary->tmpBufferInDisk);
// //
...@@ -4090,12 +4089,13 @@ static void enableExecutionForNextTable(SQueryRuntimeEnv *pRuntimeEnv) { ...@@ -4090,12 +4089,13 @@ static void enableExecutionForNextTable(SQueryRuntimeEnv *pRuntimeEnv) {
static int64_t queryOnDataBlocks(SQInfo *pQInfo) { static int64_t queryOnDataBlocks(SQInfo *pQInfo) {
SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv; SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
SQuery * pQuery = pRuntimeEnv->pQuery; SQuery * pQuery = pRuntimeEnv->pQuery;
SQueryCostInfo* summary = &pRuntimeEnv->summary;
int64_t st = taosGetTimestampMs(); int64_t st = taosGetTimestampMs();
TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle; TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle;
while (tsdbNextDataBlock(pQueryHandle)) { while (tsdbNextDataBlock(pQueryHandle)) {
summary->totalBlocks += 1;
if (isQueryKilled(pQInfo)) { if (isQueryKilled(pQInfo)) {
break; break;
} }
...@@ -4127,10 +4127,9 @@ static int64_t queryOnDataBlocks(SQInfo *pQInfo) { ...@@ -4127,10 +4127,9 @@ static int64_t queryOnDataBlocks(SQInfo *pQInfo) {
} }
assert(pTableQueryInfo != NULL); assert(pTableQueryInfo != NULL);
restoreIntervalQueryRange(pRuntimeEnv, pTableQueryInfo); setCurrentQueryTable(pRuntimeEnv, pTableQueryInfo);
SDataStatis *pStatis = NULL; SDataStatis *pStatis = NULL;
SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis); SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis);
if (!isIntervalQuery(pQuery)) { if (!isIntervalQuery(pQuery)) {
...@@ -4139,15 +4138,14 @@ static int64_t queryOnDataBlocks(SQInfo *pQInfo) { ...@@ -4139,15 +4138,14 @@ static int64_t queryOnDataBlocks(SQInfo *pQInfo) {
} else { // interval query } else { // interval query
TSKEY nextKey = blockInfo.window.skey; TSKEY nextKey = blockInfo.window.skey;
setIntervalQueryRange(pQInfo, nextKey); setIntervalQueryRange(pQInfo, nextKey);
int32_t ret = setAdditionalInfo(pQInfo, &pTableQueryInfo->id, pTableQueryInfo); /*int32_t ret = */setAdditionalInfo(pQInfo, &pTableQueryInfo->id, pTableQueryInfo);
if (ret != TSDB_CODE_SUCCESS) {
pQInfo->code = ret;
return taosGetTimestampMs() - st;
}
} }
stableApplyFunctionsOnBlock(pRuntimeEnv, pTableQueryInfo, &blockInfo, pStatis, pDataBlock, binarySearchForKey); summary->totalRows += blockInfo.rows;
stableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, pStatis, pDataBlock, binarySearchForKey);
qTrace("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, lastKey:%"PRId64, GET_QINFO_ADDR(pRuntimeEnv),
blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, pQuery->current->lastKey);
} }
int64_t et = taosGetTimestampMs(); int64_t et = taosGetTimestampMs();
...@@ -4509,10 +4507,6 @@ static void multiTableQueryProcess(SQInfo *pQInfo) { ...@@ -4509,10 +4507,6 @@ static void multiTableQueryProcess(SQInfo *pQInfo) {
copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult); copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
} }
if (pQuery->rec.rows == 0) {
// queryCostStatis(pSupporter);
}
qTrace("QInfo:%p current:%lld, total:%lld", pQInfo, pQuery->rec.rows, pQuery->rec.total); qTrace("QInfo:%p current:%lld, total:%lld", pQInfo, pQuery->rec.rows, pQuery->rec.total);
return; return;
} }
...@@ -4795,7 +4789,6 @@ static void tableQueryImpl(SQInfo *pQInfo) { ...@@ -4795,7 +4789,6 @@ static void tableQueryImpl(SQInfo *pQInfo) {
} }
qTrace("QInfo:%p query over, %d rows are returned", pQInfo, pQuery->rec.total); qTrace("QInfo:%p query over, %d rows are returned", pQInfo, pQuery->rec.total);
queryCostStatis(pQInfo);
return; return;
} }
...@@ -4818,7 +4811,7 @@ static void tableQueryImpl(SQInfo *pQInfo) { ...@@ -4818,7 +4811,7 @@ static void tableQueryImpl(SQInfo *pQInfo) {
} }
// record the total elapsed time // record the total elapsed time
pQInfo->elapsedTime += (taosGetTimestampUs() - st); pRuntimeEnv->summary.elapsedTime += (taosGetTimestampUs() - st);
assert(pQInfo->groupInfo.numOfTables == 1); assert(pQInfo->groupInfo.numOfTables == 1);
/* check if query is killed or not */ /* check if query is killed or not */
...@@ -4827,10 +4820,6 @@ static void tableQueryImpl(SQInfo *pQInfo) { ...@@ -4827,10 +4820,6 @@ static void tableQueryImpl(SQInfo *pQInfo) {
} else {// todo set the table uid and tid in log } else {// todo set the table uid and tid in log
qTrace("QInfo:%p query paused, %" PRId64 " rows returned, numOfTotal:%" PRId64 " rows", qTrace("QInfo:%p query paused, %" PRId64 " rows returned, numOfTotal:%" PRId64 " rows",
pQInfo, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows); pQInfo, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows);
if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
queryCostStatis(pQInfo);
}
} }
} }
...@@ -4852,13 +4841,10 @@ static void stableQueryImpl(SQInfo *pQInfo) { ...@@ -4852,13 +4841,10 @@ static void stableQueryImpl(SQInfo *pQInfo) {
} }
// record the total elapsed time // record the total elapsed time
pQInfo->elapsedTime += (taosGetTimestampUs() - st); pQInfo->runtimeEnv.summary.elapsedTime += (taosGetTimestampUs() - st);
// taosFillSetStartInfo(&pQInfo->runtimeEnv.pFillInfo, pQuery->size, pQInfo->query.fillType);
if (pQuery->rec.rows == 0) { if (pQuery->rec.rows == 0) {
qTrace("QInfo:%p over, %d tables queried, %d points are returned", pQInfo, pQInfo->groupInfo.numOfTables, qTrace("QInfo:%p over, %d tables queried, %d rows are returned", pQInfo, pQInfo->groupInfo.numOfTables, pQuery->rec.total);
pQuery->rec.total);
// queryCostStatis(pSupporter);
} }
} }
...@@ -5838,9 +5824,11 @@ int32_t qCreateQueryInfo(void *tsdb, int32_t vgId, SQueryTableMsg *pQueryMsg, qi ...@@ -5838,9 +5824,11 @@ int32_t qCreateQueryInfo(void *tsdb, int32_t vgId, SQueryTableMsg *pQueryMsg, qi
numOfGroupByCols = 0; numOfGroupByCols = 0;
} }
// todo handle the error code = tsdbQuerySTableByTagCond(tsdb, id->uid, tagCond, pQueryMsg->tagCondLen, pQueryMsg->tagNameRelType, tbnameCond, &groupInfo, pGroupColIndex,
/*int32_t ret =*/tsdbQuerySTableByTagCond(tsdb, id->uid, tagCond, pQueryMsg->tagCondLen, pQueryMsg->tagNameRelType, tbnameCond, &groupInfo, pGroupColIndex,
numOfGroupByCols); numOfGroupByCols);
if (code != TSDB_CODE_SUCCESS) {
goto _over;
}
} else { } else {
SArray* pTableGroup = taosArrayInit(1, POINTER_BYTES); SArray* pTableGroup = taosArrayInit(1, POINTER_BYTES);
...@@ -5870,7 +5858,7 @@ _over: ...@@ -5870,7 +5858,7 @@ _over:
taosArrayDestroy(pTableIdList); taosArrayDestroy(pTableIdList);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
tfree(*pQInfo); //pQInfo already freed in initQInfo, but *pQInfo may not pointer to null;
*pQInfo = NULL; *pQInfo = NULL;
} }
...@@ -5880,6 +5868,9 @@ _over: ...@@ -5880,6 +5868,9 @@ _over:
void qDestroyQueryInfo(qinfo_t pQInfo) { void qDestroyQueryInfo(qinfo_t pQInfo) {
qTrace("QInfo:%p query completed", pQInfo); qTrace("QInfo:%p query completed", pQInfo);
// print the query cost summary
queryCostStatis(pQInfo);
freeQInfo(pQInfo); freeQInfo(pQInfo);
} }
...@@ -5956,6 +5947,7 @@ int32_t qDumpRetrieveResult(qinfo_t qinfo, SRetrieveTableRsp **pRsp, int32_t *co ...@@ -5956,6 +5947,7 @@ int32_t qDumpRetrieveResult(qinfo_t qinfo, SRetrieveTableRsp **pRsp, int32_t *co
return TSDB_CODE_INVALID_QHANDLE; return TSDB_CODE_INVALID_QHANDLE;
} }
SQueryRuntimeEnv* pRuntimeEnv = &pQInfo->runtimeEnv;
SQuery *pQuery = pQInfo->runtimeEnv.pQuery; SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
size_t size = getResultSize(pQInfo, &pQuery->rec.rows); size_t size = getResultSize(pQInfo, &pQuery->rec.rows);
size += sizeof(int32_t); size += sizeof(int32_t);
...@@ -5969,7 +5961,7 @@ int32_t qDumpRetrieveResult(qinfo_t qinfo, SRetrieveTableRsp **pRsp, int32_t *co ...@@ -5969,7 +5961,7 @@ int32_t qDumpRetrieveResult(qinfo_t qinfo, SRetrieveTableRsp **pRsp, int32_t *co
int32_t code = pQInfo->code; int32_t code = pQInfo->code;
if (code == TSDB_CODE_SUCCESS) { if (code == TSDB_CODE_SUCCESS) {
(*pRsp)->offset = htobe64(pQuery->limit.offset); (*pRsp)->offset = htobe64(pQuery->limit.offset);
(*pRsp)->useconds = htobe64(pQInfo->elapsedTime); (*pRsp)->useconds = htobe64(pRuntimeEnv->summary.elapsedTime);
} else { } else {
(*pRsp)->offset = 0; (*pRsp)->offset = 0;
(*pRsp)->useconds = 0; (*pRsp)->useconds = 0;
......
...@@ -110,6 +110,14 @@ void taosDestoryFillInfo(SFillInfo* pFillInfo) { ...@@ -110,6 +110,14 @@ void taosDestoryFillInfo(SFillInfo* pFillInfo) {
tfree(pFillInfo->prevValues); tfree(pFillInfo->prevValues);
tfree(pFillInfo->nextValues); tfree(pFillInfo->nextValues);
tfree(pFillInfo->pTags); tfree(pFillInfo->pTags);
for(int32_t i = 0; i < pFillInfo->numOfCols; ++i) {
tfree(pFillInfo->pData[i]);
}
tfree(pFillInfo->pData);
tfree(pFillInfo->pFillCol);
tfree(pFillInfo); tfree(pFillInfo);
} }
...@@ -247,7 +255,7 @@ int taosDoLinearInterpolation(int32_t type, SPoint* point1, SPoint* point2, SPoi ...@@ -247,7 +255,7 @@ int taosDoLinearInterpolation(int32_t type, SPoint* point1, SPoint* point2, SPoi
} }
static void setTagsValue(SFillInfo* pColInfo, tFilePage** data, char** pTags, int32_t start, int32_t num) { static void setTagsValue(SFillInfo* pColInfo, tFilePage** data, char** pTags, int32_t start, int32_t num) {
for (int32_t j = 0, i = start; i < pColInfo->numOfCols + pColInfo->numOfTags; ++i, ++j) { for (int32_t j = 0, i = start; i < pColInfo->numOfCols; ++i, ++j) {
SFillColInfo* pCol = &pColInfo->pFillCol[i]; SFillColInfo* pCol = &pColInfo->pFillCol[i];
char* val1 = elePtrAt(data[i]->data, pCol->col.bytes, num); char* val1 = elePtrAt(data[i]->data, pCol->col.bytes, num);
...@@ -344,7 +352,7 @@ static void doInterpoResultImpl(SFillInfo* pFillInfo, tFilePage** data, int32_t* ...@@ -344,7 +352,7 @@ static void doInterpoResultImpl(SFillInfo* pFillInfo, tFilePage** data, int32_t*
setTagsValue(pFillInfo, data, pTags, numOfValCols, *num); setTagsValue(pFillInfo, data, pTags, numOfValCols, *num);
} }
} else { /* default value interpolation */ } else { /* fill the default value */
for (int32_t i = 1; i < numOfValCols; ++i) { for (int32_t i = 1; i < numOfValCols; ++i) {
SFillColInfo* pCol = &pFillInfo->pFillCol[i]; SFillColInfo* pCol = &pFillInfo->pFillCol[i];
......
...@@ -193,7 +193,7 @@ TsdbQueryHandleT* tsdbQueryTables(TsdbRepoT* tsdb, STsdbQueryCond* pCond, STable ...@@ -193,7 +193,7 @@ TsdbQueryHandleT* tsdbQueryTables(TsdbRepoT* tsdb, STsdbQueryCond* pCond, STable
} }
} }
uTrace("%p total numOfTable:%d in query", pQueryHandle, taosArrayGetSize(pQueryHandle->pTableCheckInfo)); tsdbTrace("%p total numOfTable:%d in query", pQueryHandle, taosArrayGetSize(pQueryHandle->pTableCheckInfo));
tsdbInitDataBlockLoadInfo(&pQueryHandle->dataBlockLoadInfo); tsdbInitDataBlockLoadInfo(&pQueryHandle->dataBlockLoadInfo);
tsdbInitCompBlockLoadInfo(&pQueryHandle->compBlockLoadInfo); tsdbInitCompBlockLoadInfo(&pQueryHandle->compBlockLoadInfo);
...@@ -282,10 +282,10 @@ static bool initTableMemIterator(STsdbQueryHandle* pHandle, STableCheckInfo* pCh ...@@ -282,10 +282,10 @@ static bool initTableMemIterator(STsdbQueryHandle* pHandle, STableCheckInfo* pCh
SDataRow row = SL_GET_NODE_DATA(node); SDataRow row = SL_GET_NODE_DATA(node);
TSKEY key = dataRowKey(row); // first timestamp in buffer TSKEY key = dataRowKey(row); // first timestamp in buffer
uTrace("%p uid:%" PRId64", tid:%d check data in mem from skey:%" PRId64 ", order:%d, %p", pHandle, tsdbTrace("%p uid:%" PRId64", tid:%d check data in mem from skey:%" PRId64 ", order:%d, %p", pHandle,
pCheckInfo->tableId.uid, pCheckInfo->tableId.tid, key, order, pHandle->qinfo); pCheckInfo->tableId.uid, pCheckInfo->tableId.tid, key, order, pHandle->qinfo);
} else { } else {
uTrace("%p uid:%" PRId64 ", tid:%d no data in mem", pHandle, pCheckInfo->tableId.uid, pCheckInfo->tableId.tid); tsdbTrace("%p uid:%" PRId64 ", tid:%d no data in mem", pHandle, pCheckInfo->tableId.uid, pCheckInfo->tableId.tid);
} }
if (!imemEmpty) { if (!imemEmpty) {
...@@ -294,10 +294,10 @@ static bool initTableMemIterator(STsdbQueryHandle* pHandle, STableCheckInfo* pCh ...@@ -294,10 +294,10 @@ static bool initTableMemIterator(STsdbQueryHandle* pHandle, STableCheckInfo* pCh
SDataRow row = SL_GET_NODE_DATA(node); SDataRow row = SL_GET_NODE_DATA(node);
TSKEY key = dataRowKey(row); // first timestamp in buffer TSKEY key = dataRowKey(row); // first timestamp in buffer
uTrace("%p uid:%" PRId64", tid:%d check data in imem from skey:%" PRId64 ", order:%d, %p", pHandle, tsdbTrace("%p uid:%" PRId64", tid:%d check data in imem from skey:%" PRId64 ", order:%d, %p", pHandle,
pCheckInfo->tableId.uid, pCheckInfo->tableId.tid, key, order, pHandle->qinfo); pCheckInfo->tableId.uid, pCheckInfo->tableId.tid, key, order, pHandle->qinfo);
} else { } else {
uTrace("%p uid:%"PRId64", tid:%d no data in imem", pHandle, pCheckInfo->tableId.uid, pCheckInfo->tableId.tid); tsdbTrace("%p uid:%"PRId64", tid:%d no data in imem", pHandle, pCheckInfo->tableId.uid, pCheckInfo->tableId.tid);
} }
return true; return true;
...@@ -338,7 +338,7 @@ static bool hasMoreDataInCache(STsdbQueryHandle* pHandle) { ...@@ -338,7 +338,7 @@ static bool hasMoreDataInCache(STsdbQueryHandle* pHandle) {
SDataRow row = SL_GET_NODE_DATA(node); SDataRow row = SL_GET_NODE_DATA(node);
pCheckInfo->lastKey = dataRowKey(row); // first timestamp in buffer pCheckInfo->lastKey = dataRowKey(row); // first timestamp in buffer
uTrace("%p uid:%" PRId64", tid:%d check data in buffer from skey:%" PRId64 ", order:%d, %p", pHandle, tsdbTrace("%p uid:%" PRId64", tid:%d check data in buffer from skey:%" PRId64 ", order:%d, %p", pHandle,
pCheckInfo->tableId.uid, pCheckInfo->tableId.tid, pCheckInfo->lastKey, pHandle->order, pHandle->qinfo); pCheckInfo->tableId.uid, pCheckInfo->tableId.tid, pCheckInfo->lastKey, pHandle->order, pHandle->qinfo);
// all data in mem are checked already. // all data in mem are checked already.
...@@ -1038,7 +1038,7 @@ static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo* ...@@ -1038,7 +1038,7 @@ static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo*
cur->rows = numOfRows; cur->rows = numOfRows;
cur->pos = pos; cur->pos = pos;
uTrace("%p uid:%" PRIu64",tid:%d data block created, brange:%"PRIu64"-%"PRIu64" %p", pQueryHandle, cur->win.skey, tsdbTrace("%p uid:%" PRIu64",tid:%d data block created, brange:%"PRIu64"-%"PRIu64" %p", pQueryHandle, cur->win.skey,
cur->win.ekey, cur->rows, pQueryHandle->qinfo); cur->win.ekey, cur->rows, pQueryHandle->qinfo);
} }
...@@ -1138,7 +1138,7 @@ static int32_t dataBlockOrderCompar(const void* pLeft, const void* pRight, void* ...@@ -1138,7 +1138,7 @@ static int32_t dataBlockOrderCompar(const void* pLeft, const void* pRight, void*
if (pLeftBlockInfoEx->compBlock->offset == pRightBlockInfoEx->compBlock->offset && if (pLeftBlockInfoEx->compBlock->offset == pRightBlockInfoEx->compBlock->offset &&
pLeftBlockInfoEx->compBlock->last == pRightBlockInfoEx->compBlock->last) { pLeftBlockInfoEx->compBlock->last == pRightBlockInfoEx->compBlock->last) {
// todo add more information // todo add more information
uError("error in header file, two block with same offset:%p", pLeftBlockInfoEx->compBlock->offset); tsdbError("error in header file, two block with same offset:%p", pLeftBlockInfoEx->compBlock->offset);
} }
return pLeftBlockInfoEx->compBlock->offset > pRightBlockInfoEx->compBlock->offset ? 1 : -1; return pLeftBlockInfoEx->compBlock->offset > pRightBlockInfoEx->compBlock->offset ? 1 : -1;
...@@ -1200,7 +1200,7 @@ static int32_t createDataBlocksInfo(STsdbQueryHandle* pQueryHandle, int32_t numO ...@@ -1200,7 +1200,7 @@ static int32_t createDataBlocksInfo(STsdbQueryHandle* pQueryHandle, int32_t numO
numOfQualTables++; numOfQualTables++;
} }
uTrace("%p create data blocks info struct completed, %d blocks in %d tables", pQueryHandle, cnt, numOfQualTables); tsdbTrace("%p create data blocks info struct completed, %d blocks in %d tables", pQueryHandle, cnt, numOfQualTables);
assert(cnt <= numOfBlocks && numOfQualTables <= numOfTables); // the pTableQueryInfo[j]->numOfBlocks may be 0 assert(cnt <= numOfBlocks && numOfQualTables <= numOfTables); // the pTableQueryInfo[j]->numOfBlocks may be 0
sup.numOfTables = numOfQualTables; sup.numOfTables = numOfQualTables;
...@@ -1236,7 +1236,7 @@ static int32_t createDataBlocksInfo(STsdbQueryHandle* pQueryHandle, int32_t numO ...@@ -1236,7 +1236,7 @@ static int32_t createDataBlocksInfo(STsdbQueryHandle* pQueryHandle, int32_t numO
* } * }
*/ */
uTrace("%p %d data blocks sort completed", pQueryHandle, cnt); tsdbTrace("%p %d data blocks sort completed", pQueryHandle, cnt);
cleanBlockOrderSupporter(&sup, numOfTables); cleanBlockOrderSupporter(&sup, numOfTables);
free(pTree); free(pTree);
...@@ -1257,7 +1257,7 @@ static bool getDataBlocksInFilesImpl(STsdbQueryHandle* pQueryHandle) { ...@@ -1257,7 +1257,7 @@ static bool getDataBlocksInFilesImpl(STsdbQueryHandle* pQueryHandle) {
break; break;
} }
uTrace("%p %d blocks found in file for %d table(s), fid:%d", pQueryHandle, numOfBlocks, tsdbTrace("%p %d blocks found in file for %d table(s), fid:%d", pQueryHandle, numOfBlocks,
numOfTables, pQueryHandle->pFileGroup->fileId); numOfTables, pQueryHandle->pFileGroup->fileId);
assert(numOfBlocks >= 0); assert(numOfBlocks >= 0);
...@@ -1583,7 +1583,7 @@ static int tsdbReadRowsFromCache(SSkipListIterator* pIter, STable* pTable, TSKEY ...@@ -1583,7 +1583,7 @@ static int tsdbReadRowsFromCache(SSkipListIterator* pIter, STable* pTable, TSKEY
if ((key > maxKey && ASCENDING_TRAVERSE(pQueryHandle->order)) || if ((key > maxKey && ASCENDING_TRAVERSE(pQueryHandle->order)) ||
(key < maxKey && !ASCENDING_TRAVERSE(pQueryHandle->order))) { (key < maxKey && !ASCENDING_TRAVERSE(pQueryHandle->order))) {
uTrace("%p key:%"PRIu64" beyond qrange:%"PRId64" - %"PRId64", no more data in buffer", pQueryHandle, key, pQueryHandle->window.skey, tsdbTrace("%p key:%"PRIu64" beyond qrange:%"PRId64" - %"PRId64", no more data in buffer", pQueryHandle, key, pQueryHandle->window.skey,
pQueryHandle->window.ekey); pQueryHandle->window.ekey);
break; break;
...@@ -1958,7 +1958,7 @@ SArray* createTableGroup(SArray* pTableList, STSchema* pTagSchema, SColIndex* pC ...@@ -1958,7 +1958,7 @@ SArray* createTableGroup(SArray* pTableList, STSchema* pTagSchema, SColIndex* pC
size_t size = taosArrayGetSize(pTableList); size_t size = taosArrayGetSize(pTableList);
if (size == 0) { if (size == 0) {
uTrace("no qualified tables"); tsdbTrace("no qualified tables");
return pTableGroup; return pTableGroup;
} }
...@@ -1970,7 +1970,7 @@ SArray* createTableGroup(SArray* pTableList, STSchema* pTagSchema, SColIndex* pC ...@@ -1970,7 +1970,7 @@ SArray* createTableGroup(SArray* pTableList, STSchema* pTagSchema, SColIndex* pC
} }
taosArrayPush(pTableGroup, &sa); taosArrayPush(pTableGroup, &sa);
uTrace("all %d tables belong to one group", size); tsdbTrace("all %d tables belong to one group", size);
} else { } else {
STableGroupSupporter *pSupp = (STableGroupSupporter *) calloc(1, sizeof(STableGroupSupporter)); STableGroupSupporter *pSupp = (STableGroupSupporter *) calloc(1, sizeof(STableGroupSupporter));
pSupp->tsdbMeta = tsdbGetMeta(tsdb); pSupp->tsdbMeta = tsdbGetMeta(tsdb);
...@@ -2069,12 +2069,12 @@ int32_t tsdbQuerySTableByTagCond(TsdbRepoT* tsdb, uint64_t uid, const char* pTag ...@@ -2069,12 +2069,12 @@ int32_t tsdbQuerySTableByTagCond(TsdbRepoT* tsdb, uint64_t uid, const char* pTag
SColIndex* pColIndex, int32_t numOfCols) { SColIndex* pColIndex, int32_t numOfCols) {
STable* pTable = tsdbGetTableByUid(tsdbGetMeta(tsdb), uid); STable* pTable = tsdbGetTableByUid(tsdbGetMeta(tsdb), uid);
if (pTable == NULL) { if (pTable == NULL) {
uError("%p failed to get stable, uid:%" PRIu64, tsdb, uid); tsdbError("%p failed to get stable, uid:%" PRIu64, tsdb, uid);
return TSDB_CODE_INVALID_TABLE_ID; return TSDB_CODE_INVALID_TABLE_ID;
} }
if (pTable->type != TSDB_SUPER_TABLE) { if (pTable->type != TSDB_SUPER_TABLE) {
uError("%p query normal tag not allowed, uid:%" PRIu64 ", tid:%d, name:%s", tsdbError("%p query normal tag not allowed, uid:%" PRIu64 ", tid:%d, name:%s",
tsdb, uid, pTable->tableId.tid, pTable->name); tsdb, uid, pTable->tableId.tid, pTable->name);
return TSDB_CODE_OPS_NOT_SUPPORT; //basically, this error is caused by invalid sql issued by client return TSDB_CODE_OPS_NOT_SUPPORT; //basically, this error is caused by invalid sql issued by client
...@@ -2090,7 +2090,7 @@ int32_t tsdbQuerySTableByTagCond(TsdbRepoT* tsdb, uint64_t uid, const char* pTag ...@@ -2090,7 +2090,7 @@ int32_t tsdbQuerySTableByTagCond(TsdbRepoT* tsdb, uint64_t uid, const char* pTag
pGroupInfo->numOfTables = taosArrayGetSize(res); pGroupInfo->numOfTables = taosArrayGetSize(res);
pGroupInfo->pGroupList = createTableGroup(res, pTagSchema, pColIndex, numOfCols, tsdb); pGroupInfo->pGroupList = createTableGroup(res, pTagSchema, pColIndex, numOfCols, tsdb);
uTrace("no tbname condition or tagcond, all tables belongs to one group, numOfTables:%d", pGroupInfo->numOfTables); tsdbTrace("no tbname condition or tagcond, all tables belongs to one group, numOfTables:%d", pGroupInfo->numOfTables);
} else { } else {
// todo add error // todo add error
} }
......
...@@ -47,7 +47,7 @@ typedef struct SCacheDataNode { ...@@ -47,7 +47,7 @@ typedef struct SCacheDataNode {
typedef struct STrashElem { typedef struct STrashElem {
struct STrashElem *prev; struct STrashElem *prev;
struct STrashElem *next; struct STrashElem *next;
SCacheDataNode * pData; SCacheDataNode *pData;
} STrashElem; } STrashElem;
typedef struct { typedef struct {
......
...@@ -118,7 +118,7 @@ extern "C" { ...@@ -118,7 +118,7 @@ extern "C" {
int32_t strdequote(char *src); int32_t strdequote(char *src);
void strtrim(char *src); size_t strtrim(char *src);
char *strnchr(char *haystack, char needle, int32_t len, bool skipquote); char *strnchr(char *haystack, char needle, int32_t len, bool skipquote);
......
...@@ -529,7 +529,7 @@ void taosHashTableResize(SHashObj *pHashObj) { ...@@ -529,7 +529,7 @@ void taosHashTableResize(SHashObj *pHashObj) {
} }
SHashNode *doCreateHashNode(const void *key, size_t keyLen, const void *pData, size_t dsize, uint32_t hashVal) { SHashNode *doCreateHashNode(const void *key, size_t keyLen, const void *pData, size_t dsize, uint32_t hashVal) {
size_t totalSize = dsize + sizeof(SHashNode) + keyLen + 1; // one extra byte for null size_t totalSize = dsize + sizeof(SHashNode) + keyLen;
SHashNode *pNewNode = calloc(1, totalSize); SHashNode *pNewNode = calloc(1, totalSize);
if (pNewNode == NULL) { if (pNewNode == NULL) {
...@@ -544,7 +544,6 @@ SHashNode *doCreateHashNode(const void *key, size_t keyLen, const void *pData, s ...@@ -544,7 +544,6 @@ SHashNode *doCreateHashNode(const void *key, size_t keyLen, const void *pData, s
pNewNode->keyLen = keyLen; pNewNode->keyLen = keyLen;
pNewNode->hashVal = hashVal; pNewNode->hashVal = hashVal;
return pNewNode; return pNewNode;
} }
...@@ -559,7 +558,6 @@ SHashNode *doUpdateHashNode(SHashNode *pNode, const void *key, size_t keyLen, co ...@@ -559,7 +558,6 @@ SHashNode *doUpdateHashNode(SHashNode *pNode, const void *key, size_t keyLen, co
memcpy(pNewNode->data, pData, dsize); memcpy(pNewNode->data, pData, dsize);
pNewNode->key = pNewNode->data + dsize; pNewNode->key = pNewNode->data + dsize;
assert(memcmp(pNewNode->key, key, keyLen) == 0 && keyLen == pNewNode->keyLen); assert(memcmp(pNewNode->key, key, keyLen) == 0 && keyLen == pNewNode->keyLen);
memcpy(pNewNode->key, key, keyLen); memcpy(pNewNode->key, key, keyLen);
......
...@@ -77,7 +77,7 @@ static FORCE_INLINE void taosFreeNode(void *data) { ...@@ -77,7 +77,7 @@ static FORCE_INLINE void taosFreeNode(void *data) {
* @param lifespan total survial expiredTime from now * @param lifespan total survial expiredTime from now
* @return SCacheDataNode * @return SCacheDataNode
*/ */
static SCacheDataNode *taosCreateHashNode(const char *key, size_t keyLen, const char *pData, size_t size, static SCacheDataNode *taosCreateCacheNode(const char *key, size_t keyLen, const char *pData, size_t size,
uint64_t duration) { uint64_t duration) {
size_t totalSize = size + sizeof(SCacheDataNode) + keyLen + 1; size_t totalSize = size + sizeof(SCacheDataNode) + keyLen + 1;
...@@ -242,13 +242,14 @@ static SCacheDataNode *taosUpdateCacheImpl(SCacheObj *pCacheObj, SCacheDataNode ...@@ -242,13 +242,14 @@ static SCacheDataNode *taosUpdateCacheImpl(SCacheObj *pCacheObj, SCacheDataNode
// only a node is not referenced by any other object, in-place update it // only a node is not referenced by any other object, in-place update it
if (T_REF_VAL_GET(pNode) == 0) { if (T_REF_VAL_GET(pNode) == 0) {
size_t newSize = sizeof(SCacheDataNode) + dataSize + keyLen; size_t newSize = sizeof(SCacheDataNode) + dataSize + keyLen + 1;
pNewNode = (SCacheDataNode *)realloc(pNode, newSize); pNewNode = (SCacheDataNode *)realloc(pNode, newSize);
if (pNewNode == NULL) { if (pNewNode == NULL) {
return NULL; return NULL;
} }
memset(pNewNode, 0, newSize);
pNewNode->signature = (uint64_t)pNewNode; pNewNode->signature = (uint64_t)pNewNode;
memcpy(pNewNode->data, pData, dataSize); memcpy(pNewNode->data, pData, dataSize);
...@@ -267,7 +268,7 @@ static SCacheDataNode *taosUpdateCacheImpl(SCacheObj *pCacheObj, SCacheDataNode ...@@ -267,7 +268,7 @@ static SCacheDataNode *taosUpdateCacheImpl(SCacheObj *pCacheObj, SCacheDataNode
} else { } else {
taosCacheMoveToTrash(pCacheObj, pNode); taosCacheMoveToTrash(pCacheObj, pNode);
pNewNode = taosCreateHashNode(key, keyLen, pData, dataSize, duration); pNewNode = taosCreateCacheNode(key, keyLen, pData, dataSize, duration);
if (pNewNode == NULL) { if (pNewNode == NULL) {
return NULL; return NULL;
} }
...@@ -293,7 +294,7 @@ static SCacheDataNode *taosUpdateCacheImpl(SCacheObj *pCacheObj, SCacheDataNode ...@@ -293,7 +294,7 @@ static SCacheDataNode *taosUpdateCacheImpl(SCacheObj *pCacheObj, SCacheDataNode
*/ */
static FORCE_INLINE SCacheDataNode *taosAddToCacheImpl(SCacheObj *pCacheObj, const char *key, size_t keyLen, const void *pData, static FORCE_INLINE SCacheDataNode *taosAddToCacheImpl(SCacheObj *pCacheObj, const char *key, size_t keyLen, const void *pData,
size_t dataSize, uint64_t duration) { size_t dataSize, uint64_t duration) {
SCacheDataNode *pNode = taosCreateHashNode(key, keyLen, pData, dataSize, duration); SCacheDataNode *pNode = taosCreateCacheNode(key, keyLen, pData, dataSize, duration);
if (pNode == NULL) { if (pNode == NULL) {
return NULL; return NULL;
} }
......
...@@ -60,7 +60,7 @@ int32_t strdequote(char *z) { ...@@ -60,7 +60,7 @@ int32_t strdequote(char *z) {
return j + 1; // only one quote, do nothing return j + 1; // only one quote, do nothing
} }
void strtrim(char *z) { size_t strtrim(char *z) {
int32_t i = 0; int32_t i = 0;
int32_t j = 0; int32_t j = 0;
...@@ -71,7 +71,7 @@ void strtrim(char *z) { ...@@ -71,7 +71,7 @@ void strtrim(char *z) {
if (z[j] == 0) { if (z[j] == 0) {
z[0] = 0; z[0] = 0;
return; return 0;
} }
delta = j; delta = j;
...@@ -89,9 +89,12 @@ void strtrim(char *z) { ...@@ -89,9 +89,12 @@ void strtrim(char *z) {
if (stop > 0) { if (stop > 0) {
z[stop - delta] = 0; z[stop - delta] = 0;
return (stop - delta);
} else if (j != i) { } else if (j != i) {
z[i] = 0; z[i] = 0;
} }
return i;
} }
char **strsplit(char *z, const char *delim, int32_t *num) { char **strsplit(char *z, const char *delim, int32_t *num) {
......
...@@ -20,10 +20,10 @@ TEST(testCase, string_dequote_test) { ...@@ -20,10 +20,10 @@ TEST(testCase, string_dequote_test) {
EXPECT_STRCASEEQ(t1, "abc"); EXPECT_STRCASEEQ(t1, "abc");
char t21[] = " abc "; char t21[] = " abc ";
strtrim(t21); int32_t lx = strtrim(t21);
EXPECT_STREQ("abc", t21); EXPECT_STREQ("abc", t21);
EXPECT_EQ(3, strlen(t21)); EXPECT_EQ(3, lx);
} }
TEST(testCase, string_replace_test) { TEST(testCase, string_replace_test) {
......
...@@ -26,13 +26,12 @@ ...@@ -26,13 +26,12 @@
void taosMsleep(int mseconds); void taosMsleep(int mseconds);
static int32_t doQuery(TAOS* taos, const char* sql) { static int32_t doQuery(TAOS* taos, const char* sql) {
int32_t code = taos_query(taos, sql); TAOS_RES* res = taos_query(taos, sql);
if (code != 0) { if (taos_errno(res) != 0) {
printf("failed to execute query, reason:%s\n", taos_errstr(taos)); printf("failed to execute query, reason:%s\n", taos_errstr(taos));
return -1; return -1;
} }
TAOS_RES* res = taos_use_result(taos);
TAOS_ROW row = NULL; TAOS_ROW row = NULL;
char buf[512] = {0}; char buf[512] = {0};
...@@ -46,7 +45,6 @@ static int32_t doQuery(TAOS* taos, const char* sql) { ...@@ -46,7 +45,6 @@ static int32_t doQuery(TAOS* taos, const char* sql) {
} }
taos_free_result(res); taos_free_result(res);
return 0; return 0;
} }
...@@ -81,6 +79,7 @@ static __attribute__((unused)) void multiThreadTest(int32_t numOfThreads, void* ...@@ -81,6 +79,7 @@ static __attribute__((unused)) void multiThreadTest(int32_t numOfThreads, void*
pthread_join(threadId[i], NULL); pthread_join(threadId[i], NULL);
} }
free(threadId);
pthread_attr_destroy(&thattr); pthread_attr_destroy(&thattr);
} }
...@@ -114,19 +113,6 @@ int main(int argc, char *argv[]) { ...@@ -114,19 +113,6 @@ int main(int argc, char *argv[]) {
// doQuery(taos, "insert into t1 values(now, 2)"); // doQuery(taos, "insert into t1 values(now, 2)");
// } // }
// doQuery(taos, "create table t1(ts timestamp, k binary(12), f nchar(2))"); // doQuery(taos, "create table t1(ts timestamp, k binary(12), f nchar(2))");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:1', 'abc')");
// doQuery(taos, "create table if not exists tm0 (ts timestamp, k int);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:1', 1);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:2', 2);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:3', 3);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:4', 4);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:5', 5);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:6', 6);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:7', 7);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:8', 8);");
// doQuery(taos, "insert into tm0 values('2020-1-1 1:1:9', 9);");
// doQuery(taos, "select sum(k),count(*) from m1 group by a");
taos_close(taos); taos_close(taos);
return 0; return 0;
...@@ -173,10 +159,6 @@ int main(int argc, char *argv[]) { ...@@ -173,10 +159,6 @@ int main(int argc, char *argv[]) {
exit(1); exit(1);
} }
result = taos_use_result(taos);
if (result == NULL) { if (result == NULL) {
printf("failed to get result, reason:%s\n", taos_errstr(taos)); printf("failed to get result, reason:%s\n", taos_errstr(taos));
exit(1); exit(1);
......
...@@ -609,7 +609,8 @@ class StateDbOnly(AnyState): ...@@ -609,7 +609,8 @@ class StateDbOnly(AnyState):
] ]
def verifyTasksToState(self, tasks, newState): def verifyTasksToState(self, tasks, newState):
self.assertAtMostOneSuccess(tasks, DropDbTask) # not true in massively parralel cases if ( not self.hasTask(tasks, CreateDbTask) ):
self.assertAtMostOneSuccess(tasks, DropDbTask) # only if we don't create any more
self.assertIfExistThenSuccess(tasks, DropDbTask) self.assertIfExistThenSuccess(tasks, DropDbTask)
# self.assertAtMostOneSuccess(tasks, CreateFixedTableTask) # not true in massively parrallel cases # self.assertAtMostOneSuccess(tasks, CreateFixedTableTask) # not true in massively parrallel cases
# Nothing to be said about adding data task # Nothing to be said about adding data task
...@@ -619,7 +620,8 @@ class StateDbOnly(AnyState): ...@@ -619,7 +620,8 @@ class StateDbOnly(AnyState):
# self._state = self.STATE_EMPTY # self._state = self.STATE_EMPTY
elif ( self.hasSuccess(tasks, CreateFixedSuperTableTask) ): # did not drop db, create table success elif ( self.hasSuccess(tasks, CreateFixedSuperTableTask) ): # did not drop db, create table success
# self.assertHasTask(tasks, CreateFixedTableTask) # tried to create table # self.assertHasTask(tasks, CreateFixedTableTask) # tried to create table
self.assertAtMostOneSuccess(tasks, CreateFixedSuperTableTask) # at most 1 attempt is successful if ( not self.hasTask(tasks, DropFixedSuperTableTask) ):
self.assertAtMostOneSuccess(tasks, CreateFixedSuperTableTask) # at most 1 attempt is successful, if we don't drop anything
self.assertNoTask(tasks, DropDbTask) # should have have tried self.assertNoTask(tasks, DropDbTask) # should have have tried
# if ( not self.hasSuccess(tasks, AddFixedDataTask) ): # just created table, no data yet # if ( not self.hasSuccess(tasks, AddFixedDataTask) ): # just created table, no data yet
# # can't say there's add-data attempts, since they may all fail # # can't say there's add-data attempts, since they may all fail
...@@ -674,7 +676,7 @@ class StateHasData(AnyState): ...@@ -674,7 +676,7 @@ class StateHasData(AnyState):
if ( not self.hasTask(tasks, CreateDbTask)): # without a create_db task if ( not self.hasTask(tasks, CreateDbTask)): # without a create_db task
self.assertNoTask(tasks, DropDbTask) # we must have drop_db task self.assertNoTask(tasks, DropDbTask) # we must have drop_db task
self.hasSuccess(tasks, DropFixedSuperTableTask) self.hasSuccess(tasks, DropFixedSuperTableTask)
self.assertAtMostOneSuccess(tasks, DropFixedSuperTableTask) # TODO: dicy # self.assertAtMostOneSuccess(tasks, DropFixedSuperTableTask) # TODO: dicy
elif ( newState.equals(AnyState.STATE_TABLE_ONLY) ): # data deleted elif ( newState.equals(AnyState.STATE_TABLE_ONLY) ): # data deleted
self.assertNoTask(tasks, DropDbTask) self.assertNoTask(tasks, DropDbTask)
self.assertNoTask(tasks, DropFixedSuperTableTask) self.assertNoTask(tasks, DropFixedSuperTableTask)
...@@ -689,9 +691,9 @@ class StateHasData(AnyState): ...@@ -689,9 +691,9 @@ class StateHasData(AnyState):
# State of the database as we believe it to be # State of the database as we believe it to be
class DbState(): class DbState():
def __init__(self): def __init__(self, resetDb = True):
self.tableNumQueue = LinearQueue() self.tableNumQueue = LinearQueue()
self._lastTick = datetime.datetime(2019, 1, 1) # initial date time tick self._lastTick = self.setupLastTick() # datetime.datetime(2019, 1, 1) # initial date time tick
self._lastInt = 0 # next one is initial integer self._lastInt = 0 # next one is initial integer
self._lock = threading.RLock() self._lock = threading.RLock()
...@@ -712,12 +714,32 @@ class DbState(): ...@@ -712,12 +714,32 @@ class DbState():
except: except:
print("[=] Unexpected exception") print("[=] Unexpected exception")
raise raise
self._dbConn.resetDb() # drop and recreate DB
self._state = StateEmpty() # initial state, the result of above if resetDb :
self._dbConn.resetDb() # drop and recreate DB
self._state = self._findCurrentState()
def getDbConn(self): def getDbConn(self):
return self._dbConn return self._dbConn
def getState(self):
return self._state
# We aim to create a starting time tick, such that, whenever we run our test here once
# We should be able to safely create 100,000 records, which will not have any repeated time stamp
# when we re-run the test in 3 minutes (180 seconds), basically we should expand time duration
# by a factor of 500.
# TODO: what if it goes beyond 10 years into the future
def setupLastTick(self):
t1 = datetime.datetime(2020, 5, 30)
t2 = datetime.datetime.now()
elSec = t2.timestamp() - t1.timestamp()
# print("elSec = {}".format(elSec))
t3 = datetime.datetime(2012, 1, 1) # default "keep" is 10 years
t4 = datetime.datetime.fromtimestamp( t3.timestamp() + elSec * 500) # see explanation above
logger.info("Setting up TICKS to start from: {}".format(t4))
return t4
def pickAndAllocateTable(self): # pick any table, and "use" it def pickAndAllocateTable(self): # pick any table, and "use" it
return self.tableNumQueue.pickAndAllocate() return self.tableNumQueue.pickAndAllocate()
...@@ -743,7 +765,7 @@ class DbState(): ...@@ -743,7 +765,7 @@ class DbState():
return self._lastInt return self._lastInt
def getNextBinary(self): def getNextBinary(self):
return "Los_Angeles_{}".format(self.getNextInt()) return "Beijing_Shanghai_Los_Angeles_New_York_San_Francisco_Chicago_Beijing_Shanghai_Los_Angeles_New_York_San_Francisco_Chicago_{}".format(self.getNextInt())
def getNextFloat(self): def getNextFloat(self):
return 0.9 + self.getNextInt() return 0.9 + self.getNextInt()
...@@ -1089,7 +1111,7 @@ class CreateFixedSuperTableTask(StateTransitionTask): ...@@ -1089,7 +1111,7 @@ class CreateFixedSuperTableTask(StateTransitionTask):
def _executeInternal(self, te: TaskExecutor, wt: WorkerThread): def _executeInternal(self, te: TaskExecutor, wt: WorkerThread):
tblName = self._dbState.getFixedSuperTableName() tblName = self._dbState.getFixedSuperTableName()
wt.execSql("create table db.{} (ts timestamp, speed int) tags (b binary(20), f float) ".format(tblName)) wt.execSql("create table db.{} (ts timestamp, speed int) tags (b binary(200), f float) ".format(tblName))
# No need to create the regular tables, INSERT will do that automatically # No need to create the regular tables, INSERT will do that automatically
...@@ -1148,12 +1170,13 @@ class AddFixedDataTask(StateTransitionTask): ...@@ -1148,12 +1170,13 @@ class AddFixedDataTask(StateTransitionTask):
ds = self._dbState ds = self._dbState
wt.execSql("use db") # TODO: seems to be an INSERT bug to require this wt.execSql("use db") # TODO: seems to be an INSERT bug to require this
for i in range(10): # 0 to 9 for i in range(10): # 0 to 9
sql = "insert into db.reg_table_{} using {} tags ('{}', {}) values ('{}', {});".format( for j in range(10) :
i, sql = "insert into db.reg_table_{} using {} tags ('{}', {}) values ('{}', {});".format(
ds.getFixedSuperTableName(), i,
ds.getNextBinary(), ds.getNextFloat(), ds.getFixedSuperTableName(),
ds.getNextTick(), ds.getNextInt()) ds.getNextBinary(), ds.getNextFloat(),
wt.execSql(sql) ds.getNextTick(), ds.getNextInt())
wt.execSql(sql)
#---------- Non State-Transition Related Tasks ----------# #---------- Non State-Transition Related Tasks ----------#
...@@ -1301,7 +1324,9 @@ def main(): ...@@ -1301,7 +1324,9 @@ def main():
ch = logging.StreamHandler() ch = logging.StreamHandler()
logger.addHandler(ch) logger.addHandler(ch)
dbState = DbState() # resetDb = False # DEBUG only
# dbState = DbState(resetDb) # DBEUG only!
dbState = DbState() # Regular function
Dice.seed(0) # initial seeding of dice Dice.seed(0) # initial seeding of dice
tc = ThreadCoordinator( tc = ThreadCoordinator(
ThreadPool(dbState, gConfig.num_threads, gConfig.max_steps, 0), ThreadPool(dbState, gConfig.num_threads, gConfig.max_steps, 0),
...@@ -1309,6 +1334,43 @@ def main(): ...@@ -1309,6 +1334,43 @@ def main():
dbState dbState
) )
# # Hack to exercise reading from disk, imcreasing coverage. TODO: fix
# dbc = dbState.getDbConn()
# sTbName = dbState.getFixedSuperTableName()
# dbc.execute("create database if not exists db")
# if not dbState.getState().equals(StateEmpty()):
# dbc.execute("use db")
# rTables = None
# try: # the super table may not exist
# sql = "select TBNAME from db.{}".format(sTbName)
# logger.info("Finding out tables in super table: {}".format(sql))
# dbc.query(sql) # TODO: analyze result set later
# logger.info("Fetching result")
# rTables = dbc.getQueryResult()
# logger.info("Result: {}".format(rTables))
# except taos.error.ProgrammingError as err:
# logger.info("Initial Super table OPS error: {}".format(err))
# # sys.exit()
# if ( not rTables == None):
# # print("rTables[0] = {}, type = {}".format(rTables[0], type(rTables[0])))
# try:
# for rTbName in rTables : # regular tables
# ds = dbState
# logger.info("Inserting into table: {}".format(rTbName[0]))
# sql = "insert into db.{} values ('{}', {});".format(
# rTbName[0],
# ds.getNextTick(), ds.getNextInt())
# dbc.execute(sql)
# for rTbName in rTables : # regular tables
# dbc.query("select * from db.{}".format(rTbName[0])) # TODO: check success failure
# logger.info("Initial READING operation is successful")
# except taos.error.ProgrammingError as err:
# logger.info("Initial WRITE/READ error: {}".format(err))
# Sandbox testing code # Sandbox testing code
# dbc = dbState.getDbConn() # dbc = dbState.getDbConn()
# while True: # while True:
......
此差异已折叠。
#!/bin/bash
# This is the script for us to try to cause the TDengine server or client to crash
#
# PREPARATION
#
# 1. Build an compile the TDengine source code that comes with this script, in the same directory tree
# 2. Please follow the direction in our README.md, and build TDengine in the build/ directory
# 3. Adjust the configuration file if needed under build/test/cfg/taos.cfg
# 4. Run the TDengine server instance: cd build; ./build/bin/taosd -c test/cfg
# 5. Make sure you have a working Python3 environment: run /usr/bin/python3 --version, and you should get 3.6 or above
# 6. Make sure you have the proper Python packages: # sudo apt install python3-setuptools python3-pip python3-distutils
#
# RUNNING THIS SCRIPT
#
# This script assumes the source code directory is intact, and that the binaries has been built in the
# build/ directory, as such, will will load the Python libraries in the directory tree, and also load
# the TDengine client shared library (so) file, in the build/directory, as evidenced in the env
# variables below.
#
# Running the script is simple, no parameter is needed (for now, but will change in the future).
#
# Happy Crashing...
# Due to the heavy path name assumptions/usage, let us require that the user be in the current directory
EXEC_DIR=`dirname "$0"`
if [[ $EXEC_DIR != "." ]]
then
echo "ERROR: Please execute `basename "$0"` in its own directory (for now anyway, pardon the dust)"
exit -1
fi
# First we need to set up a path for Python to find our own TAOS modules, so that "import" can work.
export PYTHONPATH=$(pwd)/../../src/connector/python/linux/python3
# Then let us set up the library path so that our compiled SO file can be loaded by Python
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(pwd)/../../build/build/lib
# Now we are all let, and let's see if we can find a crash. Note we pass all params
./crash_gen_0519.py $@
...@@ -60,17 +60,10 @@ if $rows != 75 then ...@@ -60,17 +60,10 @@ if $rows != 75 then
return -1 return -1
endi endi
sql select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where tbcol = '1' group by tgcol -x step13 print select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where tbcol = '1'
return -1 sql_error select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where tbcol = '1' group by tgcol
step13: sql_error select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where ts < now + 4m and tbcol = '1' group by tgcol
sql_error select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where tbcol = '1' interval(1d) group by tgcol
sql select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where ts < now + 4m and tbcol = '1' group by tgcol -x step14
return -1
step14:
sql select count(tbcol), avg(tbcol), sum(tbcol), min(tbcol), max(tbcol), first(tbcol), last(tbcol) from $mt where tbcol = '1' interval(1d) group by tgcol -x step15
return -1
step15:
#can't filter binary fields #can't filter binary fields
......
...@@ -133,6 +133,7 @@ $limit = $rowNum ...@@ -133,6 +133,7 @@ $limit = $rowNum
$offset = $limit / 2 $offset = $limit / 2
sql select max(c1), min(c2), sum(c3), avg(c4), stddev(c5), spread(c6), first(c7), last(c8), first(c9) from $tb where ts >= $ts0 and ts <= $tsu interval(5m) fill(value, -1, -2) limit $limit offset $offset sql select max(c1), min(c2), sum(c3), avg(c4), stddev(c5), spread(c6), first(c7), last(c8), first(c9) from $tb where ts >= $ts0 and ts <= $tsu interval(5m) fill(value, -1, -2) limit $limit offset $offset
if $rows != $limit then if $rows != $limit then
print expect $limit, actual $rows
return -1 return -1
endi endi
if $data01 != 0 then if $data01 != 0 then
...@@ -147,6 +148,7 @@ $limit = $rowNum ...@@ -147,6 +148,7 @@ $limit = $rowNum
$offset = $limit / 2 $offset = $limit / 2
sql select max(c1), min(c2), sum(c3), avg(c4), stddev(c5), spread(c6), first(c7), last(c8), first(c9) from $tb where ts >= $ts0 and ts <= $tsu interval(5m) fill(linear) limit $limit offset $offset sql select max(c1), min(c2), sum(c3), avg(c4), stddev(c5), spread(c6), first(c7), last(c8), first(c9) from $tb where ts >= $ts0 and ts <= $tsu interval(5m) fill(linear) limit $limit offset $offset
if $rows != $limit then if $rows != $limit then
print expect $limit, actual $rows
return -1 return -1
endi endi
if $data01 != 0 then if $data01 != 0 then
...@@ -182,6 +184,7 @@ $limit = $rowNum ...@@ -182,6 +184,7 @@ $limit = $rowNum
$offset = $limit / 2 $offset = $limit / 2
sql select max(c1), min(c2), sum(c3), avg(c4), stddev(c5), spread(c6), first(c7), last(c8), first(c9) from $tb where ts >= $ts0 and ts <= $tsu interval(5m) fill(prev) limit $limit offset $offset sql select max(c1), min(c2), sum(c3), avg(c4), stddev(c5), spread(c6), first(c7), last(c8), first(c9) from $tb where ts >= $ts0 and ts <= $tsu interval(5m) fill(prev) limit $limit offset $offset
if $rows != $limit then if $rows != $limit then
print expect $limit, actual: $rows
return -1 return -1
endi endi
......
...@@ -40,45 +40,47 @@ ...@@ -40,45 +40,47 @@
#run general/parser/nchar.sim #run general/parser/nchar.sim
#sleep 2000 #sleep 2000
##run general/parser/null_char.sim ##run general/parser/null_char.sim
sleep 2000 #sleep 2000
run general/parser/single_row_in_tb.sim #run general/parser/single_row_in_tb.sim
sleep 2000 #sleep 2000
run general/parser/select_from_cache_disk.sim #run general/parser/select_from_cache_disk.sim
sleep 2000 #sleep 2000
run general/parser/selectResNum.sim #run general/parser/selectResNum.sim
sleep 2000 #sleep 2000
run general/parser/mixed_blocks.sim #run general/parser/mixed_blocks.sim
sleep 2000 #sleep 2000
run general/parser/limit1.sim #run general/parser/limit1.sim
sleep 2000 #sleep 2000
run general/parser/limit.sim #run general/parser/limit.sim
sleep 2000 #sleep 2000
run general/parser/limit1_tblocks100.sim #run general/parser/limit1_tblocks100.sim
sleep 2000 #sleep 2000
run general/parser/select_across_vnodes.sim #run general/parser/select_across_vnodes.sim
sleep 2000 #sleep 2000
run general/parser/slimit1.sim #run general/parser/slimit1.sim
sleep 2000 #sleep 2000
run general/parser/tbnameIn.sim #run general/parser/tbnameIn.sim
sleep 2000 #sleep 2000
run general/parser/projection_limit_offset.sim run general/parser/projection_limit_offset.sim
sleep 2000 sleep 2000
run general/parser/limit2.sim run general/parser/limit2.sim
sleep 2000 sleep 2000
run general/parser/fill.sim #run general/parser/fill.sim
sleep 2000 #sleep 2000
run general/parser/fill_stb.sim #run general/parser/fill_stb.sim
sleep 2000 #sleep 2000
run general/parser/where.sim #run general/parser/where.sim
sleep 2000 #sleep 2000
run general/parser/slimit.sim #run general/parser/slimit.sim
#sleep 2000
#run general/parser/select_with_tags.sim
#sleep 2000
#run general/parser/interp.sim
sleep 2000 sleep 2000
run general/parser/select_with_tags.sim run general/parser/tags_dynamically_specifiy.sim
sleep 2000 sleep 2000
run general/parser/interp.sim run general/parser/groupby.sim
sleep 2000
run general/parser/tags_dynamically_specifiy.sim
sleep 2000 sleep 2000
run general/parser/set_tag_vals.sim run general/parser/set_tag_vals.sim
...@@ -97,9 +99,6 @@ sleep 2000 ...@@ -97,9 +99,6 @@ sleep 2000
run general/parser/join.sim run general/parser/join.sim
sleep 2000 sleep 2000
run general/parser/join_multivnode.sim run general/parser/join_multivnode.sim
sleep 2000
run general/parser/groupby.sim
sleep 2000 sleep 2000
run general/parser/binary_escapeCharacter.sim run general/parser/binary_escapeCharacter.sim
sleep 2000 sleep 2000
......
...@@ -75,7 +75,7 @@ endi ...@@ -75,7 +75,7 @@ endi
system_content curl -u root:taosdata -d '[{"metric": "ab1234567890123456789012345678ab1234567890123456789012345678","timestamp": 1346846400,"value": 18,"tags": {"host": "web01","group1": "1","dc": "lga"}}]' 127.0.0.1:6020/opentsdb/db/put system_content curl -u root:taosdata -d '[{"metric": "ab1234567890123456789012345678ab1234567890123456789012345678","timestamp": 1346846400,"value": 18,"tags": {"host": "web01","group1": "1","dc": "lga"}}]' 127.0.0.1:6020/opentsdb/db/put
print $system_content print $system_content
if $system_content != @{"errors":[{"datapoint":{"metric":"ab1234567890123456789012345678ab1234567890123456789012345678","stable":"ab1234567890123456789012345678ab1234567890123456789012345678_d_bbb","table":"ab1234567890123456789012345678ab1234567890123456789012345678_d_bbb_lga_1_web01","timestamp":1346846400,"value":18.000000,"tags":{"dc":"lga","group1":"1","host":"web01"},"status":"error","code":-2147483389}}],"failed":1,"success":0,"affected_rows":0}@ then if $system_content != @{"errors":[{"datapoint":{"metric":"ab1234567890123456789012345678ab1234567890123456789012345678","stable":"ab1234567890123456789012345678ab1234567890123456789012345678_d_bbb","table":"ab1234567890123456789012345678ab1234567890123456789012345678_d_bbb_lga_1_web01","timestamp":1346846400,"value":18.000000,"tags":{"dc":"lga","group1":"1","host":"web01"},"status":"error","code":-2147482999}}],"failed":1,"success":0,"affected_rows":0}@ then
return -1 return -1
endi endi
...@@ -125,7 +125,7 @@ endi ...@@ -125,7 +125,7 @@ endi
system_content curl -u root:taosdata -d '[{"metric": "sys_cpu","timestamp": 1346846400,"value": 18,"tags": {"host": "web01","group1": "1","group1": "1","group1": "1","group1": "1","group1": "1","dc": "lga"}}]' 127.0.0.1:6020/opentsdb/db/put system_content curl -u root:taosdata -d '[{"metric": "sys_cpu","timestamp": 1346846400,"value": 18,"tags": {"host": "web01","group1": "1","group1": "1","group1": "1","group1": "1","group1": "1","dc": "lga"}}]' 127.0.0.1:6020/opentsdb/db/put
print $system_content print $system_content
if $system_content != @{"errors":[{"datapoint":{"metric":"sys_cpu","stable":"sys_cpu_d_bbbbbbb","table":"sys_cpu_d_bbbbbbb_lga_1_1_1_1_1_web01","timestamp":1346846400,"value":18.000000,"tags":{"dc":"lga","group1":"1","group1":"1","group1":"1","group1":"1","group1":"1","host":"web01"},"status":"error","code":-2147483445}}],"failed":1,"success":0,"affected_rows":0}@ then if $system_content != @{"errors":[{"datapoint":{"metric":"sys_cpu","stable":"sys_cpu_d_bbbbbbb","table":"sys_cpu_d_bbbbbbb_lga_1_1_1_1_1_web01","timestamp":1346846400,"value":18.000000,"tags":{"dc":"lga","group1":"1","group1":"1","group1":"1","group1":"1","group1":"1","host":"web01"},"status":"error","code":-2147483135}}],"failed":1,"success":0,"affected_rows":0}@ then
return -1 return -1
endi endi
......
...@@ -122,10 +122,26 @@ void* taos_execute(void *param) { ...@@ -122,10 +122,26 @@ void* taos_execute(void *param) {
int64_t timestamp = 1530374400000L; int64_t timestamp = 1530374400000L;
sprintf(sql, "insert into db.t%d values(%ld, %d, %d, %d)", pThread->index, timestamp, 0, 0, 0); sprintf(sql, "insert into db.t%d values(%ld, %d, %d, %d)", pThread->index, timestamp, 0, 0, 0);
int code = taos_query(taos, sql); TAOS_RES *pSql = taos_query(taos, sql);
if (code != 0) printf("error code:%d, sql:%s\n", code, sql); int code = taos_errno(pSql);
if (code != 0)
{
printf("error code:%d, sql:%s\n", code, sql);
taos_free_result(pSql);
taos_close(taos);
return NULL;
}
int affectrows = taos_affected_rows(taos); int affectrows = taos_affected_rows(taos);
if (affectrows != 1) printf("affect rows:%d, sql:%s\n", affectrows, sql); if (affectrows != 1)
{
printf("affect rows:%d, sql:%s\n", affectrows, sql);
taos_free_result(pSql);
taos_close(taos);
return NULL;
}
taos_free_result(pSql);
pSql = NULL;
timestamp -= 1000; timestamp -= 1000;
...@@ -133,17 +149,34 @@ void* taos_execute(void *param) { ...@@ -133,17 +149,34 @@ void* taos_execute(void *param) {
for (int i = 1; i < rowNum; ++i) { for (int i = 1; i < rowNum; ++i) {
sprintf(sql, "import into db.t%d values(%ld, %d, %d, %d)", pThread->index, timestamp, i, i, i); sprintf(sql, "import into db.t%d values(%ld, %d, %d, %d)", pThread->index, timestamp, i, i, i);
code = taos_query(taos, sql);
if (code != 0) printf("error code:%d, sql:%s\n", code, sql); pSql = taos_query(taos, sql);
code = taos_errno(pSql);
if (code != 0)
{
printf("error code:%d, sql:%s\n", code, sql);
taos_free_result(pSql);
pSql = NULL;
taos_close(taos);
return NULL;
}
int affectrows = taos_affected_rows(taos); int affectrows = taos_affected_rows(taos);
if (affectrows != 1) printf("affect rows:%d, sql:%s\n", affectrows, sql); if (affectrows != 1) {
printf("affect rows:%d, sql:%s\n", affectrows, sql);
taos_free_result(pSql);
pSql = NULL;
taos_close(taos);
}
total_affect_rows += affectrows; total_affect_rows += affectrows;
taos_free_result(pSql);
pSql = NULL;
timestamp -= 1000; timestamp -= 1000;
} }
printf("thread:%d run finished total_affect_rows:%d\n", pThread->index, total_affect_rows); printf("thread:%d run finished total_affect_rows:%d\n", pThread->index, total_affect_rows);
taos_close(taos);
return NULL; return NULL;
} }
...@@ -635,17 +635,20 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) { ...@@ -635,17 +635,20 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) {
SCmdLine *line = &script->lines[script->linePos]; SCmdLine *line = &script->lines[script->linePos];
int ret = -1; int ret = -1;
TAOS_RES* pSql = NULL;
for (int attempt = 0; attempt < 3; ++attempt) { for (int attempt = 0; attempt < 3; ++attempt) {
simLogSql(rest); simLogSql(rest);
ret = taos_query(script->taos, rest); pSql = taos_query(script->taos, rest);
if (ret == TSDB_CODE_TABLE_ALREADY_EXIST || ret = taos_errno(pSql);
ret == TSDB_CODE_DB_ALREADY_EXIST) {
if (ret == TSDB_CODE_TABLE_ALREADY_EXIST || ret == TSDB_CODE_DB_ALREADY_EXIST) {
simTrace("script:%s, taos:%p, %s success, ret:%d:%s", script->fileName, script->taos, rest, ret, tstrerror(ret)); simTrace("script:%s, taos:%p, %s success, ret:%d:%s", script->fileName, script->taos, rest, ret, tstrerror(ret));
ret = 0; ret = 0;
break; break;
} else if (ret != 0) { } else if (ret != 0) {
simTrace("script:%s, taos:%p, %s failed, ret:%d:%s, error:%s", simTrace("script:%s, taos:%p, %s failed, ret:%d:%s, error:%s",
script->fileName, script->taos, rest, ret, tstrerror(ret), taos_errstr(script->taos)); script->fileName, script->taos, rest, ret, tstrerror(ret), taos_errstr(pSql));
if (line->errorJump == SQL_JUMP_TRUE) { if (line->errorJump == SQL_JUMP_TRUE) {
script->linePos = line->jump; script->linePos = line->jump;
...@@ -655,6 +658,8 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) { ...@@ -655,6 +658,8 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) {
} else { } else {
break; break;
} }
taos_free_result(pSql);
} }
if (ret) { if (ret) {
...@@ -663,10 +668,9 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) { ...@@ -663,10 +668,9 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) {
} }
int numOfRows = 0; int numOfRows = 0;
int num_fields = taos_field_count(script->taos); int num_fields = taos_field_count(pSql);
if (num_fields != 0) { if (num_fields != 0) {
TAOS_RES *result = taos_use_result(script->taos); if (pSql == NULL) {
if (result == NULL) {
simTrace("script:%s, taos:%p, %s failed, result is null", script->fileName, script->taos, rest); simTrace("script:%s, taos:%p, %s failed, result is null", script->fileName, script->taos, rest);
if (line->errorJump == SQL_JUMP_TRUE) { if (line->errorJump == SQL_JUMP_TRUE) {
script->linePos = line->jump; script->linePos = line->jump;
...@@ -679,10 +683,10 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) { ...@@ -679,10 +683,10 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) {
TAOS_ROW row; TAOS_ROW row;
while ((row = taos_fetch_row(result))) { while ((row = taos_fetch_row(pSql))) {
if (numOfRows < MAX_QUERY_ROW_NUM) { if (numOfRows < MAX_QUERY_ROW_NUM) {
TAOS_FIELD *fields = taos_fetch_fields(result); TAOS_FIELD *fields = taos_fetch_fields(pSql);
int* length = taos_fetch_lengths(result); int* length = taos_fetch_lengths(pSql);
for (int i = 0; i < num_fields; i++) { for (int i = 0; i < num_fields; i++) {
char *value = NULL; char *value = NULL;
...@@ -768,11 +772,11 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) { ...@@ -768,11 +772,11 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) {
} }
} }
taos_free_result(result);
} else { } else {
numOfRows = taos_affected_rows(script->taos); numOfRows = taos_affected_rows(pSql);
} }
taos_free_result(pSql);
sprintf(script->rows, "%d", numOfRows); sprintf(script->rows, "%d", numOfRows);
script->linePos++; script->linePos++;
...@@ -911,13 +915,16 @@ bool simExecuteSqlErrorCmd(SScript *script, char *rest) { ...@@ -911,13 +915,16 @@ bool simExecuteSqlErrorCmd(SScript *script, char *rest) {
} }
int ret; int ret;
TAOS_RES* pSql = NULL;
if (simAsyncQuery) { if (simAsyncQuery) {
char command[4096]; char command[4096];
sprintf(command, "curl -H 'Authorization: Taosd %s' -d '%s' 127.0.0.1:6020/rest/sql", script->auth, rest); sprintf(command, "curl -H 'Authorization: Taosd %s' -d '%s' 127.0.0.1:6020/rest/sql", script->auth, rest);
ret = simExecuteRestFulCommand(script, command); ret = simExecuteRestFulCommand(script, command);
} }
else { else {
ret = taos_query(script->taos, rest); pSql = taos_query(script->taos, rest);
ret = taos_errno(pSql);
taos_free_result(pSql);
} }
if (ret != TSDB_CODE_SUCCESS) { if (ret != TSDB_CODE_SUCCESS) {
...@@ -926,6 +933,7 @@ bool simExecuteSqlErrorCmd(SScript *script, char *rest) { ...@@ -926,6 +933,7 @@ bool simExecuteSqlErrorCmd(SScript *script, char *rest) {
script->linePos++; script->linePos++;
return true; return true;
} }
sprintf(script->error, "lineNum:%d. sql:%s expect failed, but success, ret:%d:%s", line->lineNum, rest, ret, tstrerror(ret)); sprintf(script->error, "lineNum:%d. sql:%s expect failed, but success, ret:%d:%s", line->lineNum, rest, ret, tstrerror(ret));
return false; return false;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册