diff --git a/cmake/tz_CMakeLists.txt.in b/cmake/tz_CMakeLists.txt.in new file mode 100644 index 0000000000..a2e3636d9a --- /dev/null +++ b/cmake/tz_CMakeLists.txt.in @@ -0,0 +1,15 @@ +# timezone +ExternalProject_Add(tz + GIT_REPOSITORY https://github.com/eggert/tz.git + GIT_TAG main + SOURCE_DIR "${TD_CONTRIB_DIR}/tz" + BINARY_DIR "" + CONFIGURE_COMMAND "" + #BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" + GIT_SHALLOW true + GIT_PROGRESS true + BUILD_COMMAND "" +) + diff --git a/contrib/CMakeLists.txt b/contrib/CMakeLists.txt index 7741ae4e14..78eded3928 100644 --- a/contrib/CMakeLists.txt +++ b/contrib/CMakeLists.txt @@ -106,6 +106,10 @@ cat("${TD_SUPPORT_DIR}/zlib_CMakeLists.txt.in" ${CONTRIB_TMP_FILE}) # cJson cat("${TD_SUPPORT_DIR}/cjson_CMakeLists.txt.in" ${CONTRIB_TMP_FILE}) +if(NOT ${TD_WINDOWS}) + cat("${TD_SUPPORT_DIR}/tz_CMakeLists.txt.in" ${CONTRIB_TMP_FILE}) +endif(NOT ${TD_WINDOWS}) + # xz # cat("${TD_SUPPORT_DIR}/xz_CMakeLists.txt.in" ${CONTRIB_TMP_FILE}) @@ -651,6 +655,35 @@ if(${TD_LINUX} AND ${BUILD_WITH_S3}) add_subdirectory(azure-cmake EXCLUDE_FROM_ALL) endif() +IF(TD_LINUX) + SET(TZ_OUTPUT_PATH /usr/share/zoneinfo) +ELSEIF(TD_DARWIN) + SET(TZ_OUTPUT_PATH /var/db/timezone/zoneinfo) +ENDIF() + + +if(NOT ${TD_WINDOWS}) + MESSAGE(STATUS "timezone file path: " ${TZ_OUTPUT_PATH}) + + execute_process( + COMMAND make TZDIR=${TZ_OUTPUT_PATH}/ clean tzdir.h + WORKING_DIRECTORY "${TD_CONTRIB_DIR}/tz" + ) + + set(TZ_SRC_DIR "${TD_SOURCE_DIR}/source/os/src/timezone") + file(REMOVE_RECURSE ${TZ_SRC_DIR}) + file(MAKE_DIRECTORY ${TZ_SRC_DIR}) + file(COPY ${TD_CONTRIB_DIR}/tz/private.h ${TD_CONTRIB_DIR}/tz/tzdir.h ${TD_CONTRIB_DIR}/tz/tzfile.h + ${TD_CONTRIB_DIR}/tz/localtime.c ${TD_CONTRIB_DIR}/tz/strftime.c + DESTINATION ${TZ_SRC_DIR}) +endif(NOT ${TD_WINDOWS}) + +#if(NOT ${TD_WINDOWS}) +# execute_process( +# COMMAND make CFLAGS+=-fPIC CFLAGS+=-g TZDIR=${TZ_OUTPUT_PATH} clean libtz.a +# WORKING_DIRECTORY "${TD_CONTRIB_DIR}/tz" +# ) +#endif(NOT ${TD_WINDOWS}) # ================================================================================================ # Build test # ================================================================================================ diff --git a/docs/en/14-reference/05-connector/10-cpp.mdx b/docs/en/14-reference/05-connector/10-cpp.mdx index ef3026bd0c..7e643304c3 100644 --- a/docs/en/14-reference/05-connector/10-cpp.mdx +++ b/docs/en/14-reference/05-connector/10-cpp.mdx @@ -688,6 +688,27 @@ The basic API is used to establish database connections and provide a runtime en - `arg`: [Input] Setting item value. - **Return Value**: `0`: Success, `-1`: Failure. +- `int taos_options_connection(TAOS *taos, TSDB_OPTION_CONNECTION option, const void *arg, ...)` + - **description**:Set each connection option on the client side. Currently, it supports character set setting(`TSDB_OPTION_CONNECTION_CHARSET`), time zone setting(`TSDB_OPTION_CONNECTION_TIMEZONE`), user IP setting(`TSDB_OPTION_CONNECTION_USER_IP`), and user APP setting(`TSDB_OPTION_CONNECTION_USER_APP`). + - **input**: + - `taos`: returned by taos_connect. + - `option`: option name. + - `arg`: option value. + - **return**: + - `0`: success. + - `others`: fail. + - **notice**: + - The character set and time zone default to the current settings of the operating system, and Windows does not support connection level time zone settings. + - When arg is NULL, it means resetting the option. + - This interface is only valid for the current connection and will not affect other connections. + - If the same parameter is called multiple times, the latter shall prevail and can be used as a modification method. + - The option of TSDB_OPTION_CONNECTION_CLEAR is used to reset all connection options. + - After resetting the time zone and character set, using the operating system settings, the user IP and user app will be reset to empty. + - The values of the connection options are all string type, and the maximum value of the user app parameter is 23, which will be truncated if exceeded; Error reported when other parameters are illegal. + - If time zone value can not be used to find a time zone file or can not be interpreted as a direct specification, UTC is used, which is the same as the operating system time zone rules. Please refer to the tzset function description for details. You can view the current time zone of the connection by sql:select timezone(). + - Time zones and character sets only work on the client side and do not affect related behaviors on the server side. + - The time zone file uses the operating system time zone file and can be updated by oneself. If there is an error when setting the time zone, please check if the time zone file or path (mac:/var/db/timezone/zoneinfo, Linux:/var/share/zoneinfo) is correct. + - `char *taos_get_client_info()` - **Interface Description**: Gets client version information. - **Return Value**: Returns client version information. diff --git a/docs/zh/14-reference/05-connector/10-cpp.mdx b/docs/zh/14-reference/05-connector/10-cpp.mdx index 7164baad2a..b434ff98a0 100644 --- a/docs/zh/14-reference/05-connector/10-cpp.mdx +++ b/docs/zh/14-reference/05-connector/10-cpp.mdx @@ -686,6 +686,25 @@ TDengine 客户端驱动的版本号与 TDengine 服务端的版本号是一一 - `arg`:[入参] 设置项值。 - **返回值**:`0`:成功,`-1`:失败。 +- `int taos_options_connection(TAOS *taos, TSDB_OPTION_CONNECTION option, const void *arg, ...)` + - **接口说明**:设置客户端每个连接选项,目前支持字符集设置(`TSDB_OPTION_CONNECTION_CHARSET`)、时区设置(`TSDB_OPTION_CONNECTION_TIMEZONE`)、用户 IP 设置(`TSDB_OPTION_CONNECTION_USER_IP`)、用户 APP 设置(`TSDB_OPTION_CONNECTION_USER_APP`)。 + - **参数说明**: + - `taos`: [入参] taos_connect 返回的连接句柄。 + - `option`:[入参] 设置项类型。 + - `arg`:[入参] 设置项值。 + - **返回值**:`0`:成功,`非0`:失败。 + - **说明**: + - 字符集、时区默认为操作系统当前设置,windows 不支持连接级别的时区设置。 + - arg 为 NULL 时表示重置该选项。 + - 该接口只对当前连接有效,不会影响其他连接。 + - 同样参数多次调用该接口,以后面的为准,可以作为修改的方法。 + - TSDB_OPTION_CONNECTION_CLEAR 选项用于重置所有连接选项。 + - 时区和字符集重置后,使用系统的设置,user ip 和 user app 重置后为空。 + - 连接选项的值都是 string 类型,user app 参数值最大为 23,超过该值会被截断;其他参数非法时报错。 + - 时区配置找不到时区文件或者不能按照规范解释时,默认为 UTC,和操作系统时区规则相同,详见 tzset 函数说明。可通过 select timezone() 查看当前连接的时区。 + - 时区和字符集只在 client 侧起作用,对于在服务端的相关行为不起作用。 + - 时区文件使用操作系统时区文件,可以自行更新操作系统时区文件。如果设置时区报错,请检查是否有时区文件或路径(mac:/var/db/timezone/zoneinfo, linux:/usr/share/zoneinfo)是否正确。 + - `char *taos_get_client_info()` - **接口说明**:获取客户端版本信息。 - **返回值**:返回客户端版本信息。 diff --git a/include/client/taos.h b/include/client/taos.h index 360a58ca2b..e59ea9d418 100644 --- a/include/client/taos.h +++ b/include/client/taos.h @@ -64,6 +64,15 @@ typedef enum { TSDB_MAX_OPTIONS } TSDB_OPTION; +typedef enum { + TSDB_OPTION_CONNECTION_CLEAR = -1, // means clear all option in this connection + TSDB_OPTION_CONNECTION_CHARSET, // charset, Same as the scope supported by the system + TSDB_OPTION_CONNECTION_TIMEZONE, // timezone, Same as the scope supported by the system + TSDB_OPTION_CONNECTION_USER_IP, // user ip + TSDB_OPTION_CONNECTION_USER_APP, // user app, max lengthe is 23, truncated if longer than 23 + TSDB_MAX_OPTIONS_CONNECTION +} TSDB_OPTION_CONNECTION; + typedef enum { TSDB_SML_UNKNOWN_PROTOCOL = 0, TSDB_SML_LINE_PROTOCOL = 1, @@ -174,11 +183,12 @@ typedef struct TAOS_STMT_OPTIONS { DLL_EXPORT void taos_cleanup(void); DLL_EXPORT int taos_options(TSDB_OPTION option, const void *arg, ...); +DLL_EXPORT int taos_options_connection(TAOS *taos, TSDB_OPTION_CONNECTION option, const void *arg, ...); DLL_EXPORT setConfRet taos_set_config(const char *config); DLL_EXPORT int taos_init(void); DLL_EXPORT TAOS *taos_connect(const char *ip, const char *user, const char *pass, const char *db, uint16_t port); -DLL_EXPORT TAOS *taos_connect_auth(const char *ip, const char *user, const char *auth, const char *db, uint16_t port); -DLL_EXPORT void taos_close(TAOS *taos); +DLL_EXPORT TAOS *taos_connect_auth(const char *ip, const char *user, const char *auth, const char *db, uint16_t port); +DLL_EXPORT void taos_close(TAOS *taos); DLL_EXPORT const char *taos_data_type(int type); diff --git a/include/common/tdataformat.h b/include/common/tdataformat.h index f899fc5589..cb05f98f45 100644 --- a/include/common/tdataformat.h +++ b/include/common/tdataformat.h @@ -154,7 +154,7 @@ int32_t tEncodeTag(SEncoder *pEncoder, const STag *pTag); int32_t tDecodeTag(SDecoder *pDecoder, STag **ppTag); int32_t tTagToValArray(const STag *pTag, SArray **ppArray); void debugPrintSTag(STag *pTag, const char *tag, int32_t ln); // TODO: remove -int32_t parseJsontoTagData(const char *json, SArray *pTagVals, STag **ppTag, void *pMsgBuf); +int32_t parseJsontoTagData(const char *json, SArray *pTagVals, STag **ppTag, void *pMsgBuf, void *charsetCxt); // SColData ================================ typedef struct { diff --git a/include/common/tmsg.h b/include/common/tmsg.h index 4db4f1600a..7abf38fdcf 100644 --- a/include/common/tmsg.h +++ b/include/common/tmsg.h @@ -1242,7 +1242,7 @@ typedef struct { } STsBufInfo; typedef struct { - int32_t tz; // query client timezone + void* timezone; char intervalUnit; char slidingUnit; char offsetUnit; @@ -3452,6 +3452,8 @@ typedef struct { SAppHbReq app; SQueryHbReqBasic* query; SHashObj* info; // hash + char userApp[TSDB_APP_NAME_LEN]; + uint32_t userIp; } SClientHbReq; typedef struct { @@ -3873,7 +3875,7 @@ typedef struct { int8_t igExists; int8_t intervalUnit; int8_t slidingUnit; - int8_t timezone; + int8_t timezone; // int8_t is not enough, timezone is unit of second int32_t dstVgId; // for stream int64_t interval; int64_t offset; diff --git a/include/common/ttime.h b/include/common/ttime.h index a54f8b2490..47875752d5 100644 --- a/include/common/ttime.h +++ b/include/common/ttime.h @@ -61,22 +61,9 @@ static FORCE_INLINE int64_t taosGetTimestamp(int32_t precision) { * precision == TSDB_TIME_PRECISION_MILLI, it returns timestamp in millisecond. * precision == TSDB_TIME_PRECISION_NANO, it returns timestamp in nanosecond. */ -static FORCE_INLINE int64_t taosGetTimestampToday(int32_t precision) { - int64_t factor = (precision == TSDB_TIME_PRECISION_MILLI) ? 1000 - : (precision == TSDB_TIME_PRECISION_MICRO) ? 1000000 - : 1000000000; - time_t t; - (void) taosTime(&t); - struct tm tm; - (void) taosLocalTime(&t, &tm, NULL, 0); - tm.tm_hour = 0; - tm.tm_min = 0; - tm.tm_sec = 0; +int64_t taosGetTimestampToday(int32_t precision, timezone_t tz); - return (int64_t)taosMktime(&tm) * factor; -} - -int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision); +int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision, timezone_t tz); int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval); int64_t taosTimeGetIntervalEnd(int64_t ts, const SInterval* pInterval); @@ -86,13 +73,12 @@ void calcIntervalAutoOffset(SInterval* interval); int32_t parseAbsoluteDuration(const char* token, int32_t tokenlen, int64_t* ts, char* unit, int32_t timePrecision); int32_t parseNatualDuration(const char* token, int32_t tokenLen, int64_t* duration, char* unit, int32_t timePrecision, bool negativeAllow); -int32_t taosParseTime(const char* timestr, int64_t* pTime, int32_t len, int32_t timePrec, int8_t dayligth); -void deltaToUtcInitOnce(); +int32_t taosParseTime(const char* timestr, int64_t* pTime, int32_t len, int32_t timePrec, timezone_t tz); char getPrecisionUnit(int32_t precision); int64_t convertTimePrecision(int64_t ts, int32_t fromPrecision, int32_t toPrecision); int32_t convertTimeFromPrecisionToUnit(int64_t time, int32_t fromPrecision, char toUnit, int64_t* pRes); -int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec, int64_t* timeVal); +int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec, int64_t* timeVal, timezone_t tz, void* charsetCxt); int32_t getDuration(int64_t val, char unit, int64_t* result, int32_t timePrecision); int32_t taosFormatUtcTime(char* buf, int32_t bufLen, int64_t ts, int32_t precision); @@ -102,8 +88,8 @@ struct STm { int64_t fsec; // in NANOSECOND }; -int32_t taosTs2Tm(int64_t ts, int32_t precision, struct STm* tm); -int32_t taosTm2Ts(struct STm* tm, int64_t* ts, int32_t precision); +int32_t taosTs2Tm(int64_t ts, int32_t precision, struct STm* tm, timezone_t tz); +int32_t taosTm2Ts(struct STm* tm, int64_t* ts, int32_t precision, timezone_t tz); /// @brief convert a timestamp to a formatted string /// @param format the timestamp format, must null terminated @@ -112,7 +98,7 @@ int32_t taosTm2Ts(struct STm* tm, int64_t* ts, int32_t precision); /// formats array; If not NULL, [formats] will be used instead of [format] to skip parse formats again. /// @param out output buffer, should be initialized by memset /// @notes remember to free the generated formats -int32_t taosTs2Char(const char* format, SArray** formats, int64_t ts, int32_t precision, char* out, int32_t outLen); +int32_t taosTs2Char(const char* format, SArray** formats, int64_t ts, int32_t precision, char* out, int32_t outLen, timezone_t tz); /// @brief convert a formatted timestamp string to a timestamp /// @param format must null terminated /// @param [in, out] formats, see taosTs2Char @@ -120,7 +106,7 @@ int32_t taosTs2Char(const char* format, SArray** formats, int64_t ts, int32_t pr /// @retval 0 for success, otherwise error occured /// @notes remember to free the generated formats even when error occured int32_t taosChar2Ts(const char* format, SArray** formats, const char* tsStr, int64_t* ts, int32_t precision, char* errMsg, - int32_t errMsgLen); + int32_t errMsgLen, timezone_t tz); int32_t TEST_ts2char(const char* format, int64_t ts, int32_t precision, char* out, int32_t outLen); int32_t TEST_char2ts(const char* format, int64_t* ts, int32_t precision, const char* tsStr); diff --git a/include/libs/command/command.h b/include/libs/command/command.h index 9fb2ca40b9..dd2441a115 100644 --- a/include/libs/command/command.h +++ b/include/libs/command/command.h @@ -22,7 +22,7 @@ typedef struct SExplainCtx SExplainCtx; -int32_t qExecCommand(int64_t* pConnId, bool sysInfoUser, SNode *pStmt, SRetrieveTableRsp **pRsp, int8_t biMode); +int32_t qExecCommand(int64_t* pConnId, bool sysInfoUser, SNode *pStmt, SRetrieveTableRsp **pRsp, int8_t biMode, void* charsetCxt); int32_t qExecStaticExplain(SQueryPlan *pDag, SRetrieveTableRsp **pRsp); int32_t qExecExplainBegin(SQueryPlan *pDag, SExplainCtx **pCtx, int64_t startTs); diff --git a/include/libs/function/function.h b/include/libs/function/function.h index 51d9e752a4..0ca1962b4e 100644 --- a/include/libs/function/function.h +++ b/include/libs/function/function.h @@ -292,8 +292,16 @@ struct SScalarParam { void *param; // other parameter, such as meta handle from vnode, to extract table name/tag value int32_t numOfRows; int32_t numOfQualified; // number of qualified elements in the final results + timezone_t tz; + void *charsetCxt; }; +static inline void setTzCharset(SScalarParam* param, timezone_t tz, void* charsetCxt){ + if (param == NULL) return; + param->tz = tz; + param->charsetCxt = charsetCxt; +} + #define cleanupResultRowEntry(p) p->initialized = false #define isRowEntryCompleted(p) (p->complete) #define isRowEntryInitialized(p) (p->initialized) diff --git a/include/libs/nodes/querynodes.h b/include/libs/nodes/querynodes.h index 667d610eab..5e4e8b6292 100644 --- a/include/libs/nodes/querynodes.h +++ b/include/libs/nodes/querynodes.h @@ -129,8 +129,10 @@ typedef struct SValueNode { double d; char* p; } datum; - int64_t typeData; - int8_t unit; + int64_t typeData; + int8_t unit; + timezone_t tz; + void *charsetCxt; } SValueNode; typedef struct SLeftValueNode { @@ -159,6 +161,8 @@ typedef struct SOperatorNode { EOperatorType opType; SNode* pLeft; SNode* pRight; + timezone_t tz; + void* charsetCxt; } SOperatorNode; typedef struct SLogicConditionNode { @@ -190,7 +194,9 @@ typedef struct SFunctionNode { bool hasOriginalFunc; int32_t originalFuncId; ETrimType trimType; - bool dual; // whether select stmt without from stmt, true for without. + bool dual; // whether select stmt without from stmt, true for without. + timezone_t tz; + void *charsetCxt; } SFunctionNode; typedef struct STableNode { @@ -332,6 +338,7 @@ typedef struct SIntervalWindowNode { SNode* pSliding; // SValueNode SNode* pFill; STimeWindow timeRange; + void* timezone; } SIntervalWindowNode; typedef struct SEventWindowNode { @@ -401,6 +408,8 @@ typedef struct SCaseWhenNode { SNode* pCase; SNode* pElse; SNodeList* pWhenThenList; + timezone_t tz; + void* charsetCxt; } SCaseWhenNode; typedef struct SWindowOffsetNode { diff --git a/include/libs/parser/parser.h b/include/libs/parser/parser.h index fbbe7cc40c..82985457a8 100644 --- a/include/libs/parser/parser.h +++ b/include/libs/parser/parser.h @@ -101,6 +101,8 @@ typedef struct SParseContext { int8_t biMode; SArray* pSubMetaList; setQueryFn setQueryFp; + timezone_t timezone; + void *charsetCxt; } SParseContext; int32_t qParseSql(SParseContext* pCxt, SQuery** pQuery); @@ -139,28 +141,28 @@ void qDestroyStmtDataBlock(STableDataCxt* pBlock); STableMeta* qGetTableMetaInDataBlock(STableDataCxt* pDataBlock); int32_t qCloneCurrentTbData(STableDataCxt* pDataBlock, SSubmitTbData** pData); -int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx); +int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx, void *charsetCxt); int32_t qStmtParseQuerySql(SParseContext* pCxt, SQuery* pQuery); int32_t qBindStmtStbColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, - STSchema** pTSchema, SBindInfo* pBindInfos); -int32_t qBindStmtColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen); + STSchema** pTSchema, SBindInfo* pBindInfos, void* charsetCxt); +int32_t qBindStmtColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, void* charsetCxt); int32_t qBindStmtSingleColValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, - int32_t colIdx, int32_t rowNum); + int32_t colIdx, int32_t rowNum, void* charsetCxt); int32_t qBuildStmtColFields(void* pDataBlock, int32_t* fieldNum, TAOS_FIELD_E** fields); int32_t qBuildStmtStbColFields(void* pBlock, void* boundTags, bool hasCtbName, int32_t* fieldNum, TAOS_FIELD_STB** fields); int32_t qBuildStmtTagFields(void* pBlock, void* boundTags, int32_t* fieldNum, TAOS_FIELD_E** fields); int32_t qBindStmtTagsValue(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, - TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen); + TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, void* charsetCxt); -int32_t qStmtBindParams2(SQuery* pQuery, TAOS_STMT2_BIND* pParams, int32_t colIdx); +int32_t qStmtBindParams2(SQuery* pQuery, TAOS_STMT2_BIND* pParams, int32_t colIdx, void* charsetCxt); int32_t qBindStmtStbColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, - STSchema** pTSchema, SBindInfo2* pBindInfos); -int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen); + STSchema** pTSchema, SBindInfo2* pBindInfos, void *charsetCxt); +int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, void *charsetCxt); int32_t qBindStmtSingleColValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, - int32_t colIdx, int32_t rowNum); + int32_t colIdx, int32_t rowNum, void *charsetCxt); int32_t qBindStmtTagsValue2(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, - TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen); + TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, void *charsetCxt); void destroyBoundColumnInfo(void* pBoundInfo); int32_t qCreateSName(SName* pName, const char* pTableName, int32_t acctId, char* dbName, char* msgBuf, @@ -170,13 +172,13 @@ void qDestroyBoundColInfo(void* pInfo); int32_t smlInitHandle(SQuery** query); int32_t smlBuildRow(STableDataCxt* pTableCxt); -int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* kv, int32_t index); +int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* kv, int32_t index, void* charsetCxt); int32_t smlInitTableDataCtx(SQuery* query, STableMeta* pTableMeta, STableDataCxt** cxt); void clearColValArraySml(SArray* pCols); int32_t smlBindData(SQuery* handle, bool dataFormat, SArray* tags, SArray* colsSchema, SArray* cols, STableMeta* pTableMeta, char* tableName, const char* sTableName, int32_t sTableNameLen, int32_t ttl, - char* msgBuf, int32_t msgBufLen); + char* msgBuf, int32_t msgBufLen, void* charsetCxt); int32_t smlBuildOutput(SQuery* handle, SHashObj* pVgHash); int rawBlockBindData(SQuery* query, STableMeta* pTableMeta, void* data, SVCreateTbReq* pCreateTb, void* fields, int numFields, bool needChangeLength, char* errstr, int32_t errstrLen, bool raw); diff --git a/include/libs/planner/planner.h b/include/libs/planner/planner.h index a78fc4d2a6..92417bbf32 100644 --- a/include/libs/planner/planner.h +++ b/include/libs/planner/planner.h @@ -46,6 +46,7 @@ typedef struct SPlanContext { int64_t allocatorId; bool destHasPrimaryKey; bool sourceHasPrimaryKey; + void* timezone; } SPlanContext; // Create the physical plan for the query, according to the AST. diff --git a/include/libs/qcom/query.h b/include/libs/qcom/query.h index d62edb158d..1d4542b531 100644 --- a/include/libs/qcom/query.h +++ b/include/libs/qcom/query.h @@ -338,7 +338,7 @@ SSchema createSchema(int8_t type, int32_t bytes, col_id_t colId, const char* nam void destroyQueryExecRes(SExecResult* pRes); int32_t dataConverToStr(char* str, int64_t capacity, int type, void* buf, int32_t bufSize, int32_t* len); -void parseTagDatatoJson(void* p, char** jsonStr); +void parseTagDatatoJson(void* p, char** jsonStr, void *charsetCxt); int32_t cloneTableMeta(STableMeta* pSrc, STableMeta** pDst); void getColumnTypeFromMeta(STableMeta* pMeta, char* pName, ETableColumnType* pType); int32_t cloneDbVgInfo(SDBVgInfo* pSrc, SDBVgInfo** pDst); diff --git a/include/libs/scalar/scalar.h b/include/libs/scalar/scalar.h index 4b89a6a439..fd936dd087 100644 --- a/include/libs/scalar/scalar.h +++ b/include/libs/scalar/scalar.h @@ -105,7 +105,6 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara int32_t timeDiffFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput); int32_t nowFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput); int32_t todayFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput); -int32_t timeZoneStrLen(); int32_t timezoneFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput); int32_t weekdayFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput); int32_t dayofweekFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput); diff --git a/include/os/osEnv.h b/include/os/osEnv.h index f235d3f235..85fdb7c38c 100644 --- a/include/os/osEnv.h +++ b/include/os/osEnv.h @@ -25,10 +25,9 @@ extern "C" { extern char tsOsName[]; extern char tsTimezoneStr[]; -extern enum TdTimezone tsTimezone; extern char tsCharset[]; +extern void *tsCharsetCxt; extern char tsLocale[]; -extern int8_t tsDaylight; extern bool tsEnableCoreFile; extern int64_t tsPageSizeKB; extern int64_t tsOpenMax; @@ -67,8 +66,7 @@ bool osDataSpaceSufficient(); bool osTempSpaceSufficient(); int32_t osSetTimezone(const char *timezone); -void osSetSystemLocale(const char *inLocale, const char *inCharSet); -void osSetProcPath(int32_t argc, char **argv); +void osSetProcPath(int32_t argc, char **argv); #ifdef __cplusplus } diff --git a/include/os/osLocale.h b/include/os/osLocale.h index 5f2a1c35de..d7a3540887 100644 --- a/include/os/osLocale.h +++ b/include/os/osLocale.h @@ -30,7 +30,7 @@ extern "C" { char *taosCharsetReplace(char *charsetstr); void taosGetSystemLocale(char *outLocale, char *outCharset); -int32_t taosSetSystemLocale(const char *inLocale, const char *inCharSet); +int32_t taosSetSystemLocale(const char *inLocale); #ifdef __cplusplus } diff --git a/include/os/osSocket.h b/include/os/osSocket.h index 49acf285ee..5d95ff308c 100644 --- a/include/os/osSocket.h +++ b/include/os/osSocket.h @@ -26,8 +26,8 @@ #define epoll_create EPOLL_CREATE_FUNC_TAOS_FORBID #define epoll_ctl EPOLL_CTL_FUNC_TAOS_FORBID #define epoll_wait EPOLL_WAIT_FUNC_TAOS_FORBID -#define inet_addr INET_ADDR_FUNC_TAOS_FORBID #define inet_ntoa INET_NTOA_FUNC_TAOS_FORBID +#define inet_addr INET_ADDR_FUNC_TAOS_FORBID #endif #if defined(WINDOWS) @@ -55,10 +55,10 @@ #define __BIG_ENDIAN BIG_ENDIAN #define __LITTLE_ENDIAN LITTLE_ENDIAN #define __PDP_ENDIAN PDP_ENDIAN - #else #include #include +#include #if defined(_TD_DARWIN_64) #include @@ -162,10 +162,10 @@ int32_t taosGetSocketName(TdSocketPtr pSocket, struct sockaddr *destAddr, int *a int32_t taosBlockSIGPIPE(); int32_t taosGetIpv4FromFqdn(const char *fqdn, uint32_t *ip); int32_t taosGetFqdn(char *); -void tinet_ntoa(char *ipstr, uint32_t ip); -uint32_t ip2uint(const char *const ip_addr); +void taosInetNtoa(char *ipstr, uint32_t ip); +uint32_t taosInetAddr(const char *ipstr); int32_t taosIgnSIGPIPE(); -const char *taosInetNtoa(struct in_addr ipInt, char *dstStr, int32_t len); +const char *taosInetNtop(struct in_addr ipInt, char *dstStr, int32_t len); uint64_t taosHton64(uint64_t val); uint64_t taosNtoh64(uint64_t val); diff --git a/include/os/osString.h b/include/os/osString.h index 995aa4a591..c30437ee2c 100644 --- a/include/os/osString.h +++ b/include/os/osString.h @@ -22,12 +22,24 @@ extern "C" { typedef wchar_t TdWchar; typedef int32_t TdUcs4; -#if !defined(DISALLOW_NCHAR_WITHOUT_ICONV) && defined(DARWIN) +#if !defined(DISALLOW_NCHAR_WITHOUT_ICONV)// && defined(DARWIN) #include "iconv.h" #else typedef void *iconv_t; #endif -typedef enum { M2C = 0, C2M } ConvType; +typedef enum { M2C = 0, C2M, CM_NUM } ConvType; + +typedef struct { + iconv_t conv; + int8_t inUse; +} SConv; + +typedef struct { + SConv *gConv[CM_NUM]; + int32_t convUsed[CM_NUM]; + int32_t gConvMaxNum[CM_NUM]; + char charset[TD_CHARSET_LEN]; +} SConvInfo; // If the error is in a third-party library, place this header file under the third-party library header file. // When you want to use this feature, you should find or add the same function in the following section. @@ -78,13 +90,11 @@ int32_t taosStr2int16(const char *str, int16_t *val); int32_t taosStr2int32(const char *str, int32_t *val); int32_t taosStr2int8(const char *str, int8_t *val); -int32_t taosConvInit(void); -void taosConvDestroy(); -iconv_t taosAcquireConv(int32_t *idx, ConvType type); -void taosReleaseConv(int32_t idx, iconv_t conv, ConvType type); -int32_t taosUcs4ToMbs(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs); +iconv_t taosAcquireConv(int32_t *idx, ConvType type, void* charsetCxt); +void taosReleaseConv(int32_t idx, iconv_t conv, ConvType type, void* charsetCxt); +int32_t taosUcs4ToMbs(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs, void* charsetCxt); int32_t taosUcs4ToMbsEx(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs, iconv_t conv); -bool taosMbsToUcs4(const char *mbs, size_t mbs_len, TdUcs4 *ucs4, int32_t ucs4_max_len, int32_t *len); +bool taosMbsToUcs4(const char *mbs, size_t mbs_len, TdUcs4 *ucs4, int32_t ucs4_max_len, int32_t *len, void* charsetCxt); int32_t tasoUcs4Compare(TdUcs4 *f1_ucs4, TdUcs4 *f2_ucs4, int32_t bytes); int32_t tasoUcs4Copy(TdUcs4 *target_ucs4, TdUcs4 *source_ucs4, int32_t len_ucs4); bool taosValidateEncodec(const char *encodec); diff --git a/include/os/osTime.h b/include/os/osTime.h index 7a65efe28d..69ae8f5e2e 100644 --- a/include/os/osTime.h +++ b/include/os/osTime.h @@ -24,6 +24,7 @@ extern "C" { // When you want to use this feature, you should find or add the same function in the following section. #ifndef ALLOW_FORBID_FUNC #define strptime STRPTIME_FUNC_TAOS_FORBID +#define strftime STRFTIME_FUNC_TAOS_FORBID #define gettimeofday GETTIMEOFDAY_FUNC_TAOS_FORBID #define localtime LOCALTIME_FUNC_TAOS_FORBID #define localtime_s LOCALTIMES_FUNC_TAOS_FORBID @@ -42,6 +43,7 @@ extern "C" { #define MILLISECOND_PER_SECOND ((int64_t)1000LL) #endif +#include "osTimezone.h" #define MILLISECOND_PER_MINUTE (MILLISECOND_PER_SECOND * 60) #define MILLISECOND_PER_HOUR (MILLISECOND_PER_MINUTE * 60) #define MILLISECOND_PER_DAY (MILLISECOND_PER_HOUR * 24) @@ -91,13 +93,17 @@ static FORCE_INLINE int64_t taosGetMonoTimestampMs() { } char *taosStrpTime(const char *buf, const char *fmt, struct tm *tm); -struct tm *taosLocalTime(const time_t *timep, struct tm *result, char *buf, int32_t bufSize); -struct tm *taosLocalTimeNolock(struct tm *result, const time_t *timep, int dst); +size_t taosStrfTime(char *s, size_t maxsize, char const *format, struct tm const *t); +struct tm *taosLocalTime(const time_t *timep, struct tm *result, char *buf, int32_t bufSize, timezone_t tz); +struct tm *taosGmTimeR(const time_t *timep, struct tm *result); +time_t taosTimeGm(struct tm *tmp); int32_t taosTime(time_t *t); -time_t taosMktime(struct tm *timep); +time_t taosMktime(struct tm *timep, timezone_t tz); int64_t user_mktime64(const uint32_t year, const uint32_t mon, const uint32_t day, const uint32_t hour, const uint32_t min, const uint32_t sec, int64_t time_zone); +//struct tm *taosLocalTimeRz(timezone_t state, const time_t *timep, struct tm *result); +//time_t taosMktimeRz(timezone_t state, struct tm *timep); #ifdef __cplusplus } #endif diff --git a/include/os/osTimezone.h b/include/os/osTimezone.h index 2a8d5a442d..f770a9dba0 100644 --- a/include/os/osTimezone.h +++ b/include/os/osTimezone.h @@ -20,43 +20,29 @@ extern "C" { #endif -// If the error is in a third-party library, place this header file under the third-party library header file. -// When you want to use this feature, you should find or add the same function in the following section. -#ifndef ALLOW_FORBID_FUNC -#define tzset TZSET_FUNC_TAOS_FORBID +#define TdEastZone8 8*60*60 +#define TZ_UNKNOWN "n/a" + +extern void* pTimezoneNameMap; + +#ifdef WINDOWS +typedef void *timezone_t; +#else +typedef struct state *timezone_t; + +struct tm* localtime_rz(timezone_t , time_t const *, struct tm *); +time_t mktime_z(timezone_t, struct tm *); +timezone_t tzalloc(char const *); +void tzfree(timezone_t); +void getTimezoneStr(char *tz); + #endif -enum TdTimezone { - TdWestZone12 = -12, - TdWestZone11, - TdWestZone10, - TdWestZone9, - TdWestZone8, - TdWestZone7, - TdWestZone6, - TdWestZone5, - TdWestZone4, - TdWestZone3, - TdWestZone2, - TdWestZone1, - TdZeroZone, - TdEastZone1, - TdEastZone2, - TdEastZone3, - TdEastZone4, - TdEastZone5, - TdEastZone6, - TdEastZone7, - TdEastZone8, - TdEastZone9, - TdEastZone10, - TdEastZone11, - TdEastZone12 -}; - -int32_t taosGetSystemTimezone(char *outTimezone, enum TdTimezone *tsTimezone); -int32_t taosSetSystemTimezone(const char *inTimezone, char *outTimezone, int8_t *outDaylight, enum TdTimezone *tsTimezone); +int32_t taosGetLocalTimezoneOffset(); +int32_t taosGetSystemTimezone(char *outTimezone); +int32_t taosSetGlobalTimezone(const char *tz); +int32_t taosFormatTimezoneStr(time_t t, const char* tzStr, timezone_t sp, char *outTimezoneStr); #ifdef __cplusplus } #endif diff --git a/include/util/taoserror.h b/include/util/taoserror.h index a01bbf66a6..a5942606eb 100644 --- a/include/util/taoserror.h +++ b/include/util/taoserror.h @@ -210,6 +210,7 @@ int32_t taosGetErrSize(); #define TSDB_CODE_TSC_COMPRESS_LEVEL_ERROR TAOS_DEF_ERROR_CODE(0, 0x0234) #define TSDB_CODE_TSC_FAIL_GENERATE_JSON TAOS_DEF_ERROR_CODE(0, 0x0235) #define TSDB_CODE_TSC_STMT_BIND_NUMBER_ERROR TAOS_DEF_ERROR_CODE(0, 0x0236) +#define TSDB_CODE_NOT_SUPPORTTED_IN_WINDOWS TAOS_DEF_ERROR_CODE(0, 0x0237) #define TSDB_CODE_TSC_INTERNAL_ERROR TAOS_DEF_ERROR_CODE(0, 0x02FF) // mnode-common @@ -480,7 +481,7 @@ int32_t taosGetErrSize(); #define TSDB_CODE_DNODE_INVALID_MONITOR_PARAS TAOS_DEF_ERROR_CODE(0, 0x0429) #define TSDB_CODE_MNODE_STOPPED TAOS_DEF_ERROR_CODE(0, 0x042A) -// anode +// anode #define TSDB_CODE_MND_ANODE_ALREADY_EXIST TAOS_DEF_ERROR_CODE(0, 0x0430) #define TSDB_CODE_MND_ANODE_NOT_EXIST TAOS_DEF_ERROR_CODE(0, 0x0431) #define TSDB_CODE_MND_ANODE_TOO_LONG_URL TAOS_DEF_ERROR_CODE(0, 0x0432) diff --git a/include/util/tconfig.h b/include/util/tconfig.h index 3fc247982f..947ef67902 100644 --- a/include/util/tconfig.h +++ b/include/util/tconfig.h @@ -34,7 +34,8 @@ typedef enum { CFG_STYPE_APOLLO_URL, CFG_STYPE_ARG_LIST, CFG_STYPE_TAOS_OPTIONS, - CFG_STYPE_ALTER_CMD, + CFG_STYPE_ALTER_CLIENT_CMD, + CFG_STYPE_ALTER_SERVER_CMD, } ECfgSrcType; typedef enum { diff --git a/include/util/tconv.h b/include/util/tconv.h new file mode 100644 index 0000000000..c886b38f51 --- /dev/null +++ b/include/util/tconv.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * This program is free software: you can use, redistribute, and/or modify + * it under the terms of the GNU Affero General Public License, version 3 + * or later ("AGPL"), as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#ifndef TDENGINE_TCONV_H +#define TDENGINE_TCONV_H + +#ifdef __cplusplus +extern "C" { +#endif + +//#include "osString.h" +// +//bool taosValidateEncodec(const char *encodec); +//int32_t taosUcs4len(TdUcs4 *ucs4); +void* taosConvInit(const char* charset); +void taosConvDestroy(); +//iconv_t taosAcquireConv(int32_t *idx, ConvType type, void* charsetCxt); +//void taosReleaseConv(int32_t idx, iconv_t conv, ConvType type, void* charsetCxt); +//int32_t taosUcs4ToMbs(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs, void* charsetCxt); +//int32_t taosUcs4ToMbsEx(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs, iconv_t conv); +//bool taosMbsToUcs4(const char *mbs, size_t mbs_len, TdUcs4 *ucs4, int32_t ucs4_max_len, int32_t *len, void* charsetCxt); +//int32_t tasoUcs4Compare(TdUcs4 *f1_ucs4, TdUcs4 *f2_ucs4, int32_t bytes); +//int32_t tasoUcs4Copy(TdUcs4 *target_ucs4, TdUcs4 *source_ucs4, int32_t len_ucs4); + +#ifdef __cplusplus +} +#endif + +#endif // TDENGINE_TCONV_H diff --git a/include/util/tencode.h b/include/util/tencode.h index b66e79fa60..270d9e75df 100644 --- a/include/util/tencode.h +++ b/include/util/tencode.h @@ -413,21 +413,26 @@ static FORCE_INLINE int32_t tDecodeBinary(SDecoder* pCoder, uint8_t** val, uint3 static FORCE_INLINE int32_t tDecodeCStrAndLen(SDecoder* pCoder, char** val, uint32_t* len) { TAOS_CHECK_RETURN(tDecodeBinary(pCoder, (uint8_t**)val, len)); - (*len) -= 1; + if (*len > 0) { // notice!!! *len maybe 0 + (*len) -= 1; + } return 0; } static FORCE_INLINE int32_t tDecodeCStr(SDecoder* pCoder, char** val) { - uint32_t len; + uint32_t len = 0; return tDecodeCStrAndLen(pCoder, val, &len); } static int32_t tDecodeCStrTo(SDecoder* pCoder, char* val) { - char* pStr; - uint32_t len; + char* pStr = NULL; + uint32_t len = 0; TAOS_CHECK_RETURN(tDecodeCStrAndLen(pCoder, &pStr, &len)); - TAOS_MEMCPY(val, pStr, len + 1); + if (len < pCoder->size) { + TAOS_MEMCPY(val, pStr, len + 1); + } + return 0; } @@ -479,12 +484,14 @@ static FORCE_INLINE int32_t tDecodeBinaryAlloc32(SDecoder* pCoder, void** val, u static FORCE_INLINE int32_t tDecodeCStrAndLenAlloc(SDecoder* pCoder, char** val, uint64_t* len) { TAOS_CHECK_RETURN(tDecodeBinaryAlloc(pCoder, (void**)val, len)); - (*len) -= 1; + if (*len > 0){ + (*len) -= 1; + } return 0; } static FORCE_INLINE int32_t tDecodeCStrAlloc(SDecoder* pCoder, char** val) { - uint64_t len; + uint64_t len = 0; return tDecodeCStrAndLenAlloc(pCoder, val, &len); } diff --git a/include/util/tutil.h b/include/util/tutil.h index c1b6b2505b..d88363bf37 100644 --- a/include/util/tutil.h +++ b/include/util/tutil.h @@ -48,11 +48,6 @@ int32_t taosHexStrToByteArray(char hexstr[], char bytes[]); int32_t tintToHex(uint64_t val, char hex[]); int32_t titoa(uint64_t val, size_t radix, char str[]); -char *taosIpStr(uint32_t ipInt); -uint32_t ip2uint(const char *const ip_addr); -void taosIp2String(uint32_t ip, char *str); -void taosIpPort2String(uint32_t ip, uint16_t port, char *str); - void *tmemmem(const char *haystack, int hlen, const char *needle, int nlen); int32_t parseCfgReal(const char *str, float *out); diff --git a/packaging/tools/make_install.sh b/packaging/tools/make_install.sh index 0874433e94..0bc82cdbd1 100755 --- a/packaging/tools/make_install.sh +++ b/packaging/tools/make_install.sh @@ -52,6 +52,7 @@ else installDir="/usr/local/taos" fi fi + install_main_dir=${installDir} bin_dir="${installDir}/bin" cfg_dir="${installDir}/cfg" diff --git a/source/client/inc/clientInt.h b/source/client/inc/clientInt.h index da56dcf75e..bc80cb2673 100644 --- a/source/client/inc/clientInt.h +++ b/source/client/inc/clientInt.h @@ -153,6 +153,13 @@ typedef struct { __taos_notify_fn_t fp; } SWhiteListInfo; +typedef struct { + timezone_t timezone; + void *charsetCxt; + char userApp[TSDB_APP_NAME_LEN]; + uint32_t userIp; +}SOptionInfo; + typedef struct STscObj { char user[TSDB_USER_LEN]; char pass[TSDB_PASSWORD_LEN]; @@ -175,6 +182,7 @@ typedef struct STscObj { SPassInfo passInfo; SWhiteListInfo whiteListInfo; STscNotifyInfo userDroppedInfo; + SOptionInfo optionInfo; } STscObj; typedef struct STscDbg { @@ -211,6 +219,7 @@ typedef struct SReqResultInfo { int32_t precision; int32_t payloadLen; char* convertJson; + void* charsetCxt; } SReqResultInfo; typedef struct SRequestSendRecvBody { @@ -338,6 +347,7 @@ extern int32_t clientReqRefPool; extern int32_t clientConnRefPool; extern int32_t timestampDeltaLimit; extern int64_t lastClusterId; +extern SHashObj* pTimezoneMap; __async_send_cb_fn_t getMsgRspHandle(int32_t msgType); @@ -437,6 +447,9 @@ void stopAllQueries(SRequestObj* pRequest); void doRequestCallback(SRequestObj* pRequest, int32_t code); void freeQueryParam(SSyncQueryParam* param); +int32_t tzInit(); +void tzCleanup(); + #ifdef TD_ENTERPRISE int32_t clientParseSqlImpl(void* param, const char* dbName, const char* sql, bool parseOnly, const char* effeciveUser, SParseSqlRes* pRes); diff --git a/source/client/src/clientEnv.c b/source/client/src/clientEnv.c index 072cbee2f4..a3ffa7f3c2 100644 --- a/source/client/src/clientEnv.c +++ b/source/client/src/clientEnv.c @@ -36,6 +36,7 @@ #include "tsched.h" #include "ttime.h" #include "tversion.h" +#include "tconv.h" #if defined(CUS_NAME) || defined(CUS_PROMPT) || defined(CUS_EMAIL) #include "cus_name.h" @@ -74,6 +75,7 @@ int64_t lastClusterId = 0; int32_t clientReqRefPool = -1; int32_t clientConnRefPool = -1; int32_t clientStop = -1; +SHashObj* pTimezoneMap = NULL; int32_t timestampDeltaLimit = 900; // s @@ -559,6 +561,7 @@ int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj (*pRequest)->metric.start = taosGetTimestampUs(); (*pRequest)->body.resInfo.convertUcs4 = true; // convert ucs4 by default + (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt; (*pRequest)->type = type; (*pRequest)->allocatorRefId = -1; @@ -956,25 +959,31 @@ void taos_init_imp(void) { return; } taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst); - deltaToUtcInitOnce(); const char *logName = CUS_PROMPT "slog"; ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output"); if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) { (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(errno), configDir); - tscInitRes = -1; + tscInitRes = terrno; return; } ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg"); initQueryModuleMsgHandle(); - ENV_ERR_RET(taosConvInit(), "failed to init conv"); + if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL){ + tscInitRes = terrno; + tscError("failed to init conv"); + return; + } +#ifndef WINDOWS + ENV_ERR_RET(tzInit(), "failed to init timezone"); +#endif ENV_ERR_RET(monitorInit(), "failed to init monitor"); ENV_ERR_RET(rpcInit(), "failed to init rpc"); if (InitRegexCache() != 0) { - tscInitRes = -1; + tscInitRes = terrno; (void)printf("failed to init regex cache\n"); return; } diff --git a/source/client/src/clientHb.c b/source/client/src/clientHb.c index 07be4bb596..23b3b0315f 100644 --- a/source/client/src/clientHb.c +++ b/source/client/src/clientHb.c @@ -1194,6 +1194,9 @@ int32_t hbGatherAllInfo(SAppHbMgr *pAppHbMgr, SClientHbBatchReq **pBatchReq) { continue; } + tstrncpy(pOneReq->userApp, pTscObj->optionInfo.userApp, sizeof(pOneReq->userApp)); + pOneReq->userIp = pTscObj->optionInfo.userIp; + pOneReq = taosArrayPush((*pBatchReq)->reqs, pOneReq); if (NULL == pOneReq) { releaseTscObj(connKey->tscRid); diff --git a/source/client/src/clientImpl.c b/source/client/src/clientImpl.c index 2c98ecac1b..e5e304bc79 100644 --- a/source/client/src/clientImpl.c +++ b/source/client/src/clientImpl.c @@ -300,7 +300,9 @@ int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtC .svrVer = pTscObj->sVer, .nodeOffline = (pTscObj->pAppInfo->onlineDnodes < pTscObj->pAppInfo->totalDnodes), .isStmtBind = pRequest->isStmtBind, - .setQueryFp = setQueryRequest}; + .setQueryFp = setQueryRequest, + .timezone = pTscObj->optionInfo.timezone, + .charsetCxt = pTscObj->optionInfo.charsetCxt,}; cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp); int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog); @@ -331,7 +333,7 @@ int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery, SStmtC int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) { SRetrieveTableRsp* pRsp = NULL; int8_t biMode = atomic_load_8(&pRequest->pTscObj->biMode); - int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode); + int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, biMode, pRequest->pTscObj->optionInfo.charsetCxt); if (TSDB_CODE_SUCCESS == code && NULL != pRsp) { code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4); } @@ -369,7 +371,7 @@ void asyncExecLocalCmd(SRequestObj* pRequest, SQuery* pQuery) { } int32_t code = qExecCommand(&pRequest->pTscObj->id, pRequest->pTscObj->sysInfo, pQuery->pRoot, &pRsp, - atomic_load_8(&pRequest->pTscObj->biMode)); + atomic_load_8(&pRequest->pTscObj->biMode), pRequest->pTscObj->optionInfo.charsetCxt); if (TSDB_CODE_SUCCESS == code && NULL != pRsp) { code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp, pRequest->body.resInfo.convertUcs4); } @@ -507,6 +509,7 @@ int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArra .pMsg = pRequest->msgBuf, .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE, .pUser = pRequest->pTscObj->user, + .timezone = pRequest->pTscObj->optionInfo.timezone, .sysInfo = pRequest->pTscObj->sysInfo}; return qCreateQueryPlan(&cxt, pPlan, pNodeList); @@ -1361,6 +1364,7 @@ static int32_t asyncExecSchQuery(SRequestObj* pRequest, SQuery* pQuery, SMetaDat .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE, .pUser = pRequest->pTscObj->user, .sysInfo = pRequest->pTscObj->sysInfo, + .timezone = pRequest->pTscObj->optionInfo.timezone, .allocatorId = pRequest->allocatorRefId}; if (TSDB_CODE_SUCCESS == code) { code = qCreateQueryPlan(&cxt, &pDag, pMnodeList); @@ -2086,7 +2090,7 @@ static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) { static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength) { int32_t idx = -1; - iconv_t conv = taosAcquireConv(&idx, C2M); + iconv_t conv = taosAcquireConv(&idx, C2M, pResultInfo->charsetCxt); if (conv == (iconv_t)-1) return TSDB_CODE_TSC_INTERNAL_ERROR; for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) { @@ -2096,7 +2100,7 @@ static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength) { if (type == TSDB_DATA_TYPE_NCHAR && colLength[i] > 0) { char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]); if (p == NULL) { - taosReleaseConv(idx, conv, C2M); + taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt); return terrno; } @@ -2113,7 +2117,7 @@ static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength) { "doConvertUCS4 error, invalid data. len:%d, bytes:%d, (p + len):%p, (pResultInfo->convertBuf[i] + " "colLength[i]):%p", len, bytes, (p + len), (pResultInfo->convertBuf[i] + colLength[i])); - taosReleaseConv(idx, conv, C2M); + taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt); return TSDB_CODE_TSC_INTERNAL_ERROR; } @@ -2127,7 +2131,7 @@ static int32_t doConvertUCS4(SReqResultInfo* pResultInfo, int32_t* colLength) { pResultInfo->row[i] = pResultInfo->pCol[i].pData; } } - taosReleaseConv(idx, conv, C2M); + taosReleaseConv(idx, conv, C2M, pResultInfo->charsetCxt); return TSDB_CODE_SUCCESS; } @@ -2292,7 +2296,7 @@ static int32_t doConvertJson(SReqResultInfo* pResultInfo) { varDataSetLen(dst, strlen(varDataVal(dst))); } else if (tTagIsJson(data)) { char* jsonString = NULL; - parseTagDatatoJson(data, &jsonString); + parseTagDatatoJson(data, &jsonString, pResultInfo->charsetCxt); if (jsonString == NULL) { tscError("doConvertJson error: parseTagDatatoJson failed"); return terrno; @@ -2302,9 +2306,10 @@ static int32_t doConvertJson(SReqResultInfo* pResultInfo) { } else if (jsonInnerType == TSDB_DATA_TYPE_NCHAR) { // value -> "value" *(char*)varDataVal(dst) = '\"'; int32_t length = taosUcs4ToMbs((TdUcs4*)varDataVal(jsonInnerData), varDataLen(jsonInnerData), - varDataVal(dst) + CHAR_BYTES); + varDataVal(dst) + CHAR_BYTES, pResultInfo->charsetCxt); if (length <= 0) { - tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC, tsCharset); + tscError("charset:%s to %s. convert failed.", DEFAULT_UNICODE_ENCODEC, + pResultInfo->charsetCxt != NULL ? ((SConvInfo *)(pResultInfo->charsetCxt))->charset : tsCharset); length = 0; } varDataSetLen(dst, length + CHAR_BYTES * 2); diff --git a/source/client/src/clientMain.c b/source/client/src/clientMain.c index 1f41a9b0b0..d80c7df2e4 100644 --- a/source/client/src/clientMain.c +++ b/source/client/src/clientMain.c @@ -30,6 +30,7 @@ #include "tref.h" #include "trpc.h" #include "version.h" +#include "tconv.h" #define TSC_VAR_NOT_RELEASE 1 #define TSC_VAR_RELEASED 0 @@ -38,11 +39,13 @@ static int32_t sentinel = TSC_VAR_NOT_RELEASE; static int32_t createParseContext(const SRequestObj *pRequest, SParseContext **pCxt, SSqlCallbackWrapper *pWrapper); int taos_options(TSDB_OPTION option, const void *arg, ...) { + if (arg == NULL) { + return TSDB_CODE_INVALID_PARA; + } static int32_t lock = 0; for (int i = 1; atomic_val_compare_exchange_32(&lock, 0, 1) != 0; ++i) { if (i % 1000 == 0) { - tscInfo("haven't acquire lock after spin %d times.", i); (void)sched_yield(); } } @@ -51,6 +54,167 @@ int taos_options(TSDB_OPTION option, const void *arg, ...) { atomic_store_32(&lock, 0); return ret; } + +#ifndef WINDOWS +static void freeTz(void *p){ + timezone_t tz = *(timezone_t *)p; + tzfree(tz); +} + +int32_t tzInit(){ + pTimezoneMap = taosHashInit(0, MurmurHash3_32, false, HASH_ENTRY_LOCK); + if (pTimezoneMap == NULL) { + return terrno; + } + taosHashSetFreeFp(pTimezoneMap, freeTz); + + pTimezoneNameMap = taosHashInit(0, taosIntHash_64, false, HASH_ENTRY_LOCK); + if (pTimezoneNameMap == NULL) { + return terrno; + } + return 0; +} + +void tzCleanup(){ + taosHashCleanup(pTimezoneMap); + taosHashCleanup(pTimezoneNameMap); +} + +static timezone_t setConnnectionTz(const char* val){ + timezone_t tz = NULL; + timezone_t *tmp = taosHashGet(pTimezoneMap, val, strlen(val)); + if (tmp != NULL && *tmp != NULL){ + tz = *tmp; + goto END; + } + + tscDebug("set timezone to %s", val); + tz = tzalloc(val); + if (tz == NULL) { + tscWarn("%s unknown timezone %s change to UTC", __func__, val); + tz = tzalloc("UTC"); + if (tz == NULL) { + tscError("%s set timezone UTC error", __func__); + terrno = TAOS_SYSTEM_ERROR(errno); + goto END; + } + } + int32_t code = taosHashPut(pTimezoneMap, val, strlen(val), &tz, sizeof(timezone_t)); + if (code != 0){ + tscError("%s put timezone to tz map error:%d", __func__, code); + tzfree(tz); + tz = NULL; + goto END; + } + + time_t tx1 = taosGetTimestampSec(); + char output[TD_TIMEZONE_LEN] = {0}; + taosFormatTimezoneStr(tx1, val, tz, output); + code = taosHashPut(pTimezoneNameMap, &tz, sizeof(timezone_t), output, strlen(output) + 1); + if (code != 0){ + tscError("failed to put timezone %s to map", val); + } + +END: + return tz; +} +#endif + +static int32_t setConnectionOption(TAOS *taos, TSDB_OPTION_CONNECTION option, const char* val){ + if (taos == NULL) { + return TSDB_CODE_INVALID_PARA; + } + +#ifdef WINDOWS + if (option == TSDB_OPTION_CONNECTION_TIMEZONE){ + return TSDB_CODE_NOT_SUPPORTTED_IN_WINDOWS; + } +#endif + + if (option < TSDB_OPTION_CONNECTION_CLEAR || option >= TSDB_MAX_OPTIONS_CONNECTION){ + return TSDB_CODE_INVALID_PARA; + } + + int32_t code = taos_init(); + // initialize global config + if (code != 0) { + return code; + } + + STscObj *pObj = acquireTscObj(*(int64_t *)taos); + if (NULL == pObj) { + tscError("invalid parameter for %s", __func__); + return terrno; + } + + if (option == TSDB_OPTION_CONNECTION_CLEAR){ + val = NULL; + } + + if (option == TSDB_OPTION_CONNECTION_CHARSET || option == TSDB_OPTION_CONNECTION_CLEAR) { + if (val != NULL) { + if (!taosValidateEncodec(val)) { + code = terrno; + goto END; + } + void *tmp = taosConvInit(val); + if (tmp == NULL) { + code = terrno; + goto END; + } + pObj->optionInfo.charsetCxt = tmp; + }else{ + pObj->optionInfo.charsetCxt = NULL; + } + } + + if (option == TSDB_OPTION_CONNECTION_TIMEZONE || option == TSDB_OPTION_CONNECTION_CLEAR) { +#ifndef WINDOWS + if (val != NULL){ + if (val[0] == 0){ + val = "UTC"; + } + timezone_t tz = setConnnectionTz(val); + if (tz == NULL){ + code = terrno; + goto END; + } + pObj->optionInfo.timezone = tz; + } else { + pObj->optionInfo.timezone = NULL; + } +#endif + } + + if (option == TSDB_OPTION_CONNECTION_USER_APP || option == TSDB_OPTION_CONNECTION_CLEAR) { + if (val != NULL) { + tstrncpy(pObj->optionInfo.userApp, val, sizeof(pObj->optionInfo.userApp)); + } else { + pObj->optionInfo.userApp[0] = 0; + } + } + + if (option == TSDB_OPTION_CONNECTION_USER_IP || option == TSDB_OPTION_CONNECTION_CLEAR) { + if (val != NULL) { + pObj->optionInfo.userIp = taosInetAddr(val); + if (pObj->optionInfo.userIp == INADDR_NONE){ + code = TSDB_CODE_INVALID_PARA; + goto END; + } + } else { + pObj->optionInfo.userIp = INADDR_NONE; + } + } + +END: + releaseTscObj(*(int64_t *)taos); + return code; +} + +int taos_options_connection(TAOS *taos, TSDB_OPTION_CONNECTION option, const void *arg, ...){ + return setConnectionOption(taos, option, (const char *)arg); +} + // this function may be called by user or system, or by both simultaneously. void taos_cleanup(void) { tscDebug("start to cleanup client environment"); @@ -73,6 +237,9 @@ void taos_cleanup(void) { tscWarn("failed to cleanup task queue"); } +#ifndef WINDOWS + tzCleanup(); +#endif tmqMgmtClose(); int32_t id = clientReqRefPool; @@ -1244,7 +1411,9 @@ int32_t createParseContext(const SRequestObj *pRequest, SParseContext **pCxt, SS .allocatorId = pRequest->allocatorRefId, .parseSqlFp = clientParseSql, .parseSqlParam = pWrapper, - .setQueryFp = setQueryRequest}; + .setQueryFp = setQueryRequest, + .timezone = pTscObj->optionInfo.timezone, + .charsetCxt = pTscObj->optionInfo.charsetCxt}; int8_t biMode = atomic_load_8(&((STscObj *)pTscObj)->biMode); (*pCxt)->biMode = biMode; return TSDB_CODE_SUCCESS; diff --git a/source/client/src/clientRawBlockWrite.c b/source/client/src/clientRawBlockWrite.c index 9ce2f726a5..76aec26ff4 100644 --- a/source/client/src/clientRawBlockWrite.c +++ b/source/client/src/clientRawBlockWrite.c @@ -432,7 +432,7 @@ static void buildChildElement(cJSON* json, SVCreateTbReq* pCreateReq) { uError("p->nTag == 0"); goto end; } - parseTagDatatoJson(pTag, &pJson); + parseTagDatatoJson(pTag, &pJson, NULL); RAW_NULL_CHECK(pJson); cJSON* tag = cJSON_CreateObject(); RAW_NULL_CHECK(tag); @@ -745,7 +745,7 @@ static void processAlterTable(SMqMetaRsp* metaRsp, cJSON** pJson) { uError("processAlterTable isJson false"); goto end; } - parseTagDatatoJson(vAlterTbReq.pTagVal, &buf); + parseTagDatatoJson(vAlterTbReq.pTagVal, &buf, NULL); if (buf == NULL) { uError("parseTagDatatoJson failed, buf == NULL"); goto end; diff --git a/source/client/src/clientSml.c b/source/client/src/clientSml.c index 0b1637bebf..cc96d61b18 100644 --- a/source/client/src/clientSml.c +++ b/source/client/src/clientSml.c @@ -267,7 +267,7 @@ bool isSmlColAligned(SSmlHandle *info, int cnt, SSmlKv *kv) { goto END; } // bind data - int32_t ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kv, cnt + 1); + int32_t ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kv, cnt + 1, info->taos->optionInfo.charsetCxt); if (unlikely(ret != TSDB_CODE_SUCCESS)) { uDebug("smlBuildCol error, retry"); goto END; @@ -411,8 +411,8 @@ int32_t smlParseEndTelnetJsonFormat(SSmlHandle *info, SSmlLineInfo *elements, SS int32_t code = 0; int32_t lino = 0; uDebug("SML:0x%" PRIx64 " %s format true, ts:%" PRId64, info->id, __FUNCTION__ , kvTs->i); - SML_CHECK_CODE(smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kvTs, 0)); - SML_CHECK_CODE(smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kv, 1)); + SML_CHECK_CODE(smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kvTs, 0, info->taos->optionInfo.charsetCxt)); + SML_CHECK_CODE(smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kv, 1, info->taos->optionInfo.charsetCxt)); SML_CHECK_CODE(smlBuildRow(info->currTableDataCtx)); END: @@ -438,7 +438,7 @@ END: int32_t smlParseEndLine(SSmlHandle *info, SSmlLineInfo *elements, SSmlKv *kvTs) { if (info->dataFormat) { uDebug("SML:0x%" PRIx64 " %s format true, ts:%" PRId64, info->id, __FUNCTION__, kvTs->i); - int32_t ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kvTs, 0); + int32_t ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, kvTs, 0, info->taos->optionInfo.charsetCxt); if (ret == TSDB_CODE_SUCCESS) { ret = smlBuildRow(info->currTableDataCtx); } @@ -1486,7 +1486,7 @@ static int32_t smlInsertData(SSmlHandle *info) { SML_CHECK_CODE(smlBindData(info->pQuery, info->dataFormat, tableData->tags, (*pMeta)->cols, tableData->cols, (*pMeta)->tableMeta, tableData->childTableName, measure, measureLen, info->ttl, info->msgBuf.buf, - info->msgBuf.len)); + info->msgBuf.len, info->taos->optionInfo.charsetCxt)); taosMemoryFreeClear(measure); oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable); } diff --git a/source/client/src/clientStmt.c b/source/client/src/clientStmt.c index b1f5af4593..9cad219614 100644 --- a/source/client/src/clientStmt.c +++ b/source/client/src/clientStmt.c @@ -1071,7 +1071,7 @@ int stmtSetTbTags(TAOS_STMT* stmt, TAOS_MULTI_BIND* tags) { tscDebug("start to bind stmt tag values"); STMT_ERR_RET(qBindStmtTagsValue(*pDataBlock, pStmt->bInfo.boundTags, pStmt->bInfo.tbSuid, pStmt->bInfo.stbFName, pStmt->bInfo.sname.tname, tags, pStmt->exec.pRequest->msgBuf, - pStmt->exec.pRequest->msgBufLen)); + pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt)); return TSDB_CODE_SUCCESS; } @@ -1239,7 +1239,7 @@ int stmtBindBatch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, int32_t colIdx) { } if (STMT_TYPE_QUERY == pStmt->sql.type) { - STMT_ERR_RET(qStmtBindParams(pStmt->sql.pQuery, bind, colIdx)); + STMT_ERR_RET(qStmtBindParams(pStmt->sql.pQuery, bind, colIdx, pStmt->taos->optionInfo.charsetCxt)); SParseContext ctx = {.requestId = pStmt->exec.pRequest->requestId, .acctId = pStmt->taos->acctId, @@ -1325,10 +1325,10 @@ int stmtBindBatch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, int32_t colIdx) { if (pStmt->sql.stbInterlaceMode) { (*pDataBlock)->pData->flags = 0; code = qBindStmtStbColsValue(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, - pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo); + pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo, pStmt->taos->optionInfo.charsetCxt); } else { code = - qBindStmtColsValue(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen); + qBindStmtColsValue(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt); } if (code) { @@ -1353,7 +1353,7 @@ int stmtBindBatch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, int32_t colIdx) { } code = qBindStmtSingleColValue(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, - pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum); + pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum, pStmt->taos->optionInfo.charsetCxt); if (code) { tscError("qBindStmtSingleColValue failed, error:%s", tstrerror(code)); STMT_ERR_RET(code); diff --git a/source/client/src/clientStmt2.c b/source/client/src/clientStmt2.c index be883ba9f0..f03879f199 100644 --- a/source/client/src/clientStmt2.c +++ b/source/client/src/clientStmt2.c @@ -1015,7 +1015,7 @@ int stmtSetTbTags2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* tags) { tscDebug("start to bind stmt tag values"); STMT_ERR_RET(qBindStmtTagsValue2(*pDataBlock, pStmt->bInfo.boundTags, pStmt->bInfo.tbSuid, pStmt->bInfo.stbFName, pStmt->bInfo.sname.tname, tags, pStmt->exec.pRequest->msgBuf, - pStmt->exec.pRequest->msgBufLen)); + pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt)); return TSDB_CODE_SUCCESS; } @@ -1331,7 +1331,7 @@ int stmtBindBatch2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* bind, int32_t colIdx) { } if (STMT_TYPE_QUERY == pStmt->sql.type) { - STMT_ERR_RET(qStmtBindParams2(pStmt->sql.pQuery, bind, colIdx)); + STMT_ERR_RET(qStmtBindParams2(pStmt->sql.pQuery, bind, colIdx, pStmt->taos->optionInfo.charsetCxt)); SParseContext ctx = {.requestId = pStmt->exec.pRequest->requestId, .acctId = pStmt->taos->acctId, @@ -1415,10 +1415,10 @@ int stmtBindBatch2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* bind, int32_t colIdx) { if (pStmt->sql.stbInterlaceMode) { (*pDataBlock)->pData->flags = 0; code = qBindStmtStbColsValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, - pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo); + pStmt->exec.pRequest->msgBufLen, &pStmt->sql.siInfo.pTSchema, pStmt->sql.pBindInfo, pStmt->taos->optionInfo.charsetCxt); } else { code = - qBindStmtColsValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen); + qBindStmtColsValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, pStmt->exec.pRequest->msgBufLen, pStmt->taos->optionInfo.charsetCxt); } if (code) { @@ -1443,7 +1443,7 @@ int stmtBindBatch2(TAOS_STMT2* stmt, TAOS_STMT2_BIND* bind, int32_t colIdx) { } code = qBindStmtSingleColValue2(*pDataBlock, pCols, bind, pStmt->exec.pRequest->msgBuf, - pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum); + pStmt->exec.pRequest->msgBufLen, colIdx, pStmt->bInfo.sBindRowNum, pStmt->taos->optionInfo.charsetCxt); if (code) { tscError("qBindStmtSingleColValue failed, error:%s", tstrerror(code)); STMT_ERR_RET(code); diff --git a/source/client/test/CMakeLists.txt b/source/client/test/CMakeLists.txt index 9393bfc449..fecddbbff4 100644 --- a/source/client/test/CMakeLists.txt +++ b/source/client/test/CMakeLists.txt @@ -11,6 +11,12 @@ TARGET_LINK_LIBRARIES( os util common transport parser catalog scheduler gtest ${TAOS_LIB_STATIC} qcom executor function ) +ADD_EXECUTABLE(connectOptionsTest connectOptionsTest.cpp) +TARGET_LINK_LIBRARIES( + connectOptionsTest + os util common transport parser catalog scheduler gtest ${TAOS_LIB_STATIC} qcom executor function +) + ADD_EXECUTABLE(tmqTest tmqTest.cpp) TARGET_LINK_LIBRARIES( tmqTest @@ -41,11 +47,21 @@ TARGET_INCLUDE_DIRECTORIES( PRIVATE "${TD_SOURCE_DIR}/source/client/inc" ) +TARGET_INCLUDE_DIRECTORIES( + connectOptionsTest + PUBLIC "${TD_SOURCE_DIR}/include/client/" + PRIVATE "${TD_SOURCE_DIR}/source/client/inc" +) + IF(${TD_LINUX}) add_test( NAME clientTest COMMAND clientTest ) + add_test( + NAME connectOptionsTest + COMMAND connectOptionsTest + ) ENDIF () TARGET_INCLUDE_DIRECTORIES( @@ -80,3 +96,4 @@ add_test( NAME userOperTest COMMAND userOperTest ) + diff --git a/source/client/test/clientTests.cpp b/source/client/test/clientTests.cpp index 307ef7e06f..fa0871b812 100644 --- a/source/client/test/clientTests.cpp +++ b/source/client/test/clientTests.cpp @@ -1609,5 +1609,4 @@ TEST(clientCase, timezone_Test) { taos_close(pConn); } } - #pragma GCC diagnostic pop diff --git a/source/client/test/connectOptionsTest.cpp b/source/client/test/connectOptionsTest.cpp new file mode 100644 index 0000000000..d44e43417b --- /dev/null +++ b/source/client/test/connectOptionsTest.cpp @@ -0,0 +1,946 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * This program is free software: you can use, redistribute, and/or modify + * it under the terms of the GNU Affero General Public License, version 3 + * or later ("AGPL"), as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include +#include +#include "taoserror.h" +#include "tglobal.h" +#include "thash.h" + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wwrite-strings" +#pragma GCC diagnostic ignored "-Wunused-function" +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wsign-compare" + +#include "executor.h" +#include "taos.h" +#include "clientInt.h" + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} + +TAOS* getConnWithGlobalOption(const char *tz){ + int code = taos_options(TSDB_OPTION_TIMEZONE, tz); + ASSERT(code == 0); + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConn != nullptr); + return pConn; +} + +TAOS* getConnWithOption(const char *tz){ + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConn != nullptr); + if (tz != NULL){ + int code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_TIMEZONE, tz); + ASSERT(code == 0); + } + return pConn; +} + +void execQuery(TAOS* pConn, const char *sql){ + TAOS_RES* pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == TSDB_CODE_SUCCESS); + taos_free_result(pRes); +} + +void execQueryFail(TAOS* pConn, const char *sql){ + printf("execQueryFail: %s\n", sql); + TAOS_RES* pRes = taos_query(pConn, sql); +#ifndef WINDOWS + ASSERT(taos_errno(pRes) != TSDB_CODE_SUCCESS); +#endif + taos_free_result(pRes); +} + +void checkRows(TAOS* pConn, const char *sql, int32_t expectedRows){ + printf("checkRows sql:%s,rows:%d\n", sql, expectedRows); + TAOS_RES* pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == TSDB_CODE_SUCCESS); + TAOS_ROW pRow = NULL; + int rows = 0; + while ((pRow = taos_fetch_row(pRes)) != NULL) { + rows++; + } + ASSERT(rows == expectedRows); + taos_free_result(pRes); +} + +void check_timezone(TAOS* pConn, const char *sql, const char* tz){ + TAOS_RES *pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == 0); + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(pRes)) != NULL) { + if (strcmp((const char*)row[0], "timezone") == 0){ + ASSERT(strstr((const char*)row[1], tz) != NULL); + } + } + taos_free_result(pRes); +} + +void check_sql_result_partial(TAOS* pConn, const char *sql, const char* result){ + TAOS_RES *pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == 0); + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(pRes)) != NULL) { + ASSERT(strstr((const char*)row[0], result) != NULL); + } + taos_free_result(pRes); +} + +int64_t get_sql_result(TAOS* pConn, const char *sql){ + int64_t ts = 0; + TAOS_RES *pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == 0); + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(pRes)) != NULL) { + ts = *(int64_t*)row[0]; + } + taos_free_result(pRes); + return ts; +} + +void check_sql_result(TAOS* pConn, const char *sql, const char* result){ + printf("check_sql_result sql:%s,result:%s\n", sql, result); + TAOS_RES *pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == 0); + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(pRes)) != NULL) { +#ifndef WINDOWS + ASSERT (memcmp((const char*)row[0], result, strlen(result)) == 0); +#endif + } + taos_free_result(pRes); +} + +void check_sql_result_integer(TAOS* pConn, const char *sql, int64_t result){ + printf("check_sql_result_integer sql:%s,result:%ld\n", sql, result); + TAOS_RES *pRes = taos_query(pConn, sql); + ASSERT(taos_errno(pRes) == 0); + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(pRes)) != NULL) { +#ifndef WINDOWS + ASSERT (*(int64_t*)row[0] == result); +#endif + } + taos_free_result(pRes); +} + +void check_set_timezone(TAOS* optionFunc(const char *tz)){ + { + TAOS* pConn = optionFunc("UTC-8"); + check_timezone(pConn, "show local variables", "UTC-8"); + + execQuery(pConn, "drop database if exists db1"); + execQuery(pConn, "create database db1"); + execQuery(pConn, "create table db1.t1 (ts timestamp, v int)"); + + execQuery(pConn, "insert into db1.t1 values('2023-09-16 17:00:00', 1)"); + checkRows(pConn, "select * from db1.t1 where ts == '2023-09-16 17:00:00'", 1); + + taos_close(pConn); + } + + { + TAOS* pConn = optionFunc("UTC+8"); + check_timezone(pConn, "show local variables", "UTC+8"); + checkRows(pConn, "select * from db1.t1 where ts == '2023-09-16 01:00:00'", 1); + execQuery(pConn, "insert into db1.t1 values('2023-09-16 17:00:01', 1)"); + + taos_close(pConn); + } + + { + TAOS* pConn = optionFunc("UTC+0"); + check_timezone(pConn, "show local variables", "UTC+0"); + checkRows(pConn, "select * from db1.t1 where ts == '2023-09-16 09:00:00'", 1); + checkRows(pConn, "select * from db1.t1 where ts == '2023-09-17 01:00:01'", 1); + + taos_close(pConn); + } +} + +#define CHECK_TAOS_OPTION_POINTER(taos, option, isnull) \ + { \ + STscObj* pObj = acquireTscObj(*(int64_t*)taos); \ + ASSERT(pObj != nullptr); \ + if (isnull) { \ + ASSERT(pObj->optionInfo.option == nullptr); \ + } else { \ + ASSERT(pObj->optionInfo.option != nullptr); \ + } \ + } + +#define CHECK_TAOS_OPTION_APP(taos, option, val) \ + { \ + STscObj* pObj = acquireTscObj(*(int64_t*)taos); \ + ASSERT(pObj != nullptr); \ + ASSERT(strcmp(pObj->optionInfo.option, val) == 0); \ + } + +#define CHECK_TAOS_OPTION_IP_ERROR(taos, option, val) \ + { \ + STscObj* pObj = acquireTscObj(*(int64_t*)taos); \ + ASSERT(pObj != nullptr); \ + ASSERT(pObj->optionInfo.option == val); \ + } + +#define CHECK_TAOS_OPTION_IP(taos, option, val) \ + { \ + STscObj* pObj = acquireTscObj(*(int64_t*)taos); \ + ASSERT(pObj != nullptr); \ + char ip[TD_IP_LEN] = {0}; \ + taosInetNtoa(ip, pObj->optionInfo.option); \ + ASSERT(strcmp(ip, val) == 0); \ + } + +TEST(connectionCase, setConnectionOption_Test) { + int32_t code = taos_options_connection(NULL, TSDB_OPTION_CONNECTION_CHARSET, NULL); + ASSERT(code != 0); + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConn != nullptr); + + code = taos_options_connection(pConn, TSDB_MAX_OPTIONS_CONNECTION, NULL); + ASSERT(code != 0); + + // test charset + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_CHARSET, ""); + ASSERT(code != 0); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_CHARSET, NULL); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, charsetCxt, true); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_CHARSET, "Asia/Shanghai"); + ASSERT(code != 0); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_CHARSET, "gbk"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, charsetCxt, false); + +#ifndef WINDOWS + // test timezone + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_TIMEZONE, ""); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, timezone, false); + check_sql_result(pConn, "select timezone()", "UTC (UTC, +0000)"); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_TIMEZONE, NULL); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, timezone, true); + check_sql_result(pConn, "select timezone()", "Asia/Shanghai (CST, +0800)"); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_TIMEZONE, "UTC"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, timezone, false); + check_sql_result(pConn, "select timezone()", "UTC (UTC, +0000)"); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_TIMEZONE, "Asia/Kolkata"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, timezone, false); + check_sql_result(pConn, "select timezone()", "Asia/Kolkata (IST, +0530)"); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_TIMEZONE, "adbc"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, timezone, false); + check_sql_result(pConn, "select timezone()", "adbc (UTC, +0000)"); +#endif + + // test user APP + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_APP, ""); + ASSERT(code == 0); + CHECK_TAOS_OPTION_APP(pConn, userApp, ""); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_APP, NULL); + ASSERT(code == 0); + CHECK_TAOS_OPTION_APP(pConn, userApp, ""); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_APP, "aaaaaaaaaaaaaaaaaaaaaabbbbbbb"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_APP(pConn, userApp, "aaaaaaaaaaaaaaaaaaaaaab"); + + + // test user IP + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_IP, ""); + ASSERT(code != 0); + CHECK_TAOS_OPTION_IP_ERROR(pConn, userIp, INADDR_NONE); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_IP, NULL); + ASSERT(code == 0); + CHECK_TAOS_OPTION_IP_ERROR(pConn, userIp, INADDR_NONE); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_IP, "aaaaaaaaaaaaaaaaaaaaaabbbbbbb"); + ASSERT(code != 0); + CHECK_TAOS_OPTION_IP_ERROR(pConn, userIp, INADDR_NONE); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_IP, "1292.168.0.2"); + ASSERT(code != 0); + CHECK_TAOS_OPTION_IP_ERROR(pConn, userIp, INADDR_NONE); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_IP, "192.168.0.2"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_IP(pConn, userIp, "192.168.0.2"); + + taosMsleep(2 * HEARTBEAT_INTERVAL); + + //test user APP and user IP + check_sql_result(pConn, "select user_app from performance_schema.perf_connections", "aaaaaaaaaaaaaaaaaaaaaab"); + check_sql_result(pConn, "select user_ip from performance_schema.perf_connections", "192.168.0.2"); + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_IP, "192.168.1.2"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_IP(pConn, userIp, "192.168.1.2"); + + + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_USER_APP, "user"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_APP(pConn, userApp, "user"); + + taosMsleep(2 * HEARTBEAT_INTERVAL); + + check_sql_result(pConn, "select user_app from performance_schema.perf_connections", "user"); + check_sql_result(pConn, "select user_ip from performance_schema.perf_connections", "192.168.1.2"); + + + // test clear + code = taos_options_connection(pConn, TSDB_OPTION_CONNECTION_CLEAR, "192.168.0.2"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConn, charsetCxt, true); + +#ifndef WINDOWS + CHECK_TAOS_OPTION_POINTER(pConn, timezone, true); + check_sql_result(pConn, "select timezone()", "Asia/Shanghai (CST, +0800)"); +#endif + + CHECK_TAOS_OPTION_APP(pConn, userApp, ""); + CHECK_TAOS_OPTION_IP_ERROR(pConn, userIp, INADDR_NONE); + + taos_close(pConn); +} + +TEST(charsetCase, charset_Test) { + // 1. build connection with different charset + TAOS* pConnGbk = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConnGbk != nullptr); + + TAOS* pConnUTF8 = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConnUTF8 != nullptr); + + TAOS* pConnDefault = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConnDefault != nullptr); + + int32_t code = taos_options_connection(pConnGbk, TSDB_OPTION_CONNECTION_CHARSET, "gbk"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConnGbk, charsetCxt, false); + + code = taos_options_connection(pConnUTF8, TSDB_OPTION_CONNECTION_CHARSET, "UTF-8"); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConnUTF8, charsetCxt, false); + + // 2. build test string + char sqlTag[256] = {0}; + char sqlCol[256] = {0}; + + // 芬 gbk encode is 0xB7D2, UTF-8 encode is 0xE88AAC + // 中国 gbk encode is 0xD6D0B9FA, UTF-8 encode is 0xE4B8ADE59BBD + char fenUtf8[32] = {0}; + char fenGbk[32] = {0}; + char zhongGbk[32] = {0}; + char zhongguoUtf8[32] = {0}; + char guoUtf8[32] = {0}; + char zhongguoGbk[32] = {0}; + snprintf(fenUtf8, sizeof(fenUtf8), "%c%c%c", 0xE8, 0x8A, 0xAC); + snprintf(fenGbk, sizeof(fenGbk), "%c%c", 0xB7, 0xD2); + snprintf(zhongguoUtf8, sizeof(zhongguoUtf8), "%c%c%c%c%c%c", 0xE4, 0xB8, 0xAD, 0xE5, 0x9B, 0xBD); + snprintf(guoUtf8, sizeof(guoUtf8), "%c%c%c", 0xE5, 0x9B, 0xBD); + snprintf(zhongguoGbk, sizeof(zhongguoGbk), "%c%c%c%c", 0xD6, 0xD0, 0xB9, 0xFA); + snprintf(zhongGbk, sizeof(zhongGbk), "%c%c", 0xD6, 0xD0); + + // 3. create stable + execQuery(pConnGbk, "drop database if exists db1"); + execQuery(pConnGbk, "create database db1"); + execQuery(pConnGbk, "create table db1.stb (ts timestamp, c1 nchar(32), c2 int) tags(t1 timestamp, t2 nchar(32), t3 int)"); + + // 4. test tag with different charset + snprintf(sqlTag, sizeof(sqlTag), "create table db1.ctb1 using db1.stb tags('2023-09-16 17:00:00+05:00', '%s', 1)", fenUtf8); + execQueryFail(pConnGbk, sqlTag); + + snprintf(sqlTag, sizeof(sqlTag), "create table db1.ctb1 using db1.stb tags('2023-09-16 17:00:00+05:00', '%s', 1)", fenGbk); + execQuery(pConnGbk, sqlTag); + + // 5. test column with different charset + snprintf(sqlCol, sizeof(sqlCol), "insert into db1.ctb1 values(1732178775133, '%s', 1)", zhongguoUtf8); + execQueryFail(pConnGbk, sqlCol); + + snprintf(sqlCol, sizeof(sqlCol), "insert into db1.ctb1 values(1732178775133, '%s', 1)", zhongguoGbk); + execQuery(pConnGbk, sqlCol); + + // 6. check result with different charset + check_sql_result(pConnGbk, "select t2 from db1.ctb1", fenGbk); + check_sql_result(pConnUTF8, "select t2 from db1.ctb1", fenUtf8); + + check_sql_result(pConnGbk, "select c1 from db1.ctb1", zhongguoGbk); + check_sql_result(pConnUTF8, "select c1 from db1.ctb1", zhongguoUtf8); + + // 7. test function with different charset + // 7.1 concat + char zhongguofenGbk[32] = {0}; + snprintf(zhongguofenGbk, sizeof(zhongguofenGbk), "%s%s", zhongguoGbk, fenGbk); + char sql[256] = {0}; + snprintf(sql, sizeof(sql), "select concat(c1, '%s') from db1.ctb1", fenGbk); + execQueryFail(pConnGbk, sql); + snprintf(sql, sizeof(sql), "select concat(c1, '%s') from db1.ctb1", fenUtf8); + check_sql_result(pConnGbk, sql, zhongguofenGbk); + + // 7.2 trim + snprintf(sql, sizeof(sql), "select trim(LEADING c1 from '%s') from db1.ctb1", zhongguofenGbk); + check_sql_result(pConnGbk, sql, zhongguofenGbk); + char zhongguofenUtf8[32] = {0}; + snprintf(zhongguofenUtf8, sizeof(zhongguofenUtf8), "%s%s", zhongguoUtf8, fenUtf8); + snprintf(sql, sizeof(sql), "select trim(LEADING c1 from '%s') from db1.ctb1", zhongguofenUtf8); + check_sql_result(pConnGbk, sql, fenUtf8); + + check_sql_result(pConnGbk, "select char(c1) from db1.ctb1", ""); + + check_sql_result_integer(pConnGbk, "select ascii(c1) from db1.ctb1", 0xE4); + check_sql_result_integer(pConnUTF8, "select ascii(c1) from db1.ctb1", 0xE4); + check_sql_result_integer(pConnGbk, "select LENGTH(c1) from db1.ctb1", 8); + check_sql_result_integer(pConnUTF8, "select LENGTH(c1) from db1.ctb1", 8); + check_sql_result_integer(pConnGbk, "select CHAR_LENGTH(c1) from db1.ctb1", 2); + check_sql_result_integer(pConnUTF8, "select CHAR_LENGTH(c1) from db1.ctb1", 2); + + execQuery(pConnGbk, "select LOWER(c1) from db1.ctb1"); + execQuery(pConnGbk, "select UPPER(c1) from db1.ctb1"); + + snprintf(sql, sizeof(sql), "select position(c1 in '%s') from db1.ctb1", zhongguofenGbk); + check_sql_result_integer(pConnGbk, sql, 0); + + snprintf(sql, sizeof(sql), "select position('%s' in c1) from db1.ctb1", guoUtf8); + check_sql_result_integer(pConnUTF8, sql, 2); + + snprintf(sql, sizeof(sql), "select replace(c1, '%s', 'a') from db1.ctb1", zhongguoGbk); + execQueryFail(pConnGbk, sql); + + snprintf(sql, sizeof(sql), "select replace(c1, '%s', 'a') from db1.ctb1", zhongguoUtf8); + check_sql_result(pConnUTF8, sql, "a"); + + snprintf(sql, sizeof(sql), "%s%s", zhongguoGbk, zhongguoGbk); + check_sql_result(pConnGbk, "select repeat(c1, 2) from db1.ctb1", sql); + + check_sql_result(pConnGbk, "select cast(c1 as binary(32)) from db1.ctb1", zhongguoUtf8); + + check_sql_result(pConnUTF8, "select substr(c1,2,1) from db1.ctb1", guoUtf8); + + snprintf(sql, sizeof(sql), "select SUBSTRING_INDEX(c1,'%s',1) from db1.ctb1", guoUtf8); + check_sql_result(pConnGbk, sql, zhongGbk); + + // 8. test default charset + snprintf(sqlCol, sizeof(sqlCol), "insert into db1.ctb1 values(1732178775134, '%s', 1)", zhongguoUtf8); + execQuery(pConnDefault, sqlCol); + check_sql_result(pConnDefault, "select c1 from db1.ctb1 where ts = 1732178775134", zhongguoUtf8); + + // 9. test json tag with different charset + execQuery(pConnUTF8, "create table db1.jsta (ts timestamp, c1 nchar(32), c2 int) tags(t1 json)"); + snprintf(sqlCol, sizeof(sqlCol), "create table db1.jsta1 using db1.jsta tags('{\"k\":\"%s\"}')", fenUtf8); + execQuery(pConnUTF8, sqlCol); + snprintf(sqlCol, sizeof(sqlCol), "insert into db1.jsta1 values(1732178775133, '%s', 1)", zhongguoUtf8); + execQuery(pConnUTF8, sqlCol); + + char resJsonTag[32] = {0}; + snprintf(resJsonTag, sizeof(resJsonTag), "{\"k\":\"%s\"}", fenGbk); + check_sql_result(pConnGbk, "select t1 from db1.jsta1", resJsonTag); + + // 10. reset charset to default(utf-8 + code = taos_options_connection(pConnGbk, TSDB_OPTION_CONNECTION_CHARSET, NULL); + ASSERT(code == 0); + CHECK_TAOS_OPTION_POINTER(pConnGbk, charsetCxt, true); + check_sql_result(pConnGbk, "select t2 from db1.ctb1 where ts = 1732178775134", fenUtf8); + check_sql_result(pConnGbk, "select c1 from db1.ctb1 where ts = 1732178775134", zhongguoUtf8); + + taos_close(pConnGbk); + taos_close(pConnUTF8); + taos_close(pConnDefault); + +} + +TEST(charsetCase, alter_charset_Test) { + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConn != nullptr); + + execQueryFail(pConn, "alter dnode 1 'charset gbk'"); + execQueryFail(pConn, "local 'charset gbk'"); + + taos_close(pConn); +} + +#ifndef WINDOWS +TEST(timezoneCase, set_timezone_Test) { + check_set_timezone(getConnWithGlobalOption); + check_set_timezone(getConnWithOption); +} + +TEST(timezoneCase, alter_timezone_Test) { + TAOS* pConn = getConnWithGlobalOption("UTC-8"); + check_timezone(pConn, "show local variables", "UTC-8"); + + execQuery(pConn, "alter local 'timezone Asia/Kolkata'"); + check_timezone(pConn, "show local variables", "Asia/Kolkata"); + + execQuery(pConn, "alter local 'timezone Asia/Shanghai'"); + check_timezone(pConn, "show local variables", "Asia/Shanghai"); + + execQueryFail(pConn, "alter dnode 1 'timezone Asia/Kolkata'"); + + taos_close(pConn); +} + +char *tz_test[] = { + "2023-09-16 17:00:00+", + "2023-09-16 17:00:00+a", + "2023-09-16 17:00:00+8", + "2023-09-16 17:00:00+832", + "2023-09-16 17:00:00+8323", + "2023-09-16 17:00:00+:", + "2023-09-16 17:00:00+8:", + "2023-09-16 17:00:00++:", + "2023-09-16 17:00:00+d:", + "2023-09-16 17:00:00+09:", + "2023-09-16 17:00:00+8f:", + "2023-09-16 17:00:00+080:", + "2023-09-16 17:00:00+:30", + "2023-09-16 17:00:00+:3", + "2023-09-16 17:00:00+:093", + "2023-09-16 17:00:00+:-30", + "2023-09-16 17:00:00++:-30", + "2023-09-16 17:00:00+8:8", + "2023-09-16 17:00:00+8:2a", + "2023-09-16 17:00:00+8:08", + "2023-09-16 17:00:00+8:038", + "2023-09-16 17:00:00+08:8", + "2023-09-16 17:00:00+09:3a", + "2023-09-16 17:00:00+09:abc", + "2023-09-16 17:00:00+09:001", +}; + +void do_insert_failed(){ + TAOS* pConn = getConnWithGlobalOption("UTC-8"); + + for (unsigned int i = 0; i < sizeof (tz_test) / sizeof (tz_test[0]); ++i){ + char sql[1024] = {0}; + (void)snprintf(sql, sizeof(sql), "insert into db1.ctb1 values('%s', '%s', 1)", tz_test[i], tz_test[i]); + + execQueryFail(pConn, sql); + } + taos_close(pConn); +} + +struct insert_params +{ + const char *tz; + const char *tbname; + const char *t1; + const char *t2; +}; + +struct insert_params params1[] = { + {"UTC", "ntb", "2023-09-16 17:00:00", "2023-09-16 17:00:00+08:00"}, + {"UTC", "ctb1", "2023-09-16 17:00:00", "2023-09-16 17:00:00+08:00"}, +}; + +struct insert_params params2[] = { + {"UTC+9", "ntb", "2023-09-16 08:00:00", "2023-09-16 08:00:00-01:00"}, + {"UTC+9", "ctb1", "2023-09-16 08:00:00", "2023-09-16 11:00:00+02:00"}, +}; + +void do_insert(struct insert_params params){ + TAOS* pConn = getConnWithOption(params.tz); + char sql[1024] = {0}; + (void)snprintf(sql, sizeof(sql), "insert into db1.%s values('%s', '%s', 1)", params.tbname, params.t1, params.t2); + execQuery(pConn, sql); + taos_close(pConn); +} + +void do_select(struct insert_params params){ + TAOS* pConn = getConnWithOption(params.tz); + char sql[1024] = {0}; + (void)snprintf(sql, sizeof(sql), "select * from db1.%s where ts == '%s' and c1 == '%s'", params.tbname, params.t1, params.t2); + checkRows(pConn, sql, 1); + taos_close(pConn); +} + +// test insert string and integer to timestamp both normal table and child table(and tag) +TEST(timezoneCase, insert_with_timezone_Test) { + /* + * 1. prepare data, create db and tables + */ + TAOS* pConn1 = getConnWithOption("UTC+2"); + execQuery(pConn1, "drop database if exists db1"); + execQuery(pConn1, "create database db1"); + execQuery(pConn1, "create table db1.ntb (ts timestamp, c1 timestamp, c2 int)"); + execQuery(pConn1, "create table db1.stb (ts timestamp, c1 timestamp, c2 int) tags(t1 timestamp, t2 timestamp, t3 int)"); + execQuery(pConn1, "create table db1.ctb1 using db1.stb tags(\"2023-09-16 17:00:00+05:00\", \"2023-09-16 17:00:00\", 1)"); + execQuery(pConn1, "create table db1.ctb2 using db1.stb tags(1732178775000, 1732178775000, 1)"); + execQuery(pConn1, "insert into db1.ntb values(1732178775133, 1732178775133, 1)"); + execQuery(pConn1, "insert into db1.ctb1 values(1732178775133, 1732178775133, 1)"); //2024-11-21 10:46:15.133+02:00 + execQuery(pConn1, "insert into db1.ctb2 values(1732178775133, 1732178775133, 1)"); + + /* + * 2. test tag and timestamp with integer format + */ + TAOS* pConn2 = getConnWithOption("UTC-2"); + checkRows(pConn2, "select * from db1.stb where t1 == '2023-09-16 17:00:00+05:00' and t2 == '2023-09-16 21:00:00'", 1); + checkRows(pConn2, "select * from db1.stb where t1 == '2024-11-21 16:46:15+08:00' and t2 == '2024-11-21 09:46:15+01:00'", 1); + checkRows(pConn2, "select * from db1.ntb where ts == '2024-11-21 09:46:15.133+01:00' and c1 == '2024-11-21 10:46:15.133'", 1); + checkRows(pConn2, "select * from db1.ctb1 where ts == '2024-11-21 09:46:15.133+01:00' and c1 == '2024-11-21 10:46:15.133'", 1); + + check_sql_result(pConn2, "select TO_ISO8601(ts) from db1.ctb1", "2024-11-21T10:46:15.133+0200"); // 2024-01-01 23:00:00+0200 + + + /* + * 3. test timestamp with string format + */ + for (unsigned int i = 0; i < sizeof (params1) / sizeof (params1[0]); ++i){ + do_insert(params1[i]); + do_select(params1[i]); + do_select(params2[i]); + } + + do_insert_failed(); + /* + * 4. test NULL timezone, use default timezone UTC-8 + */ + TAOS* pConn3 = getConnWithOption(NULL); + checkRows(pConn3, "select * from db1.stb where t1 == '2023-09-16 20:00:00' and t2 == '2023-09-17 03:00:00'", 2); + checkRows(pConn3, "select * from db1.stb where t1 == 1732178775000 and t2 == 1732178775000", 1); + checkRows(pConn3, "select * from db1.ntb where ts == '2024-11-21 16:46:15.133' and c1 == '2024-11-21 16:46:15.133'", 1); + checkRows(pConn3, "select * from db1.ctb1 where ts == '2023-09-17 01:00:00' and c1 == '2023-09-16 17:00:00'", 1); + + /* + * 5. test multi connection with different timezone + */ + checkRows(pConn2, "select * from db1.ctb1 where ts == '2024-11-21 09:46:15.133+01:00' and c1 == '2024-11-21 10:46:15.133'", 1); + checkRows(pConn1, "select * from db1.ctb1 where ts == '2024-11-21 09:46:15.133+01:00' and c1 == '2024-11-21 06:46:15.133'", 1); + + taos_close(pConn1); + taos_close(pConn2); + taos_close(pConn3); +} + +TEST(timezoneCase, func_timezone_Test) { + TAOS* pConn = getConnWithGlobalOption("UTC+8"); + check_sql_result(pConn, "select timezone()", "UTC+8 (UTC, -0800)"); + taos_close(pConn); + + pConn = getConnWithOption("UTC-2"); + + execQuery(pConn, "drop database if exists db1"); + execQuery(pConn, "create database db1"); + execQuery(pConn, "create table db1.ntb (ts timestamp, c1 binary(32), c2 int)"); + execQuery(pConn, "insert into db1.ntb values(1704142800000, '2024-01-01 23:00:00', 1)"); // 2024-01-01 23:00:00+0200 + + // test timezone + check_sql_result(pConn, "select timezone()", "UTC-2 (UTC, +0200)"); + + // test timetruncate + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 23:00:00', 1d, 0))", "2024-01-01T02:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 01:00:00', 1d, 0))", "2023-12-31T02:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 01:00:00+0300', 1d, 0))", "2023-12-31T02:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 01:00:00-0300', 1d, 0))", "2024-01-01T02:00:00.000+0200"); + + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 23:00:00', 1w, 0))", "2024-01-04T02:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 01:00:00', 1w, 0))", "2023-12-28T02:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 01:00:00+0300', 1w, 0))", "2023-12-28T02:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 01:00:00-0300', 1w, 0))", "2024-01-04T02:00:00.000+0200"); + + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 23:00:00', 1d, 1))", "2024-01-01T00:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 01:00:00', 1d, 1))", "2024-01-01T00:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 01:00:00+0500', 1d, 1))", "2023-12-31T00:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-01 01:00:00-0300', 1d, 1))", "2024-01-01T00:00:00.000+0200"); + + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 23:00:00', 1w, 1))", "2024-01-04T00:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 01:00:00', 1w, 1))", "2024-01-04T00:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 01:00:00+0500', 1w, 1))", "2023-12-28T00:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE('2024-01-04 01:00:00-0300', 1w, 1))", "2024-01-04T00:00:00.000+0200"); + + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE(1704142800000, 1d, 0))", "2024-01-01T02:00:00.000+0200"); // 2024-01-01 23:00:00+0200 + check_sql_result(pConn, "select TO_ISO8601(TIMETRUNCATE(ts, 1w, 1)) from db1.ntb", "2023-12-28T00:00:00.000+0200"); // 2024-01-01 23:00:00+0200 + + // TODAY + check_sql_result_partial(pConn, "select TO_ISO8601(today())", "T00:00:00.000+0200"); + + // NOW + check_sql_result_partial(pConn, "select TO_ISO8601(now())", "+0200"); + + // WEEKDAY + check_sql_result_integer(pConn, "select WEEKDAY('2024-01-01')", 0); + check_sql_result_integer(pConn, "select WEEKDAY('2024-01-01 03:00:00')", 0); + check_sql_result_integer(pConn, "select WEEKDAY('2024-01-01 23:00:00+0200')", 0); + check_sql_result_integer(pConn, "select WEEKDAY('2024-01-01 23:00:00-1100')", 1); + check_sql_result_integer(pConn, "select WEEKDAY(1704142800000)", 0); + check_sql_result_integer(pConn, "select WEEKDAY(ts) from db1.ntb", 1); + + // DAYOFWEEK + check_sql_result_integer(pConn, "select DAYOFWEEK('2024-01-01')", 2); + check_sql_result_integer(pConn, "select DAYOFWEEK('2024-01-01 03:00:00')", 2); + check_sql_result_integer(pConn, "select DAYOFWEEK('2024-01-01 23:00:00+0200')", 2); + check_sql_result_integer(pConn, "select DAYOFWEEK('2024-01-01 23:00:00-1100')", 3); + check_sql_result_integer(pConn, "select DAYOFWEEK(1704142800000)", 2); + check_sql_result_integer(pConn, "select DAYOFWEEK(ts) from db1.ntb", 3); + + // WEEK + check_sql_result_integer(pConn, "select WEEK('2024-01-07')", 1); + check_sql_result_integer(pConn, "select WEEK('2024-01-07 02:00:00')", 1); + check_sql_result_integer(pConn, "select WEEK('2024-01-07 02:00:00+0200')", 1); + check_sql_result_integer(pConn, "select WEEK('2024-01-07 02:00:00+1100')", 0); + check_sql_result_integer(pConn, "select WEEK(1704142800000)", 0); // 2024-01-01 23:00:00+0200 + check_sql_result_integer(pConn, "select WEEK(ts) from db1.ntb", 0); // 2024-01-01 23:00:00+0200 + + check_sql_result_integer(pConn, "select WEEK('2024-01-07', 3)", 1); + check_sql_result_integer(pConn, "select WEEK('2024-01-07 02:00:00', 3)", 1); + check_sql_result_integer(pConn, "select WEEK('2024-01-07 02:00:00+0200', 3)", 1); + check_sql_result_integer(pConn, "select WEEK('2024-01-01 02:00:00+1100', 3)", 52); + check_sql_result_integer(pConn, "select WEEK(1704142800000, 3)", 1); // 2024-01-01 23:00:00+0200 + check_sql_result_integer(pConn, "select WEEK(ts, 3) from db1.ntb", 1); // 2024-01-01 23:00:00+0200 + + // WEEKOFYEAR + check_sql_result_integer(pConn, "select WEEKOFYEAR('2024-01-07')", 1); + check_sql_result_integer(pConn, "select WEEKOFYEAR('2024-01-07 02:00:00')", 1); + check_sql_result_integer(pConn, "select WEEKOFYEAR('2024-01-07 02:00:00+0200')", 1); + check_sql_result_integer(pConn, "select WEEKOFYEAR('2024-01-01 02:00:00+1100')", 52); + check_sql_result_integer(pConn, "select WEEKOFYEAR(1704142800000)", 1); // 2024-01-01 23:00:00+0200 + check_sql_result_integer(pConn, "select WEEKOFYEAR(ts) from db1.ntb", 1); // 2024-01-01 23:00:00+0200 + + // TO_ISO8601 + check_sql_result(pConn, "select TO_ISO8601(ts) from db1.ntb", "2024-01-01T23:00:00.000+0200"); + check_sql_result(pConn, "select TO_ISO8601(ts,'-08') from db1.ntb", "2024-01-01T13:00:00.000-08"); + check_sql_result(pConn, "select TO_ISO8601(1)", "1970-01-01T02:00:00.001+0200"); + check_sql_result(pConn, "select TO_ISO8601(1,'+0800')", "1970-01-01T08:00:00.001+0800"); + + // TO_UNIXTIMESTAMP + check_sql_result_integer(pConn, "select TO_UNIXTIMESTAMP(c1) from db1.ntb", 1704121200000); // use timezone in server UTC-8 + check_sql_result_integer(pConn, "select TO_UNIXTIMESTAMP('2024-01-01T23:00:00.000+0200')", 1704142800000); + check_sql_result_integer(pConn, "select TO_UNIXTIMESTAMP('2024-01-01T13:00:00.000-08')", 1704142800000); + check_sql_result_integer(pConn, "select TO_UNIXTIMESTAMP('2024-01-01T23:00:00.001')", 1704142800001); + + // TO_TIMESTAMP + check_sql_result_integer(pConn, "select TO_TIMESTAMP(c1,'yyyy-mm-dd hh24:mi:ss') from db1.ntb", 1704121200000); // use timezone in server UTC-8 + check_sql_result_integer(pConn, "select TO_TIMESTAMP('2024-01-01 23:00:00+02:00', 'yyyy-mm-dd hh24:mi:ss tzh')", 1704142800000); + check_sql_result_integer(pConn, "select TO_TIMESTAMP('2024-01-01T13:00:00-08', 'yyyy-mm-ddThh24:mi:ss tzh')", 1704142800000); + check_sql_result_integer(pConn, "select TO_TIMESTAMP('2024/01/01 23:00:00', 'yyyy/mm/dd hh24:mi:ss')", 1704142800000); + + // TO_CHAR + check_sql_result(pConn, "select TO_CHAR(ts,'yyyy-mm-dd hh24:mi:ss') from db1.ntb", "2024-01-02 05:00:00"); // use timezone in server UTC-8 + check_sql_result(pConn, "select TO_CHAR(cast(1704142800000 as timestamp), 'yyyy-mm-dd hh24:mi:ss tzh')", "2024-01-01 23:00:00 +02"); + check_sql_result(pConn, "select TO_CHAR(cast(1704142800000 as timestamp), 'yyyy-mm-dd hh24:mi:ss')", "2024-01-01 23:00:00"); + + // TIMEDIFF + check_sql_result_integer(pConn, "select TIMEDIFF(c1, '2024-01-01T23:00:00.001+02') from db1.ntb", -21600001); // use timezone in server UTC-8 + check_sql_result_integer(pConn, "select TIMEDIFF(c1, '2024-01-01T23:00:00.001') from db1.ntb", -1); // use timezone in server UTC-8 + check_sql_result_integer(pConn, "select TIMEDIFF('2024-01-01T23:00:00.001', '2024-01-01T13:00:00.000-08')", 1); + + // CAST + check_sql_result_integer(pConn, "select CAST(c1 as timestamp) from db1.ntb", 1704121200000); + check_sql_result_integer(pConn, "select CAST('2024-01-01T23:00:00.000+02' as timestamp)", 1704142800000); + check_sql_result_integer(pConn, "select CAST('2024-01-01T23:00:00.000' as timestamp)", 1704142800000); + + taos_close(pConn); + + // hash join + pConn = getConnWithOption("UTC+1"); + + execQuery(pConn, "drop database if exists db1"); + execQuery(pConn, "create database db1"); + execQuery(pConn, "create table db1.ntb (ts timestamp, c1 binary(32), c2 int)"); + execQuery(pConn, "create table db1.ntb1 (ts timestamp, c1 binary(32), c2 int)"); + execQuery(pConn, "insert into db1.ntb values(1703987400000, '2023-12-31 00:50:00', 1)"); // 2023-12-31 00:50:00-0100 + execQuery(pConn, "insert into db1.ntb1 values(1704070200000, '2023-12-31 23:50:00', 11)"); // 2023-12-31 23:50:00-0100 + checkRows(pConn, "select a.ts,b.ts from db1.ntb a join db1.ntb1 b on timetruncate(a.ts, 1d) = timetruncate(b.ts, 1d)", 1); + + // operator +1n +1y + check_sql_result(pConn, "select TO_ISO8601(CAST('2023-01-31T00:00:00.000-01' as timestamp) + 1n)", "2023-02-28T00:00:00.000-0100"); + check_sql_result(pConn, "select TO_ISO8601(CAST('2024-01-31T00:00:00.000-01' as timestamp) + 1n)", "2024-02-29T00:00:00.000-0100"); + check_sql_result(pConn, "select TO_ISO8601(CAST('2024-02-29T00:00:00.000-01' as timestamp) + 1y)", "2025-02-28T00:00:00.000-0100"); + check_sql_result(pConn, "select TO_ISO8601(CAST('2024-01-31T00:00:00.000-01' as timestamp) + 1y)", "2025-01-31T00:00:00.000-0100"); + + check_sql_result(pConn, "select TO_ISO8601(CAST('2024-01-01T00:00:00.000+01' as timestamp) + 1n)", "2024-01-31T22:00:00.000-0100"); + check_sql_result(pConn, "select TO_ISO8601(CAST('2024-01-01T00:00:00.000+01' as timestamp) + 1y)", "2024-12-31T22:00:00.000-0100"); + + // case when + check_sql_result_integer(pConn, "select case CAST('2024-01-01T00:00:00.000+01' as timestamp) when 1704063600000 then 1 end", 1); + check_sql_result_integer(pConn, "select case CAST('2024-01-01T00:00:00.000' as timestamp) when 1704070800000 then 1 end", 1); + + taos_close(pConn); + +} + +time_t time_winter = 1731323281; // 2024-11-11 19:08:01+0800 +time_t time_summer = 1731323281 - 120 * 24 * 60 * 60; + +struct test_times +{ + const char *name; + time_t t; + const char *timezone; +} test_tz[] = { + {"", time_winter, " (UTC, +0000)"}, + {"America/New_York", time_winter, "America/New_York (EST, -0500)"}, // 2024-11-11 19:08:01+0800 + {"America/New_York", time_summer, "America/New_York (EDT, -0400)"}, + {"Asia/Kolkata", time_winter, "Asia/Kolkata (IST, +0530)"}, + {"Asia/Shanghai", time_winter, "Asia/Shanghai (CST, +0800)"}, + {"Europe/London", time_winter, "Europe/London (GMT, +0000)"}, + {"Europe/London", time_summer, "Europe/London (BST, +0100)"} +}; + +void timezone_str_test(const char* tz, time_t t, const char* tzStr) { + int code = setenv("TZ", tz, 1); + ASSERT(-1 != code); + tzset(); + + char str1[TD_TIMEZONE_LEN] = {0}; + ASSERT(taosFormatTimezoneStr(t, tz, NULL, str1) == 0); + ASSERT_STREQ(str1, tzStr); +} + +void timezone_rz_str_test(const char* tz, time_t t, const char* tzStr) { + timezone_t sp = tzalloc(tz); + ASSERT(sp); + + char str1[TD_TIMEZONE_LEN] = {0}; + ASSERT(taosFormatTimezoneStr(t, tz, sp, str1) == 0); + ASSERT_STREQ(str1, tzStr); + tzfree(sp); +} + +TEST(timezoneCase, format_timezone_Test) { + for (unsigned int i = 0; i < sizeof (test_tz) / sizeof (test_tz[0]); ++i){ + timezone_str_test(test_tz[i].name, test_tz[i].t, test_tz[i].timezone); + timezone_str_test(test_tz[i].name, test_tz[i].t, test_tz[i].timezone); + } +} + +TEST(timezoneCase, get_tz_Test) { + { + char tz[TD_TIMEZONE_LEN] = {0}; + getTimezoneStr(tz); + ASSERT_STREQ(tz, "Asia/Shanghai"); + +// getTimezoneStr(tz); +// ASSERT_STREQ(tz, "Asia/Shanghai"); +// +// getTimezoneStr(tz); +// ASSERT_STREQ(tz, TZ_UNKNOWN); + } +} + +struct { + const char * env; + time_t expected; +} test_mk[] = { + {"MST", 832935315}, + {"", 832910115}, + {":UTC", 832910115}, + {"UTC", 832910115}, + {"UTC0", 832910115} +}; + + +TEST(timezoneCase, mktime_Test){ + struct tm tm; + time_t t; + + memset (&tm, 0, sizeof (tm)); + tm.tm_isdst = 0; + tm.tm_year = 96; /* years since 1900 */ + tm.tm_mon = 4; + tm.tm_mday = 24; + tm.tm_hour = 3; + tm.tm_min = 55; + tm.tm_sec = 15; + + for (unsigned int i = 0; i < sizeof (test_mk) / sizeof (test_mk[0]); ++i) + { + setenv ("TZ", test_mk[i].env, 1); + t = taosMktime (&tm, NULL); + ASSERT (t == test_mk[i].expected); + } +} + +TEST(timezoneCase, mktime_rz_Test){ + struct tm tm; + time_t t; + + memset (&tm, 0, sizeof (tm)); + tm.tm_isdst = 0; + tm.tm_year = 96; /* years since 1900 */ + tm.tm_mon = 4; + tm.tm_mday = 24; + tm.tm_hour = 3; + tm.tm_min = 55; + tm.tm_sec = 15; + + for (unsigned int i = 0; i < sizeof (test_mk) / sizeof (test_mk[0]); ++i) + { + timezone_t tz = tzalloc(test_mk[i].env); + ASSERT(tz); + t = taosMktime(&tm, tz); + ASSERT (t == test_mk[i].expected); + tzfree(tz); + } +} + +TEST(timezoneCase, localtime_performance_Test) { + timezone_t sp = tzalloc("Asia/Shanghai"); + ASSERT(sp); + + int cnt = 1000000; + int times = 10; + int64_t time_localtime = 0; + int64_t time_localtime_rz = 0; +// int cnt = 1000000; + for (int i = 0; i < times; ++i) { + int64_t t1 = taosGetTimestampNs(); + for (int j = 0; j < cnt; ++j) { + time_t t = time_winter - j; + struct tm tm1; + ASSERT (taosLocalTime(&t, &tm1, NULL, 0, NULL)); + } + int64_t tmp = taosGetTimestampNs() - t1; + printf("localtime cost:%" PRId64 " ns, run %d times", tmp, cnt); + time_localtime += tmp/cnt; + + printf("\n"); + + + + int64_t t2 = taosGetTimestampNs(); + for (int j = 0; j < cnt; ++j) { + time_t t = time_winter - j; + struct tm tm1; + ASSERT (taosLocalTime(&t, &tm1, NULL, 0, sp)); + } + tmp = taosGetTimestampNs() - t2; + printf("localtime_rz cost:%" PRId64 " ns, run %d times", tmp, cnt); + time_localtime_rz += tmp/cnt; + printf("\n\n"); + } + printf("average: localtime cost:%" PRId64 " ns, localtime_rz cost:%" PRId64 " ns\n", time_localtime/times, time_localtime_rz/times); + tzfree(sp); +} +#endif + +#pragma GCC diagnostic pop diff --git a/source/common/src/msg/tmsg.c b/source/common/src/msg/tmsg.c index e8708a94f0..842b290f46 100644 --- a/source/common/src/msg/tmsg.c +++ b/source/common/src/msg/tmsg.c @@ -302,6 +302,8 @@ static int32_t tSerializeSClientHbReq(SEncoder *pEncoder, const SClientHbReq *pR TAOS_CHECK_RETURN(tEncodeSKv(pEncoder, kv)); pIter = taosHashIterate(pReq->info, pIter); } + TAOS_CHECK_RETURN(tEncodeU32(pEncoder, pReq->userIp)); + TAOS_CHECK_RETURN(tEncodeCStr(pEncoder, pReq->userApp)); return 0; } @@ -399,6 +401,10 @@ static int32_t tDeserializeSClientHbReq(SDecoder *pDecoder, SClientHbReq *pReq) return terrno = code; } } + if (!tDecodeIsEnd(pDecoder)) { + TAOS_CHECK_RETURN(tDecodeU32(pDecoder, &pReq->userIp)); + TAOS_CHECK_RETURN(tDecodeCStrTo(pDecoder, pReq->userApp)); + } return 0; } diff --git a/source/common/src/systable.c b/source/common/src/systable.c index fcf24d02c2..0028622ff5 100644 --- a/source/common/src/systable.c +++ b/source/common/src/systable.c @@ -515,6 +515,8 @@ static const SSysDbTableSchema connectionsSchema[] = { {.name = "end_point", .bytes = TSDB_EP_LEN + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_BINARY, .sysInfo = false}, {.name = "login_time", .bytes = 8, .type = TSDB_DATA_TYPE_TIMESTAMP, .sysInfo = false}, {.name = "last_access", .bytes = 8, .type = TSDB_DATA_TYPE_TIMESTAMP, .sysInfo = false}, + {.name = "user_app", .bytes = TSDB_APP_NAME_LEN + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_BINARY, .sysInfo = false}, + {.name = "user_ip", .bytes = TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_VARCHAR, .sysInfo = false}, }; static const SSysDbTableSchema consumerSchema[] = { @@ -556,6 +558,8 @@ static const SSysDbTableSchema querySchema[] = { {.name = "sub_num", .bytes = 4, .type = TSDB_DATA_TYPE_INT, .sysInfo = false}, {.name = "sub_status", .bytes = TSDB_SHOW_SUBQUERY_LEN + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_VARCHAR, .sysInfo = false}, {.name = "sql", .bytes = TSDB_SHOW_SQL_LEN + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_VARCHAR, .sysInfo = false}, + {.name = "user_app", .bytes = TSDB_APP_NAME_LEN + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_VARCHAR, .sysInfo = false}, + {.name = "user_ip", .bytes = TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE, .type = TSDB_DATA_TYPE_VARCHAR, .sysInfo = false}, }; static const SSysDbTableSchema appSchema[] = { diff --git a/source/common/src/tdatablock.c b/source/common/src/tdatablock.c index 94ebcc7033..bd18c9ceb9 100644 --- a/source/common/src/tdatablock.c +++ b/source/common/src/tdatablock.c @@ -2494,12 +2494,12 @@ static int32_t formatTimestamp(char* buf, size_t cap, int64_t val, int precision } } struct tm ptm = {0}; - if (taosLocalTime(&tt, &ptm, buf, cap) == NULL) { + if (taosLocalTime(&tt, &ptm, buf, cap, NULL) == NULL) { code = TSDB_CODE_INTERNAL_ERROR; TSDB_CHECK_CODE(code, lino, _end); } - size_t pos = strftime(buf, cap, "%Y-%m-%d %H:%M:%S", &ptm); + size_t pos = taosStrfTime(buf, cap, "%Y-%m-%d %H:%M:%S", &ptm); if (pos == 0) { code = TSDB_CODE_OUT_OF_BUFFER; TSDB_CHECK_CODE(code, lino, _end); @@ -2641,7 +2641,7 @@ int32_t dumpBlockData(SSDataBlock* pDataBlock, const char* flag, char** pDataBuf char* pData = colDataGetVarData(pColInfoData, j); int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData)); memset(pBuf, 0, sizeof(pBuf)); - code = taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf); + code = taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf, NULL); if (code < 0) { uError("func %s failed to convert to ucs charset since %s", __func__, tstrerror(code)); lino = __LINE__; diff --git a/source/common/src/tglobal.c b/source/common/src/tglobal.c index 5076006f29..e43bdc4687 100644 --- a/source/common/src/tglobal.c +++ b/source/common/src/tglobal.c @@ -327,6 +327,7 @@ bool tsExperimental = true; int32_t tsMaxTsmaNum = 3; int32_t tsMaxTsmaCalcDelay = 600; int64_t tsmaDataDeleteMark = 1000 * 60 * 60 * 24; // in ms, default to 1d +void* pTimezoneNameMap = NULL; #define TAOS_CHECK_GET_CFG_ITEM(pCfg, pItem, pName) \ if ((pItem = cfgGetItem(pCfg, pName)) == NULL) { \ @@ -1348,34 +1349,6 @@ static int32_t taosSetClientCfg(SConfig *pCfg) { static int32_t taosSetSystemCfg(SConfig *pCfg) { SConfigItem *pItem = NULL; - TAOS_CHECK_GET_CFG_ITEM(pCfg, pItem, "timezone"); - if (0 == strlen(pItem->str)) { - uError("timezone is not set"); - } else { - TAOS_CHECK_RETURN(osSetTimezone(pItem->str)); - uDebug("timezone format changed from %s to %s", pItem->str, tsTimezoneStr); - } - TAOS_CHECK_RETURN(cfgSetItem(pCfg, "timezone", tsTimezoneStr, pItem->stype, true)); - - TAOS_CHECK_GET_CFG_ITEM(pCfg, pItem, "locale"); - const char *locale = pItem->str; - - TAOS_CHECK_GET_CFG_ITEM(pCfg, pItem, "charset"); - const char *charset = pItem->str; - - int32_t code = taosSetSystemLocale(locale, charset); - if (TSDB_CODE_SUCCESS != code) { - uError("failed to set locale:%s, since: %s", locale, tstrerror(code)); - char curLocale[TD_LOCALE_LEN] = {0}; - char curCharset[TD_CHARSET_LEN] = {0}; - taosGetSystemLocale(curLocale, curCharset); - if (0 != strlen(curLocale) && 0 != strlen(curCharset)) { - uInfo("current locale: %s, charset: %s", curLocale, curCharset); - } - } - - osSetSystemLocale(locale, charset); - TAOS_CHECK_GET_CFG_ITEM(pCfg, pItem, "enableCoreFile"); tsEnableCoreFile = pItem->bval; taosSetCoreDump(tsEnableCoreFile); @@ -2104,6 +2077,9 @@ static int32_t taosCfgDynamicOptionsForClient(SConfig *pCfg, const char *name) { int32_t code = TSDB_CODE_SUCCESS; int32_t lino = 0; + if (strcasecmp("charset", name) == 0 || strcasecmp("timezone", name) == 0) { + goto _out; + } cfgLock(pCfg); SConfigItem *pItem = cfgGetItem(pCfg, name); @@ -2195,18 +2171,15 @@ static int32_t taosCfgDynamicOptionsForClient(SConfig *pCfg, const char *name) { case 'l': { if (strcasecmp("locale", name) == 0) { SConfigItem *pLocaleItem = cfgGetItem(pCfg, "locale"); - SConfigItem *pCharsetItem = cfgGetItem(pCfg, "charset"); - if (pLocaleItem == NULL || pCharsetItem == NULL) { - uError("failed to get locale or charset from cfg"); + if (pLocaleItem == NULL) { + uError("failed to get locale from cfg"); code = TSDB_CODE_CFG_NOT_FOUND; goto _out; } const char *locale = pLocaleItem->str; - const char *charset = pCharsetItem->str; - TAOS_CHECK_GOTO(taosSetSystemLocale(locale, charset), &lino, _out); - osSetSystemLocale(locale, charset); - uInfo("locale set to '%s', charset set to '%s'", locale, charset); + TAOS_CHECK_GOTO(taosSetSystemLocale(locale), &lino, _out); + uInfo("locale set to '%s'", locale); matched = true; } break; @@ -2281,13 +2254,7 @@ static int32_t taosCfgDynamicOptionsForClient(SConfig *pCfg, const char *name) { break; } case 't': { - if (strcasecmp("timezone", name) == 0) { - TAOS_CHECK_GOTO(osSetTimezone(pItem->str), &lino, _out); - uInfo("%s set from %s to %s", name, tsTimezoneStr, pItem->str); - - TAOS_CHECK_GOTO(cfgSetItem(pCfg, "timezone", tsTimezoneStr, pItem->stype, false), &lino, _out); - matched = true; - } else if (strcasecmp("tempDir", name) == 0) { + if (strcasecmp("tempDir", name) == 0) { uInfo("%s set from %s to %s", name, tsTempDir, pItem->str); tstrncpy(tsTempDir, pItem->str, PATH_MAX); TAOS_CHECK_GOTO(taosExpandDir(tsTempDir, tsTempDir, PATH_MAX), &lino, _out); diff --git a/source/common/src/tmisce.c b/source/common/src/tmisce.c index 8988fab56a..aa1804c1e9 100644 --- a/source/common/src/tmisce.c +++ b/source/common/src/tmisce.c @@ -299,6 +299,7 @@ _start: char value[TSDB_CONFIG_PATH_LEN + VARSTR_HEADER_SIZE] = {0}; int32_t valueLen = 0; + SDiskCfg* pDiskCfg = NULL; if (strcasecmp(pItem->name, "dataDir") == 0 && exSize > 0) { char* buf = &value[VARSTR_HEADER_SIZE]; diff --git a/source/common/src/tname.c b/source/common/src/tname.c index 964741e2c4..9ced37eb38 100644 --- a/source/common/src/tname.c +++ b/source/common/src/tname.c @@ -20,73 +20,6 @@ #define VALID_NAME_TYPE(x) ((x) == TSDB_DB_NAME_T || (x) == TSDB_TABLE_NAME_T) -#if 0 -int64_t taosGetIntervalStartTimestamp(int64_t startTime, int64_t slidingTime, int64_t intervalTime, char timeUnit, int16_t precision) { - if (slidingTime == 0) { - return startTime; - } - int64_t start = startTime; - if (timeUnit == 'n' || timeUnit == 'y') { - start /= 1000; - if (precision == TSDB_TIME_PRECISION_MICRO) { - start /= 1000; - } - struct tm tm; - time_t t = (time_t)start; - taosLocalTime(&t, &tm, NULL, 0); - tm.tm_sec = 0; - tm.tm_min = 0; - tm.tm_hour = 0; - tm.tm_mday = 1; - - if (timeUnit == 'y') { - tm.tm_mon = 0; - tm.tm_year = (int)(tm.tm_year / slidingTime * slidingTime); - } else { - int mon = tm.tm_year * 12 + tm.tm_mon; - mon = (int)(mon / slidingTime * slidingTime); - tm.tm_year = mon / 12; - tm.tm_mon = mon % 12; - } - - start = mktime(&tm) * 1000L; - if (precision == TSDB_TIME_PRECISION_MICRO) { - start *= 1000L; - } - } else { - int64_t delta = startTime - intervalTime; - int32_t factor = delta > 0? 1:-1; - - start = (delta / slidingTime + factor) * slidingTime; - - if (timeUnit == 'd' || timeUnit == 'w') { - /* - * here we revised the start time of day according to the local time zone, - * but in case of DST, the start time of one day need to be dynamically decided. - */ - // todo refactor to extract function that is available for Linux/Windows/Mac platform -#if defined(WINDOWS) && _MSC_VER >= 1900 - // see https://docs.microsoft.com/en-us/cpp/c-runtime-library/daylight-dstbias-timezone-and-tzname?view=vs-2019 - int64_t timezone = _timezone; - int32_t daylight = _daylight; - char** tzname = _tzname; -#endif - - int64_t t = (precision == TSDB_TIME_PRECISION_MILLI) ? MILLISECOND_PER_SECOND : MILLISECOND_PER_SECOND * 1000L; - start += timezone * t; - } - - int64_t end = start + intervalTime - 1; - if (end < startTime) { - start += slidingTime; - } - } - - return start; -} - -#endif - void toName(int32_t acctId, const char* pDbName, const char* pTableName, SName* pName) { if (pName == NULL){ return; diff --git a/source/common/src/ttime.c b/source/common/src/ttime.c index b24ded5c0c..9746fea034 100644 --- a/source/common/src/ttime.c +++ b/source/common/src/ttime.c @@ -25,42 +25,26 @@ #include "tlog.h" -// ==== mktime() kernel code =================// -static int64_t m_deltaUtc = 0; - -void deltaToUtcInitOnce() { - struct tm tm = {0}; - if (taosStrpTime("1970-01-01 00:00:00", (const char*)("%Y-%m-%d %H:%M:%S"), &tm) == NULL) { - uError("failed to parse time string"); - } - m_deltaUtc = (int64_t)taosMktime(&tm); - // printf("====delta:%lld\n\n", seconds); -} - static int32_t parseFraction(char* str, char** end, int32_t timePrec, int64_t* pFraction); static int32_t parseTimeWithTz(const char* timestr, int64_t* time, int32_t timePrec, char delim); -static int32_t parseLocaltime(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim); -static int32_t parseLocaltimeDst(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim); +static int32_t parseLocaltimeDst(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim, timezone_t tz); static char* forwardToTimeStringEnd(char* str); static bool checkTzPresent(const char* str, int32_t len); static int32_t parseTimezone(char* str, int64_t* tzOffset); -static int32_t (*parseLocaltimeFp[])(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim) = { - parseLocaltime, parseLocaltimeDst}; - -int32_t taosParseTime(const char* timestr, int64_t* utime, int32_t len, int32_t timePrec, int8_t day_light) { +int32_t taosParseTime(const char* timestr, int64_t* utime, int32_t len, int32_t timePrec, timezone_t tz) { /* parse datatime string in with tz */ if (strnchr(timestr, 'T', len, false) != NULL) { if (checkTzPresent(timestr, len)) { return parseTimeWithTz(timestr, utime, timePrec, 'T'); } else { - return parseLocaltimeDst((char*)timestr, len, utime, timePrec, 'T'); + return parseLocaltimeDst((char*)timestr, len, utime, timePrec, 'T', tz); } } else { if (checkTzPresent(timestr, len)) { return parseTimeWithTz(timestr, utime, timePrec, 0); } else { - return parseLocaltimeDst((char*)timestr, len, utime, timePrec, 0); + return parseLocaltimeDst((char*)timestr, len, utime, timePrec, 0, tz); } } } @@ -146,8 +130,15 @@ int32_t parseFraction(char* str, char** end, int32_t timePrec, int64_t* pFractio TAOS_RETURN(TSDB_CODE_SUCCESS); } +#define PARSE(str,len,result) \ + if (len != 2) {\ + TAOS_RETURN(TSDB_CODE_INVALID_PARA);\ + }\ + result = strnatoi(str, len); + int32_t parseTimezone(char* str, int64_t* tzOffset) { int64_t hour = 0; + int64_t minute = 0; int32_t i = 0; if (str[i] != '+' && str[i] != '-') { @@ -168,27 +159,29 @@ int32_t parseTimezone(char* str, int64_t* tzOffset) { char* sep = strchr(&str[i], ':'); if (sep != NULL) { - int32_t len = (int32_t)(sep - &str[i]); + int32_t hourSize = (int32_t)(sep - &str[i]); + PARSE(&str[i], hourSize, hour); - hour = strnatoi(&str[i], len); - i += len + 1; + i += hourSize + 1; + size_t minSize = strlen(&str[i]); + PARSE(&str[i], minSize, minute); } else { - hour = strnatoi(&str[i], 2); - i += 2; + size_t hourSize = strlen(&str[i]); + if (hourSize > 2){ + hourSize = 2; + } + PARSE(&str[i], hourSize, hour) + i += hourSize; + size_t minSize = strlen(&str[i]); + if (minSize > 0){ + PARSE(&str[i], minSize, minute); + } } - if (hour > 12 || hour < 0) { + if (hour > 13 || hour < 0) { TAOS_RETURN(TSDB_CODE_INVALID_PARA); } - - // return error if there're illegal charaters after min(2 Digits) - char* minStr = &str[i]; - if (minStr[1] != '\0' && minStr[2] != '\0') { - TAOS_RETURN(TSDB_CODE_INVALID_PARA); - } - - int64_t minute = strnatoi(&str[i], 2); - if (minute > 59 || (hour == 12 && minute > 0)) { + if (minute > 59 || minute < 0) { TAOS_RETURN(TSDB_CODE_INVALID_PARA); } @@ -245,7 +238,10 @@ int32_t parseTimeWithTz(const char* timestr, int64_t* time, int32_t timePrec, ch int64_t seconds = user_mktime64(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 0); // int64_t seconds = gmtime(&tm); #else - int64_t seconds = timegm(&tm); + int64_t seconds = taosTimeGm(&tm); + if (seconds == -1){ + TAOS_RETURN(TAOS_SYSTEM_ERROR(errno)); + } #endif int64_t fraction = 0; @@ -310,48 +306,7 @@ static FORCE_INLINE bool validateTm(struct tm* pTm) { return true; } -int32_t parseLocaltime(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim) { - *utime = 0; - struct tm tm = {0}; - - char* str; - if (delim == 'T') { - str = taosStrpTime(timestr, "%Y-%m-%dT%H:%M:%S", &tm); - } else if (delim == 0) { - str = taosStrpTime(timestr, "%Y-%m-%d %H:%M:%S", &tm); - } else { - str = NULL; - } - - if (str == NULL || (((str - timestr) < len) && (*str != '.')) || !validateTm(&tm)) { - // if parse failed, try "%Y-%m-%d" format - str = taosStrpTime(timestr, "%Y-%m-%d", &tm); - if (str == NULL || (((str - timestr) < len) && (*str != '.')) || !validateTm(&tm)) { - TAOS_RETURN(TSDB_CODE_INVALID_PARA); - } - } - -#ifdef _MSC_VER -#if _MSC_VER >= 1900 - int64_t timezone = _timezone; -#endif -#endif - - int64_t seconds = - user_mktime64(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, timezone); - - int64_t fraction = 0; - - if (*str == '.') { - /* parse the second fraction part */ - TAOS_CHECK_RETURN(parseFraction(str + 1, &str, timePrec, &fraction)); - } - - *utime = TSDB_TICK_PER_SECOND(timePrec) * seconds + fraction; - TAOS_RETURN(TSDB_CODE_SUCCESS); -} - -int32_t parseLocaltimeDst(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim) { +int32_t parseLocaltimeDst(char* timestr, int32_t len, int64_t* utime, int32_t timePrec, char delim, timezone_t tz) { *utime = 0; struct tm tm = {0}; tm.tm_isdst = -1; @@ -373,8 +328,7 @@ int32_t parseLocaltimeDst(char* timestr, int32_t len, int64_t* utime, int32_t ti } } - /* mktime will be affected by TZ, set by using taos_options */ - int64_t seconds = taosMktime(&tm); + int64_t seconds = taosMktime(&tm, tz); int64_t fraction = 0; if (*str == '.') { @@ -535,7 +489,7 @@ int32_t convertTimeFromPrecisionToUnit(int64_t time, int32_t fromPrecision, char TAOS_RETURN(TSDB_CODE_SUCCESS); } -int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec, int64_t* timeVal) { +int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec, int64_t* timeVal, timezone_t tz, void* charsetCxt) { int32_t charLen = varDataLen(inputData); char* newColData; if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_VARBINARY) { @@ -544,7 +498,7 @@ int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec TAOS_RETURN(terrno); } (void)memcpy(newColData, varDataVal(inputData), charLen); - int32_t ret = taosParseTime(newColData, timeVal, charLen, (int32_t)timePrec, tsDaylight); + int32_t ret = taosParseTime(newColData, timeVal, charLen, (int32_t)timePrec, tz); if (ret != TSDB_CODE_SUCCESS) { taosMemoryFree(newColData); TAOS_RETURN(TSDB_CODE_INVALID_TIMESTAMP); @@ -555,13 +509,13 @@ int32_t convertStringToTimestamp(int16_t type, char* inputData, int64_t timePrec if (NULL == newColData) { TAOS_RETURN(terrno); } - int len = taosUcs4ToMbs((TdUcs4*)varDataVal(inputData), charLen, newColData); + int len = taosUcs4ToMbs((TdUcs4*)varDataVal(inputData), charLen, newColData, charsetCxt); if (len < 0) { taosMemoryFree(newColData); TAOS_RETURN(TSDB_CODE_FAILED); } newColData[len] = 0; - int32_t ret = taosParseTime(newColData, timeVal, len, (int32_t)timePrec, tsDaylight); + int32_t ret = taosParseTime(newColData, timeVal, len, (int32_t)timePrec, tz); if (ret != TSDB_CODE_SUCCESS) { taosMemoryFree(newColData); TAOS_RETURN(ret); @@ -678,7 +632,7 @@ int32_t parseNatualDuration(const char* token, int32_t tokenLen, int64_t* durati static bool taosIsLeapYear(int32_t year) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } -int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision) { +int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision, timezone_t tz) { if (duration == 0) { return t; } @@ -693,7 +647,10 @@ int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision) { struct tm tm; time_t tt = (time_t)(t / TSDB_TICK_PER_SECOND(precision)); - struct tm* ptm = taosLocalTime(&tt, &tm, NULL, 0); + if(taosLocalTime(&tt, &tm, NULL, 0, tz) == NULL) { + uError("failed to convert time to gm time, code:%d", errno); + return t; + } int32_t mon = tm.tm_year * 12 + tm.tm_mon + (int32_t)numOfMonth; tm.tm_year = mon / 12; tm.tm_mon = mon % 12; @@ -704,7 +661,13 @@ int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision) { if (tm.tm_mday > daysOfMonth[tm.tm_mon]) { tm.tm_mday = daysOfMonth[tm.tm_mon]; } - return (int64_t)(taosMktime(&tm) * TSDB_TICK_PER_SECOND(precision) + fraction); + + tt = taosMktime(&tm, tz); + if (tt == -1){ + uError("failed to convert gm time to time, code:%d", errno); + return t; + } + return (int64_t)(tt * TSDB_TICK_PER_SECOND(precision) + fraction); } /** @@ -743,7 +706,7 @@ int32_t taosTimeCountIntervalForFill(int64_t skey, int64_t ekey, int64_t interva ekey = skey; skey = tmp; } - int32_t ret; + int32_t ret = 0; if (unit != 'n' && unit != 'y') { ret = (int32_t)((ekey - skey) / interval); @@ -754,11 +717,17 @@ int32_t taosTimeCountIntervalForFill(int64_t skey, int64_t ekey, int64_t interva struct tm tm; time_t t = (time_t)skey; - struct tm* ptm = taosLocalTime(&t, &tm, NULL, 0); + if (taosLocalTime(&t, &tm, NULL, 0, NULL) == NULL) { + uError("%s failed to convert time to local time, code:%d", __FUNCTION__, errno); + return ret; + } int32_t smon = tm.tm_year * 12 + tm.tm_mon; t = (time_t)ekey; - ptm = taosLocalTime(&t, &tm, NULL, 0); + if (taosLocalTime(&t, &tm, NULL, 0, NULL) == NULL) { + uError("%s failed to convert time to local time, code:%d", __FUNCTION__, errno); + return ret; + } int32_t emon = tm.tm_year * 12 + tm.tm_mon; if (unit == 'y') { @@ -782,7 +751,10 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { start /= (int64_t)(TSDB_TICK_PER_SECOND(precision)); struct tm tm; time_t tt = (time_t)start; - struct tm* ptm = taosLocalTime(&tt, &tm, NULL, 0); + if (taosLocalTime(&tt, &tm, NULL, 0, pInterval->timezone) == NULL){ + uError("%s failed to convert time to local time, code:%d", __FUNCTION__, errno); + return ts; + } tm.tm_sec = 0; tm.tm_min = 0; tm.tm_hour = 0; @@ -798,7 +770,12 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { tm.tm_mon = mon % 12; } - start = (int64_t)(taosMktime(&tm) * TSDB_TICK_PER_SECOND(precision)); + tt = taosMktime(&tm, pInterval->timezone); + if (tt == -1){ + uError("%s failed to convert local time to time, code:%d", __FUNCTION__, errno); + return ts; + } + start = (int64_t)(tt * TSDB_TICK_PER_SECOND(precision)); } else { if (IS_CALENDAR_TIME_DURATION(pInterval->intervalUnit)) { int64_t news = (ts / pInterval->sliding) * pInterval->sliding; @@ -812,12 +789,12 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { start = news; if (news <= ts) { int64_t prev = news; - int64_t newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision) - 1; + int64_t newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision, pInterval->timezone) - 1; if (newe < ts) { // move towards the greater endpoint while (newe < ts && news < ts) { news += pInterval->sliding; - newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision) - 1; + newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision, pInterval->timezone) - 1; } prev = news; @@ -825,7 +802,7 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { while (newe >= ts) { prev = news; news -= pInterval->sliding; - newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision) - 1; + newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision, pInterval->timezone) - 1; } } @@ -847,8 +824,6 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { // see // https://docs.microsoft.com/en-us/cpp/c-runtime-library/daylight-dstbias-timezone-and-tzname?view=vs-2019 int64_t timezone = _timezone; - int32_t daylight = _daylight; - char** tzname = _tzname; #endif start += (int64_t)(timezone * TSDB_TICK_PER_SECOND(precision)); @@ -858,7 +833,7 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { // not enough time range if (start < 0 || INT64_MAX - start > pInterval->interval - 1) { - end = taosTimeAdd(start, pInterval->interval, pInterval->intervalUnit, precision) - 1; + end = taosTimeAdd(start, pInterval->interval, pInterval->intervalUnit, precision, pInterval->timezone) - 1; while (end < ts) { // move forward to the correct time window start += pInterval->sliding; @@ -877,15 +852,15 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { if (pInterval->offset > 0) { // try to move current window to the left-hande-side, due to the offset effect. - int64_t newe = taosTimeAdd(start, pInterval->interval, pInterval->intervalUnit, precision) - 1; + int64_t newe = taosTimeAdd(start, pInterval->interval, pInterval->intervalUnit, precision, pInterval->timezone) - 1; int64_t slidingStart = start; while (newe >= ts) { start = slidingStart; - slidingStart = taosTimeAdd(slidingStart, -pInterval->sliding, pInterval->slidingUnit, precision); - int64_t news = taosTimeAdd(slidingStart, pInterval->offset, pInterval->offsetUnit, precision); - newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision) - 1; + slidingStart = taosTimeAdd(slidingStart, -pInterval->sliding, pInterval->slidingUnit, precision, pInterval->timezone); + int64_t news = taosTimeAdd(slidingStart, pInterval->offset, pInterval->offsetUnit, precision, pInterval->timezone); + newe = taosTimeAdd(news, pInterval->interval, pInterval->intervalUnit, precision, pInterval->timezone) - 1; } - start = taosTimeAdd(start, pInterval->offset, pInterval->offsetUnit, precision); + start = taosTimeAdd(start, pInterval->offset, pInterval->offsetUnit, precision, pInterval->timezone); } return start; @@ -893,7 +868,7 @@ int64_t taosTimeTruncate(int64_t ts, const SInterval* pInterval) { // used together with taosTimeTruncate. when offset is great than zero, slide-start/slide-end is the anchor point int64_t taosTimeGetIntervalEnd(int64_t intervalStart, const SInterval* pInterval) { - return taosTimeAdd(intervalStart, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1; + return taosTimeAdd(intervalStart, pInterval->interval, pInterval->intervalUnit, pInterval->precision, pInterval->timezone) - 1; } void calcIntervalAutoOffset(SInterval* interval) { @@ -912,7 +887,7 @@ void calcIntervalAutoOffset(SInterval* interval) { TSKEY news = start; while (news <= skey) { start = news; - news = taosTimeAdd(start, interval->sliding, interval->slidingUnit, interval->precision); + news = taosTimeAdd(start, interval->sliding, interval->slidingUnit, interval->precision, interval->timezone); if (news < start) { // overflow happens uError("%s failed and skip, skey [%" PRId64 "], inter[%" PRId64 "(%c)], slid[%" PRId64 "(%c)], precision[%d]", @@ -938,15 +913,15 @@ const char* fmtts(int64_t ts) { if (ts > -62135625943 && ts < 32503651200) { time_t t = (time_t)ts; - if (taosLocalTime(&t, &tm, buf, sizeof(buf)) == NULL) { + if (taosLocalTime(&t, &tm, buf, sizeof(buf), NULL) == NULL) { return buf; } - pos += strftime(buf + pos, sizeof(buf), "s=%Y-%m-%d %H:%M:%S", &tm); + pos += taosStrfTime(buf + pos, sizeof(buf), "s=%Y-%m-%d %H:%M:%S", &tm); } if (ts > -62135625943000 && ts < 32503651200000) { time_t t = (time_t)(ts / 1000); - if (taosLocalTime(&t, &tm, buf, sizeof(buf)) == NULL) { + if (taosLocalTime(&t, &tm, buf, sizeof(buf), NULL) == NULL) { return buf; } if (pos > 0) { @@ -954,13 +929,13 @@ const char* fmtts(int64_t ts) { buf[pos++] = '|'; buf[pos++] = ' '; } - pos += strftime(buf + pos, sizeof(buf), "ms=%Y-%m-%d %H:%M:%S", &tm); + pos += taosStrfTime(buf + pos, sizeof(buf), "ms=%Y-%m-%d %H:%M:%S", &tm); pos += sprintf(buf + pos, ".%03d", (int32_t)(ts % 1000)); } { time_t t = (time_t)(ts / 1000000); - if (taosLocalTime(&t, &tm, buf, sizeof(buf)) == NULL) { + if (taosLocalTime(&t, &tm, buf, sizeof(buf), NULL) == NULL) { return buf; } if (pos > 0) { @@ -968,7 +943,7 @@ const char* fmtts(int64_t ts) { buf[pos++] = '|'; buf[pos++] = ' '; } - pos += strftime(buf + pos, sizeof(buf), "us=%Y-%m-%d %H:%M:%S", &tm); + pos += taosStrfTime(buf + pos, sizeof(buf), "us=%Y-%m-%d %H:%M:%S", &tm); pos += sprintf(buf + pos, ".%06d", (int32_t)(ts % 1000000)); } @@ -1014,28 +989,28 @@ int32_t taosFormatUtcTime(char* buf, int32_t bufLen, int64_t t, int32_t precisio TAOS_RETURN(TSDB_CODE_INVALID_PARA); } - if (NULL == taosLocalTime(", &ptm, buf, bufLen)) { + if (NULL == taosLocalTime(", &ptm, buf, bufLen, NULL)) { TAOS_RETURN(TAOS_SYSTEM_ERROR(errno)); } - int32_t length = (int32_t)strftime(ts, 40, "%Y-%m-%dT%H:%M:%S", &ptm); + int32_t length = (int32_t)taosStrfTime(ts, 40, "%Y-%m-%dT%H:%M:%S", &ptm); length += tsnprintf(ts + length, fractionLen, format, mod); - length += (int32_t)strftime(ts + length, 40 - length, "%z", &ptm); + length += (int32_t)taosStrfTime(ts + length, 40 - length, "%z", &ptm); tstrncpy(buf, ts, bufLen); TAOS_RETURN(TSDB_CODE_SUCCESS); } -int32_t taosTs2Tm(int64_t ts, int32_t precision, struct STm* tm) { +int32_t taosTs2Tm(int64_t ts, int32_t precision, struct STm* tm, timezone_t tz) { tm->fsec = ts % TICK_PER_SECOND[precision] * (TICK_PER_SECOND[TSDB_TIME_PRECISION_NANO] / TICK_PER_SECOND[precision]); time_t t = ts / TICK_PER_SECOND[precision]; - if (NULL == taosLocalTime(&t, &tm->tm, NULL, 0)) { + if (NULL == taosLocalTime(&t, &tm->tm, NULL, 0, tz)) { TAOS_RETURN(TAOS_SYSTEM_ERROR(errno)); } return TSDB_CODE_SUCCESS; } -int32_t taosTm2Ts(struct STm* tm, int64_t* ts, int32_t precision) { - *ts = taosMktime(&tm->tm); +int32_t taosTm2Ts(struct STm* tm, int64_t* ts, int32_t precision, timezone_t tz) { + *ts = taosMktime(&tm->tm, tz); *ts *= TICK_PER_SECOND[precision]; *ts += tm->fsec / (TICK_PER_SECOND[TSDB_TIME_PRECISION_NANO] / TICK_PER_SECOND[precision]); return TSDB_CODE_SUCCESS; @@ -1502,10 +1477,17 @@ static int32_t tm2char(const SArray* formats, const struct STm* tm, char* s, int (void)sprintf(s, "%09" PRId64, tm->fsec); s += 9; break; - case TSFKW_TZH: - (void)sprintf(s, "%s%02d", tsTimezone < 0 ? "-" : "+", tsTimezone); + case TSFKW_TZH:{ +#ifdef WINDOWS + int32_t gmtoff = -_timezone; +#else + int32_t gmtoff = tm->tm.tm_gmtoff; +#endif + (void)sprintf(s, "%c%02d", (gmtoff >= 0) ? '+' : '-', + abs(gmtoff) / 3600); s += strlen(s); break; + } case TSFKW_YYYY: (void)sprintf(s, "%04d", tm->tm.tm_year + 1900); s += strlen(s); @@ -1635,13 +1617,13 @@ static bool needMoreDigits(SArray* formats, int32_t curIdx) { /// @retval -2 if datetime err, like 2023-13-32 25:61:69 /// @retval -3 if not supported static int32_t char2ts(const char* s, SArray* formats, int64_t* ts, int32_t precision, const char** sErrPos, - int32_t* fErrIdx) { + int32_t* fErrIdx, timezone_t tz) { int32_t size = taosArrayGetSize(formats); int32_t pm = 0; // default am int32_t hour12 = 0; // default HH24 int32_t year = 0, mon = 0, yd = 0, md = 1, wd = 0; int32_t hour = 0, min = 0, sec = 0, us = 0, ms = 0, ns = 0; - int32_t tzSign = 1, tz = tsTimezone; + int32_t tzHour = 0; int32_t err = 0; bool withYD = false, withMD = false; @@ -1768,8 +1750,7 @@ static int32_t char2ts(const char* s, SArray* formats, int64_t* ts, int32_t prec } } break; case TSFKW_TZH: { - tzSign = *s == '-' ? -1 : 1; - const char* newPos = tsFormatStr2Int32(&tz, s, -1, needMoreDigits(formats, i)); + const char* newPos = tsFormatStr2Int32(&tzHour, s, -1, needMoreDigits(formats, i)); if (NULL == newPos) err = -1; else { @@ -1922,14 +1903,21 @@ static int32_t char2ts(const char* s, SArray* formats, int64_t* ts, int32_t prec tm.tm.tm_min = min; tm.tm.tm_sec = sec; if (!checkTm(&tm.tm)) return -2; - if (tz < -12 || tz > 12) return -2; + if (tzHour < -13 || tzHour > 13) return -2; tm.fsec = ms * 1000000 + us * 1000 + ns; - int32_t ret = taosTm2Ts(&tm, ts, precision); - *ts += 60 * 60 * (tsTimezone - tz) * TICK_PER_SECOND[precision]; + int32_t ret = taosTm2Ts(&tm, ts, precision, tz); + if (tzHour != 0) { +#ifdef WINDOWS + int32_t gmtoff = -_timezone; +#else + int32_t gmtoff = tm.tm.tm_gmtoff; +#endif + *ts += (gmtoff - tzHour * 3600) * TICK_PER_SECOND[precision]; + } return ret; } -int32_t taosTs2Char(const char* format, SArray** formats, int64_t ts, int32_t precision, char* out, int32_t outLen) { +int32_t taosTs2Char(const char* format, SArray** formats, int64_t ts, int32_t precision, char* out, int32_t outLen, timezone_t tz) { if (!*formats) { *formats = taosArrayInit(8, sizeof(TSFormatNode)); if (!*formats) { @@ -1938,12 +1926,12 @@ int32_t taosTs2Char(const char* format, SArray** formats, int64_t ts, int32_t pr TAOS_CHECK_RETURN(parseTsFormat(format, *formats)); } struct STm tm; - TAOS_CHECK_RETURN(taosTs2Tm(ts, precision, &tm)); + TAOS_CHECK_RETURN(taosTs2Tm(ts, precision, &tm, tz)); return tm2char(*formats, &tm, out, outLen); } int32_t taosChar2Ts(const char* format, SArray** formats, const char* tsStr, int64_t* ts, int32_t precision, - char* errMsg, int32_t errMsgLen) { + char* errMsg, int32_t errMsgLen, timezone_t tz) { const char* sErrPos; int32_t fErrIdx; if (!*formats) { @@ -1953,7 +1941,7 @@ int32_t taosChar2Ts(const char* format, SArray** formats, const char* tsStr, int } TAOS_CHECK_RETURN(parseTsFormat(format, *formats)); } - int32_t code = char2ts(tsStr, *formats, ts, precision, &sErrPos, &fErrIdx); + int32_t code = char2ts(tsStr, *formats, ts, precision, &sErrPos, &fErrIdx, tz); if (code == -1) { TSFormatNode* fNode = (taosArrayGet(*formats, fErrIdx)); snprintf(errMsg, errMsgLen, "mismatch format for: %s and %s", sErrPos, @@ -1978,7 +1966,7 @@ int32_t TEST_ts2char(const char* format, int64_t ts, int32_t precision, char* ou } TAOS_CHECK_RETURN(parseTsFormat(format, formats)); struct STm tm; - TAOS_CHECK_GOTO(taosTs2Tm(ts, precision, &tm), NULL, _exit); + TAOS_CHECK_GOTO(taosTs2Tm(ts, precision, &tm, NULL), NULL, _exit); TAOS_CHECK_GOTO(tm2char(formats, &tm, out, outLen), NULL, _exit); _exit: @@ -1991,7 +1979,7 @@ int32_t TEST_char2ts(const char* format, int64_t* ts, int32_t precision, const c int32_t fErrIdx; SArray* formats = taosArrayInit(4, sizeof(TSFormatNode)); TAOS_CHECK_RETURN(parseTsFormat(format, formats)); - int32_t code = char2ts(tsStr, formats, ts, precision, &sErrPos, &fErrIdx); + int32_t code = char2ts(tsStr, formats, ts, precision, &sErrPos, &fErrIdx, NULL); if (code == -1) { (void)printf("failed position: %s\n", sErrPos); (void)printf("failed format: %s\n", ((TSFormatNode*)taosArrayGet(formats, fErrIdx))->key->name); @@ -2107,3 +2095,30 @@ bool checkRecursiveTsmaInterval(int64_t baseInterval, int8_t baseUnit, int64_t i } return true; } + +int64_t taosGetTimestampToday(int32_t precision, timezone_t tz) { + int64_t factor = (precision == TSDB_TIME_PRECISION_SECONDS) ? 1 + : (precision == TSDB_TIME_PRECISION_MILLI) ? 1000 + : (precision == TSDB_TIME_PRECISION_MICRO) ? 1000000 + : 1000000000; + time_t t; + int32_t code = taosTime(&t); + if (code != 0) { + return -1; + } + struct tm tm; + if (taosLocalTime(&t, &tm, NULL, 0, tz) == NULL){ + uError("%s failed to get local time, code:%d", __FUNCTION__, errno); + return t; + } + tm.tm_hour = 0; + tm.tm_min = 0; + tm.tm_sec = 0; + + time_t tmp = taosMktime(&tm, tz); + if (tmp == (time_t)-1) { + uError("%s failed to get timestamp of today, code:%d", __FUNCTION__, errno); + return t; + } + return (int64_t)tmp * factor; +} \ No newline at end of file diff --git a/source/common/test/commonTests.cpp b/source/common/test/commonTests.cpp index b85af42d1c..a6ffe2cd40 100644 --- a/source/common/test/commonTests.cpp +++ b/source/common/test/commonTests.cpp @@ -429,9 +429,9 @@ void test_timestamp_tm_conversion(int64_t ts, int32_t precision, int32_t y, int3 struct STm tm; taosFormatUtcTime(buf, 128, ts, precision); printf("formated ts of %ld, precision: %d is: %s\n", ts, precision, buf); - taosTs2Tm(ts, precision, &tm); + taosTs2Tm(ts, precision, &tm, NULL); check_tm(&tm, y, mon, d, h, m, s, fsec); - taosTm2Ts(&tm, &ts_tmp, precision); + taosTm2Ts(&tm, &ts_tmp, precision, NULL); ASSERT_EQ(ts, ts_tmp); } @@ -442,15 +442,15 @@ TEST(timeTest, timestamp2tm) { int64_t ts, tmp_ts = 0; struct STm tm; - ASSERT_EQ(TSDB_CODE_SUCCESS, taosParseTime(ts_str_ns, &ts, strlen(ts_str_ns), TSDB_TIME_PRECISION_NANO, 0)); + ASSERT_EQ(TSDB_CODE_SUCCESS, taosParseTime(ts_str_ns, &ts, strlen(ts_str_ns), TSDB_TIME_PRECISION_NANO, NULL)); test_timestamp_tm_conversion(ts, TSDB_TIME_PRECISION_NANO, 2023 - 1900, 9 /* mon start from 0*/, 12, 11, 29, 0, 775726171L); - ASSERT_EQ(TSDB_CODE_SUCCESS, taosParseTime(ts_str_us, &ts, strlen(ts_str_us), TSDB_TIME_PRECISION_MICRO, 0)); + ASSERT_EQ(TSDB_CODE_SUCCESS, taosParseTime(ts_str_us, &ts, strlen(ts_str_us), TSDB_TIME_PRECISION_MICRO, NULL)); test_timestamp_tm_conversion(ts, TSDB_TIME_PRECISION_MICRO, 2023 - 1900, 9 /* mon start from 0*/, 12, 11, 29, 0, 775726000L); - ASSERT_EQ(TSDB_CODE_SUCCESS, taosParseTime(ts_str_ms, &ts, strlen(ts_str_ms), TSDB_TIME_PRECISION_MILLI, 0)); + ASSERT_EQ(TSDB_CODE_SUCCESS, taosParseTime(ts_str_ms, &ts, strlen(ts_str_ms), TSDB_TIME_PRECISION_MILLI, NULL)); test_timestamp_tm_conversion(ts, TSDB_TIME_PRECISION_MILLI, 2023 - 1900, 9 /* mon start from 0*/, 12, 11, 29, 0, 775000000L); @@ -477,7 +477,7 @@ void test_ts2char(int64_t ts, const char* format, int32_t precison, const char* TEST(timeTest, ts2char) { osDefaultInit(); - if (tsTimezone != TdEastZone8) GTEST_SKIP(); + if (taosGetLocalTimezoneOffset() != TdEastZone8) GTEST_SKIP(); int64_t ts; const char* format = "YYYY-MM-DD"; ts = 0; @@ -529,7 +529,7 @@ TEST(timeTest, ts2char) { TEST(timeTest, char2ts) { osDefaultInit(); - if (tsTimezone != TdEastZone8) GTEST_SKIP(); + if (taosGetLocalTimezoneOffset() != TdEastZone8) GTEST_SKIP(); int64_t ts; int32_t code = TEST_char2ts("YYYY-DD-MM HH12:MI:SS:MSPM", &ts, TSDB_TIME_PRECISION_MILLI, "2023-10-10 12:00:00.000AM"); @@ -630,7 +630,7 @@ TEST(timeTest, char2ts) { // default to 1970-1-1 00:00:00+08 -> 1969-12-31 16:00:00+00 ASSERT_EQ(0, TEST_char2ts("YYYY", &ts, TSDB_TIME_PRECISION_SECONDS, "1970")); - ASSERT_EQ(ts, -1 * tsTimezone * 60 * 60); + ASSERT_EQ(ts, -1 * taosGetLocalTimezoneOffset()); ASSERT_EQ(0, TEST_char2ts("yyyyMM1/dd ", &ts, TSDB_TIME_PRECISION_MICRO, "210001/2")); ASSERT_EQ(ts, 4102502400000000LL); diff --git a/source/dnode/mgmt/exe/dmMain.c b/source/dnode/mgmt/exe/dmMain.c index 4aa76d9284..ebe246da4c 100644 --- a/source/dnode/mgmt/exe/dmMain.c +++ b/source/dnode/mgmt/exe/dmMain.c @@ -20,6 +20,7 @@ #include "tconfig.h" #include "tglobal.h" #include "version.h" +#include "tconv.h" #ifdef TD_JEMALLOC_ENABLED #include "jemalloc/jemalloc.h" #endif @@ -477,7 +478,7 @@ int mainWindows(int argc, char **argv) { return code; } - if ((code = taosConvInit()) != 0) { + if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) { dError("failed to init conv"); taosCloseLog(); taosCleanupArgs(); diff --git a/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c b/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c index c01fdcc85b..f00222161a 100644 --- a/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c +++ b/source/dnode/mgmt/mgmt_dnode/src/dmHandle.c @@ -197,7 +197,7 @@ void dmSendStatusReq(SDnodeMgmt *pMgmt) { req.clusterCfg.monitorParas.tsSlowLogThreshold = tsSlowLogThreshold; tstrncpy(req.clusterCfg.monitorParas.tsSlowLogExceptDb, tsSlowLogExceptDb, TSDB_DB_NAME_LEN); char timestr[32] = "1970-01-01 00:00:00.00"; - if (taosParseTime(timestr, &req.clusterCfg.checkTime, (int32_t)strlen(timestr), TSDB_TIME_PRECISION_MILLI, 0) != 0) { + if (taosParseTime(timestr, &req.clusterCfg.checkTime, (int32_t)strlen(timestr), TSDB_TIME_PRECISION_MILLI, NULL) != 0) { dError("failed to parse time since %s", tstrerror(code)); } memcpy(req.clusterCfg.timezone, tsTimezoneStr, TD_TIMEZONE_LEN); @@ -355,7 +355,7 @@ int32_t dmProcessConfigReq(SDnodeMgmt *pMgmt, SRpcMsg *pMsg) { SConfig *pCfg = taosGetCfg(); - code = cfgSetItem(pCfg, cfgReq.config, cfgReq.value, CFG_STYPE_ALTER_CMD, true); + code = cfgSetItem(pCfg, cfgReq.config, cfgReq.value, CFG_STYPE_ALTER_SERVER_CMD, true); if (code != 0) { if (strncasecmp(cfgReq.config, "resetlog", strlen("resetlog")) == 0) { code = 0; diff --git a/source/dnode/mgmt/node_mgmt/src/dmMgmt.c b/source/dnode/mgmt/node_mgmt/src/dmMgmt.c index 9f1c292a90..f11e1508a8 100644 --- a/source/dnode/mgmt/node_mgmt/src/dmMgmt.c +++ b/source/dnode/mgmt/node_mgmt/src/dmMgmt.c @@ -22,6 +22,7 @@ #include "tglobal.h" #include "tgrant.h" #include "tstream.h" +#include "tconv.h" static bool dmRequireNode(SDnode *pDnode, SMgmtWrapper *pWrapper) { SMgmtInputOpt input = dmBuildMgmtInputOpt(pWrapper); diff --git a/source/dnode/mnode/impl/inc/mndDef.h b/source/dnode/mnode/impl/inc/mndDef.h index d2d9b2e8eb..65708628b3 100644 --- a/source/dnode/mnode/impl/inc/mndDef.h +++ b/source/dnode/mnode/impl/inc/mndDef.h @@ -489,7 +489,7 @@ typedef struct { int64_t dstTbUid; int8_t intervalUnit; int8_t slidingUnit; - int8_t timezone; + int8_t timezone; // int8_t is not enough, timezone is unit of second int32_t dstVgId; // for stream int64_t interval; int64_t offset; diff --git a/source/dnode/mnode/impl/src/mndMain.c b/source/dnode/mnode/impl/src/mndMain.c index 9dd43225b1..fbd8bde5f3 100644 --- a/source/dnode/mnode/impl/src/mndMain.c +++ b/source/dnode/mnode/impl/src/mndMain.c @@ -713,7 +713,7 @@ SMnode *mndOpen(const char *path, const SMnodeOpt *pOption) { } char timestr[24] = "1970-01-01 00:00:00.00"; - code = taosParseTime(timestr, &pMnode->checkTime, (int32_t)strlen(timestr), TSDB_TIME_PRECISION_MILLI, 0); + code = taosParseTime(timestr, &pMnode->checkTime, (int32_t)strlen(timestr), TSDB_TIME_PRECISION_MILLI, NULL); if (code < 0) { mError("failed to parse time since %s", tstrerror(code)); (void)taosThreadRwlockDestroy(&pMnode->lock); diff --git a/source/dnode/mnode/impl/src/mndProfile.c b/source/dnode/mnode/impl/src/mndProfile.c index fd02367f6d..9eefaf6a20 100644 --- a/source/dnode/mnode/impl/src/mndProfile.c +++ b/source/dnode/mnode/impl/src/mndProfile.c @@ -45,6 +45,8 @@ typedef struct { int32_t numOfQueries; SRWLatch queryLock; SArray *pQueries; // SArray + char userApp[TSDB_APP_NAME_LEN]; + uint32_t userIp; } SConnObj; typedef struct { @@ -135,6 +137,13 @@ void mndCleanupProfile(SMnode *pMnode) { } } +static void setUserInfo2Conn(SConnObj* connObj, char* userApp, uint32_t userIp){ + if (connObj == NULL){ + return; + } + tstrncpy(connObj->userApp, userApp, sizeof(connObj->userApp)); + connObj->userIp = userIp; +} static SConnObj *mndCreateConn(SMnode *pMnode, const char *user, int8_t connType, uint32_t ip, uint16_t port, int32_t pid, const char *app, int64_t startTime) { SProfileMgmt *pMgmt = &pMnode->profileMgmt; @@ -232,7 +241,7 @@ static int32_t mndProcessConnectReq(SRpcMsg *pReq) { SConnObj *pConn = NULL; int32_t code = 0; SConnectReq connReq = {0}; - char ip[24] = {0}; + char ip[TD_IP_LEN] = {0}; const STraceId *trace = &pReq->info.traceId; if ((code = tDeserializeSConnectReq(pReq->pCont, pReq->contLen, &connReq)) != 0) { @@ -244,7 +253,7 @@ static int32_t mndProcessConnectReq(SRpcMsg *pReq) { goto _OVER; } - taosIp2String(pReq->info.conn.clientIp, ip); + taosInetNtoa(ip, pReq->info.conn.clientIp); if ((code = mndCheckOperPrivilege(pMnode, pReq->info.conn.user, MND_OPER_CONNECT)) != 0) { mGError("user:%s, failed to login from %s since %s", pReq->info.conn.user, ip, tstrerror(code)); goto _OVER; @@ -513,6 +522,7 @@ static int32_t mndProcessQueryHeartBeat(SMnode *pMnode, SRpcMsg *pMsg, SClientHb } } + setUserInfo2Conn(pConn, pHbReq->userApp, pHbReq->userIp); SQueryHbRspBasic *rspBasic = taosMemoryCalloc(1, sizeof(SQueryHbRspBasic)); if (rspBasic == NULL) { mndReleaseConn(pMnode, pConn, true); @@ -896,9 +906,10 @@ static int32_t mndRetrieveConns(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl return code; } - char endpoint[TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; - (void)sprintf(&endpoint[VARSTR_HEADER_SIZE], "%s:%d", taosIpStr(pConn->ip), pConn->port); - varDataLen(endpoint) = strlen(&endpoint[VARSTR_HEADER_SIZE]); + char endpoint[TD_IP_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; + taosInetNtoa(varDataVal(endpoint), pConn->ip); + (void)sprintf(varDataVal(endpoint) + strlen(varDataVal(endpoint)), ":%d", pConn->port); + varDataLen(endpoint) = strlen(varDataVal(endpoint)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); code = colDataSetVal(pColInfo, numOfRows, (const char *)endpoint, false); if (code != 0) { @@ -920,6 +931,27 @@ static int32_t mndRetrieveConns(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBl return code; } + char userApp[TSDB_APP_NAME_LEN + VARSTR_HEADER_SIZE]; + STR_TO_VARSTR(userApp, pConn->userApp); + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); + code = colDataSetVal(pColInfo, numOfRows, (const char *)userApp, false); + if (code != 0) { + mError("failed to set user app since %s", tstrerror(code)); + return code; + } + + char userIp[TD_IP_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; + if (pConn->userIp != 0 && pConn->userIp != INADDR_NONE){ + taosInetNtoa(varDataVal(userIp), pConn->userIp); + varDataLen(userIp) = strlen(varDataVal(userIp)); + } + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); + code = colDataSetVal(pColInfo, numOfRows, (const char *)userIp, false); + if (code != 0) { + mError("failed to set user ip since %s", tstrerror(code)); + return code; + } + numOfRows++; } @@ -1006,8 +1038,9 @@ static int32_t packQueriesIntoBlock(SShowObj *pShow, SConnObj *pConn, SSDataBloc return code; } - char endpoint[TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; - (void)sprintf(&endpoint[VARSTR_HEADER_SIZE], "%s:%d", taosIpStr(pConn->ip), pConn->port); + char endpoint[TD_IP_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; + taosInetNtoa(varDataVal(endpoint), pConn->ip); + (void)sprintf(varDataVal(endpoint) + strlen(varDataVal(endpoint)), ":%d", pConn->port); varDataLen(endpoint) = strlen(&endpoint[VARSTR_HEADER_SIZE]); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); code = colDataSetVal(pColInfo, curRowIndex, (const char *)endpoint, false); @@ -1091,6 +1124,29 @@ static int32_t packQueriesIntoBlock(SShowObj *pShow, SConnObj *pConn, SSDataBloc return code; } + char userApp[TSDB_APP_NAME_LEN + VARSTR_HEADER_SIZE]; + STR_TO_VARSTR(userApp, pConn->userApp); + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); + code = colDataSetVal(pColInfo, curRowIndex, (const char *)userApp, false); + if (code != 0) { + mError("failed to set user app since %s", tstrerror(code)); + taosRUnLockLatch(&pConn->queryLock); + return code; + } + + char userIp[TD_IP_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; + if (pConn->userIp != 0 && pConn->userIp != INADDR_NONE){ + taosInetNtoa(varDataVal(userIp), pConn->userIp); + varDataLen(userIp) = strlen(varDataVal(userIp)); + } + pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); + code = colDataSetVal(pColInfo, curRowIndex, (const char *)userIp, false); + if (code != 0) { + mError("failed to set user ip since %s", tstrerror(code)); + taosRUnLockLatch(&pConn->queryLock); + return code; + } + pBlock->info.rows++; } @@ -1165,9 +1221,9 @@ static int32_t mndRetrieveApps(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlo return code; } - char ip[TSDB_IPv4ADDR_LEN + 6 + VARSTR_HEADER_SIZE] = {0}; - (void)sprintf(&ip[VARSTR_HEADER_SIZE], "%s", taosIpStr(pApp->ip)); - varDataLen(ip) = strlen(&ip[VARSTR_HEADER_SIZE]); + char ip[TD_IP_LEN + VARSTR_HEADER_SIZE] = {0}; + taosInetNtoa(varDataVal(ip), pApp->ip); + varDataLen(ip) = strlen(varDataVal(ip)); pColInfo = taosArrayGet(pBlock->pDataBlock, cols++); code = colDataSetVal(pColInfo, numOfRows, (const char *)ip, false); if (code != 0) { diff --git a/source/dnode/mnode/impl/src/mndSma.c b/source/dnode/mnode/impl/src/mndSma.c index aadc67c41f..64a11fbe5b 100644 --- a/source/dnode/mnode/impl/src/mndSma.c +++ b/source/dnode/mnode/impl/src/mndSma.c @@ -316,7 +316,7 @@ static void *mndBuildVCreateSmaReq(SMnode *pMnode, SVgObj *pVgroup, SSmaObj *pSm req.version = 0; req.intervalUnit = pSma->intervalUnit; req.slidingUnit = pSma->slidingUnit; - req.timezoneInt = pSma->timezone; +// req.timezoneInt = pSma->timezone; tstrncpy(req.indexName, (char *)tNameGetTableName(&name), TSDB_INDEX_NAME_LEN); req.exprLen = pSma->exprLen; req.tagsFilterLen = pSma->tagsFilterLen; @@ -617,9 +617,9 @@ static int32_t mndCreateSma(SMnode *pMnode, SRpcMsg *pReq, SMCreateSmaReq *pCrea smaObj.intervalUnit = pCreate->intervalUnit; smaObj.slidingUnit = pCreate->slidingUnit; #if 0 - smaObj.timezone = pCreate->timezone; +// smaObj.timezone = pCreate->timezone; #endif - smaObj.timezone = tsTimezone; // use timezone of server +// smaObj.timezone = taosGetLocalTimezoneOffset(); // use timezone of server smaObj.interval = pCreate->interval; smaObj.offset = pCreate->offset; smaObj.sliding = pCreate->sliding; @@ -1554,7 +1554,7 @@ static void initSMAObj(SCreateTSMACxt* pCxt) { pCxt->pSma->dbUid = pCxt->pDb->uid; pCxt->pSma->interval = pCxt->pCreateSmaReq->interval; pCxt->pSma->intervalUnit = pCxt->pCreateSmaReq->intervalUnit; - pCxt->pSma->timezone = tsTimezone; +// pCxt->pSma->timezone = taosGetLocalTimezoneOffset(); pCxt->pSma->version = 1; pCxt->pSma->exprLen = pCxt->pCreateSmaReq->exprLen; diff --git a/source/dnode/vnode/src/meta/metaQuery.c b/source/dnode/vnode/src/meta/metaQuery.c index e2ba8d9ccb..87beb8842b 100644 --- a/source/dnode/vnode/src/meta/metaQuery.c +++ b/source/dnode/vnode/src/meta/metaQuery.c @@ -1328,7 +1328,7 @@ int32_t metaFilterTableIds(void *pVnode, SMetaFltParam *arg, SArray *pUids) { TAOS_CHECK_GOTO(terrno, NULL, END); } - if (false == taosMbsToUcs4(tagData, nTagData, (TdUcs4 *)buf, maxSize, &maxSize)) { + if (false == taosMbsToUcs4(tagData, nTagData, (TdUcs4 *)buf, maxSize, &maxSize, NULL)) { TAOS_CHECK_GOTO(terrno, NULL, END); } diff --git a/source/dnode/vnode/src/meta/metaTable.c b/source/dnode/vnode/src/meta/metaTable.c index 65e520bb4a..bce8bb3e29 100644 --- a/source/dnode/vnode/src/meta/metaTable.c +++ b/source/dnode/vnode/src/meta/metaTable.c @@ -153,7 +153,7 @@ static int metaSaveJsonVarToIdx(SMeta *pMeta, const SMetaEntry *pCtbEntry, const if (val == NULL) { TAOS_CHECK_GOTO(terrno, NULL, _exception); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)pTagVal->pData, pTagVal->nData, val + VARSTR_HEADER_SIZE); + int32_t len = taosUcs4ToMbs((TdUcs4 *)pTagVal->pData, pTagVal->nData, val + VARSTR_HEADER_SIZE, NULL); if (len < 0) { TAOS_CHECK_GOTO(len, NULL, _exception); } @@ -237,7 +237,7 @@ int metaDelJsonVarFromIdx(SMeta *pMeta, const SMetaEntry *pCtbEntry, const SSche if (val == NULL) { TAOS_CHECK_GOTO(terrno, NULL, _exception); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)pTagVal->pData, pTagVal->nData, val + VARSTR_HEADER_SIZE); + int32_t len = taosUcs4ToMbs((TdUcs4 *)pTagVal->pData, pTagVal->nData, val + VARSTR_HEADER_SIZE, NULL); if (len < 0) { TAOS_CHECK_GOTO(len, NULL, _exception); } diff --git a/source/libs/catalog/src/catalog.c b/source/libs/catalog/src/catalog.c index 0ea1d98312..c194b51b07 100644 --- a/source/libs/catalog/src/catalog.c +++ b/source/libs/catalog/src/catalog.c @@ -447,7 +447,7 @@ int32_t ctgGetTbTag(SCatalog* pCtg, SRequestConnInfo* pConn, SName* pTableName, } char* pJson = NULL; - parseTagDatatoJson(pTag, &pJson); + parseTagDatatoJson(pTag, &pJson, NULL); if(NULL == pJson) { taosArrayDestroy(pTagVals); CTG_ERR_JRET(terrno); diff --git a/source/libs/catalog/src/ctgAsync.c b/source/libs/catalog/src/ctgAsync.c index 9bfb4102aa..e3f7ad4811 100644 --- a/source/libs/catalog/src/ctgAsync.c +++ b/source/libs/catalog/src/ctgAsync.c @@ -2340,7 +2340,7 @@ int32_t ctgHandleGetTbTagRsp(SCtgTaskReq* tReq, int32_t reqType, const SDataBuf* } char* pJson = NULL; - parseTagDatatoJson(pTag, &pJson); + parseTagDatatoJson(pTag, &pJson, NULL); if (NULL == pJson) { taosArrayDestroy(pTagVals); CTG_ERR_JRET(terrno); diff --git a/source/libs/command/src/command.c b/source/libs/command/src/command.c index 353bc1fa18..88c3d7307b 100644 --- a/source/libs/command/src/command.c +++ b/source/libs/command/src/command.c @@ -573,7 +573,7 @@ static void appendTagNameFields(char* buf, int32_t* len, STableCfg* pCfg) { } } -static int32_t appendTagValues(char* buf, int32_t* len, STableCfg* pCfg) { +static int32_t appendTagValues(char* buf, int32_t* len, STableCfg* pCfg, void* charsetCxt) { int32_t code = TSDB_CODE_SUCCESS; SArray* pTagVals = NULL; STag* pTag = (STag*)pCfg->pTags; @@ -585,7 +585,7 @@ static int32_t appendTagValues(char* buf, int32_t* len, STableCfg* pCfg) { if (tTagIsJson(pTag)) { char* pJson = NULL; - parseTagDatatoJson(pTag, &pJson); + parseTagDatatoJson(pTag, &pJson, charsetCxt); if (NULL == pJson) { qError("failed to parse tag to json, pJson is NULL"); return terrno; @@ -726,7 +726,7 @@ static void appendTableOptions(char* buf, int32_t* len, SDbCfgInfo* pDbCfg, STab } } -static int32_t setCreateTBResultIntoDataBlock(SSDataBlock* pBlock, SDbCfgInfo* pDbCfg, char* tbName, STableCfg* pCfg) { +static int32_t setCreateTBResultIntoDataBlock(SSDataBlock* pBlock, SDbCfgInfo* pDbCfg, char* tbName, STableCfg* pCfg, void* charsetCxt) { int32_t code = TSDB_CODE_SUCCESS; QRY_ERR_RET(blockDataEnsureCapacity(pBlock, 1)); pBlock->info.rows = 1; @@ -760,7 +760,7 @@ static int32_t setCreateTBResultIntoDataBlock(SSDataBlock* pBlock, SDbCfgInfo* p appendTagNameFields(buf2, &len, pCfg); len += tsnprintf(buf2 + VARSTR_HEADER_SIZE + len, SHOW_CREATE_TB_RESULT_FIELD2_LEN - (VARSTR_HEADER_SIZE + len), ") TAGS ("); - code = appendTagValues(buf2, &len, pCfg); + code = appendTagValues(buf2, &len, pCfg, charsetCxt); TAOS_CHECK_ERRNO(code); len += snprintf(buf2 + VARSTR_HEADER_SIZE + len, SHOW_CREATE_TB_RESULT_FIELD2_LEN - (VARSTR_HEADER_SIZE + len), ")"); @@ -817,11 +817,11 @@ static int32_t setCreateViewResultIntoDataBlock(SSDataBlock* pBlock, SShowCreate return code; } -static int32_t execShowCreateTable(SShowCreateTableStmt* pStmt, SRetrieveTableRsp** pRsp) { +static int32_t execShowCreateTable(SShowCreateTableStmt* pStmt, SRetrieveTableRsp** pRsp, void* charsetCxt) { SSDataBlock* pBlock = NULL; int32_t code = buildCreateTbResultDataBlock(&pBlock); if (TSDB_CODE_SUCCESS == code) { - code = setCreateTBResultIntoDataBlock(pBlock, pStmt->pDbCfg, pStmt->tableName, pStmt->pTableCfg); + code = setCreateTBResultIntoDataBlock(pBlock, pStmt->pDbCfg, pStmt->tableName, pStmt->pTableCfg, charsetCxt); } if (TSDB_CODE_SUCCESS == code) { code = buildRetrieveTableRsp(pBlock, SHOW_CREATE_TB_RESULT_COLS, pRsp); @@ -830,14 +830,14 @@ static int32_t execShowCreateTable(SShowCreateTableStmt* pStmt, SRetrieveTableRs return code; } -static int32_t execShowCreateSTable(SShowCreateTableStmt* pStmt, SRetrieveTableRsp** pRsp) { +static int32_t execShowCreateSTable(SShowCreateTableStmt* pStmt, SRetrieveTableRsp** pRsp, void* charsetCxt) { STableCfg* pCfg = (STableCfg*)pStmt->pTableCfg; if (TSDB_SUPER_TABLE != pCfg->tableType) { terrno = TSDB_CODE_TSC_NOT_STABLE_ERROR; return terrno; } - return execShowCreateTable(pStmt, pRsp); + return execShowCreateTable(pStmt, pRsp, charsetCxt); } static int32_t execAlterCmd(char* cmd, char* value, bool* processed) { @@ -909,7 +909,7 @@ static int32_t execAlterLocal(SAlterLocalStmt* pStmt) { return terrno; } - if (cfgSetItem(tsCfg, pStmt->config, pStmt->value, CFG_STYPE_ALTER_CMD, true)) { + if (cfgSetItem(tsCfg, pStmt->config, pStmt->value, CFG_STYPE_ALTER_CLIENT_CMD, true)) { return terrno; } @@ -1058,7 +1058,7 @@ static int32_t execShowCreateView(SShowCreateViewStmt* pStmt, SRetrieveTableRsp* return code; } -int32_t qExecCommand(int64_t* pConnId, bool sysInfoUser, SNode* pStmt, SRetrieveTableRsp** pRsp, int8_t biMode) { +int32_t qExecCommand(int64_t* pConnId, bool sysInfoUser, SNode* pStmt, SRetrieveTableRsp** pRsp, int8_t biMode, void* charsetCxt) { switch (nodeType(pStmt)) { case QUERY_NODE_DESCRIBE_STMT: return execDescribe(sysInfoUser, pStmt, pRsp, biMode); @@ -1067,9 +1067,9 @@ int32_t qExecCommand(int64_t* pConnId, bool sysInfoUser, SNode* pStmt, SRetrieve case QUERY_NODE_SHOW_CREATE_DATABASE_STMT: return execShowCreateDatabase((SShowCreateDatabaseStmt*)pStmt, pRsp); case QUERY_NODE_SHOW_CREATE_TABLE_STMT: - return execShowCreateTable((SShowCreateTableStmt*)pStmt, pRsp); + return execShowCreateTable((SShowCreateTableStmt*)pStmt, pRsp, charsetCxt); case QUERY_NODE_SHOW_CREATE_STABLE_STMT: - return execShowCreateSTable((SShowCreateTableStmt*)pStmt, pRsp); + return execShowCreateSTable((SShowCreateTableStmt*)pStmt, pRsp, charsetCxt); case QUERY_NODE_SHOW_CREATE_VIEW_STMT: return execShowCreateView((SShowCreateViewStmt*)pStmt, pRsp); case QUERY_NODE_ALTER_LOCAL_STMT: diff --git a/source/libs/executor/src/executil.c b/source/libs/executor/src/executil.c index d8ef097ce7..ccb7005dbd 100644 --- a/source/libs/executor/src/executil.c +++ b/source/libs/executor/src/executil.c @@ -2418,7 +2418,7 @@ void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindow* w, b w->skey = key; } - w->ekey = taosTimeAdd(w->skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1; + w->ekey = taosTimeAdd(w->skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL) - 1; } } @@ -2473,15 +2473,15 @@ STimeWindow getActiveTimeWindow(SDiskbasedBuf* pBuf, SResultRowInfo* pResultRowI TSKEY getNextTimeWindowStart(const SInterval* pInterval, TSKEY start, int32_t order) { int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order); - TSKEY nextStart = taosTimeAdd(start, -1 * pInterval->offset, pInterval->offsetUnit, pInterval->precision); - nextStart = taosTimeAdd(nextStart, factor * pInterval->sliding, pInterval->slidingUnit, pInterval->precision); - nextStart = taosTimeAdd(nextStart, pInterval->offset, pInterval->offsetUnit, pInterval->precision); + TSKEY nextStart = taosTimeAdd(start, -1 * pInterval->offset, pInterval->offsetUnit, pInterval->precision, NULL); + nextStart = taosTimeAdd(nextStart, factor * pInterval->sliding, pInterval->slidingUnit, pInterval->precision, NULL); + nextStart = taosTimeAdd(nextStart, pInterval->offset, pInterval->offsetUnit, pInterval->precision, NULL); return nextStart; } void getNextTimeWindow(const SInterval* pInterval, STimeWindow* tw, int32_t order) { tw->skey = getNextTimeWindowStart(pInterval, tw->skey, order); - tw->ekey = taosTimeAdd(tw->skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1; + tw->ekey = taosTimeAdd(tw->skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL) - 1; } bool hasLimitOffsetInfo(SLimitInfo* pLimitInfo) { diff --git a/source/libs/executor/src/filloperator.c b/source/libs/executor/src/filloperator.c index d6a518ccc4..bcbd3f7563 100644 --- a/source/libs/executor/src/filloperator.c +++ b/source/libs/executor/src/filloperator.c @@ -568,7 +568,7 @@ static void reviseFillStartAndEndKey(SFillOperatorInfo* pInfo, int32_t order) { next = ekey; while (next < pInfo->win.ekey) { next = taosTimeAdd(ekey, pInfo->pFillInfo->interval.sliding, pInfo->pFillInfo->interval.slidingUnit, - pInfo->pFillInfo->interval.precision); + pInfo->pFillInfo->interval.precision, NULL); ekey = next > pInfo->win.ekey ? ekey : next; } pInfo->win.ekey = ekey; @@ -577,7 +577,7 @@ static void reviseFillStartAndEndKey(SFillOperatorInfo* pInfo, int32_t order) { next = skey; while (next < pInfo->win.skey) { next = taosTimeAdd(skey, pInfo->pFillInfo->interval.sliding, pInfo->pFillInfo->interval.slidingUnit, - pInfo->pFillInfo->interval.precision); + pInfo->pFillInfo->interval.precision, NULL); skey = next > pInfo->win.skey ? skey : next; } taosFillUpdateStartTimestampInfo(pInfo->pFillInfo, skey); diff --git a/source/libs/executor/src/hashjoinoperator.c b/source/libs/executor/src/hashjoinoperator.c index 06498d73e7..27efd59c12 100644 --- a/source/libs/executor/src/hashjoinoperator.c +++ b/source/libs/executor/src/hashjoinoperator.c @@ -114,7 +114,7 @@ int32_t hJoinLaunchPrimExpr(SSDataBlock* pBlock, SHJoinTableCtx* pTable, int32_t SColumnInfoData* pPrimOut = taosArrayGet(pBlock->pDataBlock, pTable->primCtx.targetSlotId); if (0 != pCtx->timezoneUnit) { for (int32_t i = startIdx; i <= endIdx; ++i) { - ((int64_t*)pPrimOut->pData)[i] = ((int64_t*)pPrimIn->pData)[i] - (((int64_t*)pPrimIn->pData)[i] - pCtx->timezoneUnit) % pCtx->truncateUnit; + ((int64_t*)pPrimOut->pData)[i] = ((int64_t*)pPrimIn->pData)[i] - (((int64_t*)pPrimIn->pData)[i] + pCtx->timezoneUnit) % pCtx->truncateUnit; } } else { for (int32_t i = startIdx; i <= endIdx; ++i) { diff --git a/source/libs/executor/src/streamfilloperator.c b/source/libs/executor/src/streamfilloperator.c index 9039a26f0b..ffaa62721e 100644 --- a/source/libs/executor/src/streamfilloperator.c +++ b/source/libs/executor/src/streamfilloperator.c @@ -281,12 +281,12 @@ static void calcRowDeltaData(SResultRowData* pEndRow, SArray* pEndPoins, SFillCo } static void setFillInfoStart(TSKEY ts, SInterval* pInterval, SStreamFillInfo* pFillInfo) { - ts = taosTimeAdd(ts, pInterval->sliding, pInterval->slidingUnit, pInterval->precision); + ts = taosTimeAdd(ts, pInterval->sliding, pInterval->slidingUnit, pInterval->precision, NULL); pFillInfo->start = ts; } static void setFillInfoEnd(TSKEY ts, SInterval* pInterval, SStreamFillInfo* pFillInfo) { - ts = taosTimeAdd(ts, pInterval->sliding * -1, pInterval->slidingUnit, pInterval->precision); + ts = taosTimeAdd(ts, pInterval->sliding * -1, pInterval->slidingUnit, pInterval->precision, NULL); pFillInfo->end = ts; } @@ -303,7 +303,7 @@ void setDeleteFillValueInfo(TSKEY start, TSKEY end, SStreamFillSupporter* pFillS } TSKEY realStart = taosTimeAdd(pFillSup->prev.key, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); pFillInfo->needFill = true; pFillInfo->start = realStart; @@ -542,7 +542,7 @@ static void doStreamFillNormal(SStreamFillSupporter* pFillSup, SStreamFillInfo* QUERY_CHECK_CODE(code, lino, _end); } pFillInfo->current = taosTimeAdd(pFillInfo->current, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); } _end: @@ -564,7 +564,7 @@ static void doStreamFillLinear(SStreamFillSupporter* pFillSup, SStreamFillInfo* if ((pFillSup->hasDelete && !ckRes) || !inWinRange(&pFillSup->winRange, &st)) { pFillInfo->current = taosTimeAdd(pFillInfo->current, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); pFillInfo->pLinearInfo->winIndex++; continue; } @@ -610,7 +610,7 @@ static void doStreamFillLinear(SStreamFillSupporter* pFillSup, SStreamFillInfo* } } pFillInfo->current = taosTimeAdd(pFillInfo->current, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); pBlock->info.rows++; } @@ -1343,7 +1343,7 @@ static int32_t doStreamForceFillImpl(SOperatorInfo* pOperator) { break; } resTs = taosTimeAdd(resTs, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); } } } diff --git a/source/libs/executor/src/streamtimesliceoperator.c b/source/libs/executor/src/streamtimesliceoperator.c index 8611678e5a..44004a4c6b 100644 --- a/source/libs/executor/src/streamtimesliceoperator.c +++ b/source/libs/executor/src/streamtimesliceoperator.c @@ -467,7 +467,7 @@ static void fillNormalRange(SStreamFillSupporter* pFillSup, SStreamFillInfo* pFi QUERY_CHECK_CODE(code, lino, _end); // } pFillInfo->current = taosTimeAdd(pFillInfo->current, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); } _end: @@ -527,7 +527,7 @@ static void fillLinearRange(SStreamFillSupporter* pFillSup, SStreamFillInfo* pFi } } pFillInfo->current = taosTimeAdd(pFillInfo->current, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); if (ckRes) { pBlock->info.rows++; } @@ -547,14 +547,14 @@ static void setFillKeyInfo(TSKEY start, TSKEY end, SInterval* pInterval, SStream static TSKEY adustPrevTsKey(TSKEY pointTs, TSKEY rowTs, SInterval* pInterval) { if (rowTs >= pointTs) { - pointTs = taosTimeAdd(pointTs, pInterval->sliding, pInterval->slidingUnit, pInterval->precision); + pointTs = taosTimeAdd(pointTs, pInterval->sliding, pInterval->slidingUnit, pInterval->precision, NULL); } return pointTs; } static TSKEY adustEndTsKey(TSKEY pointTs, TSKEY rowTs, SInterval* pInterval) { if (rowTs <= pointTs) { - pointTs = taosTimeAdd(pointTs, pInterval->sliding * -1, pInterval->slidingUnit, pInterval->precision); + pointTs = taosTimeAdd(pointTs, pInterval->sliding * -1, pInterval->slidingUnit, pInterval->precision, NULL); } return pointTs; } @@ -954,7 +954,7 @@ static int32_t getPointInfoFromState(SStreamAggSupporter* pAggSup, SStreamFillSu } } else { pNextPoint->key.ts = taosTimeAdd(pCurPoint->key.ts, pFillSup->interval.sliding, pFillSup->interval.slidingUnit, - pFillSup->interval.precision); + pFillSup->interval.precision, NULL); code = pAggSup->stateStore.streamStateFillAddIfNotExist(pState, &pNextPoint->key, (void**)&pNextPoint->pResPos, &nextVLen, &tmpRes); QUERY_CHECK_CODE(code, lino, _end); diff --git a/source/libs/executor/src/streamtimewindowoperator.c b/source/libs/executor/src/streamtimewindowoperator.c index 039baca54c..e576e0d920 100644 --- a/source/libs/executor/src/streamtimewindowoperator.c +++ b/source/libs/executor/src/streamtimewindowoperator.c @@ -358,7 +358,7 @@ static int32_t closeStreamIntervalWindow(SSHashObj* pHashMap, STimeWindowAggSupp void* chIds = taosHashGet(pPullDataMap, pWinKey, sizeof(SWinKey)); STimeWindow win = { .skey = pWinKey->ts, - .ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1, + .ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL) - 1, }; if (isCloseWindow(&win, pTwSup)) { if (chIds && pPullDataMap) { @@ -391,7 +391,7 @@ _end: STimeWindow getFinalTimeWindow(int64_t ts, SInterval* pInterval) { STimeWindow w = {.skey = ts, .ekey = INT64_MAX}; - w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1; + w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL) - 1; return w; } @@ -851,7 +851,7 @@ static int32_t processPullOver(SSDataBlock* pBlock, SHashObj* pMap, SHashObj* pF } } } - winTs = taosTimeAdd(winTs, pInterval->sliding, pInterval->slidingUnit, pInterval->precision); + winTs = taosTimeAdd(winTs, pInterval->sliding, pInterval->slidingUnit, pInterval->precision, NULL); } } if (pBeOver) { diff --git a/source/libs/executor/src/sysscanoperator.c b/source/libs/executor/src/sysscanoperator.c index b9d2f97bcd..6d21f43889 100644 --- a/source/libs/executor/src/sysscanoperator.c +++ b/source/libs/executor/src/sysscanoperator.c @@ -978,7 +978,7 @@ int32_t convertTagDataToStr(char* str, int32_t strBuffLen, int type, void* buf, return TSDB_CODE_TSC_INVALID_VALUE; } - int32_t length = taosUcs4ToMbs((TdUcs4*)buf, bufSize, str); + int32_t length = taosUcs4ToMbs((TdUcs4*)buf, bufSize, str, NULL); if (length <= 0) { return TSDB_CODE_TSC_INVALID_VALUE; } @@ -1129,7 +1129,7 @@ static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, if (tagData != NULL) { if (tagType == TSDB_DATA_TYPE_JSON) { char* tagJson = NULL; - parseTagDatatoJson(tagData, &tagJson); + parseTagDatatoJson(tagData, &tagJson, NULL); if (tagJson == NULL) { code = terrno; goto _end; diff --git a/source/libs/executor/src/tfill.c b/source/libs/executor/src/tfill.c index 190b327522..ecbb389f8a 100644 --- a/source/libs/executor/src/tfill.c +++ b/source/libs/executor/src/tfill.c @@ -143,7 +143,7 @@ bool fillIfWindowPseudoColumn(SFillInfo* pFillInfo, SFillColInfo* pCol, SColumnI // TODO: include endpoint SInterval* pInterval = &pFillInfo->interval; int64_t windowEnd = - taosTimeAdd(pFillInfo->currentKey, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + taosTimeAdd(pFillInfo->currentKey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL); code = colDataSetVal(pDstColInfoData, rowIndex, (const char*)&windowEnd, false); QUERY_CHECK_CODE(code, lino, _end); return true; @@ -264,7 +264,7 @@ static void doFillOneRow(SFillInfo* pFillInfo, SSDataBlock* pBlock, SSDataBlock* // setTagsValue(pFillInfo, data, index); SInterval* pInterval = &pFillInfo->interval; pFillInfo->currentKey = - taosTimeAdd(pFillInfo->currentKey, pInterval->sliding * step, pInterval->slidingUnit, pInterval->precision); + taosTimeAdd(pFillInfo->currentKey, pInterval->sliding * step, pInterval->slidingUnit, pInterval->precision, NULL); pBlock->info.rows += 1; pFillInfo->numOfCurrent++; @@ -484,7 +484,7 @@ static int32_t fillResultImpl(SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t // set the tag value for final result SInterval* pInterval = &pFillInfo->interval; pFillInfo->currentKey = - taosTimeAdd(pFillInfo->currentKey, pInterval->sliding * step, pInterval->slidingUnit, pInterval->precision); + taosTimeAdd(pFillInfo->currentKey, pInterval->sliding * step, pInterval->slidingUnit, pInterval->precision, NULL); pBlock->info.rows += 1; pFillInfo->index += 1; diff --git a/source/libs/executor/src/timesliceoperator.c b/source/libs/executor/src/timesliceoperator.c index 6a3052c75c..3a639772c8 100644 --- a/source/libs/executor/src/timesliceoperator.c +++ b/source/libs/executor/src/timesliceoperator.c @@ -901,7 +901,7 @@ static void doTimesliceImpl(SOperatorInfo* pOperator, STimeSliceOperatorInfo* pS doKeepLinearInfo(pSliceInfo, pBlock, i); pSliceInfo->current = - taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL); if (checkWindowBoundReached(pSliceInfo)) { break; @@ -927,7 +927,7 @@ static void doTimesliceImpl(SOperatorInfo* pOperator, STimeSliceOperatorInfo* pS break; } else { pSliceInfo->current = - taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL); } } @@ -955,7 +955,7 @@ static void doTimesliceImpl(SOperatorInfo* pOperator, STimeSliceOperatorInfo* pS break; } else { pSliceInfo->current = - taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL); } } @@ -965,7 +965,7 @@ static void doTimesliceImpl(SOperatorInfo* pOperator, STimeSliceOperatorInfo* pS QUERY_CHECK_CODE(code, lino, _end); pSliceInfo->current = - taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL); } doKeepPrevRows(pSliceInfo, pBlock, i); @@ -1003,7 +1003,7 @@ static void genInterpAfterDataBlock(STimeSliceOperatorInfo* pSliceInfo, SOperato while (pSliceInfo->current <= pSliceInfo->win.ekey) { (void)genInterpolationResult(pSliceInfo, &pOperator->exprSupp, pResBlock, NULL, index, false, pOperator->pTaskInfo); pSliceInfo->current = - taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision); + taosTimeAdd(pSliceInfo->current, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL); } } diff --git a/source/libs/executor/src/timewindowoperator.c b/source/libs/executor/src/timewindowoperator.c index 00c0e9e61f..c2aa07dacc 100644 --- a/source/libs/executor/src/timewindowoperator.c +++ b/source/libs/executor/src/timewindowoperator.c @@ -1922,7 +1922,7 @@ static void doMergeAlignedIntervalAggImpl(SOperatorInfo* pOperatorInfo, SResultR STimeWindow win = {0}; win.skey = miaInfo->curTs; - win.ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1; + win.ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL) - 1; int32_t ret = setSingleOutputTupleBuf(pResultRowInfo, &win, &miaInfo->pResultRow, pSup, &iaInfo->aggSup); if (ret != TSDB_CODE_SUCCESS || miaInfo->pResultRow == NULL) { @@ -1949,7 +1949,7 @@ static void doMergeAlignedIntervalAggImpl(SOperatorInfo* pOperatorInfo, SResultR miaInfo->curTs = tsCols[currPos]; currWin.skey = miaInfo->curTs; - currWin.ekey = taosTimeAdd(currWin.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1; + currWin.ekey = taosTimeAdd(currWin.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision, NULL) - 1; startPos = currPos; ret = setSingleOutputTupleBuf(pResultRowInfo, &win, &miaInfo->pResultRow, pSup, &iaInfo->aggSup); diff --git a/source/libs/executor/test/queryPlanTests.cpp b/source/libs/executor/test/queryPlanTests.cpp index 69097ce755..5d397be623 100755 --- a/source/libs/executor/test/queryPlanTests.cpp +++ b/source/libs/executor/test/queryPlanTests.cpp @@ -592,7 +592,7 @@ void qptGetRandValue(uint8_t* pType, int32_t* pLen, void** ppVal) { memset(pTmp, 'A' + taosRand() % 26, *pLen); *ppVal = taosMemoryCalloc(1, *pLen * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); assert(*ppVal); - assert(taosMbsToUcs4(pTmp, *pLen, (TdUcs4 *)varDataVal(*ppVal), *pLen * TSDB_NCHAR_SIZE, NULL)); + assert(taosMbsToUcs4(pTmp, *pLen, (TdUcs4 *)varDataVal(*ppVal), *pLen * TSDB_NCHAR_SIZE, NULL, NULL)); *pLen *= TSDB_NCHAR_SIZE; varDataSetLen(*ppVal, *pLen); taosMemoryFree(pTmp); diff --git a/source/libs/executor/test/sortTests.cpp b/source/libs/executor/test/sortTests.cpp index b2313f35a1..ce2da01b66 100644 --- a/source/libs/executor/test/sortTests.cpp +++ b/source/libs/executor/test/sortTests.cpp @@ -93,7 +93,7 @@ SSDataBlock* getSingleColDummyBlock(void* param) { char strOri[128] = {0}; taosRandStr(strOri, size); int32_t len = 0; - bool ret = taosMbsToUcs4(strOri, size, (TdUcs4*)varDataVal(str), size * TSDB_NCHAR_SIZE, &len); + bool ret = taosMbsToUcs4(strOri, size, (TdUcs4*)varDataVal(str), size * TSDB_NCHAR_SIZE, &len, NULL); if (!ret) { (void) printf("error\n"); return NULL; @@ -331,7 +331,7 @@ TEST(testCase, external_mem_sort_Test) { if(pInfo[i].type == TSDB_DATA_TYPE_NCHAR){ char buf[128] = {0}; - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(v), varDataLen(v), buf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(v), varDataLen(v), buf, NULL); printf("%d: %s\n", row++, buf); }else if(pInfo[i].type == TSDB_DATA_TYPE_BINARY || pInfo[i]->type == TSDB_DATA_TYPE_GEOMETRY){ char buf[128] = {0}; diff --git a/source/libs/function/src/builtins.c b/source/libs/function/src/builtins.c index aeaac16707..95a332ac05 100644 --- a/source/libs/function/src/builtins.c +++ b/source/libs/function/src/builtins.c @@ -186,16 +186,16 @@ static int32_t countTrailingSpaces(const SValueNode* pVal, bool isLtrim) { return numOfSpaces; } -static int32_t addTimezoneParam(SNodeList* pList) { - char buf[TD_TIME_STR_LEN] = {0}; - time_t t; +static int32_t addTimezoneParam(SNodeList* pList, timezone_t tz) { + char buf[TD_TIME_STR_LEN] = {0}; + time_t t; int32_t code = taosTime(&t); if (code != 0) { return code; } struct tm tmInfo; - if (taosLocalTime(&t, &tmInfo, buf, sizeof(buf)) != NULL) { - (void)strftime(buf, sizeof(buf), "%z", &tmInfo); + if (taosLocalTime(&t, &tmInfo, buf, sizeof(buf), tz) != NULL) { + (void)taosStrfTime(buf, sizeof(buf), "%z", &tmInfo); } int32_t len = (int32_t)strlen(buf); @@ -1445,7 +1445,7 @@ static int32_t translateToIso8601(SFunctionNode* pFunc, char* pErrBuf, int32_t l return buildFuncErrMsg(pErrBuf, len, TSDB_CODE_FUNC_FUNTION_ERROR, "Invalid timzone format"); } } else { // add default client timezone - int32_t code = addTimezoneParam(pFunc->pParameterList); + int32_t code = addTimezoneParam(pFunc->pParameterList, pFunc->tz); if (code != TSDB_CODE_SUCCESS) { return code; } @@ -1500,7 +1500,7 @@ static int32_t translateTimeTruncate(SFunctionNode* pFunc, char* pErrBuf, int32_ } // add client timezone as param - code = addTimezoneParam(pFunc->pParameterList); + code = addTimezoneParam(pFunc->pParameterList, pFunc->tz); if (code != TSDB_CODE_SUCCESS) { return code; } @@ -1657,9 +1657,18 @@ static int32_t translateOutVarchar(SFunctionNode* pFunc, char* pErrBuf, int32_t case FUNCTION_TYPE_TBNAME: bytes = TSDB_TABLE_FNAME_LEN - 1 + VARSTR_HEADER_SIZE; break; - case FUNCTION_TYPE_TIMEZONE: - bytes = timeZoneStrLen(); + case FUNCTION_TYPE_TIMEZONE:{ + if (pFunc->tz == NULL) { + bytes = VARSTR_HEADER_SIZE + strlen(tsTimezoneStr); + }else{ + char *tzName = (char*)taosHashGet(pTimezoneNameMap, &pFunc->tz, sizeof(timezone_t)); + if (tzName == NULL){ + tzName = TZ_UNKNOWN; + } + bytes = strlen(tzName) + VARSTR_HEADER_SIZE; + } break; + } case FUNCTION_TYPE_IRATE_PARTIAL: bytes = getIrateInfoSize((pFunc->hasPk) ? pFunc->pkBytes : 0) + VARSTR_HEADER_SIZE; break; diff --git a/source/libs/parser/inc/parUtil.h b/source/libs/parser/inc/parUtil.h index 7298b04eb0..aec5fb4cd6 100644 --- a/source/libs/parser/inc/parUtil.h +++ b/source/libs/parser/inc/parUtil.h @@ -136,7 +136,7 @@ int32_t trimString(const char* src, int32_t len, char* dst, int32_t dlen); int32_t getVnodeSysTableTargetName(int32_t acctId, SNode* pWhere, SName* pName); int32_t checkAndTrimValue(SToken* pToken, char* tmpTokenBuf, SMsgBuf* pMsgBuf, int8_t type); int32_t parseTagValue(SMsgBuf* pMsgBuf, const char** pSql, uint8_t precision, SSchema* pTagSchema, SToken* pToken, - SArray* pTagName, SArray* pTagVals, STag** pTag); + SArray* pTagName, SArray* pTagVals, STag** pTag, timezone_t tz, void *charsetCxt); int32_t parseTbnameToken(SMsgBuf* pMsgBuf, char* tname, SToken* pToken, bool* pFoundCtbName); int32_t buildCatalogReq(const SParseMetaCache* pMetaCache, SCatalogReq* pCatalogReq); diff --git a/source/libs/parser/src/parAstCreater.c b/source/libs/parser/src/parAstCreater.c index a3e97329c3..5ecef23de7 100644 --- a/source/libs/parser/src/parAstCreater.c +++ b/source/libs/parser/src/parAstCreater.c @@ -420,6 +420,8 @@ SNode* createValueNode(SAstCreateContext* pCxt, int32_t dataType, const SToken* val->node.resType.precision = TSDB_TIME_PRECISION_MILLI; } val->translate = false; + val->tz = pCxt->pQueryCxt->timezone; + val->charsetCxt = pCxt->pQueryCxt->charsetCxt; return (SNode*)val; _err: return NULL; @@ -963,6 +965,8 @@ SNode* createOperatorNode(SAstCreateContext* pCxt, EOperatorType type, SNode* pL op->opType = type; op->pLeft = pLeft; op->pRight = pRight; + op->tz = pCxt->pQueryCxt->timezone; + op->charsetCxt = pCxt->pQueryCxt->charsetCxt; return (SNode*)op; _err: nodesDestroyNode(pLeft); @@ -1041,6 +1045,8 @@ SNode* createFunctionNode(SAstCreateContext* pCxt, const SToken* pFuncName, SNod CHECK_MAKE_NODE(func); COPY_STRING_FORM_ID_TOKEN(func->functionName, pFuncName); func->pParameterList = pParameterList; + func->tz = pCxt->pQueryCxt->timezone; + func->charsetCxt = pCxt->pQueryCxt->charsetCxt; return (SNode*)func; _err: nodesDestroyList(pParameterList); @@ -1061,6 +1067,9 @@ SNode* createCastFunctionNode(SAstCreateContext* pCxt, SNode* pExpr, SDataType d } pCxt->errCode = nodesListMakeAppend(&func->pParameterList, pExpr); CHECK_PARSER_STATUS(pCxt); + func->tz = pCxt->pQueryCxt->timezone; + func->charsetCxt = pCxt->pQueryCxt->charsetCxt; + return (SNode*)func; _err: nodesDestroyNode((SNode*)func); @@ -1095,6 +1104,7 @@ SNode* createTrimFunctionNode(SAstCreateContext* pCxt, SNode* pExpr, ETrimType t func->trimType = type; pCxt->errCode = nodesListMakeAppend(&func->pParameterList, pExpr); CHECK_PARSER_STATUS(pCxt); + func->charsetCxt = pCxt->pQueryCxt->charsetCxt; return (SNode*)func; _err: nodesDestroyNode((SNode*)func); @@ -1113,6 +1123,7 @@ SNode* createTrimFunctionNodeExt(SAstCreateContext* pCxt, SNode* pExpr, SNode* p CHECK_PARSER_STATUS(pCxt); pCxt->errCode = nodesListMakeAppend(&func->pParameterList, pExpr2); CHECK_PARSER_STATUS(pCxt); + func->charsetCxt = pCxt->pQueryCxt->charsetCxt; return (SNode*)func; _err: nodesDestroyNode((SNode*)func); @@ -1400,6 +1411,7 @@ SNode* createIntervalWindowNode(SAstCreateContext* pCxt, SNode* pInterval, SNode interval->pSliding = pSliding; interval->pFill = pFill; interval->timeRange = TSWINDOW_INITIALIZER; + interval->timezone = pCxt->pQueryCxt->timezone; return (SNode*)interval; _err: nodesDestroyNode((SNode*)interval); @@ -1514,6 +1526,8 @@ SNode* createCaseWhenNode(SAstCreateContext* pCxt, SNode* pCase, SNodeList* pWhe pCaseWhen->pCase = pCase; pCaseWhen->pWhenThenList = pWhenThenList; pCaseWhen->pElse = pElse; + pCaseWhen->tz = pCxt->pQueryCxt->timezone; + pCaseWhen->charsetCxt = pCxt->pQueryCxt->charsetCxt; return (SNode*)pCaseWhen; _err: nodesDestroyNode(pCase); diff --git a/source/libs/parser/src/parInsertSml.c b/source/libs/parser/src/parInsertSml.c index b5cdf1e4ee..22d1f7edda 100644 --- a/source/libs/parser/src/parInsertSml.c +++ b/source/libs/parser/src/parInsertSml.c @@ -98,7 +98,7 @@ end: * @return int32_t */ static int32_t smlBuildTagRow(SArray* cols, SBoundColInfo* tags, SSchema* pSchema, STag** ppTag, SArray** tagName, - SMsgBuf* msg) { + SMsgBuf* msg, void* charsetCxt) { SArray* pTagArray = taosArrayInit(tags->numOfBound, sizeof(STagVal)); if (!pTagArray) { return terrno; @@ -142,7 +142,7 @@ static int32_t smlBuildTagRow(SArray* cols, SBoundColInfo* tags, SSchema* pSchem code = terrno; goto end; } - if (!taosMbsToUcs4(kv->value, kv->length, (TdUcs4*)(p), kv->length * TSDB_NCHAR_SIZE, &output)) { + if (!taosMbsToUcs4(kv->value, kv->length, (TdUcs4*)(p), kv->length * TSDB_NCHAR_SIZE, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { taosMemoryFree(p); code = generateSyntaxErrMsg(msg, TSDB_CODE_PAR_VALUE_TOO_LONG, pTagSchema->name); @@ -221,7 +221,7 @@ int32_t smlBuildRow(STableDataCxt* pTableCxt) { return TSDB_CODE_SUCCESS; } -int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* data, int32_t index) { +int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* data, int32_t index, void* charsetCxt) { int ret = TSDB_CODE_SUCCESS; SSchema* pColSchema = schema + index; SColVal* pVal = taosArrayGet(pTableCxt->pValues, index); @@ -256,7 +256,7 @@ int32_t smlBuildCol(STableDataCxt* pTableCxt, SSchema* schema, void* data, int32 ret = terrno; goto end; } - if (!taosMbsToUcs4(kv->value, kv->length, (TdUcs4*)pUcs4, size, &len)) { + if (!taosMbsToUcs4(kv->value, kv->length, (TdUcs4*)pUcs4, size, &len, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { taosMemoryFree(pUcs4); ret = TSDB_CODE_PAR_VALUE_TOO_LONG; @@ -291,7 +291,7 @@ end: int32_t smlBindData(SQuery* query, bool dataFormat, SArray* tags, SArray* colsSchema, SArray* cols, STableMeta* pTableMeta, char* tableName, const char* sTableName, int32_t sTableNameLen, int32_t ttl, - char* msgBuf, int32_t msgBufLen) { + char* msgBuf, int32_t msgBufLen, void* charsetCxt) { SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; SSchema* pTagsSchema = getTableTagSchema(pTableMeta); @@ -313,7 +313,7 @@ int32_t smlBindData(SQuery* query, bool dataFormat, SArray* tags, SArray* colsSc STag* pTag = NULL; - ret = smlBuildTagRow(tags, &bindTags, pTagsSchema, &pTag, &tagName, &pBuf); + ret = smlBuildTagRow(tags, &bindTags, pTagsSchema, &pTag, &tagName, &pBuf, charsetCxt); if (ret != TSDB_CODE_SUCCESS) { goto end; } @@ -411,7 +411,7 @@ int32_t smlBindData(SQuery* query, bool dataFormat, SArray* tags, SArray* colsSc ret = terrno; goto end; } - if (!taosMbsToUcs4(kv->value, kv->length, (TdUcs4*)pUcs4, pColSchema->bytes - VARSTR_HEADER_SIZE, &len)) { + if (!taosMbsToUcs4(kv->value, kv->length, (TdUcs4*)pUcs4, pColSchema->bytes - VARSTR_HEADER_SIZE, &len, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { uError("sml bind taosMbsToUcs4 error, kv length:%d, bytes:%d, kv->value:%s", (int)kv->length, pColSchema->bytes, kv->value); diff --git a/source/libs/parser/src/parInsertSql.c b/source/libs/parser/src/parInsertSql.c index 5d34809c12..c5e9ad4ae4 100644 --- a/source/libs/parser/src/parInsertSql.c +++ b/source/libs/parser/src/parInsertSql.c @@ -247,14 +247,14 @@ static int32_t parseBoundColumns(SInsertParseContext* pCxt, const char** pSql, E return code; } -static int32_t parseTimestampOrInterval(const char** end, SToken* pToken, int16_t timePrec, int64_t* ts, - int64_t* interval, SMsgBuf* pMsgBuf, bool* isTs) { +static int32_t parseTimestampOrInterval(const char** end, SToken* pToken, int16_t timePrec, int64_t* ts, int64_t* interval, + SMsgBuf* pMsgBuf, bool* isTs, timezone_t tz) { if (pToken->type == TK_NOW) { *isTs = true; *ts = taosGetTimestamp(timePrec); } else if (pToken->type == TK_TODAY) { *isTs = true; - *ts = taosGetTimestampToday(timePrec); + *ts = taosGetTimestampToday(timePrec, tz); } else if (pToken->type == TK_NK_INTEGER) { *isTs = true; if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, ts)) { @@ -268,7 +268,7 @@ static int32_t parseTimestampOrInterval(const char** end, SToken* pToken, int16_ } } else { // parse the RFC-3339/ISO-8601 timestamp format string *isTs = true; - if (taosParseTime(pToken->z, ts, pToken->n, timePrec, tsDaylight) != TSDB_CODE_SUCCESS) { + if (taosParseTime(pToken->z, ts, pToken->n, timePrec, tz) != TSDB_CODE_SUCCESS) { if ((pToken->n == 0) || (pToken->type != TK_NK_STRING && pToken->type != TK_NK_HEX && pToken->type != TK_NK_BIN)) { return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp format", pToken->z); @@ -278,7 +278,7 @@ static int32_t parseTimestampOrInterval(const char** end, SToken* pToken, int16_ *ts = taosGetTimestamp(timePrec); } else if (IS_TODAY_STR(pToken->z, pToken->n)) { *isTs = true; - *ts = taosGetTimestampToday(timePrec); + *ts = taosGetTimestampToday(timePrec, tz); } else if (TSDB_CODE_SUCCESS == toIntegerPure(pToken->z, pToken->n, 10, ts)) { *isTs = true; } else { @@ -290,7 +290,7 @@ static int32_t parseTimestampOrInterval(const char** end, SToken* pToken, int16_ return TSDB_CODE_SUCCESS; } -static int parseTime(const char** end, SToken* pToken, int16_t timePrec, int64_t* time, SMsgBuf* pMsgBuf) { +static int parseTime(const char** end, SToken* pToken, int16_t timePrec, int64_t* time, SMsgBuf* pMsgBuf, timezone_t tz) { int32_t index = 0, i = 0; int64_t interval = 0, tempInterval = 0; int64_t ts = 0, tempTs = 0; @@ -298,7 +298,7 @@ static int parseTime(const char** end, SToken* pToken, int16_t timePrec, int64_t const char* pTokenEnd = *end; if (TSDB_CODE_SUCCESS != - parseTimestampOrInterval(&pTokenEnd, pToken, timePrec, &ts, &interval, pMsgBuf, &firstIsTS)) { + parseTimestampOrInterval(&pTokenEnd, pToken, timePrec, &ts, &interval, pMsgBuf, &firstIsTS, tz)) { return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp format", pToken->z); } @@ -372,7 +372,7 @@ static int parseTime(const char** end, SToken* pToken, int16_t timePrec, int64_t } if (TSDB_CODE_SUCCESS != - parseTimestampOrInterval(&pTokenEnd, &valueToken, timePrec, &tempTs, &tempInterval, pMsgBuf, &secondIsTs)) { + parseTimestampOrInterval(&pTokenEnd, &valueToken, timePrec, &tempTs, &tempInterval, pMsgBuf, &secondIsTs, tz)) { return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp format", pToken->z); } @@ -478,7 +478,7 @@ static int32_t parseVarbinary(SToken* pToken, uint8_t** pData, uint32_t* nData, } static int32_t parseTagToken(const char** end, SToken* pToken, SSchema* pSchema, int16_t timePrec, STagVal* val, - SMsgBuf* pMsgBuf) { + SMsgBuf* pMsgBuf, timezone_t tz, void *charsetCxt) { int64_t iv; uint64_t uv; char* endptr = NULL; @@ -686,13 +686,13 @@ static int32_t parseTagToken(const char** end, SToken* pToken, SSchema* pSchema, if (p == NULL) { return terrno; } - if (!taosMbsToUcs4(pToken->z, pToken->n, (TdUcs4*)(p), realLen, &output)) { + if (!taosMbsToUcs4(pToken->z, pToken->n, (TdUcs4*)(p), realLen, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { taosMemoryFree(p); return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); } char buf[512] = {0}; - snprintf(buf, tListLen(buf), " taosMbsToUcs4 error:%s", strerror(terrno)); + snprintf(buf, tListLen(buf), " taosMbsToUcs4 error:%s %d %d", strerror(terrno), errno, EILSEQ); taosMemoryFree(p); return buildSyntaxErrMsg(pMsgBuf, buf, pToken->z); } @@ -701,7 +701,7 @@ static int32_t parseTagToken(const char** end, SToken* pToken, SSchema* pSchema, break; } case TSDB_DATA_TYPE_TIMESTAMP: { - if (parseTime(end, pToken, timePrec, &iv, pMsgBuf) != TSDB_CODE_SUCCESS) { + if (parseTime(end, pToken, timePrec, &iv, pMsgBuf, tz) != TSDB_CODE_SUCCESS) { return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp", pToken->z); } @@ -733,7 +733,7 @@ static int32_t parseBoundTagsClause(SInsertParseContext* pCxt, SVnodeModifyOpStm } int32_t parseTagValue(SMsgBuf* pMsgBuf, const char** pSql, uint8_t precision, SSchema* pTagSchema, SToken* pToken, - SArray* pTagName, SArray* pTagVals, STag** pTag) { + SArray* pTagName, SArray* pTagVals, STag** pTag, timezone_t tz, void *charsetCxt) { bool isNull = isNullValue(pTagSchema->type, pToken); if (!isNull && pTagName) { if (NULL == taosArrayPush(pTagName, pTagSchema->name)) { @@ -749,14 +749,14 @@ int32_t parseTagValue(SMsgBuf* pMsgBuf, const char** pSql, uint8_t precision, SS if (isNull) { return tTagNew(pTagVals, 1, true, pTag); } else { - return parseJsontoTagData(pToken->z, pTagVals, pTag, pMsgBuf); + return parseJsontoTagData(pToken->z, pTagVals, pTag, pMsgBuf, charsetCxt); } } if (isNull) return 0; STagVal val = {0}; - int32_t code = parseTagToken(pSql, pToken, pTagSchema, precision, &val, pMsgBuf); + int32_t code = parseTagToken(pSql, pToken, pTagSchema, precision, &val, pMsgBuf, tz, charsetCxt); if (TSDB_CODE_SUCCESS == code) { if (NULL == taosArrayPush(pTagVals, &val)) { code = terrno; @@ -979,7 +979,7 @@ static int32_t parseTagsClauseImpl(SInsertParseContext* pCxt, SVnodeModifyOpStmt code = buildSyntaxErrMsg(&pCxt->msg, "not expected tags values ", token.z); } if (TSDB_CODE_SUCCESS == code) { - code = parseTagValue(&pCxt->msg, &pStmt->pSql, precision, pTagSchema, &token, pTagName, pTagVals, &pTag); + code = parseTagValue(&pCxt->msg, &pStmt->pSql, precision, pTagSchema, &token, pTagName, pTagVals, &pTag, pCxt->pComCxt->timezone, pCxt->pComCxt->charsetCxt); } } @@ -1630,7 +1630,7 @@ static int32_t parseValueTokenImpl(SInsertParseContext* pCxt, const char** pSql, if (NULL == pUcs4) { return terrno; } - if (!taosMbsToUcs4(pToken->z, pToken->n, (TdUcs4*)pUcs4, realLen, &len)) { + if (!taosMbsToUcs4(pToken->z, pToken->n, (TdUcs4*)pUcs4, realLen, &len, pCxt->pComCxt->charsetCxt)) { taosMemoryFree(pUcs4); if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { return generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); @@ -1685,7 +1685,7 @@ static int32_t parseValueTokenImpl(SInsertParseContext* pCxt, const char** pSql, break; } case TSDB_DATA_TYPE_TIMESTAMP: { - if (parseTime(pSql, pToken, timePrec, &pVal->value.val, &pCxt->msg) != TSDB_CODE_SUCCESS) { + if (parseTime(pSql, pToken, timePrec, &pVal->value.val, &pCxt->msg, pCxt->pComCxt->timezone) != TSDB_CODE_SUCCESS) { return buildSyntaxErrMsg(&pCxt->msg, "invalid timestamp", pToken->z); } break; @@ -1798,7 +1798,7 @@ static int32_t processCtbTagsAfterCtbName(SInsertParseContext* pCxt, SVnodeModif if (code == TSDB_CODE_SUCCESS) { code = parseTagValue(&pCxt->msg, NULL, precision, pTagSchema, pTagToken, pStbRowsCxt->aTagNames, - pStbRowsCxt->aTagVals, &pStbRowsCxt->pTag); + pStbRowsCxt->aTagVals, &pStbRowsCxt->pTag, pCxt->pComCxt->timezone, pCxt->pComCxt->charsetCxt); } } if (code == TSDB_CODE_SUCCESS && !pStbRowsCxt->isJsonTag) { @@ -1895,7 +1895,7 @@ static int32_t doGetStbRowValues(SInsertParseContext* pCxt, SVnodeModifyOpStmt* } if (code == TSDB_CODE_SUCCESS) { code = parseTagValue(&pCxt->msg, ppSql, precision, (SSchema*)pTagSchema, pToken, pTagNames, pTagVals, - &pStbRowsCxt->pTag); + &pStbRowsCxt->pTag, pCxt->pComCxt->timezone, pCxt->pComCxt->charsetCxt); } } } else if (pCols->pColIndex[i] == tbnameIdx) { diff --git a/source/libs/parser/src/parInsertStmt.c b/source/libs/parser/src/parInsertStmt.c index fe0f4671b4..9e6abe1517 100644 --- a/source/libs/parser/src/parInsertStmt.c +++ b/source/libs/parser/src/parInsertStmt.c @@ -123,7 +123,7 @@ int32_t qBuildStmtOutput(SQuery* pQuery, SHashObj* pVgHash, SHashObj* pBlockHash } int32_t qBindStmtTagsValue(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, - TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen) { + TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, void* charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; int32_t code = TSDB_CODE_SUCCESS; @@ -183,7 +183,7 @@ int32_t qBindStmtTagsValue(void* pBlock, void* boundTags, int64_t suid, const ch goto end; } memcpy(tmp, bind[c].buffer, colLen); - code = parseJsontoTagData(tmp, pTagArray, &pTag, &pBuf); + code = parseJsontoTagData(tmp, pTagArray, &pTag, &pBuf, charsetCxt); taosMemoryFree(tmp); if (code != TSDB_CODE_SUCCESS) { goto end; @@ -208,7 +208,7 @@ int32_t qBindStmtTagsValue(void* pBlock, void* boundTags, int64_t suid, const ch code = terrno; goto end; } - if (!taosMbsToUcs4(bind[c].buffer, colLen, (TdUcs4*)(p), colLen * TSDB_NCHAR_SIZE, &output)) { + if (!taosMbsToUcs4(bind[c].buffer, colLen, (TdUcs4*)(p), colLen * TSDB_NCHAR_SIZE, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { taosMemoryFree(p); code = generateSyntaxErrMsg(&pBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pTagSchema->name); @@ -266,7 +266,7 @@ end: return code; } -int32_t convertStmtNcharCol(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_MULTI_BIND* src, TAOS_MULTI_BIND* dst) { +int32_t convertStmtNcharCol(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_MULTI_BIND* src, TAOS_MULTI_BIND* dst, void* charsetCxt) { int32_t output = 0; int32_t newBuflen = (pSchema->bytes - VARSTR_HEADER_SIZE) * src->num; if (dst->buffer_length < newBuflen) { @@ -292,7 +292,7 @@ int32_t convertStmtNcharCol(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_MULTI_BIND* } if (!taosMbsToUcs4(((char*)src->buffer) + src->buffer_length * i, src->length[i], - (TdUcs4*)(((char*)dst->buffer) + dst->buffer_length * i), dst->buffer_length, &output)) { + (TdUcs4*)(((char*)dst->buffer) + dst->buffer_length * i), dst->buffer_length, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); } @@ -312,7 +312,7 @@ int32_t convertStmtNcharCol(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_MULTI_BIND* } int32_t qBindStmtStbColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, - STSchema** pTSchema, SBindInfo* pBindInfos) { + STSchema** pTSchema, SBindInfo* pBindInfos, void* charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; @@ -349,7 +349,7 @@ int32_t qBindStmtStbColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind } if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { - code = convertStmtNcharCol(&pBuf, pColSchema, bind + c, &ncharBind); + code = convertStmtNcharCol(&pBuf, pColSchema, bind + c, &ncharBind, charsetCxt); if (code) { goto _return; } @@ -380,7 +380,7 @@ _return: return code; } -int32_t qBindStmtColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen) { +int32_t qBindStmtColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, void* charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; @@ -406,7 +406,7 @@ int32_t qBindStmtColsValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, c } if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { - code = convertStmtNcharCol(&pBuf, pColSchema, bind + c, &ncharBind); + code = convertStmtNcharCol(&pBuf, pColSchema, bind + c, &ncharBind, charsetCxt); if (code) { goto _return; } @@ -434,7 +434,7 @@ _return: } int32_t qBindStmtSingleColValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bind, char* msgBuf, int32_t msgBufLen, - int32_t colIdx, int32_t rowNum) { + int32_t colIdx, int32_t rowNum, void* charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; @@ -459,7 +459,7 @@ int32_t qBindStmtSingleColValue(void* pBlock, SArray* pCols, TAOS_MULTI_BIND* bi } if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { - code = convertStmtNcharCol(&pBuf, pColSchema, bind, &ncharBind); + code = convertStmtNcharCol(&pBuf, pColSchema, bind, &ncharBind, charsetCxt); if (code) { goto _return; } @@ -483,7 +483,7 @@ _return: } int32_t qBindStmtTagsValue2(void* pBlock, void* boundTags, int64_t suid, const char* sTableName, char* tName, - TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen) { + TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, void* charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SMsgBuf pBuf = {.buf = msgBuf, .len = msgBufLen}; int32_t code = TSDB_CODE_SUCCESS; @@ -543,7 +543,7 @@ int32_t qBindStmtTagsValue2(void* pBlock, void* boundTags, int64_t suid, const c goto end; } memcpy(tmp, bind[c].buffer, colLen); - code = parseJsontoTagData(tmp, pTagArray, &pTag, &pBuf); + code = parseJsontoTagData(tmp, pTagArray, &pTag, &pBuf, charsetCxt); taosMemoryFree(tmp); if (code != TSDB_CODE_SUCCESS) { goto end; @@ -568,7 +568,7 @@ int32_t qBindStmtTagsValue2(void* pBlock, void* boundTags, int64_t suid, const c code = terrno; goto end; } - if (!taosMbsToUcs4(bind[c].buffer, colLen, (TdUcs4*)(p), colLen * TSDB_NCHAR_SIZE, &output)) { + if (!taosMbsToUcs4(bind[c].buffer, colLen, (TdUcs4*)(p), colLen * TSDB_NCHAR_SIZE, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { taosMemoryFree(p); code = generateSyntaxErrMsg(&pBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pTagSchema->name); @@ -626,7 +626,7 @@ end: return code; } -static int32_t convertStmtStbNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STMT2_BIND* src, TAOS_STMT2_BIND* dst) { +static int32_t convertStmtStbNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STMT2_BIND* src, TAOS_STMT2_BIND* dst, void *charsetCxt) { int32_t output = 0; const int32_t max_buf_len = pSchema->bytes - VARSTR_HEADER_SIZE; @@ -648,7 +648,7 @@ static int32_t convertStmtStbNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_ continue; } - if (!taosMbsToUcs4(src_buf, src->length[i], (TdUcs4*)dst_buf, max_buf_len, &output)) { + if (!taosMbsToUcs4(src_buf, src->length[i], (TdUcs4*)dst_buf, max_buf_len, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); } @@ -670,7 +670,7 @@ static int32_t convertStmtStbNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_ } int32_t qBindStmtStbColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, - STSchema** pTSchema, SBindInfo2* pBindInfos) { + STSchema** pTSchema, SBindInfo2* pBindInfos, void *charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; @@ -720,7 +720,7 @@ int32_t qBindStmtStbColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bin } if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { - code = convertStmtStbNcharCol2(&pBuf, pColSchema, bind + c, &ncharBind); + code = convertStmtStbNcharCol2(&pBuf, pColSchema, bind + c, &ncharBind, charsetCxt); if (code) { goto _return; } @@ -755,7 +755,7 @@ _return: return code; } -static int32_t convertStmtNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STMT2_BIND* src, TAOS_STMT2_BIND* dst) { +static int32_t convertStmtNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STMT2_BIND* src, TAOS_STMT2_BIND* dst, void *charsetCxt) { int32_t output = 0; const int32_t max_buf_len = pSchema->bytes - VARSTR_HEADER_SIZE; @@ -785,7 +785,7 @@ static int32_t convertStmtNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STM /*if (!taosMbsToUcs4(((char*)src->buffer) + src->buffer_length * i, src->length[i], (TdUcs4*)(((char*)dst->buffer) + dst->buffer_length * i), dst->buffer_length, &output)) {*/ - if (!taosMbsToUcs4(src_buf, src->length[i], (TdUcs4*)dst_buf, max_buf_len, &output)) { + if (!taosMbsToUcs4(src_buf, src->length[i], (TdUcs4*)dst_buf, max_buf_len, &output, charsetCxt)) { if (terrno == TAOS_SYSTEM_ERROR(E2BIG)) { return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name); } @@ -806,7 +806,7 @@ static int32_t convertStmtNcharCol2(SMsgBuf* pMsgBuf, SSchema* pSchema, TAOS_STM return TSDB_CODE_SUCCESS; } -int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen) { +int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, void *charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; @@ -836,7 +836,7 @@ int32_t qBindStmtColsValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, } if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { - code = convertStmtNcharCol2(&pBuf, pColSchema, bind + c, &ncharBind); + code = convertStmtNcharCol2(&pBuf, pColSchema, bind + c, &ncharBind, charsetCxt); if (code) { goto _return; } @@ -864,7 +864,7 @@ _return: } int32_t qBindStmtSingleColValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* bind, char* msgBuf, int32_t msgBufLen, - int32_t colIdx, int32_t rowNum) { + int32_t colIdx, int32_t rowNum, void *charsetCxt) { STableDataCxt* pDataBlock = (STableDataCxt*)pBlock; SSchema* pSchema = getTableColumnSchema(pDataBlock->pMeta); SBoundColInfo* boundInfo = &pDataBlock->boundColsInfo; @@ -889,7 +889,7 @@ int32_t qBindStmtSingleColValue2(void* pBlock, SArray* pCols, TAOS_STMT2_BIND* b } if (TSDB_DATA_TYPE_NCHAR == pColSchema->type) { - code = convertStmtNcharCol2(&pBuf, pColSchema, bind, &ncharBind); + code = convertStmtNcharCol2(&pBuf, pColSchema, bind, &ncharBind, charsetCxt); if (code) { goto _return; } diff --git a/source/libs/parser/src/parTranslater.c b/source/libs/parser/src/parTranslater.c index 7626bddfed..a36d44db7a 100755 --- a/source/libs/parser/src/parTranslater.c +++ b/source/libs/parser/src/parTranslater.c @@ -1967,7 +1967,7 @@ static int32_t parseTimeFromValueNode(STranslateContext* pCxt, SValueNode* pVal) return TSDB_CODE_SUCCESS; } else if (IS_VAR_DATA_TYPE(pVal->node.resType.type) || TSDB_DATA_TYPE_TIMESTAMP == pVal->node.resType.type) { if (TSDB_CODE_SUCCESS == taosParseTime(pVal->literal, &pVal->datum.i, pVal->node.resType.bytes, - pVal->node.resType.precision, tsDaylight)) { + pVal->node.resType.precision, pVal->tz)) { return TSDB_CODE_SUCCESS; } char* pEnd = NULL; @@ -2169,7 +2169,7 @@ static EDealRes translateNormalValue(STranslateContext* pCxt, SValueNode* pVal, int32_t len = 0; if (!taosMbsToUcs4(pVal->literal, strlen(pVal->literal), (TdUcs4*)varDataVal(pVal->datum.p), - targetDt.bytes - VARSTR_HEADER_SIZE, &len)) { + targetDt.bytes - VARSTR_HEADER_SIZE, &len, pCxt->pParseCxt->charsetCxt)) { return generateDealNodeErrMsg(pCxt, TSDB_CODE_PAR_WRONG_VALUE_TYPE, pVal->literal); } varDataSetLen(pVal->datum.p, len); @@ -5939,6 +5939,7 @@ void tryCalcIntervalAutoOffset(SIntervalWindowNode *pInterval) { .slidingUnit = (pSliding != NULL) ? pSliding->unit : pInter->unit, .offset = pOffset->datum.i, .precision = precision, + .timezone = pInterval->timezone, .timeRange = pInterval->timeRange}; /** @@ -10112,7 +10113,7 @@ static int32_t translateCreateSmaIndex(STranslateContext* pCxt, SCreateIndexStmt return code; } -int32_t createIntervalFromCreateSmaIndexStmt(SCreateIndexStmt* pStmt, SInterval* pInterval) { +int32_t createIntervalFromCreateSmaIndexStmt(SCreateIndexStmt* pStmt, SInterval* pInterval, void* timezone) { pInterval->interval = ((SValueNode*)pStmt->pOptions->pInterval)->datum.i; pInterval->intervalUnit = ((SValueNode*)pStmt->pOptions->pInterval)->unit; pInterval->offset = NULL != pStmt->pOptions->pOffset ? ((SValueNode*)pStmt->pOptions->pOffset)->datum.i : 0; @@ -10125,6 +10126,7 @@ int32_t createIntervalFromCreateSmaIndexStmt(SCreateIndexStmt* pStmt, SInterval* parserError("%s failed for invalid interval offset %" PRId64, __func__, pInterval->offset); return TSDB_CODE_INVALID_PARA; } + pInterval->timezone = timezone; return TSDB_CODE_SUCCESS; } @@ -10136,7 +10138,7 @@ int32_t translatePostCreateSmaIndex(SParseContext* pParseCxt, SQuery* pQuery, SS STranslateContext pCxt = {0}; code = initTranslateContext(pParseCxt, NULL, &pCxt); if (TSDB_CODE_SUCCESS == code) { - code = createIntervalFromCreateSmaIndexStmt(pStmt, &interval); + code = createIntervalFromCreateSmaIndexStmt(pStmt, &interval, pParseCxt->timezone); } if (TSDB_CODE_SUCCESS == code) { @@ -11971,6 +11973,7 @@ static int32_t buildIntervalForCreateStream(SCreateStreamStmt* pStmt, SInterval* (NULL != pWindow->pSliding ? ((SValueNode*)pWindow->pSliding)->unit : pInterval->intervalUnit); pInterval->precision = ((SColumnNode*)pWindow->pCol)->node.resType.precision; pInterval->timeRange = pWindow->timeRange; + pInterval->timezone = pWindow->timezone; return code; } @@ -12020,7 +12023,7 @@ int32_t translatePostCreateStream(SParseContext* pParseCxt, SQuery* pQuery, SSDa if (TSDB_CODE_SUCCESS == code) { if (interval.interval > 0) { pStmt->pReq->lastTs = taosTimeAdd(taosTimeTruncate(lastTs, &interval), interval.interval, interval.intervalUnit, - interval.precision); + interval.precision, pParseCxt->timezone); } else { pStmt->pReq->lastTs = lastTs + 1; // start key of the next time window } @@ -12889,7 +12892,7 @@ static int32_t translateCreateTSMA(STranslateContext* pCxt, SCreateTSMAStmt* pSt return code; } -static int32_t buildIntervalForCreateTSMA(SCreateTSMAStmt* pStmt, SInterval* pInterval) { +static int32_t buildIntervalForCreateTSMA(SCreateTSMAStmt* pStmt, SInterval* pInterval, void* timezone) { int32_t code = TSDB_CODE_SUCCESS; pInterval->interval = ((SValueNode*)pStmt->pOptions->pInterval)->datum.i; pInterval->intervalUnit = ((SValueNode*)pStmt->pOptions->pInterval)->unit; @@ -12897,6 +12900,7 @@ static int32_t buildIntervalForCreateTSMA(SCreateTSMAStmt* pStmt, SInterval* pIn pInterval->sliding = pInterval->interval; pInterval->slidingUnit = pInterval->intervalUnit; pInterval->precision = pStmt->pOptions->tsPrecision; + pInterval->timezone = timezone; return code; } @@ -12908,7 +12912,7 @@ int32_t translatePostCreateTSMA(SParseContext* pParseCxt, SQuery* pQuery, SSData int32_t code = initTranslateContext(pParseCxt, NULL, &cxt); if (TSDB_CODE_SUCCESS == code) { - code = buildIntervalForCreateTSMA(pStmt, &interval); + code = buildIntervalForCreateTSMA(pStmt, &interval, pParseCxt->timezone); } if (TSDB_CODE_SUCCESS == code) { @@ -12918,7 +12922,7 @@ int32_t translatePostCreateTSMA(SParseContext* pParseCxt, SQuery* pQuery, SSData if (TSDB_CODE_SUCCESS == code) { if (interval.interval > 0) { pStmt->pReq->lastTs = taosTimeAdd(taosTimeTruncate(lastTs, &interval), interval.interval, interval.intervalUnit, - interval.precision); + interval.precision, pParseCxt->timezone); } else { pStmt->pReq->lastTs = lastTs + 1; // start key of the next time window } @@ -14429,7 +14433,7 @@ static int32_t buildKVRowForBindTags(STranslateContext* pCxt, SCreateSubTableCla if (pSchema->type == TSDB_DATA_TYPE_JSON) { isJson = true; } - code = parseTagValue(&pCxt->msgBuf, &tagStr, precision, pSchema, &token, tagName, pTagArray, ppTag); + code = parseTagValue(&pCxt->msgBuf, &tagStr, precision, pSchema, &token, tagName, pTagArray, ppTag, pCxt->pParseCxt->timezone, pCxt->pParseCxt->charsetCxt); } if (TSDB_CODE_SUCCESS == code) { @@ -14490,7 +14494,7 @@ static int32_t buildKVRowForAllTags(STranslateContext* pCxt, SCreateSubTableClau if (pTagSchema->type == TSDB_DATA_TYPE_JSON) { isJson = true; } - code = parseTagValue(&pCxt->msgBuf, &tagStr, precision, pTagSchema, &token, tagName, pTagArray, ppTag); + code = parseTagValue(&pCxt->msgBuf, &tagStr, precision, pTagSchema, &token, tagName, pTagArray, ppTag, pCxt->pParseCxt->timezone, pCxt->pParseCxt->charsetCxt); } if (TSDB_CODE_SUCCESS == code) { @@ -14686,7 +14690,7 @@ static int32_t fillVgroupInfo(SParseContext* pParseCxt, const SName* pName, SVgr return code; } -static int32_t parseOneStbRow(SMsgBuf* pMsgBuf, SParseFileContext* pParFileCxt) { +static int32_t parseOneStbRow(SMsgBuf* pMsgBuf, SParseFileContext* pParFileCxt, timezone_t tz, void *charsetCxt) { int32_t code = TSDB_CODE_SUCCESS; int sz = taosArrayGetSize(pParFileCxt->aTagIndexs); int32_t numOfTags = getNumOfTags(pParFileCxt->pStbMeta); @@ -14718,7 +14722,7 @@ static int32_t parseOneStbRow(SMsgBuf* pMsgBuf, SParseFileContext* pParFileCxt) if (TSDB_CODE_SUCCESS == code) { SArray* aTagNames = pParFileCxt->tagNameFilled ? NULL : pParFileCxt->aTagNames; code = parseTagValue(pMsgBuf, &pParFileCxt->pSql, precision, (SSchema*)pTagSchema, &token, aTagNames, - pParFileCxt->aTagVals, &pParFileCxt->pTag); + pParFileCxt->aTagVals, &pParFileCxt->pTag, tz, charsetCxt); } } else { // parse tbname @@ -14784,7 +14788,7 @@ static int32_t parseCsvFile(SMsgBuf* pMsgBuf, SParseContext* pParseCxt, SParseFi (void)strtolower(pLine, pLine); pParFileCxt->pSql = pLine; - code = parseOneStbRow(pMsgBuf, pParFileCxt); + code = parseOneStbRow(pMsgBuf, pParFileCxt, pParseCxt->timezone, pParseCxt->charsetCxt); if (TSDB_CODE_SUCCESS == code) { code = fillVgroupInfo(pParseCxt, &pParFileCxt->ctbName, &pParFileCxt->vg); @@ -15477,7 +15481,7 @@ static int32_t buildUpdateTagValReqImpl2(STranslateContext* pCxt, SAlterTableStm if (TSDB_CODE_SUCCESS == code) { code = parseTagValue(&pCxt->msgBuf, &tagStr, pTableMeta->tableInfo.precision, pSchema, &token, NULL, - pReq->pTagArray, &pTag); + pReq->pTagArray, &pTag, pCxt->pParseCxt->timezone, pCxt->pParseCxt->charsetCxt); if (pSchema->type == TSDB_DATA_TYPE_JSON && token.type == TK_NULL && code == TSDB_CODE_SUCCESS) { pReq->tagFree = true; } @@ -15549,7 +15553,7 @@ static int32_t buildUpdateTagValReqImpl(STranslateContext* pCxt, SAlterTableStmt if (TSDB_CODE_SUCCESS == code) { code = parseTagValue(&pCxt->msgBuf, &tagStr, pTableMeta->tableInfo.precision, pSchema, &token, NULL, - pReq->pTagArray, &pTag); + pReq->pTagArray, &pTag, pCxt->pParseCxt->timezone, pCxt->pParseCxt->charsetCxt); if (pSchema->type == TSDB_DATA_TYPE_JSON && token.type == TK_NULL && code == TSDB_CODE_SUCCESS) { pReq->tagFree = true; } diff --git a/source/libs/parser/src/parUtil.c b/source/libs/parser/src/parUtil.c index bfe9513594..8c9fd89db6 100644 --- a/source/libs/parser/src/parUtil.c +++ b/source/libs/parser/src/parUtil.c @@ -402,7 +402,7 @@ static bool isValidateTag(char* input) { return true; } -int32_t parseJsontoTagData(const char* json, SArray* pTagVals, STag** ppTag, void* pMsgBuf) { +int32_t parseJsontoTagData(const char* json, SArray* pTagVals, STag** ppTag, void* pMsgBuf, void *charsetCxt) { int32_t retCode = TSDB_CODE_SUCCESS; cJSON* root = NULL; SHashObj* keyHash = NULL; @@ -471,8 +471,9 @@ int32_t parseJsontoTagData(const char* json, SArray* pTagVals, STag** ppTag, voi goto end; } val.type = TSDB_DATA_TYPE_NCHAR; - if (valLen > 0 && !taosMbsToUcs4(jsonValue, valLen, (TdUcs4*)tmp, (int32_t)(valLen * TSDB_NCHAR_SIZE), &valLen)) { - uError("charset:%s to %s. val:%s, errno:%s, convert failed.", DEFAULT_UNICODE_ENCODEC, tsCharset, jsonValue, + if (valLen > 0 && !taosMbsToUcs4(jsonValue, valLen, (TdUcs4*)tmp, (int32_t)(valLen * TSDB_NCHAR_SIZE), &valLen, charsetCxt)) { + uError("charset:%s to %s. val:%s, errno:%s, convert failed.", DEFAULT_UNICODE_ENCODEC, + charsetCxt != NULL ? ((SConvInfo *)(charsetCxt))->charset : tsCharset, jsonValue, strerror(terrno)); retCode = buildSyntaxErrMsg(pMsgBuf, "charset convert json error", jsonValue); taosMemoryFree(tmp); diff --git a/source/libs/parser/src/parser.c b/source/libs/parser/src/parser.c index d42926e842..6d2822f038 100644 --- a/source/libs/parser/src/parser.c +++ b/source/libs/parser/src/parser.c @@ -153,7 +153,7 @@ static int32_t parseSqlSyntax(SParseContext* pCxt, SQuery** pQuery, SParseMetaCa return code; } -static int32_t setValueByBindParam(SValueNode* pVal, TAOS_MULTI_BIND* pParam) { +static int32_t setValueByBindParam(SValueNode* pVal, TAOS_MULTI_BIND* pParam, void *charsetCxt) { if (!pParam || IS_NULL_TYPE(pParam->buffer_type)) { return TSDB_CODE_APP_ERROR; } @@ -200,7 +200,7 @@ static int32_t setValueByBindParam(SValueNode* pVal, TAOS_MULTI_BIND* pParam) { int32_t output = 0; if (!taosMbsToUcs4(pParam->buffer, inputSize, (TdUcs4*)varDataVal(pVal->datum.p), pVal->node.resType.bytes, - &output)) { + &output, charsetCxt)) { return terrno; } varDataSetLen(pVal->datum.p, output); @@ -417,19 +417,19 @@ int32_t qInitKeywordsTable() { return taosInitKeywordsTable(); } void qCleanupKeywordsTable() { taosCleanupKeywordsTable(); } -int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx) { +int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx, void *charsetCxt) { int32_t code = TSDB_CODE_SUCCESS; if (colIdx < 0) { int32_t size = taosArrayGetSize(pQuery->pPlaceholderValues); for (int32_t i = 0; i < size; ++i) { - code = setValueByBindParam((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, i), pParams + i); + code = setValueByBindParam((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, i), pParams + i, charsetCxt); if (TSDB_CODE_SUCCESS != code) { return code; } } } else { - code = setValueByBindParam((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, colIdx), pParams); + code = setValueByBindParam((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, colIdx), pParams, charsetCxt); } if (TSDB_CODE_SUCCESS == code && (colIdx < 0 || colIdx + 1 == pQuery->placeholderNum)) { @@ -443,7 +443,7 @@ int32_t qStmtBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx return code; } -static int32_t setValueByBindParam2(SValueNode* pVal, TAOS_STMT2_BIND* pParam) { +static int32_t setValueByBindParam2(SValueNode* pVal, TAOS_STMT2_BIND* pParam, void* charsetCxt) { if (!pParam || IS_NULL_TYPE(pParam->buffer_type)) { return TSDB_CODE_APP_ERROR; } @@ -490,7 +490,7 @@ static int32_t setValueByBindParam2(SValueNode* pVal, TAOS_STMT2_BIND* pParam) { int32_t output = 0; if (!taosMbsToUcs4(pParam->buffer, inputSize, (TdUcs4*)varDataVal(pVal->datum.p), pVal->node.resType.bytes, - &output)) { + &output, charsetCxt)) { return terrno; } varDataSetLen(pVal->datum.p, output); @@ -509,19 +509,19 @@ static int32_t setValueByBindParam2(SValueNode* pVal, TAOS_STMT2_BIND* pParam) { return TSDB_CODE_SUCCESS; } -int32_t qStmtBindParams2(SQuery* pQuery, TAOS_STMT2_BIND* pParams, int32_t colIdx) { +int32_t qStmtBindParams2(SQuery* pQuery, TAOS_STMT2_BIND* pParams, int32_t colIdx, void* charsetCxt) { int32_t code = TSDB_CODE_SUCCESS; if (colIdx < 0) { int32_t size = taosArrayGetSize(pQuery->pPlaceholderValues); for (int32_t i = 0; i < size; ++i) { - code = setValueByBindParam2((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, i), pParams + i); + code = setValueByBindParam2((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, i), pParams + i, charsetCxt); if (TSDB_CODE_SUCCESS != code) { return code; } } } else { - code = setValueByBindParam2((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, colIdx), pParams); + code = setValueByBindParam2((SValueNode*)taosArrayGetP(pQuery->pPlaceholderValues, colIdx), pParams, charsetCxt); } if (TSDB_CODE_SUCCESS == code && (colIdx < 0 || colIdx + 1 == pQuery->placeholderNum)) { diff --git a/source/libs/planner/src/planOptimizer.c b/source/libs/planner/src/planOptimizer.c index 64f4b2a3bf..00d897cf8b 100644 --- a/source/libs/planner/src/planOptimizer.c +++ b/source/libs/planner/src/planOptimizer.c @@ -2926,7 +2926,7 @@ static int32_t smaIndexOptCreateSmaScan(SScanLogicNode* pScan, STableIndexInfo* return TSDB_CODE_SUCCESS; } -static bool smaIndexOptEqualInterval(SScanLogicNode* pScan, SWindowLogicNode* pWindow, STableIndexInfo* pIndex) { +static bool smaIndexOptEqualInterval(SScanLogicNode* pScan, SWindowLogicNode* pWindow, STableIndexInfo* pIndex, void* tz) { if (pWindow->interval != pIndex->interval || pWindow->intervalUnit != pIndex->intervalUnit || pWindow->offset != pIndex->offset || pWindow->sliding != pIndex->sliding || pWindow->slidingUnit != pIndex->slidingUnit) { @@ -2939,6 +2939,7 @@ static bool smaIndexOptEqualInterval(SScanLogicNode* pScan, SWindowLogicNode* pW .offsetUnit = TIME_UNIT_MILLISECOND, .sliding = pIndex->sliding, .slidingUnit = pIndex->slidingUnit, + .timezone = tz, .precision = pScan->node.precision}; return (pScan->scanRange.skey == taosTimeTruncate(pScan->scanRange.skey, &interval)) && (pScan->scanRange.ekey + 1 == taosTimeTruncate(pScan->scanRange.ekey + 1, &interval)); @@ -3049,9 +3050,9 @@ static int32_t smaIndexOptCreateSmaCols(SNodeList* pFuncs, uint64_t tableId, SNo return code; } -static int32_t smaIndexOptCouldApplyIndex(SScanLogicNode* pScan, STableIndexInfo* pIndex, SNodeList** pCols) { +static int32_t smaIndexOptCouldApplyIndex(SScanLogicNode* pScan, STableIndexInfo* pIndex, SNodeList** pCols, void* tz) { SWindowLogicNode* pWindow = (SWindowLogicNode*)pScan->node.pParent; - if (!smaIndexOptEqualInterval(pScan, pWindow, pIndex)) { + if (!smaIndexOptEqualInterval(pScan, pWindow, pIndex, tz)) { return TSDB_CODE_SUCCESS; } SNodeList* pSmaFuncs = NULL; @@ -3082,7 +3083,7 @@ static int32_t smaIndexOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogi for (int32_t i = 0; i < nindexes; ++i) { STableIndexInfo* pIndex = taosArrayGet(pScan->pSmaIndexes, i); SNodeList* pSmaCols = NULL; - code = smaIndexOptCouldApplyIndex(pScan, pIndex, &pSmaCols); + code = smaIndexOptCouldApplyIndex(pScan, pIndex, &pSmaCols, pCxt->pPlanCxt->timezone); if (TSDB_CODE_SUCCESS == code && NULL != pSmaCols) { code = smaIndexOptApplyIndex(pLogicSubplan, pScan, pIndex, pSmaCols); pCxt->optimized = true; @@ -6761,7 +6762,7 @@ typedef struct STSMAOptCtx { SNodeList** ppParentTsmaSubplans; } STSMAOptCtx; -static int32_t fillTSMAOptCtx(STSMAOptCtx* pTsmaOptCtx, SScanLogicNode* pScan) { +static int32_t fillTSMAOptCtx(STSMAOptCtx* pTsmaOptCtx, SScanLogicNode* pScan, void* tz) { int32_t code = 0; pTsmaOptCtx->pScan = pScan; pTsmaOptCtx->pParent = pScan->node.pParent; @@ -6781,7 +6782,7 @@ static int32_t fillTSMAOptCtx(STSMAOptCtx* pTsmaOptCtx, SScanLogicNode* pScan) { pTsmaOptCtx->queryInterval->sliding = pWindow->sliding; pTsmaOptCtx->queryInterval->slidingUnit = pWindow->slidingUnit; pTsmaOptCtx->queryInterval->precision = pWindow->node.precision; - pTsmaOptCtx->queryInterval->tz = tsTimezone; + pTsmaOptCtx->queryInterval->timezone = tz; pTsmaOptCtx->pAggFuncs = pWindow->pFuncs; pTsmaOptCtx->ppParentTsmaSubplans = &pWindow->pTsmaSubplans; } else { @@ -6972,7 +6973,7 @@ static int32_t tsmaInfoCompWithIntervalDesc(const void* pLeft, const void* pRigh return 0; } -static void tsmaOptInitIntervalFromTsma(SInterval* pInterval, const STableTSMAInfo* pTsma, int8_t precision) { +static void tsmaOptInitIntervalFromTsma(SInterval* pInterval, const STableTSMAInfo* pTsma, int8_t precision, void* tz) { pInterval->interval = pTsma->interval; pInterval->intervalUnit = pTsma->unit; pInterval->sliding = pTsma->interval; @@ -6980,15 +6981,16 @@ static void tsmaOptInitIntervalFromTsma(SInterval* pInterval, const STableTSMAIn pInterval->offset = 0; pInterval->offsetUnit = pTsma->unit; pInterval->precision = precision; + pInterval->timezone = tz; } static const STSMAOptUsefulTsma* tsmaOptFindUsefulTsma(const SArray* pUsefulTsmas, int32_t startIdx, int64_t startAlignInterval, int64_t endAlignInterval, - int8_t precision) { + int8_t precision, void* tz) { SInterval tsmaInterval; for (int32_t i = startIdx; i < pUsefulTsmas->size; ++i) { const STSMAOptUsefulTsma* pUsefulTsma = taosArrayGet(pUsefulTsmas, i); - tsmaOptInitIntervalFromTsma(&tsmaInterval, pUsefulTsma->pTsma, precision); + tsmaOptInitIntervalFromTsma(&tsmaInterval, pUsefulTsma->pTsma, precision, tz); if (taosTimeTruncate(startAlignInterval, &tsmaInterval) == startAlignInterval && taosTimeTruncate(endAlignInterval, &tsmaInterval) == endAlignInterval) { return pUsefulTsma; @@ -6997,7 +6999,7 @@ static const STSMAOptUsefulTsma* tsmaOptFindUsefulTsma(const SArray* pUsefulTsma return NULL; } -static int32_t tsmaOptSplitWindows(STSMAOptCtx* pTsmaOptCtx, const STimeWindow* pScanRange) { +static int32_t tsmaOptSplitWindows(STSMAOptCtx* pTsmaOptCtx, const STimeWindow* pScanRange, void* tz) { bool needTailWindow = false; bool isSkeyAlignedWithTsma = true, isEkeyAlignedWithTsma = true; int32_t code = 0; @@ -7013,17 +7015,17 @@ static int32_t tsmaOptSplitWindows(STSMAOptCtx* pTsmaOptCtx, const STimeWindow* if (pScanRange->ekey <= pScanRange->skey) return code; if (!pInterval) { - tsmaOptInitIntervalFromTsma(&interval, pTsma, pTsmaOptCtx->precision); + tsmaOptInitIntervalFromTsma(&interval, pTsma, pTsmaOptCtx->precision, tz); pInterval = &interval; } - tsmaOptInitIntervalFromTsma(&tsmaInterval, pTsma, pTsmaOptCtx->precision); + tsmaOptInitIntervalFromTsma(&tsmaInterval, pTsma, pTsmaOptCtx->precision, tz); // check for head windows if (pScanRange->skey != TSKEY_MIN) { startOfSkeyFirstWin = taosTimeTruncate(pScanRange->skey, pInterval); endOfSkeyFirstWin = - taosTimeAdd(startOfSkeyFirstWin, pInterval->interval, pInterval->intervalUnit, pTsmaOptCtx->precision); + taosTimeAdd(startOfSkeyFirstWin, pInterval->interval, pInterval->intervalUnit, pTsmaOptCtx->precision, tz); isSkeyAlignedWithTsma = taosTimeTruncate(pScanRange->skey, &tsmaInterval) == pScanRange->skey; } else { endOfSkeyFirstWin = TSKEY_MIN; @@ -7033,7 +7035,7 @@ static int32_t tsmaOptSplitWindows(STSMAOptCtx* pTsmaOptCtx, const STimeWindow* if (pScanRange->ekey != TSKEY_MAX) { startOfEkeyFirstWin = taosTimeTruncate(pScanRange->ekey, pInterval); endOfEkeyFirstWin = - taosTimeAdd(startOfEkeyFirstWin, pInterval->interval, pInterval->intervalUnit, pTsmaOptCtx->precision); + taosTimeAdd(startOfEkeyFirstWin, pInterval->interval, pInterval->intervalUnit, pTsmaOptCtx->precision, tz); isEkeyAlignedWithTsma = taosTimeTruncate(pScanRange->ekey + 1, &tsmaInterval) == (pScanRange->ekey + 1); if (startOfEkeyFirstWin > startOfSkeyFirstWin) { needTailWindow = true; @@ -7044,9 +7046,9 @@ static int32_t tsmaOptSplitWindows(STSMAOptCtx* pTsmaOptCtx, const STimeWindow* if (!isSkeyAlignedWithTsma) { scanRange.ekey = TMIN( scanRange.ekey, - taosTimeAdd(startOfSkeyFirstWin, pInterval->interval * 1, pInterval->intervalUnit, pTsmaOptCtx->precision) - 1); + taosTimeAdd(startOfSkeyFirstWin, pInterval->interval * 1, pInterval->intervalUnit, pTsmaOptCtx->precision, tz) - 1); const STSMAOptUsefulTsma* pTsmaFound = - tsmaOptFindUsefulTsma(pTsmaOptCtx->pUsefulTsmas, 1, scanRange.skey, scanRange.ekey + 1, pTsmaOptCtx->precision); + tsmaOptFindUsefulTsma(pTsmaOptCtx->pUsefulTsmas, 1, scanRange.skey, scanRange.ekey + 1, pTsmaOptCtx->precision, tz); STSMAOptUsefulTsma usefulTsma = {.pTsma = pTsmaFound ? pTsmaFound->pTsma : NULL, .scanRange = scanRange, .pTsmaScanCols = pTsmaFound ? pTsmaFound->pTsmaScanCols : NULL}; @@ -7071,7 +7073,7 @@ static int32_t tsmaOptSplitWindows(STSMAOptCtx* pTsmaOptCtx, const STimeWindow* scanRange.ekey = pScanRange->ekey; const STSMAOptUsefulTsma* pTsmaFound = tsmaOptFindUsefulTsma(pTsmaOptCtx->pUsefulTsmas, 1, scanRange.skey - startOfEkeyFirstWin, - scanRange.ekey + 1 - startOfEkeyFirstWin, pTsmaOptCtx->precision); + scanRange.ekey + 1 - startOfEkeyFirstWin, pTsmaOptCtx->precision, tz); STSMAOptUsefulTsma usefulTsma = {.pTsma = pTsmaFound ? pTsmaFound->pTsma : NULL, .scanRange = scanRange, .pTsmaScanCols = pTsmaFound ? pTsmaFound->pTsmaScanCols : NULL}; @@ -7509,7 +7511,7 @@ static int32_t tsmaOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan SLogicNode* pRootNode = getLogicNodeRootNode((SLogicNode*)pScan); if (getOptHint(pRootNode->pHint, HINT_SKIP_TSMA)) return code; - code = fillTSMAOptCtx(&tsmaOptCtx, pScan); + code = fillTSMAOptCtx(&tsmaOptCtx, pScan, pCxt->pPlanCxt->timezone); if (code == TSDB_CODE_SUCCESS) { // 1. extract useful tsmas code = tsmaOptFilterTsmas(&tsmaOptCtx); @@ -7518,7 +7520,7 @@ static int32_t tsmaOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan // 2. sort useful tsmas with interval taosArraySort(tsmaOptCtx.pUsefulTsmas, tsmaInfoCompWithIntervalDesc); // 3. split windows - code = tsmaOptSplitWindows(&tsmaOptCtx, tsmaOptCtx.pTimeRange); + code = tsmaOptSplitWindows(&tsmaOptCtx, tsmaOptCtx.pTimeRange, pCxt->pPlanCxt->timezone); if (TSDB_CODE_SUCCESS == code && tsmaOptIsUsingTsmas(&tsmaOptCtx)) { // 4. create logic plan code = tsmaOptGeneratePlan(&tsmaOptCtx); diff --git a/source/libs/planner/test/planTestUtil.cpp b/source/libs/planner/test/planTestUtil.cpp index da38a72953..902e254465 100644 --- a/source/libs/planner/test/planTestUtil.cpp +++ b/source/libs/planner/test/planTestUtil.cpp @@ -377,7 +377,7 @@ class PlannerTestBaseImpl { } void doBindParams(SQuery* pQuery, TAOS_MULTI_BIND* pParams, int32_t colIdx) { - DO_WITH_THROW(qStmtBindParams, pQuery, pParams, colIdx); + DO_WITH_THROW(qStmtBindParams, pQuery, pParams, colIdx, NULL); if (colIdx < 0 || pQuery->placeholderNum == colIdx + 1) { res_.boundAst_ = toString(pQuery->pRoot); } diff --git a/source/libs/qcom/src/queryUtil.c b/source/libs/qcom/src/queryUtil.c index 54e92c6a1b..22141c33ee 100644 --- a/source/libs/qcom/src/queryUtil.c +++ b/source/libs/qcom/src/queryUtil.c @@ -397,7 +397,7 @@ int32_t dataConverToStr(char* str, int64_t capacity, int type, void* buf, int32_ } *str = '"'; - int32_t length = taosUcs4ToMbs((TdUcs4*)buf, bufSize, str + 1); + int32_t length = taosUcs4ToMbs((TdUcs4*)buf, bufSize, str + 1, NULL); if (length <= 0) { return TSDB_CODE_TSC_INVALID_VALUE; } @@ -430,7 +430,7 @@ int32_t dataConverToStr(char* str, int64_t capacity, int type, void* buf, int32_ return TSDB_CODE_SUCCESS; } -void parseTagDatatoJson(void* p, char** jsonStr) { +void parseTagDatatoJson(void* p, char** jsonStr, void *charsetCxt) { if (!p || !jsonStr) { qError("parseTagDatatoJson invalid input, line:%d", __LINE__); return; @@ -475,9 +475,10 @@ void parseTagDatatoJson(void* p, char** jsonStr) { if (tagJsonValue == NULL) { goto end; } - int32_t length = taosUcs4ToMbs((TdUcs4*)pTagVal->pData, pTagVal->nData, tagJsonValue); + int32_t length = taosUcs4ToMbs((TdUcs4*)pTagVal->pData, pTagVal->nData, tagJsonValue, charsetCxt); if (length < 0) { - qError("charset:%s to %s. val:%s convert json value failed.", DEFAULT_UNICODE_ENCODEC, tsCharset, + qError("charset:%s to %s. val:%s convert json value failed.", DEFAULT_UNICODE_ENCODEC, + charsetCxt != NULL ? ((SConvInfo *)(charsetCxt))->charset : tsCharset, pTagVal->pData); taosMemoryFree(tagJsonValue); goto end; diff --git a/source/libs/scalar/src/filter.c b/source/libs/scalar/src/filter.c index d8622d93ee..f0325dd174 100644 --- a/source/libs/scalar/src/filter.c +++ b/source/libs/scalar/src/filter.c @@ -2266,7 +2266,7 @@ int32_t fltInitValFieldData(SFilterInfo *info) { // match/nmatch for nchar type need convert from ucs4 to mbs if (type == TSDB_DATA_TYPE_NCHAR && (unit->compare.optr == OP_TYPE_MATCH || unit->compare.optr == OP_TYPE_NMATCH)) { char newValData[TSDB_REGEX_STRING_DEFAULT_LEN * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE] = {0}; - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(fi->data), varDataLen(fi->data), varDataVal(newValData)); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(fi->data), varDataLen(fi->data), varDataVal(newValData), NULL); if (len < 0) { qError("filterInitValFieldData taosUcs4ToMbs error 1"); return TSDB_CODE_SCALAR_CONVERT_ERROR; @@ -3603,7 +3603,7 @@ int32_t filterExecuteImplMisc(void *pinfo, int32_t numOfRows, SColumnInfoData *p if (newColData == NULL) { FLT_ERR_RET(terrno); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(colData), varDataLen(colData), varDataVal(newColData)); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(colData), varDataLen(colData), varDataVal(newColData), NULL); if (len < 0) { qError("castConvert1 taosUcs4ToMbs error"); taosMemoryFreeClear(newColData); @@ -3678,7 +3678,7 @@ int32_t filterExecuteImpl(void *pinfo, int32_t numOfRows, SColumnInfoData *pRes, if (newColData == NULL) { FLT_ERR_RET(terrno); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(colData), varDataLen(colData), varDataVal(newColData)); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(colData), varDataLen(colData), varDataVal(newColData), NULL); if (len < 0) { qError("castConvert1 taosUcs4ToMbs error"); taosMemoryFreeClear(newColData); @@ -4614,7 +4614,7 @@ int32_t filterConverNcharColumns(SFilterInfo *info, int32_t rows, bool *gotNchar varDataCopy(dst, src); continue; } - bool ret = taosMbsToUcs4(varDataVal(src), varDataLen(src), (TdUcs4 *)varDataVal(dst), bufSize, &len); + bool ret = taosMbsToUcs4(varDataVal(src), varDataLen(src), (TdUcs4 *)varDataVal(dst), bufSize, &len, NULL); if (!ret) { qError("filterConverNcharColumns taosMbsToUcs4 error"); return TSDB_CODE_SCALAR_CONVERT_ERROR; @@ -4694,33 +4694,6 @@ EDealRes fltReviseRewriter(SNode **pNode, void *pContext) { stat->scalarMode = true; return DEAL_RES_CONTINUE; } - - /* - if (!FILTER_GET_FLAG(stat->info->options, FLT_OPTION_TIMESTAMP)) { - return DEAL_RES_CONTINUE; - } - - if (TSDB_DATA_TYPE_BINARY != valueNode->node.resType.type && TSDB_DATA_TYPE_NCHAR != - valueNode->node.resType.type && - TSDB_DATA_TYPE_GEOMETRY != valueNode->node.resType.type) { return DEAL_RES_CONTINUE; - } - - if (stat->precision < 0) { - int32_t code = fltAddValueNodeToConverList(stat, valueNode); - if (code) { - stat->code = code; - return DEAL_RES_ERROR; - } - - return DEAL_RES_CONTINUE; - } - - int32_t code = sclConvertToTsValueNode(stat->precision, valueNode); - if (code) { - stat->code = code; - return DEAL_RES_ERROR; - } - */ return DEAL_RES_CONTINUE; } @@ -4887,15 +4860,6 @@ int32_t fltReviseNodes(SFilterInfo *pInfo, SNode **pNode, SFltTreeStat *pStat) { FLT_ERR_JRET(pStat->code); - /* - int32_t nodeNum = taosArrayGetSize(pStat->nodeList); - for (int32_t i = 0; i < nodeNum; ++i) { - SValueNode *valueNode = *(SValueNode **)taosArrayGet(pStat->nodeList, i); - - FLT_ERR_JRET(sclConvertToTsValueNode(pStat->precision, valueNode)); - } - */ - _return: taosArrayDestroy(pStat->nodeList); diff --git a/source/libs/scalar/src/scalar.c b/source/libs/scalar/src/scalar.c index b3610d035f..8c6db7b8ce 100644 --- a/source/libs/scalar/src/scalar.c +++ b/source/libs/scalar/src/scalar.c @@ -24,7 +24,7 @@ int32_t scalarGetOperatorParamNum(EOperatorType type) { int32_t sclConvertToTsValueNode(int8_t precision, SValueNode *valueNode) { char *timeStr = valueNode->datum.p; int64_t value = 0; - int32_t code = convertStringToTimestamp(valueNode->node.resType.type, valueNode->datum.p, precision, &value); + int32_t code = convertStringToTimestamp(valueNode->node.resType.type, valueNode->datum.p, precision, &value, valueNode->tz, valueNode->charsetCxt); //todo tz if (code != TSDB_CODE_SUCCESS) { return code; } @@ -80,7 +80,8 @@ int32_t sclConvertValueToSclParam(SValueNode *pValueNode, SScalarParam *out, int if (code != TSDB_CODE_SUCCESS) { goto _exit; } - + setTzCharset(&in, pValueNode->tz, pValueNode->charsetCxt); + setTzCharset(out, pValueNode->tz, pValueNode->charsetCxt); code = vectorConvertSingleColImpl(&in, out, overflow, -1, -1); _exit: @@ -586,9 +587,11 @@ int32_t sclInitOperatorParams(SScalarParam **pParams, SOperatorNode *node, SScal SCL_ERR_JRET(sclSetOperatorValueType(node, ctx)); SCL_ERR_JRET(sclInitParam(node->pLeft, ¶mList[0], ctx, rowNum)); + setTzCharset(¶mList[0], node->tz, node->charsetCxt); if (paramNum > 1) { TSWAP(ctx->type.selfType, ctx->type.peerType); SCL_ERR_JRET(sclInitParam(node->pRight, ¶mList[1], ctx, rowNum)); + setTzCharset(¶mList[1], node->tz, node->charsetCxt); } *pParams = paramList; @@ -756,6 +759,7 @@ int32_t sclExecFunction(SFunctionNode *node, SScalarCtx *ctx, SScalarParam *outp int32_t paramNum = 0; int32_t code = 0; SCL_ERR_RET(sclInitParamList(¶ms, node->pParameterList, ctx, ¶mNum, &rowNum)); + setTzCharset(params, node->tz, node->charsetCxt); if (fmIsUserDefinedFunc(node->funcId)) { code = callUdfScalarFunc(node->functionName, params, paramNum, output); @@ -958,7 +962,11 @@ int32_t sclExecCaseWhen(SCaseWhenNode *node, SScalarCtx *ctx, SScalarParam *outp sclError("invalid when/then in whenThen list"); SCL_ERR_JRET(TSDB_CODE_INVALID_PARA); } - + setTzCharset(pCase, node->tz, node->charsetCxt); + setTzCharset(pWhen, node->tz, node->charsetCxt); + setTzCharset(pThen, node->tz, node->charsetCxt); + setTzCharset(pElse, node->tz, node->charsetCxt); + setTzCharset(output, node->tz, node->charsetCxt); if (pCase) { SCL_ERR_JRET(vectorCompare(pCase, pWhen, &comp, TSDB_ORDER_ASC, OP_TYPE_EQUAL)); diff --git a/source/libs/scalar/src/sclfunc.c b/source/libs/scalar/src/sclfunc.c index 788ac38d8c..1da9a8f123 100644 --- a/source/libs/scalar/src/sclfunc.c +++ b/source/libs/scalar/src/sclfunc.c @@ -12,8 +12,8 @@ typedef float (*_float_fn_2)(float, float); typedef double (*_double_fn)(double); typedef double (*_double_fn_2)(double, double); typedef int (*_conv_fn)(int); -typedef void (*_trim_space_fn)(char *, char *, int32_t, int32_t); -typedef int32_t (*_trim_fn)(char *, char *, char *, int32_t, int32_t); +typedef void (*_trim_space_fn)(char *, char *, int32_t, int32_t, void*); +typedef int32_t (*_trim_fn)(char *, char *, char *, int32_t, int32_t, void*); typedef int32_t (*_len_fn)(char *, int32_t, VarDataLenT *); /** Math functions **/ @@ -500,7 +500,7 @@ static int32_t tcharlength(char *input, int32_t type, VarDataLenT *len) { return TSDB_CODE_SUCCESS; } -static void tltrimspace(char *input, char *output, int32_t type, int32_t charLen) { +static void tltrimspace(char *input, char *output, int32_t type, int32_t charLen, void* charsetCxt) { int32_t numOfSpaces = 0; if (type == TSDB_DATA_TYPE_VARCHAR) { for (int32_t i = 0; i < charLen; ++i) { @@ -530,7 +530,7 @@ static void tltrimspace(char *input, char *output, int32_t type, int32_t charLen varDataSetLen(output, resLen); } -static void tlrtrimspace(char *input, char *output, int32_t type, int32_t charLen) { +static void tlrtrimspace(char *input, char *output, int32_t type, int32_t charLen, void* charsetCxt) { int32_t numOfLeftSpaces = 0; int32_t numOfRightSpaces = 0; if (type == TSDB_DATA_TYPE_VARCHAR) { @@ -584,7 +584,7 @@ static bool isCharStart(char c) { static int32_t trimHelper(char *orgStr, char* remStr, int32_t orgLen, int32_t remLen, bool trimLeft, bool isNchar) { if (trimLeft) { int32_t pos = 0; - for (int32_t i = 0; i < orgLen; i += remLen) { + for (int32_t i = 0; i < orgLen - remLen; i += remLen) { if (memcmp(orgStr + i, remStr, remLen) == 0) { if (isCharStart(orgStr[i + remLen]) || isNchar) { pos = i + remLen; @@ -615,12 +615,12 @@ static int32_t trimHelper(char *orgStr, char* remStr, int32_t orgLen, int32_t re } } -static int32_t convVarcharToNchar(char *input, char **output, int32_t inputLen, int32_t *outputLen) { +static int32_t convVarcharToNchar(char *input, char **output, int32_t inputLen, int32_t *outputLen, void* charsetCxt) { *output = taosMemoryCalloc(inputLen * TSDB_NCHAR_SIZE, 1); if (NULL == *output) { return terrno; } - bool ret = taosMbsToUcs4(input, inputLen, (TdUcs4 *)*output, inputLen * TSDB_NCHAR_SIZE, outputLen); + bool ret = taosMbsToUcs4(input, inputLen, (TdUcs4 *)*output, inputLen * TSDB_NCHAR_SIZE, outputLen, charsetCxt); if (!ret) { taosMemoryFreeClear(*output); return TSDB_CODE_SCALAR_CONVERT_ERROR; @@ -628,12 +628,12 @@ static int32_t convVarcharToNchar(char *input, char **output, int32_t inputLen, return TSDB_CODE_SUCCESS; } -static int32_t convNcharToVarchar(char *input, char **output, int32_t inputLen, int32_t *outputLen) { +static int32_t convNcharToVarchar(char *input, char **output, int32_t inputLen, int32_t *outputLen, void* charsetCxt) { *output = taosMemoryCalloc(inputLen, 1); if (NULL == *output) { return terrno; } - *outputLen = taosUcs4ToMbs((TdUcs4 *)input, inputLen, *output); + *outputLen = taosUcs4ToMbs((TdUcs4 *)input, inputLen, *output, charsetCxt); if (*outputLen < 0) { taosMemoryFree(*output); return TSDB_CODE_SCALAR_CONVERT_ERROR; @@ -641,14 +641,14 @@ static int32_t convNcharToVarchar(char *input, char **output, int32_t inputLen, return TSDB_CODE_SUCCESS; } -static int32_t convBetweenNcharAndVarchar(char *input, char **output, int32_t inputLen, int32_t *outputLen, int32_t wantType) { +static int32_t convBetweenNcharAndVarchar(char *input, char **output, int32_t inputLen, int32_t *outputLen, int32_t wantType, void* charsetCxt) { if (wantType == TSDB_DATA_TYPE_NCHAR) { - return convVarcharToNchar(input, output, inputLen, outputLen); + return convVarcharToNchar(input, output, inputLen, outputLen, charsetCxt); } else { - return convNcharToVarchar(input, output, inputLen, outputLen); + return convNcharToVarchar(input, output, inputLen, outputLen, charsetCxt); } } -static int32_t tltrim(char *input, char *remInput, char *output, int32_t inputType, int32_t remType) { +static int32_t tltrim(char *input, char *remInput, char *output, int32_t inputType, int32_t remType, void* charsetCxt) { int32_t orgLen = varDataLen(input); char *orgStr = varDataVal(input); int32_t remLen = varDataLen(remInput); @@ -661,7 +661,7 @@ static int32_t tltrim(char *input, char *remInput, char *output, int32_t inputTy bool needFree = false; if (inputType != remType) { - SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(remInput), &remStr, varDataLen(remInput), &remLen, inputType)); + SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(remInput), &remStr, varDataLen(remInput), &remLen, inputType, charsetCxt)); needFree = true; } @@ -683,7 +683,7 @@ static int32_t tltrim(char *input, char *remInput, char *output, int32_t inputTy return TSDB_CODE_SUCCESS; } -static void trtrimspace(char *input, char *output, int32_t type, int32_t charLen) { +static void trtrimspace(char *input, char *output, int32_t type, int32_t charLen, void *charsetCxt) { int32_t numOfSpaces = 0; if (type == TSDB_DATA_TYPE_VARCHAR) { for (int32_t i = charLen - 1; i >= 0; --i) { @@ -712,7 +712,7 @@ static void trtrimspace(char *input, char *output, int32_t type, int32_t charLen varDataSetLen(output, resLen); } -static int32_t trtrim(char *input, char *remInput, char *output, int32_t inputType, int32_t remType) { +static int32_t trtrim(char *input, char *remInput, char *output, int32_t inputType, int32_t remType, void* charsetCxt) { int32_t orgLen = varDataLen(input); char *orgStr = varDataVal(input); int32_t remLen = varDataLen(remInput); @@ -725,7 +725,7 @@ static int32_t trtrim(char *input, char *remInput, char *output, int32_t inputTy bool needFree = false; if (inputType != remType) { - SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(remInput), &remStr, varDataLen(remInput), &remLen, inputType)); + SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(remInput), &remStr, varDataLen(remInput), &remLen, inputType, charsetCxt)); needFree = true; } @@ -746,7 +746,7 @@ static int32_t trtrim(char *input, char *remInput, char *output, int32_t inputTy return TSDB_CODE_SUCCESS; } -static int32_t tlrtrim(char *input, char *remInput, char *output, int32_t inputType, int32_t remType) { +static int32_t tlrtrim(char *input, char *remInput, char *output, int32_t inputType, int32_t remType, void *charsetCxt) { int32_t orgLen = varDataLen(input); char *orgStr = varDataVal(input); int32_t remLen = varDataLen(remInput); @@ -759,7 +759,7 @@ static int32_t tlrtrim(char *input, char *remInput, char *output, int32_t inputT bool needFree = false; if (inputType != remType) { - SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(remInput), &remStr, varDataLen(remInput), &remLen, inputType)); + SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(remInput), &remStr, varDataLen(remInput), &remLen, inputType, charsetCxt)); needFree = true; } @@ -810,14 +810,14 @@ static int32_t doLengthFunction(SScalarParam *pInput, int32_t inputNum, SScalarP return TSDB_CODE_SUCCESS; } -static int32_t concatCopyHelper(const char *input, char *output, bool hasNchar, int32_t type, VarDataLenT *dataLen) { +static int32_t concatCopyHelper(const char *input, char *output, bool hasNchar, int32_t type, VarDataLenT *dataLen, void* charsetCxt) { if (hasNchar && type == TSDB_DATA_TYPE_VARCHAR) { TdUcs4 *newBuf = taosMemoryCalloc((varDataLen(input) + 1) * TSDB_NCHAR_SIZE, 1); if (NULL == newBuf) { return terrno; } int32_t len = varDataLen(input); - bool ret = taosMbsToUcs4(varDataVal(input), len, newBuf, (varDataLen(input) + 1) * TSDB_NCHAR_SIZE, &len); + bool ret = taosMbsToUcs4(varDataVal(input), len, newBuf, (varDataLen(input) + 1) * TSDB_NCHAR_SIZE, &len, charsetCxt); if (!ret) { taosMemoryFree(newBuf); return TSDB_CODE_SCALAR_CONVERT_ERROR; @@ -905,7 +905,7 @@ int32_t concatFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu int32_t rowIdx = (pInput[i].numOfRows == 1) ? 0 : k; input[i] = colDataGetData(pInputData[i], rowIdx); - SCL_ERR_JRET(concatCopyHelper(input[i], output, hasNchar, GET_PARAM_TYPE(&pInput[i]), &dataLen)); + SCL_ERR_JRET(concatCopyHelper(input[i], output, hasNchar, GET_PARAM_TYPE(&pInput[i]), &dataLen, pInput->charsetCxt)); } varDataSetLen(output, dataLen); SCL_ERR_JRET(colDataSetVal(pOutputData, k, outputBuf, false)); @@ -980,12 +980,12 @@ int32_t concatWsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p int32_t rowIdx = (pInput[i].numOfRows == 1) ? 0 : k; - SCL_ERR_JRET(concatCopyHelper(colDataGetData(pInputData[i], rowIdx), output, hasNchar, GET_PARAM_TYPE(&pInput[i]), &dataLen)); + SCL_ERR_JRET(concatCopyHelper(colDataGetData(pInputData[i], rowIdx), output, hasNchar, GET_PARAM_TYPE(&pInput[i]), &dataLen, pInput->charsetCxt)); if (i < inputNum - 1) { // insert the separator char *sep = (pInput[0].numOfRows == 1) ? colDataGetData(pInputData[0], 0) : colDataGetData(pInputData[0], k); - SCL_ERR_JRET(concatCopyHelper(sep, output, hasNchar, GET_PARAM_TYPE(&pInput[0]), &dataLen)); + SCL_ERR_JRET(concatCopyHelper(sep, output, hasNchar, GET_PARAM_TYPE(&pInput[0]), &dataLen, pInput->charsetCxt)); } } @@ -1092,7 +1092,7 @@ static int32_t doTrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarPar continue; } SCL_ERR_JRET(trimFn(colDataGetData(pInputData[1], colIdx2), colDataGetData(pInputData[0], colIdx1), - output, GET_PARAM_TYPE(&pInput[1]), GET_PARAM_TYPE(&pInput[0]))); + output, GET_PARAM_TYPE(&pInput[1]), GET_PARAM_TYPE(&pInput[0]), pInput->charsetCxt)); SCL_ERR_JRET(colDataSetVal(pOutputData, i, output, false)); } } else { @@ -1105,7 +1105,7 @@ static int32_t doTrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarPar char *input = colDataGetData(pInputData[0], i); int32_t len = varDataLen(input); int32_t charLen = (type == TSDB_DATA_TYPE_VARCHAR) ? len : len / TSDB_NCHAR_SIZE; - trimSpaceFn(input, output, type, charLen); + trimSpaceFn(input, output, type, charLen, pInput->charsetCxt); SCL_ERR_JRET(colDataSetVal(pOutputData, i, output, false)); } } @@ -1343,7 +1343,7 @@ int32_t charFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp if (convBuf == NULL) { SCL_ERR_RET(terrno); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(colDataGetData(pInput[j].columnData, colIdx)), varDataLen(colDataGetData(pInput[j].columnData, colIdx)), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(colDataGetData(pInput[j].columnData, colIdx)), varDataLen(colDataGetData(pInput[j].columnData, colIdx)), convBuf, pInput->charsetCxt); if (len < 0) { taosMemoryFree(convBuf); code = TSDB_CODE_SCALAR_CONVERT_ERROR; @@ -1386,7 +1386,7 @@ int32_t asciiFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOut int32_t inLen = varDataLen(colDataGetData(pInputData, i)); SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(colDataGetData(pInputData, i)), &in, varDataLen(colDataGetData(pInputData, i)), &inLen, - TSDB_DATA_TYPE_VARBINARY)); + TSDB_DATA_TYPE_VARBINARY, pInput->charsetCxt)); out[i] = (uint8_t)(in)[0]; taosMemoryFree(in); } else { @@ -1454,7 +1454,9 @@ int32_t positionFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p int32_t orgLen = varDataLen(colDataGetData(pInputData[1], colIdx2)); bool needFreeSub = false; if (GET_PARAM_TYPE(&pInput[1]) != GET_PARAM_TYPE(&pInput[0])) { - SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(colDataGetData(pInputData[0], colIdx1)), &substr, varDataLen(colDataGetData(pInputData[0], colIdx1)), &subLen, GET_PARAM_TYPE(&pInput[1]))); + SCL_ERR_RET(convBetweenNcharAndVarchar(varDataVal(colDataGetData(pInputData[0], colIdx1)), &substr, + varDataLen(colDataGetData(pInputData[0], colIdx1)), &subLen, + GET_PARAM_TYPE(&pInput[1]), pInput->charsetCxt)); needFreeSub = true; } @@ -1562,13 +1564,13 @@ int32_t replaceFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pO if (GET_PARAM_TYPE(&pInput[1]) != GET_PARAM_TYPE(&pInput[0])) { SCL_ERR_JRET(convBetweenNcharAndVarchar(varDataVal(colDataGetData(pInputData[1], colIdx2)), &fromStr, varDataLen(colDataGetData(pInputData[1], colIdx2)), &fromLen, - GET_PARAM_TYPE(&pInput[0]))); + GET_PARAM_TYPE(&pInput[0]), pInput->charsetCxt)); needFreeFrom = true; } if (GET_PARAM_TYPE(&pInput[2]) != GET_PARAM_TYPE(&pInput[0])) { code = convBetweenNcharAndVarchar(varDataVal(colDataGetData(pInputData[2], colIdx3)), &toStr, varDataLen(colDataGetData(pInputData[2], colIdx3)), &toLen, - GET_PARAM_TYPE(&pInput[0])); + GET_PARAM_TYPE(&pInput[0]), pInput->charsetCxt); if (TSDB_CODE_SUCCESS != code) { if (needFreeFrom) { taosMemoryFree(fromStr); @@ -1674,7 +1676,7 @@ int32_t substrIdxFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam * if (GET_PARAM_TYPE(&pInput[0]) != GET_PARAM_TYPE(&pInput[1])) { SCL_ERR_JRET(convBetweenNcharAndVarchar(varDataVal(colDataGetData(pInputData[1], colIdx2)), &delimStr, varDataLen(colDataGetData(pInputData[1], colIdx2)), &delimLen, - GET_PARAM_TYPE(&pInput[0]))); + GET_PARAM_TYPE(&pInput[0]), pInput->charsetCxt)); needFreeDelim = true; } @@ -1853,7 +1855,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(int8_t *)output = taosStr2Int8(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1872,7 +1874,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(int16_t *)output = taosStr2Int16(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1890,7 +1892,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(int32_t *)output = taosStr2Int32(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1909,7 +1911,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(int64_t *)output = taosStr2Int64(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1927,7 +1929,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(uint8_t *)output = taosStr2UInt8(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1945,7 +1947,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(uint16_t *)output = taosStr2UInt16(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1963,7 +1965,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(uint32_t *)output = taosStr2UInt32(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -1981,7 +1983,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(uint64_t *)output = taosStr2UInt64(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2000,7 +2002,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(float *)output = taosStr2Float(buf, NULL); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2018,7 +2020,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(double *)output = taosStr2Double(buf, NULL); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2036,7 +2038,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp buf[varDataLen(input)] = 0; *(bool *)output = taosStr2Int8(buf, NULL, 10); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2053,7 +2055,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp if (inputType == TSDB_DATA_TYPE_BINARY || inputType == TSDB_DATA_TYPE_NCHAR) { int64_t timePrec; GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData); - int32_t ret = convertStringToTimestamp(inputType, input, timePrec, &timeVal); + int32_t ret = convertStringToTimestamp(inputType, input, timePrec, &timeVal, pInput->tz, pInput->charsetCxt); if (ret != TSDB_CODE_SUCCESS) { *(int64_t *)output = 0; } else { @@ -2076,7 +2078,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp (void)memcpy(varDataVal(output), varDataVal(input), len); varDataSetLen(output, len); } else if (inputType == TSDB_DATA_TYPE_NCHAR) { - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf, pInput->charsetCxt); if (len < 0) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2111,7 +2113,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp if (inputType == TSDB_DATA_TYPE_BOOL) { char tmp[8] = {0}; len = tsnprintf(tmp, sizeof(tmp), "%.*s", outputCharLen, *(int8_t *)input ? "true" : "false"); - bool ret = taosMbsToUcs4(tmp, len, (TdUcs4 *)varDataVal(output), outputLen - VARSTR_HEADER_SIZE, &len); + bool ret = taosMbsToUcs4(tmp, len, (TdUcs4 *)varDataVal(output), outputLen - VARSTR_HEADER_SIZE, &len, pInput->charsetCxt); if (!ret) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2121,7 +2123,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp } else if (inputType == TSDB_DATA_TYPE_BINARY) { len = outputCharLen > varDataLen(input) ? varDataLen(input) : outputCharLen; bool ret = taosMbsToUcs4(input + VARSTR_HEADER_SIZE, len, (TdUcs4 *)varDataVal(output), - outputLen - VARSTR_HEADER_SIZE, &len); + outputLen - VARSTR_HEADER_SIZE, &len, pInput->charsetCxt); if (!ret) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2135,7 +2137,7 @@ int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutp NUM_TO_STRING(inputType, input, bufSize, buf); len = (int32_t)strlen(buf); len = outputCharLen > len ? len : outputCharLen; - bool ret = taosMbsToUcs4(buf, len, (TdUcs4 *)varDataVal(output), outputLen - VARSTR_HEADER_SIZE, &len); + bool ret = taosMbsToUcs4(buf, len, (TdUcs4 *)varDataVal(output), outputLen - VARSTR_HEADER_SIZE, &len, pInput->charsetCxt); if (!ret) { code = TSDB_CODE_SCALAR_CONVERT_ERROR; goto _end; @@ -2240,17 +2242,14 @@ int32_t toISO8601Function(SScalarParam *pInput, int32_t inputNum, SScalarParam * if (0 != offsetOfTimezone(tz, &offset)) { goto _end; } - quot -= offset + 3600 * ((int64_t)tsTimezone); + quot -= offset; struct tm tmInfo; - int32_t len = 0; - - if (taosLocalTime((const time_t *)", &tmInfo, buf, sizeof(buf)) == NULL) { - len = (int32_t)strlen(buf); + if (taosGmTimeR((const time_t *)", &tmInfo) == NULL) { goto _end; } - len = (int32_t)strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &tmInfo); + int32_t len = (int32_t)taosStrfTime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &tmInfo); len += tsnprintf(buf + len, fractionLen, format, mod); @@ -2260,10 +2259,10 @@ int32_t toISO8601Function(SScalarParam *pInput, int32_t inputNum, SScalarParam * len += tzLen; } -_end: memmove(buf + VARSTR_HEADER_SIZE, buf, len); varDataSetLen(buf, len); + _end: SCL_ERR_RET(colDataSetVal(pOutput->columnData, i, buf, false)); } @@ -2286,7 +2285,7 @@ int32_t toUnixtimestampFunction(SScalarParam *pInput, int32_t inputNum, SScalarP char *input = colDataGetData(pInput[0].columnData, i); int64_t timeVal = 0; - int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal); + int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal, pInput->tz, pInput->charsetCxt); if (ret != TSDB_CODE_SUCCESS) { colDataSetNULL(pOutput->columnData, i); } else { @@ -2326,7 +2325,7 @@ int32_t toJsonFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOu } (void)memcpy(tmp, varDataVal(input), varDataLen(input)); tmp[varDataLen(input)] = 0; - if (parseJsontoTagData(tmp, pTagVals, &pTag, NULL)) { + if (parseJsontoTagData(tmp, pTagVals, &pTag, NULL, pInput->charsetCxt)) { code = tTagNew(pTagVals, 1, true, &pTag); if (TSDB_CODE_SUCCESS != code) { tTagFree(pTag); @@ -2381,7 +2380,7 @@ int32_t toTimestampFunction(SScalarParam* pInput, int32_t inputNum, SScalarParam } int32_t precision = pOutput->columnData->info.precision; char errMsg[128] = {0}; - code = taosChar2Ts(format, &formats, tsStr, &ts, precision, errMsg, 128); + code = taosChar2Ts(format, &formats, tsStr, &ts, precision, errMsg, 128, pInput->tz); if (code) { qError("func to_timestamp failed %s", errMsg); SCL_ERR_JRET(code); @@ -2424,7 +2423,7 @@ int32_t toCharFunction(SScalarParam* pInput, int32_t inputNum, SScalarParam* pOu } } int32_t precision = pInput[0].columnData->info.precision; - SCL_ERR_JRET(taosTs2Char(format, &formats, *(int64_t *)ts, precision, varDataVal(out), TS_FORMAT_MAX_LEN)); + SCL_ERR_JRET(taosTs2Char(format, &formats, *(int64_t *)ts, precision, varDataVal(out), TS_FORMAT_MAX_LEN, pInput->tz)); varDataSetLen(out, strlen(varDataVal(out))); SCL_ERR_JRET(colDataSetVal(pOutput->columnData, i, out, false)); } @@ -2437,11 +2436,11 @@ _return: } /** Time functions **/ -int64_t offsetFromTz(char *timezone, int64_t factor) { - char *minStr = &timezone[3]; +int64_t offsetFromTz(char *timezoneStr, int64_t factor) { + char *minStr = &timezoneStr[3]; int64_t minutes = taosStr2Int64(minStr, NULL, 10); (void)memset(minStr, 0, strlen(minStr)); - int64_t hours = taosStr2Int64(timezone, NULL, 10); + int64_t hours = taosStr2Int64(timezoneStr, NULL, 10); int64_t seconds = hours * 3600 + minutes * 60; return seconds * factor; @@ -2453,7 +2452,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara int64_t timeUnit, timePrec, timeVal = 0; bool ignoreTz = true; - char timezone[20] = {0}; + char timezoneStr[20] = {0}; GET_TYPED_DATA(timeUnit, int64_t, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData); @@ -2465,7 +2464,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara } GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[timePrecIdx]), pInput[timePrecIdx].columnData->pData); - (void)memcpy(timezone, varDataVal(pInput[timeZoneIdx].columnData->pData), varDataLen(pInput[timeZoneIdx].columnData->pData)); + (void)memcpy(timezoneStr, varDataVal(pInput[timeZoneIdx].columnData->pData), varDataLen(pInput[timeZoneIdx].columnData->pData)); for (int32_t i = 0; i < pInput[0].numOfRows; ++i) { if (colDataIsNull_s(pInput[0].columnData, i)) { @@ -2476,7 +2475,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara char *input = colDataGetData(pInput[0].columnData, i); if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */ - int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal); + int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal, pInput->tz, pInput->charsetCxt); if (ret != TSDB_CODE_SUCCESS) { colDataSetNULL(pOutput->columnData, i); continue; @@ -2493,7 +2492,7 @@ int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarPara // truncate the timestamp to time_unit precision int64_t seconds = timeUnit / TSDB_TICK_PER_SECOND(timePrec); if (ignoreTz && (seconds == 604800 || seconds == 86400)) { - timeVal = timeVal - (timeVal + offsetFromTz(timezone, TSDB_TICK_PER_SECOND(timePrec))) % timeUnit; + timeVal = timeVal - (timeVal + offsetFromTz(timezoneStr, TSDB_TICK_PER_SECOND(timePrec))) % timeUnit; } else { timeVal = timeVal / timeUnit * timeUnit; } @@ -2536,7 +2535,7 @@ int32_t timeDiffFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *p int32_t type = GET_PARAM_TYPE(&pInput[k]); if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */ - int32_t ret = convertStringToTimestamp(type, input[k], TSDB_TIME_PRECISION_NANO, &timeVal[k]); + int32_t ret = convertStringToTimestamp(type, input[k], TSDB_TIME_PRECISION_NANO, &timeVal[k], pInput->tz, pInput->charsetCxt); if (ret != TSDB_CODE_SUCCESS) { hasNull = true; break; @@ -2655,7 +2654,7 @@ int32_t todayFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOut int64_t timePrec; GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[0]), pInput[0].columnData->pData); - int64_t ts = taosGetTimestampToday(timePrec); + int64_t ts = taosGetTimestampToday(timePrec, pInput->tz); for (int32_t i = 0; i < pInput->numOfRows; ++i) { colDataSetInt64(pOutput->columnData, i, &ts); } @@ -2663,14 +2662,20 @@ int32_t todayFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOut return TSDB_CODE_SUCCESS; } -int32_t timeZoneStrLen() { - return sizeof(VarDataLenT) + strlen(tsTimezoneStr); -} - int32_t timezoneFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) { char output[TD_TIMEZONE_LEN + VARSTR_HEADER_SIZE] = {0}; - (void)memcpy(varDataVal(output), tsTimezoneStr, TD_TIMEZONE_LEN); - varDataSetLen(output, strlen(tsTimezoneStr)); + char* tmp = NULL; + if (pInput->tz == NULL) { + (void)memcpy(varDataVal(output), tsTimezoneStr, TD_TIMEZONE_LEN); + } else{ + char *tzName = (char*)taosHashGet(pTimezoneNameMap, &pInput->tz, sizeof(timezone_t)); + if (tzName == NULL){ + tzName = TZ_UNKNOWN; + } + tstrncpy(varDataVal(output), tzName, strlen(tzName) + 1); + } + + varDataSetLen(output, strlen(varDataVal(output))); for (int32_t i = 0; i < pInput->numOfRows; ++i) { SCL_ERR_RET(colDataSetVal(pOutput->columnData, i, output, false)); } @@ -2694,7 +2699,7 @@ int32_t weekdayFunctionImpl(SScalarParam *pInput, int32_t inputNum, SScalarParam char *input = colDataGetData(pInput[0].columnData, i); if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */ - int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal); + int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal, pInput->tz, pInput->charsetCxt); if (ret != TSDB_CODE_SUCCESS) { colDataSetNULL(pOutput->columnData, i); continue; @@ -2705,7 +2710,7 @@ int32_t weekdayFunctionImpl(SScalarParam *pInput, int32_t inputNum, SScalarParam GET_TYPED_DATA(timeVal, int64_t, type, input); } struct STm tm; - TAOS_CHECK_RETURN(taosTs2Tm(timeVal, timePrec, &tm)); + TAOS_CHECK_RETURN(taosTs2Tm(timeVal, timePrec, &tm, pInput->tz)); int64_t ret = startFromZero ? (tm.tm.tm_wday + 6) % 7 : tm.tm.tm_wday + 1; colDataSetInt64(pOutput->columnData, i, &ret); } @@ -2804,7 +2809,7 @@ int32_t weekFunctionImpl(SScalarParam *pInput, int32_t inputNum, SScalarParam *p char *input = colDataGetData(pInput[0].columnData, i); if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */ - int32_t ret = convertStringToTimestamp(type, input, prec, &timeVal); + int32_t ret = convertStringToTimestamp(type, input, prec, &timeVal, pInput->tz, pInput->charsetCxt); if (ret != TSDB_CODE_SUCCESS) { colDataSetNULL(pOutput->columnData, i); continue; @@ -2815,7 +2820,7 @@ int32_t weekFunctionImpl(SScalarParam *pInput, int32_t inputNum, SScalarParam *p GET_TYPED_DATA(timeVal, int64_t, type, input); } struct STm tm; - SCL_ERR_RET(taosTs2Tm(timeVal, prec, &tm)); + SCL_ERR_RET(taosTs2Tm(timeVal, prec, &tm, pInput->tz)); int64_t ret = calculateWeekNum(tm.tm, weekMode(mode)); colDataSetInt64(pOutput->columnData, i, &ret); } diff --git a/source/libs/scalar/src/sclvector.c b/source/libs/scalar/src/sclvector.c index c6c8333392..393bb947cf 100644 --- a/source/libs/scalar/src/sclvector.c +++ b/source/libs/scalar/src/sclvector.c @@ -103,7 +103,7 @@ int32_t convertNcharToDouble(const void *inData, void *outData) { if (NULL == tmp) { SCL_ERR_RET(terrno); } - int len = taosUcs4ToMbs((TdUcs4 *)varDataVal(inData), varDataLen(inData), tmp); + int len = taosUcs4ToMbs((TdUcs4 *)varDataVal(inData), varDataLen(inData), tmp, NULL); if (len < 0) { sclError("castConvert taosUcs4ToMbs error 1"); SCL_ERR_JRET(TSDB_CODE_SCALAR_CONVERT_ERROR); @@ -242,7 +242,7 @@ int32_t getVectorBigintValueFn(int32_t srcType, _getBigintValue_fn_t *p) { static FORCE_INLINE int32_t varToTimestamp(char *buf, SScalarParam *pOut, int32_t rowIndex, int32_t *overflow) { int64_t value = 0; int32_t code = TSDB_CODE_SUCCESS; - if (taosParseTime(buf, &value, strlen(buf), pOut->columnData->info.precision, tsDaylight) != TSDB_CODE_SUCCESS) { + if (taosParseTime(buf, &value, strlen(buf), pOut->columnData->info.precision, pOut->tz) != TSDB_CODE_SUCCESS) { value = 0; code = TSDB_CODE_SCALAR_CONVERT_ERROR; } @@ -404,7 +404,7 @@ static FORCE_INLINE int32_t varToNchar(char *buf, SScalarParam *pOut, int32_t ro SCL_ERR_RET(terrno); } int32_t ret = - taosMbsToUcs4(varDataVal(buf), inputLen, (TdUcs4 *)varDataVal(t), outputMaxLen - VARSTR_HEADER_SIZE, &len); + taosMbsToUcs4(varDataVal(buf), inputLen, (TdUcs4 *)varDataVal(t), outputMaxLen - VARSTR_HEADER_SIZE, &len, pOut->charsetCxt); if (!ret) { sclError("failed to convert to NCHAR"); SCL_ERR_JRET(TSDB_CODE_SCALAR_CONVERT_ERROR); @@ -426,7 +426,7 @@ static FORCE_INLINE int32_t ncharToVar(char *buf, SScalarParam *pOut, int32_t ro if (NULL == t) { SCL_ERR_RET(terrno); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(buf), varDataLen(buf), varDataVal(t)); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(buf), varDataLen(buf), varDataVal(t), pOut->charsetCxt); if (len < 0) { SCL_ERR_JRET(TSDB_CODE_SCALAR_CONVERT_ERROR); } @@ -557,7 +557,7 @@ int32_t vectorConvertFromVarData(SSclVectorConvCtx *pCtx, int32_t *overflow) { SCL_ERR_JRET(TSDB_CODE_APP_ERROR); } - int len = taosUcs4ToMbs((TdUcs4 *)varDataVal(data), varDataLen(data), tmp); + int len = taosUcs4ToMbs((TdUcs4 *)varDataVal(data), varDataLen(data), tmp, pCtx->pIn->charsetCxt); if (len < 0) { sclError("castConvert taosUcs4ToMbs error 1"); SCL_ERR_JRET(TSDB_CODE_SCALAR_CONVERT_ERROR); @@ -592,18 +592,19 @@ int32_t getVectorDoubleValue_JSON(void *src, int32_t index, double *out) { SCL_RET(TSDB_CODE_SUCCESS); } -int32_t ncharTobinary(void *buf, void **out) { // todo need to remove , if tobinary is nchar +int32_t ncharTobinary(void *buf, void **out, void* charsetCxt) { // todo need to remove , if tobinary is nchar int32_t inputLen = varDataTLen(buf); *out = taosMemoryCalloc(1, inputLen); if (NULL == *out) { sclError("charset:%s to %s. val:%s convert ncharTobinary failed, since memory alloc failed.", - DEFAULT_UNICODE_ENCODEC, tsCharset, (char *)varDataVal(buf)); + DEFAULT_UNICODE_ENCODEC, charsetCxt != NULL ? ((SConvInfo *)(charsetCxt))->charset : tsCharset, (char *)varDataVal(buf)); SCL_ERR_RET(terrno); } - int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(buf), varDataLen(buf), varDataVal(*out)); + int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(buf), varDataLen(buf), varDataVal(*out), charsetCxt); if (len < 0) { - sclError("charset:%s to %s. val:%s convert ncharTobinary failed.", DEFAULT_UNICODE_ENCODEC, tsCharset, + sclError("charset:%s to %s. val:%s convert ncharTobinary failed.", DEFAULT_UNICODE_ENCODEC, + charsetCxt != NULL ? ((SConvInfo *)(charsetCxt))->charset : tsCharset, (char *)varDataVal(buf)); taosMemoryFree(*out); SCL_ERR_RET(TSDB_CODE_SCALAR_CONVERT_ERROR); @@ -614,7 +615,7 @@ int32_t ncharTobinary(void *buf, void **out) { // todo need to remove , if tobi int32_t convertJsonValue(__compar_fn_t *fp, int32_t optr, int8_t typeLeft, int8_t typeRight, char **pLeftData, char **pRightData, void *pLeftOut, void *pRightOut, bool *isNull, bool *freeLeft, - bool *freeRight, bool *result) { + bool *freeRight, bool *result, void* charsetCxt) { *result = false; if (optr == OP_TYPE_JSON_CONTAINS) { *result = true; @@ -700,13 +701,13 @@ int32_t convertJsonValue(__compar_fn_t *fp, int32_t optr, int8_t typeLeft, int8_ type == TSDB_DATA_TYPE_GEOMETRY) { if (typeLeft == TSDB_DATA_TYPE_NCHAR) { char *tmpLeft = NULL; - SCL_ERR_RET(ncharTobinary(*pLeftData, (void *)&tmpLeft)); + SCL_ERR_RET(ncharTobinary(*pLeftData, (void *)&tmpLeft, charsetCxt)); *pLeftData = tmpLeft; *freeLeft = true; } if (typeRight == TSDB_DATA_TYPE_NCHAR) { char *tmpRight = NULL; - SCL_ERR_RET(ncharTobinary(*pRightData, (void *)&tmpRight)); + SCL_ERR_RET(ncharTobinary(*pRightData, (void *)&tmpRight, charsetCxt)); *pRightData = tmpRight; *freeRight = true; } @@ -1191,7 +1192,7 @@ static int32_t vectorMathAddHelper(SColumnInfoData *pLeftCol, SColumnInfoData *p } static int32_t vectorMathTsAddHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pRightCol, SColumnInfoData *pOutputCol, - int32_t numOfRows, int32_t step, int32_t i) { + int32_t numOfRows, int32_t step, int32_t i, timezone_t tz) { _getBigintValue_fn_t getVectorBigintValueFnLeft; _getBigintValue_fn_t getVectorBigintValueFnRight; SCL_ERR_RET(getVectorBigintValueFn(pLeftCol->info.type, &getVectorBigintValueFnLeft)); @@ -1211,7 +1212,7 @@ static int32_t vectorMathTsAddHelper(SColumnInfoData *pLeftCol, SColumnInfoData SCL_ERR_RET(getVectorBigintValueFnLeft(pLeftCol->pData, i, &leftRes)); SCL_ERR_RET(getVectorBigintValueFnRight(pRightCol->pData, 0, &rightRes)); *output = - taosTimeAdd(leftRes, rightRes, pRightCol->info.scale, pRightCol->info.precision); + taosTimeAdd(leftRes, rightRes, pRightCol->info.scale, pRightCol->info.precision, tz); } } SCL_RET(TSDB_CODE_SUCCESS); @@ -1275,14 +1276,14 @@ int32_t vectorMathAdd(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *p if (pLeft->numOfRows == 1 && pRight->numOfRows == 1) { if (GET_PARAM_TYPE(pLeft) == TSDB_DATA_TYPE_TIMESTAMP) { - SCL_ERR_JRET(vectorMathTsAddHelper(pLeftCol, pRightCol, pOutputCol, pRight->numOfRows, step, i)); + SCL_ERR_JRET(vectorMathTsAddHelper(pLeftCol, pRightCol, pOutputCol, pRight->numOfRows, step, i, pLeft->tz)); } else { - SCL_ERR_JRET(vectorMathTsAddHelper(pRightCol, pLeftCol, pOutputCol, pRight->numOfRows, step, i)); + SCL_ERR_JRET(vectorMathTsAddHelper(pRightCol, pLeftCol, pOutputCol, pRight->numOfRows, step, i, pLeft->tz)); } } else if (pLeft->numOfRows == 1) { - SCL_ERR_JRET(vectorMathTsAddHelper(pRightCol, pLeftCol, pOutputCol, pRight->numOfRows, step, i)); + SCL_ERR_JRET(vectorMathTsAddHelper(pRightCol, pLeftCol, pOutputCol, pRight->numOfRows, step, i, pLeft->tz)); } else if (pRight->numOfRows == 1) { - SCL_ERR_JRET(vectorMathTsAddHelper(pLeftCol, pRightCol, pOutputCol, pLeft->numOfRows, step, i)); + SCL_ERR_JRET(vectorMathTsAddHelper(pLeftCol, pRightCol, pOutputCol, pLeft->numOfRows, step, i, pLeft->tz)); } else if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { @@ -1356,7 +1357,7 @@ static int32_t vectorMathSubHelper(SColumnInfoData *pLeftCol, SColumnInfoData *p } static int32_t vectorMathTsSubHelper(SColumnInfoData *pLeftCol, SColumnInfoData *pRightCol, SColumnInfoData *pOutputCol, - int32_t numOfRows, int32_t step, int32_t factor, int32_t i) { + int32_t numOfRows, int32_t step, int32_t factor, int32_t i, timezone_t tz) { _getBigintValue_fn_t getVectorBigintValueFnLeft; _getBigintValue_fn_t getVectorBigintValueFnRight; SCL_ERR_RET(getVectorBigintValueFn(pLeftCol->info.type, &getVectorBigintValueFnLeft)); @@ -1377,7 +1378,7 @@ static int32_t vectorMathTsSubHelper(SColumnInfoData *pLeftCol, SColumnInfoData SCL_ERR_RET(getVectorBigintValueFnLeft(pLeftCol->pData, i, &leftRes)); SCL_ERR_RET(getVectorBigintValueFnRight(pRightCol->pData, 0, &rightRes)); *output = - taosTimeAdd(leftRes, -rightRes, pRightCol->info.scale, pRightCol->info.precision) * factor; + taosTimeAdd(leftRes, -rightRes, pRightCol->info.scale, pRightCol->info.precision, tz) * factor; } } SCL_RET(TSDB_CODE_SUCCESS); @@ -1408,11 +1409,11 @@ int32_t vectorMathSub(SScalarParam *pLeft, SScalarParam *pRight, SScalarParam *p SCL_ERR_JRET(getVectorBigintValueFn(pRightCol->info.type, &getVectorBigintValueFnRight)); if (pLeft->numOfRows == 1 && pRight->numOfRows == 1) { - SCL_ERR_JRET(vectorMathTsSubHelper(pLeftCol, pRightCol, pOutputCol, pLeft->numOfRows, step, 1, i)); + SCL_ERR_JRET(vectorMathTsSubHelper(pLeftCol, pRightCol, pOutputCol, pLeft->numOfRows, step, 1, i, pLeft->tz)); } else if (pLeft->numOfRows == 1) { - SCL_ERR_JRET(vectorMathTsSubHelper(pRightCol, pLeftCol, pOutputCol, pRight->numOfRows, step, -1, i)); + SCL_ERR_JRET(vectorMathTsSubHelper(pRightCol, pLeftCol, pOutputCol, pRight->numOfRows, step, -1, i, pLeft->tz)); } else if (pRight->numOfRows == 1) { - SCL_ERR_JRET(vectorMathTsSubHelper(pLeftCol, pRightCol, pOutputCol, pLeft->numOfRows, step, 1, i)); + SCL_ERR_JRET(vectorMathTsSubHelper(pLeftCol, pRightCol, pOutputCol, pLeft->numOfRows, step, 1, i, pLeft->tz)); } else if (pLeft->numOfRows == pRight->numOfRows) { for (; i < pRight->numOfRows && i >= 0; i += step, output += 1) { if (IS_NULL) { @@ -1958,7 +1959,7 @@ int32_t doVectorCompareImpl(SScalarParam *pLeft, SScalarParam *pRight, SScalarPa bool result = false; SCL_ERR_RET(convertJsonValue(&fp, optr, GET_PARAM_TYPE(pLeft), GET_PARAM_TYPE(pRight), &pLeftData, &pRightData, - &leftOut, &rightOut, &isJsonnull, &freeLeft, &freeRight, &result)); + &leftOut, &rightOut, &isJsonnull, &freeLeft, &freeRight, &result, pLeft->charsetCxt)); if (isJsonnull) { sclError("doVectorCompareImpl: invalid json null value"); @@ -2042,6 +2043,8 @@ int32_t vectorCompareImpl(SScalarParam *pLeft, SScalarParam *pRight, SScalarPara SScalarParam *param1 = NULL; SScalarParam *param2 = NULL; int32_t code = TSDB_CODE_SUCCESS; + setTzCharset(&pLeftOut, pLeft->tz, pLeft->charsetCxt); + setTzCharset(&pRightOut, pLeft->tz, pLeft->charsetCxt); if (noConvertBeforeCompare(GET_PARAM_TYPE(pLeft), GET_PARAM_TYPE(pRight), optr)) { param1 = pLeft; param2 = pRight; diff --git a/source/libs/scalar/test/scalar/scalarTests.cpp b/source/libs/scalar/test/scalar/scalarTests.cpp index 4cab644582..6a5188f208 100644 --- a/source/libs/scalar/test/scalar/scalarTests.cpp +++ b/source/libs/scalar/test/scalar/scalarTests.cpp @@ -1450,7 +1450,7 @@ TEST(columnTest, json_column_arith_op) { SArray *tags = taosArrayInit(1, sizeof(STagVal)); ASSERT_NE(tags, nullptr); STag *row = NULL; - int32_t code = parseJsontoTagData(rightv, tags, &row, NULL); + int32_t code = parseJsontoTagData(rightv, tags, &row, NULL, NULL); ASSERT_EQ(code, TSDB_CODE_SUCCESS); const int32_t len = 8; @@ -1606,7 +1606,7 @@ void *prepareNchar(char *rightData) { int32_t inputLen = strlen(rightData); char *t = (char *)taosMemoryCalloc(1, (inputLen + 1) * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); - taosMbsToUcs4(rightData, inputLen, (TdUcs4 *)varDataVal(t), inputLen * TSDB_NCHAR_SIZE, &len); + taosMbsToUcs4(rightData, inputLen, (TdUcs4 *)varDataVal(t), inputLen * TSDB_NCHAR_SIZE, &len, NULL); varDataSetLen(t, len); return t; } @@ -1623,7 +1623,7 @@ TEST(columnTest, json_column_logic_op) { SArray *tags = taosArrayInit(1, sizeof(STagVal)); ASSERT_NE(tags, nullptr); STag *row = NULL; - code = parseJsontoTagData(rightv, tags, &row, NULL); + code = parseJsontoTagData(rightv, tags, &row, NULL, NULL); ASSERT_EQ(code, TSDB_CODE_SUCCESS); const int32_t len0 = 6; diff --git a/source/libs/sync/src/syncUtil.c b/source/libs/sync/src/syncUtil.c index 65c7f9761e..0fedd96e4c 100644 --- a/source/libs/sync/src/syncUtil.c +++ b/source/libs/sync/src/syncUtil.c @@ -62,7 +62,7 @@ bool syncUtilNodeInfo2RaftId(const SNodeInfo* pInfo, SyncGroupId vgId, SRaftId* } char ipbuf[TD_IP_LEN] = {0}; - tinet_ntoa(ipbuf, ipv4); + taosInetNtoa(ipbuf, ipv4); raftId->addr = SYNC_ADDR(pInfo); raftId->vgId = vgId; diff --git a/source/libs/sync/test/sync_test_lib/src/syncIO.c b/source/libs/sync/test/sync_test_lib/src/syncIO.c index f5a32b98d9..088a82a009 100644 --- a/source/libs/sync/test/sync_test_lib/src/syncIO.c +++ b/source/libs/sync/test/sync_test_lib/src/syncIO.c @@ -520,7 +520,7 @@ void syncUtilU642Addr(uint64_t u64, char *host, int64_t len, uint16_t *port) { uint32_t hostU32 = (uint32_t)((u64 >> 32) & 0x00000000FFFFFFFF); struct in_addr addr = {.s_addr = hostU32}; - taosInetNtoa(addr, host, len); + taosInetNtop(addr, host, len); *port = (uint16_t)((u64 & 0x00000000FFFF0000) >> 16); } diff --git a/source/libs/transport/src/thttp.c b/source/libs/transport/src/thttp.c index bdcbfeb1cd..0c0f723b8b 100644 --- a/source/libs/transport/src/thttp.c +++ b/source/libs/transport/src/thttp.c @@ -224,7 +224,7 @@ static FORCE_INLINE int32_t taosBuildDstAddr(const char* server, uint16_t port, return TSDB_CODE_RPC_FQDN_ERROR; } char buf[TD_IP_LEN] = {0}; - tinet_ntoa(buf, ip); + taosInetNtoa(buf, ip); int ret = uv_ip4_addr(buf, port, dest); if (ret != 0) { tError("http-report failed to get addr, reason:%s", uv_err_name(ret)); diff --git a/source/libs/transport/src/transCli.c b/source/libs/transport/src/transCli.c index a90c546796..ed84404d05 100644 --- a/source/libs/transport/src/transCli.c +++ b/source/libs/transport/src/transCli.c @@ -1862,8 +1862,8 @@ static FORCE_INLINE int32_t cliUpdateFqdnCache(SHashObj* cache, char* fqdn) { if (v != NULL) { if (addr != *v) { char old[TSDB_FQDN_LEN] = {0}, new[TSDB_FQDN_LEN] = {0}; - tinet_ntoa(old, *v); - tinet_ntoa(new, addr); + taosInetNtoa(old, *v); + taosInetNtoa(new, addr); tWarn("update ip of fqdn:%s, old: %s, new: %s", fqdn, old, new); code = taosHashPut(cache, fqdn, len, &addr, sizeof(addr)); } diff --git a/source/os/CMakeLists.txt b/source/os/CMakeLists.txt index 32609301a9..96deaa4196 100644 --- a/source/os/CMakeLists.txt +++ b/source/os/CMakeLists.txt @@ -1,5 +1,11 @@ aux_source_directory(src OS_SRC) -add_library(os STATIC ${OS_SRC}) +if(NOT ${TD_WINDOWS}) + add_definitions(-DTHREAD_SAFE=1) + aux_source_directory(src/timezone OS_TZ) + add_library(os STATIC ${OS_SRC} ${OS_TZ}) +else() + add_library(os STATIC ${OS_SRC}) +endif(NOT ${TD_WINDOWS}) target_include_directories( os PUBLIC "${TD_SOURCE_DIR}/include/os" @@ -70,6 +76,11 @@ IF (JEMALLOC_ENABLED) target_link_libraries(os PUBLIC -L${CMAKE_BINARY_DIR}/build/lib -ljemalloc) ENDIF () +#if(NOT ${TD_WINDOWS}) +# find_library(tz libtz.a "${TD_SOURCE_DIR}/contrib/tz") +# target_link_libraries(os PUBLIC ${tz}) +#endif(NOT ${TD_WINDOWS}) + if(${BUILD_TEST}) add_subdirectory(test) endif(${BUILD_TEST}) diff --git a/source/os/src/osEnv.c b/source/os/src/osEnv.c index 832deb574d..d5ed46cf9e 100644 --- a/source/os/src/osEnv.c +++ b/source/os/src/osEnv.c @@ -25,10 +25,9 @@ SDiskSpace tsLogSpace = {0}; SDiskSpace tsTempSpace = {0}; char tsOsName[16] = {0}; char tsTimezoneStr[TD_TIMEZONE_LEN] = {0}; -enum TdTimezone tsTimezone = TdZeroZone; char tsLocale[TD_LOCALE_LEN] = {0}; char tsCharset[TD_CHARSET_LEN] = {0}; -int8_t tsDaylight = 0; +void *tsCharsetCxt = NULL; bool tsEnableCoreFile = 1; int64_t tsPageSizeKB = 0; int64_t tsOpenMax = 0; @@ -49,14 +48,7 @@ int32_t osDefaultInit() { taosSeedRand(taosSafeRand()); taosGetSystemLocale(tsLocale, tsCharset); - code = taosGetSystemTimezone(tsTimezoneStr, &tsTimezone); - if(code != 0) { - return code; - } - if (strlen(tsTimezoneStr) > 0) { // ignore empty timezone - if ((code = taosSetSystemTimezone(tsTimezoneStr, tsTimezoneStr, &tsDaylight, &tsTimezone)) != TSDB_CODE_SUCCESS) - return code; - } + (void)taosGetSystemTimezone(tsTimezoneStr); taosGetSystemInfo(); @@ -124,12 +116,7 @@ bool osDataSpaceSufficient() { return tsDataSpace.size.avail > tsDataSpace.reser bool osTempSpaceSufficient() { return tsTempSpace.size.avail > tsTempSpace.reserved; } -int32_t osSetTimezone(const char *tz) { return taosSetSystemTimezone(tz, tsTimezoneStr, &tsDaylight, &tsTimezone); } - -void osSetSystemLocale(const char *inLocale, const char *inCharSet) { - if (inLocale) (void)memcpy(tsLocale, inLocale, strlen(inLocale) + 1); - if (inCharSet) (void)memcpy(tsCharset, inCharSet, strlen(inCharSet) + 1); -} +int32_t osSetTimezone(const char *tz) { return taosSetGlobalTimezone(tz); } void osSetProcPath(int32_t argc, char **argv) { if (argv == NULL || argc < 1) { diff --git a/source/os/src/osLocale.c b/source/os/src/osLocale.c index 21f781c7e4..cb0a2646fd 100644 --- a/source/os/src/osLocale.c +++ b/source/os/src/osLocale.c @@ -78,19 +78,17 @@ char *taosCharsetReplace(char *charsetstr) { * * In case that the setLocale failed to be executed, the right charset needs to be set. */ -int32_t taosSetSystemLocale(const char *inLocale, const char *inCharSet) { - OS_PARAM_CHECK(inLocale); - OS_PARAM_CHECK(inCharSet); - if (!taosValidateEncodec(inCharSet)) { - return terrno; - } +int32_t taosSetSystemLocale(const char *inLocale) { char *locale = setlocale(LC_CTYPE, inLocale); if (NULL == locale) { terrno = TSDB_CODE_INVALID_PARA; + uError("failed to set locale:%s", inLocale); return terrno; } + (void)memcpy(tsLocale, inLocale, strlen(inLocale) + 1); + return 0; } @@ -102,59 +100,6 @@ void taosGetSystemLocale(char *outLocale, char *outCharset) { tstrncpy(outLocale, locale, TD_LOCALE_LEN); } tstrncpy(outCharset, "UTF-8", TD_CHARSET_LEN); - -#elif defined(_TD_DARWIN_64) - /* - * originally from src/os/src/detail/osSysinfo.c - * POSIX format locale string: - * (Language Strings)_(Country/Region Strings).(code_page) - * - * example: en_US.UTF-8, zh_CN.GB18030, zh_CN.UTF-8, - * - * if user does not specify the locale in taos.cfg the program use default LC_CTYPE as system locale. - * - * In case of some CentOS systems, their default locale is "en_US.utf8", which is not valid code_page - * for libiconv that is employed to convert string in this system. This program will automatically use - * UTF-8 instead as the charset. - * - * In case of windows client, the locale string is not valid POSIX format, user needs to set the - * correct code_page for libiconv. Usually, the code_page of windows system with simple chinese is - * CP936, CP437 for English charset. - * - */ - - char sep = '.'; - char *locale = NULL; - - locale = setlocale(LC_CTYPE, ""); - if (locale == NULL) { - // printf("can't get locale from system, set it to en_US.UTF-8 since error:%d:%s", errno, strerror(errno)); - tstrncpy(outLocale, "en_US.UTF-8", TD_LOCALE_LEN); - } else { - tstrncpy(outLocale, locale, TD_LOCALE_LEN); - // printf("locale not configured, set to system default:%s", outLocale); - } - - /* if user does not specify the charset, extract it from locale */ - char *str = strrchr(outLocale, sep); - if (str != NULL) { - str++; - - char *revisedCharset = taosCharsetReplace(str); - - if (NULL == revisedCharset) { - tstrncpy(outCharset, "UTF-8", TD_CHARSET_LEN); - } else { - tstrncpy(outCharset, revisedCharset, TD_CHARSET_LEN); - - taosMemoryFree(revisedCharset); - } - // printf("charset not configured, set to system default:%s", outCharset); - } else { - tstrncpy(outCharset, "UTF-8", TD_CHARSET_LEN); - // printf("can't get locale and charset from system, set it to UTF-8"); - } - #else /* * POSIX format locale string: diff --git a/source/os/src/osSocket.c b/source/os/src/osSocket.c index 9433a76469..3051005789 100644 --- a/source/os/src/osSocket.c +++ b/source/os/src/osSocket.c @@ -150,7 +150,7 @@ int32_t taosSetSockOpt(TdSocketPtr pSocket, int32_t level, int32_t optname, void #endif } -const char *taosInetNtoa(struct in_addr ipInt, char *dstStr, int32_t len) { +const char *taosInetNtop(struct in_addr ipInt, char *dstStr, int32_t len) { const char *r = inet_ntop(AF_INET, &ipInt, dstStr, len); if (NULL == r) { terrno = TAOS_SYSTEM_ERROR(errno); @@ -396,11 +396,19 @@ int32_t taosGetFqdn(char *fqdn) { return 0; } -void tinet_ntoa(char *ipstr, uint32_t ip) { +void taosInetNtoa(char *ipstr, uint32_t ip) { if (ipstr == NULL) { return; } - (void)snprintf(ipstr, TD_IP_LEN, "%d.%d.%d.%d", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, ip >> 24); + unsigned char *bytes = (unsigned char *) &ip; + (void)snprintf(ipstr, TD_IP_LEN, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]); +} + +uint32_t taosInetAddr(const char *ipstr){ + if (ipstr == NULL) { + return 0; + } + return inet_addr(ipstr); } int32_t taosIgnSIGPIPE() { diff --git a/source/os/src/osString.c b/source/os/src/osString.c index 0ee4f1c496..1ae8ac2a28 100644 --- a/source/os/src/osString.c +++ b/source/os/src/osString.c @@ -229,80 +229,25 @@ int32_t tasoUcs4Copy(TdUcs4 *target_ucs4, TdUcs4 *source_ucs4, int32_t len_ucs4) return TSDB_CODE_SUCCESS; } -typedef struct { - iconv_t conv; - int8_t inUse; -} SConv; - -// 0: Mbs --> Ucs4 -// 1: Ucs4--> Mbs -SConv *gConv[2] = {NULL, NULL}; -int32_t convUsed[2] = {0, 0}; -int32_t gConvMaxNum[2] = {0, 0}; - -int32_t taosConvInit(void) { - int8_t M2C = 0; - gConvMaxNum[M2C] = 512; - gConvMaxNum[1 - M2C] = 512; - - gConv[M2C] = taosMemoryCalloc(gConvMaxNum[M2C], sizeof(SConv)); - if (gConv[M2C] == NULL) { - return terrno; - } - - gConv[1 - M2C] = taosMemoryCalloc(gConvMaxNum[1 - M2C], sizeof(SConv)); - if (gConv[1 - M2C] == NULL) { - taosMemoryFree(gConv[M2C]); - return terrno; - } - - for (int32_t i = 0; i < gConvMaxNum[M2C]; ++i) { - gConv[M2C][i].conv = iconv_open(DEFAULT_UNICODE_ENCODEC, tsCharset); - if ((iconv_t)-1 == gConv[M2C][i].conv) { - terrno = TAOS_SYSTEM_ERROR(errno); - return terrno; - } - } - for (int32_t i = 0; i < gConvMaxNum[1 - M2C]; ++i) { - gConv[1 - M2C][i].conv = iconv_open(tsCharset, DEFAULT_UNICODE_ENCODEC); - if ((iconv_t)-1 == gConv[1 - M2C][i].conv) { - terrno = TAOS_SYSTEM_ERROR(errno); - return terrno; - } - } - - return 0; -} - -void taosConvDestroy() { - int8_t M2C = 0; - for (int32_t i = 0; i < gConvMaxNum[M2C]; ++i) { - (void)iconv_close(gConv[M2C][i].conv); - } - for (int32_t i = 0; i < gConvMaxNum[1 - M2C]; ++i) { - (void)iconv_close(gConv[1 - M2C][i].conv); - } - taosMemoryFreeClear(gConv[M2C]); - taosMemoryFreeClear(gConv[1 - M2C]); - gConvMaxNum[M2C] = -1; - gConvMaxNum[1 - M2C] = -1; -} - -iconv_t taosAcquireConv(int32_t *idx, ConvType type) { +iconv_t taosAcquireConv(int32_t *idx, ConvType type, void* charsetCxt) { if(idx == NULL) { terrno = TSDB_CODE_INVALID_PARA; return (iconv_t)-1; } - if (gConvMaxNum[type] <= 0) { + if (charsetCxt == NULL){ + charsetCxt = tsCharsetCxt; + } + SConvInfo *info = (SConvInfo *)charsetCxt; + if (info == NULL) { *idx = -1; if (type == M2C) { - iconv_t c = iconv_open(DEFAULT_UNICODE_ENCODEC, tsCharset); + iconv_t c = iconv_open(DEFAULT_UNICODE_ENCODEC, "UTF-8"); if ((iconv_t)-1 == c) { terrno = TAOS_SYSTEM_ERROR(errno); } return c; } else { - iconv_t c = iconv_open(tsCharset, DEFAULT_UNICODE_ENCODEC); + iconv_t c = iconv_open("UTF-8", DEFAULT_UNICODE_ENCODEC); if ((iconv_t)-1 == c) { terrno = TAOS_SYSTEM_ERROR(errno); } @@ -311,9 +256,9 @@ iconv_t taosAcquireConv(int32_t *idx, ConvType type) { } while (true) { - int32_t used = atomic_add_fetch_32(&convUsed[type], 1); - if (used > gConvMaxNum[type]) { - used = atomic_sub_fetch_32(&convUsed[type], 1); + int32_t used = atomic_add_fetch_32(&info->convUsed[type], 1); + if (used > info->gConvMaxNum[type]) { + (void)atomic_sub_fetch_32(&info->convUsed[type], 1); (void)sched_yield(); continue; } @@ -321,38 +266,43 @@ iconv_t taosAcquireConv(int32_t *idx, ConvType type) { break; } - int32_t startId = taosGetSelfPthreadId() % gConvMaxNum[type]; + int32_t startId = taosGetSelfPthreadId() % info->gConvMaxNum[type]; while (true) { - if (gConv[type][startId].inUse) { - startId = (startId + 1) % gConvMaxNum[type]; + if (info->gConv[type][startId].inUse) { + startId = (startId + 1) % info->gConvMaxNum[type]; continue; } - int8_t old = atomic_val_compare_exchange_8(&gConv[type][startId].inUse, 0, 1); + int8_t old = atomic_val_compare_exchange_8(&info->gConv[type][startId].inUse, 0, 1); if (0 == old) { break; } } *idx = startId; - if ((iconv_t)0 == gConv[type][startId].conv) { + if ((iconv_t)0 == info->gConv[type][startId].conv) { return (iconv_t)-1; } else { - return gConv[type][startId].conv; + return info->gConv[type][startId].conv; } } -void taosReleaseConv(int32_t idx, iconv_t conv, ConvType type) { +void taosReleaseConv(int32_t idx, iconv_t conv, ConvType type, void* charsetCxt) { if (idx < 0) { (void)iconv_close(conv); return; } - atomic_store_8(&gConv[type][idx].inUse, 0); - (void)atomic_sub_fetch_32(&convUsed[type], 1); + if (charsetCxt == NULL){ + charsetCxt = tsCharsetCxt; + } + SConvInfo *info = (SConvInfo *)charsetCxt; + + atomic_store_8(&info->gConv[type][idx].inUse, 0); + (void)atomic_sub_fetch_32(&info->convUsed[type], 1); } -bool taosMbsToUcs4(const char *mbs, size_t mbsLength, TdUcs4 *ucs4, int32_t ucs4_max_len, int32_t *len) { +bool taosMbsToUcs4(const char *mbs, size_t mbsLength, TdUcs4 *ucs4, int32_t ucs4_max_len, int32_t *len, void* charsetCxt) { if (ucs4_max_len == 0) { return true; } @@ -368,20 +318,22 @@ bool taosMbsToUcs4(const char *mbs, size_t mbsLength, TdUcs4 *ucs4, int32_t ucs4 (void)memset(ucs4, 0, ucs4_max_len); int32_t idx = -1; - iconv_t conv = taosAcquireConv(&idx, M2C); + iconv_t conv = taosAcquireConv(&idx, M2C, charsetCxt); if ((iconv_t)-1 == conv) { return false; } - + size_t ucs4_input_len = mbsLength; size_t outLeft = ucs4_max_len; if (iconv(conv, (char **)&mbs, &ucs4_input_len, (char **)&ucs4, &outLeft) == -1) { + char buf[512] = {0}; + snprintf(buf, tListLen(buf), " taosMbsToUcs4 error:%s %d %d", strerror(terrno), errno, EILSEQ); terrno = TAOS_SYSTEM_ERROR(errno); - taosReleaseConv(idx, conv, M2C); + taosReleaseConv(idx, conv, M2C, charsetCxt); return false; } - taosReleaseConv(idx, conv, M2C); + taosReleaseConv(idx, conv, M2C, charsetCxt); if (len != NULL) { *len = (int32_t)(ucs4_max_len - outLeft); if (*len < 0) { @@ -397,7 +349,7 @@ bool taosMbsToUcs4(const char *mbs, size_t mbsLength, TdUcs4 *ucs4, int32_t ucs4 // if success, return the number of bytes written to mbs ( >= 0) // otherwise return error code ( < 0) -int32_t taosUcs4ToMbs(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs) { +int32_t taosUcs4ToMbs(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs, void* charsetCxt) { if (ucs4_max_len == 0) { return 0; } @@ -413,22 +365,22 @@ int32_t taosUcs4ToMbs(TdUcs4 *ucs4, int32_t ucs4_max_len, char *mbs) { int32_t idx = -1; int32_t code = 0; - iconv_t conv = taosAcquireConv(&idx, C2M); + iconv_t conv = taosAcquireConv(&idx, C2M, charsetCxt); if ((iconv_t)-1 == conv) { return terrno; } - + size_t ucs4_input_len = ucs4_max_len; size_t outLen = ucs4_max_len; if (iconv(conv, (char **)&ucs4, &ucs4_input_len, &mbs, &outLen) == -1) { code = TAOS_SYSTEM_ERROR(errno); - taosReleaseConv(idx, conv, C2M); - terrno = code; + taosReleaseConv(idx, conv, C2M, charsetCxt); + terrno = code; return code; } - - taosReleaseConv(idx, conv, C2M); - + + taosReleaseConv(idx, conv, C2M, charsetCxt); + return (int32_t)(ucs4_max_len - outLen); #endif } diff --git a/source/os/src/osTime.c b/source/os/src/osTime.c index 60339fc646..29cbcaeb2c 100644 --- a/source/os/src/osTime.c +++ b/source/os/src/osTime.c @@ -345,6 +345,12 @@ char *taosStrpTime(const char *buf, const char *fmt, struct tm *tm) { #endif } +size_t +taosStrfTime(char *s, size_t maxsize, char const *format, struct tm const *t){ + if (!s || !format || !t) return 0; + return strftime(s, maxsize, format, t); +} + int32_t taosGetTimeOfDay(struct timeval *tv) { if (tv == NULL) { return TSDB_CODE_INVALID_PARA; @@ -420,68 +426,53 @@ int64_t user_mktime64(const uint32_t year, const uint32_t mon, const uint32_t da return _res + time_zone; } -time_t taosMktime(struct tm *timep) { +time_t taosMktime(struct tm *timep, timezone_t tz) { #ifdef WINDOWS -#if 0 - struct tm tm1 = {0}; - LARGE_INTEGER t; - FILETIME f; - SYSTEMTIME s; - FILETIME ff; - SYSTEMTIME ss; - LARGE_INTEGER offset; - - time_t tt = 0; - localtime_s(&tm1, &tt); - ss.wYear = tm1.tm_year + 1900; - ss.wMonth = tm1.tm_mon + 1; - ss.wDay = tm1.tm_mday; - ss.wHour = tm1.tm_hour; - ss.wMinute = tm1.tm_min; - ss.wSecond = tm1.tm_sec; - ss.wMilliseconds = 0; - SystemTimeToFileTime(&ss, &ff); - offset.QuadPart = ff.dwHighDateTime; - offset.QuadPart <<= 32; - offset.QuadPart |= ff.dwLowDateTime; - - s.wYear = timep->tm_year + 1900; - s.wMonth = timep->tm_mon + 1; - s.wDay = timep->tm_mday; - s.wHour = timep->tm_hour; - s.wMinute = timep->tm_min; - s.wSecond = timep->tm_sec; - s.wMilliseconds = 0; - SystemTimeToFileTime(&s, &f); - t.QuadPart = f.dwHighDateTime; - t.QuadPart <<= 32; - t.QuadPart |= f.dwLowDateTime; - - t.QuadPart -= offset.QuadPart; - return (time_t)(t.QuadPart / 10000000); -#else time_t result = mktime(timep); if (result != -1) { return result; } -#ifdef _MSC_VER -#if _MSC_VER >= 1900 - int64_t tz = _timezone; -#endif -#endif + int64_t tzw = 0; + #ifdef _MSC_VER + #if _MSC_VER >= 1900 + tzw = _timezone; + #endif + #endif return user_mktime64(timep->tm_year + 1900, timep->tm_mon + 1, timep->tm_mday, timep->tm_hour, timep->tm_min, - timep->tm_sec, tz); -#endif + timep->tm_sec, tzw); #else - time_t r = mktime(timep); + time_t r = tz != NULL ? mktime_z(tz, timep) : mktime(timep); if (r == (time_t)-1) { terrno = TAOS_SYSTEM_ERROR(errno); } + timezone = -timep->tm_gmtoff; return r; #endif } -struct tm *taosLocalTime(const time_t *timep, struct tm *result, char *buf, int32_t bufSize) { +struct tm *taosGmTimeR(const time_t *timep, struct tm *result){ + if (timep == NULL || result == NULL) { + return NULL; + } +#ifdef WINDOWS + return gmtime_s(result, timep); +#else + return gmtime_r(timep, result); +#endif +} + +time_t taosTimeGm(struct tm *tmp){ + if (tmp == NULL) { + return -1; + } +#ifdef WINDOWS + return _mkgmtime(tmp); +#else + return timegm(tmp); +#endif +} + +struct tm *taosLocalTime(const time_t *timep, struct tm *result, char *buf, int32_t bufSize, timezone_t tz) { struct tm *res = NULL; if (timep == NULL || result == NULL) { return NULL; @@ -537,118 +528,15 @@ struct tm *taosLocalTime(const time_t *timep, struct tm *result, char *buf, int3 return NULL; } } + return result; #else - res = localtime_r(timep, result); + res = tz != NULL ? localtime_rz(tz, timep, result): localtime_r(timep, result); if (res == NULL && buf != NULL) { (void)snprintf(buf, bufSize, "NaN"); } + timezone = -result->tm_gmtoff; + return res; #endif - return result; -} - -static int isLeapYear(time_t year) { - if (year % 4) - return 0; - else if (year % 100) - return 1; - else if (year % 400) - return 0; - else - return 1; -} - -struct tm *taosLocalTimeNolock(struct tm *result, const time_t *timep, int dst) { - if (result == NULL) { - return NULL; - } -#ifdef WINDOWS - if (*timep < 0) { - return NULL; - // TODO: bugs in following code - SYSTEMTIME ss, s; - FILETIME ff, f; - LARGE_INTEGER offset; - struct tm tm1; - time_t tt = 0; - if (localtime_s(&tm1, &tt) != 0) { - return NULL; - } - ss.wYear = tm1.tm_year + 1900; - ss.wMonth = tm1.tm_mon + 1; - ss.wDay = tm1.tm_mday; - ss.wHour = tm1.tm_hour; - ss.wMinute = tm1.tm_min; - ss.wSecond = tm1.tm_sec; - ss.wMilliseconds = 0; - SystemTimeToFileTime(&ss, &ff); - offset.QuadPart = ff.dwHighDateTime; - offset.QuadPart <<= 32; - offset.QuadPart |= ff.dwLowDateTime; - offset.QuadPart += *timep * 10000000; - f.dwLowDateTime = offset.QuadPart & 0xffffffff; - f.dwHighDateTime = (offset.QuadPart >> 32) & 0xffffffff; - FileTimeToSystemTime(&f, &s); - result->tm_sec = s.wSecond; - result->tm_min = s.wMinute; - result->tm_hour = s.wHour; - result->tm_mday = s.wDay; - result->tm_mon = s.wMonth - 1; - result->tm_year = s.wYear - 1900; - result->tm_wday = s.wDayOfWeek; - result->tm_yday = 0; - result->tm_isdst = 0; - } else { - if (localtime_s(result, timep) != 0) { - return NULL; - } - } -#elif defined(LINUX) - time_t secsMin = 60, secsHour = 3600, secsDay = 3600 * 24; - long tz = timezone; - - time_t t = *timep; - t -= tz; /* Adjust for timezone. */ - t += 3600 * dst; /* Adjust for daylight time. */ - time_t days = t / secsDay; /* Days passed since epoch. */ - time_t seconds = t % secsDay; /* Remaining seconds. */ - - result->tm_isdst = dst; - result->tm_hour = seconds / secsHour; - result->tm_min = (seconds % secsHour) / secsMin; - result->tm_sec = (seconds % secsHour) % secsMin; - - /* 1/1/1970 was a Thursday, that is, day 4 from the POV of the tm structure - * where sunday = 0, so to calculate the day of the week we have to add 4 - * and take the modulo by 7. */ - result->tm_wday = (days + 4) % 7; - - /* Calculate the current year. */ - result->tm_year = 1970; - while (1) { - /* Leap years have one day more. */ - time_t daysOfYear = 365 + isLeapYear(result->tm_year); - if (daysOfYear > days) break; - days -= daysOfYear; - result->tm_year++; - } - result->tm_yday = days; /* Number of day of the current year. */ - /* We need to calculate in which month and day of the month we are. To do - * so we need to skip days according to how many days there are in each - * month, and adjust for the leap year that has one more day in February. */ - int mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - mdays[1] += isLeapYear(result->tm_year); - result->tm_mon = 0; - while (days >= mdays[result->tm_mon]) { - days -= mdays[result->tm_mon]; - result->tm_mon++; - } - - result->tm_mday = days + 1; /* Add 1 since our 'days' is zero-based. */ - result->tm_year -= 1900; /* Surprisingly tm_year is year-1900. */ -#else - localtime_r(timep, result); -#endif - return result; } int32_t taosGetTimestampSec() { return (int32_t)time(NULL); } diff --git a/source/os/src/osTimezone.c b/source/os/src/osTimezone.c index 89c7ce9e31..395c1cbb82 100644 --- a/source/os/src/osTimezone.c +++ b/source/os/src/osTimezone.c @@ -33,7 +33,8 @@ #include #pragma warning(pop) -char *win_tz[139][2] = {{"China Standard Time", "Asia/Shanghai"}, +#define W_TZ_NUM 139 +char *win_tz[W_TZ_NUM][2] = {{"China Standard Time", "Asia/Shanghai"}, {"AUS Central Standard Time", "Australia/Darwin"}, {"AUS Eastern Standard Time", "Australia/Sydney"}, {"Afghanistan Standard Time", "Asia/Kabul"}, @@ -172,7 +173,8 @@ char *win_tz[139][2] = {{"China Standard Time", "Asia/Shanghai"}, {"West Pacific Standard Time", "Pacific/Port_Moresby"}, {"Yakutsk Standard Time", "Asia/Yakutsk"}, {"Yukon Standard Time", "America/Whitehorse"}}; -char *tz_win[554][2] = {{"Asia/Shanghai", "China Standard Time"}, +#define W_TZ_CITY_NUM 554 +char *tz_win[W_TZ_CITY_NUM][2] = {{"Asia/Shanghai", "China Standard Time"}, {"Africa/Abidjan", "Greenwich Standard Time"}, {"Africa/Accra", "Greenwich Standard Time"}, {"Africa/Addis_Ababa", "E. Africa Standard Time"}, @@ -740,51 +742,19 @@ char *tz_win[554][2] = {{"Asia/Shanghai", "China Standard Time"}, #include #endif -static int isdst_now = 0; - -void parseTimeStr(char *p, char to[5]) { - for (int i = 0; i < 5; ++i) { - if (strlen(p) > i) { - to[i] = p[i]; - } else { - to[i] = '0'; - } - } - if (strlen(p) == 2) { - to[1] = '0'; - to[2] = p[1]; - } -} - -int32_t taosSetSystemTimezone(const char *inTimezoneStr, char *outTimezoneStr, int8_t *outDaylight, - enum TdTimezone *tsTimezone) { - if (inTimezoneStr == NULL || inTimezoneStr[0] == 0) { +int32_t taosSetGlobalTimezone(const char *tz) { + if (tz == NULL) { terrno = TSDB_CODE_INVALID_PARA; return terrno; } - int32_t code = TSDB_CODE_SUCCESS; - size_t len = strlen(inTimezoneStr); - if (len >= TD_TIMEZONE_LEN) { - terrno = TSDB_CODE_INVALID_PARA; - return terrno; - } - char buf[TD_TIMEZONE_LEN] = {0}; - for (int32_t i = 0; i < len; i++) { - if (inTimezoneStr[i] == ' ' || inTimezoneStr[i] == '(') { - buf[i] = 0; - break; - } - buf[i] = inTimezoneStr[i]; - } - + uDebug("[tz]set timezone to %s", tz) #ifdef WINDOWS - char winStr[TD_LOCALE_LEN * 2]; - memset(winStr, 0, sizeof(winStr)); - for (size_t i = 0; i < 554; i++) { - if (strcmp(tz_win[i][0], buf) == 0) { - char keyPath[256]; - char keyValue[100]; + char winStr[TD_TIMEZONE_LEN * 2] = {0}; + for (size_t i = 0; i < W_TZ_CITY_NUM; i++) { + if (strcmp(tz_win[i][0], tz) == 0) { + char keyPath[256] = {0}; + char keyValue[100] = {0}; DWORD keyValueSize = sizeof(keyValue); snprintf(keyPath, sizeof(keyPath), "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\%s", tz_win[i][1]); RegGetValue(HKEY_LOCAL_MACHINE, keyPath, "Display", RRF_RT_ANY, NULL, (PVOID)&keyValue, &keyValueSize); @@ -792,90 +762,127 @@ int32_t taosSetSystemTimezone(const char *inTimezoneStr, char *outTimezoneStr, i keyValue[4] = (keyValue[4] == '+' ? '-' : '+'); keyValue[10] = 0; snprintf(winStr, sizeof(winStr), "TZ=%s:00", &(keyValue[1])); - *tsTimezone = -taosStr2Int32(&keyValue[4], NULL, 10); } break; } } - if (winStr[0] == 0) { - char *p = strchr(inTimezoneStr, '+'); - if (p == NULL) p = strchr(inTimezoneStr, '-'); - if (p != NULL) { - char *pp = strchr(inTimezoneStr, '('); - char *ppp = strchr(inTimezoneStr, ','); - int indexStr; - if (pp == NULL || ppp == NULL) { - indexStr = tsnprintf(winStr, sizeof(winStr), "TZ=UTC"); - } else { - memcpy(winStr, "TZ=", 3); - pp++; - memcpy(&winStr[3], pp, ppp - pp); - indexStr = ppp - pp + 3; - } - char to[5]; - parseTimeStr(p, to); - snprintf(&winStr[indexStr], sizeof(winStr) - indexStr, "%c%c%c:%c%c:00", (to[0] == '+' ? '+' : '-'), to[1], to[2], to[3], to[4]); - *tsTimezone = -taosStr2Int32(p, NULL, 10); - } else { - *tsTimezone = 0; - } - } + _putenv(winStr); _tzset(); - if (outTimezoneStr != inTimezoneStr) { - tstrncpy(outTimezoneStr, inTimezoneStr, TD_TIMEZONE_LEN); - } - *outDaylight = 0; - -#elif defined(_TD_DARWIN_64) - - code = setenv("TZ", buf, 1); - if (-1 == code) { - terrno = TAOS_SYSTEM_ERROR(errno); - return terrno; - } - tzset(); - int32_t tz = (int32_t)((-timezone * MILLISECOND_PER_SECOND) / MILLISECOND_PER_HOUR); - *tsTimezone = tz; - tz += isdst_now; - - snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (%s, %s%02d00)", buf, tzname[isdst_now], tz >= 0 ? "+" : "-", abs(tz)); - *outDaylight = isdst_now; - #else - code = setenv("TZ", buf, 1); + code = setenv("TZ", tz, 1); if (-1 == code) { terrno = TAOS_SYSTEM_ERROR(errno); return terrno; } tzset(); - int32_t tz = (int32_t)((-timezone * MILLISECOND_PER_SECOND) / MILLISECOND_PER_HOUR); - *tsTimezone = tz; - tz += isdst_now; - (void)snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (%s, %s%02d00)", buf, tzname[isdst_now], tz >= 0 ? "+" : "-", abs(tz)); - *outDaylight = isdst_now; - #endif - return code; + time_t tx1 = taosGetTimestampSec(); + return taosFormatTimezoneStr(tx1, tz, NULL, tsTimezoneStr); } -int32_t taosGetSystemTimezone(char *outTimezoneStr, enum TdTimezone *tsTimezone) { - int32_t code = 0; +int32_t taosGetLocalTimezoneOffset() { + time_t tx1 = taosGetTimestampSec(); + struct tm tm1; + if (taosLocalTime(&tx1, &tm1, NULL, 0, NULL) == NULL) { + uError("%s failed to get local time: code:%d", __FUNCTION__, errno); + return TSDB_CODE_TIME_ERROR; + } #ifdef WINDOWS - char value[100]; - char keyPath[100]; + return -_timezone; +#else + return (int32_t)(tm1.tm_gmtoff); +#endif +} + +int32_t taosFormatTimezoneStr(time_t t, const char* tz, timezone_t sp, char *outTimezoneStr){ + struct tm tm1; + if (taosLocalTime(&t, &tm1, NULL, 0, sp) == NULL) { + uError("%s failed to get local time: code:%d", __FUNCTION__, errno); + return TSDB_CODE_TIME_ERROR; + } + + /* + * format example: + * + * Asia/Shanghai (CST, +0800) + * Europe/London (BST, +0100) + * n/a (UTC, +0000) + */ + + char str1[TD_TIMEZONE_LEN] = {0}; + if (taosStrfTime(str1, sizeof(str1), "%Z", &tm1) == 0){ + uError("failed to get timezone name"); + return TSDB_CODE_TIME_ERROR; + } + + char str2[TD_TIMEZONE_LEN] = {0}; + if (taosStrfTime(str2, sizeof(str2), "%z", &tm1) == 0){ + uError("failed to get timezone offset"); + return TSDB_CODE_TIME_ERROR; + } + (void)snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (%s, %s)", tz, str1, str2); + uDebug("[tz] system timezone:%s", outTimezoneStr); + return 0; +} + +#ifndef WINDOWS +void getTimezoneStr(char *tz) { + do { + int n = readlink("/etc/localtime", tz, TD_TIMEZONE_LEN - 1); + if (n < 0) { + uWarn("[tz] failed to readlink /etc/localtime, reason:%s", strerror(errno)); + break; + } + + char *zi = strstr(tz, "zoneinfo"); + if (zi == NULL) { + uWarn("[tz] failed to find zoneinfo in /etc/localtime"); + break; + } + zi += sizeof("zoneinfo"); + memmove(tz, zi, TD_TIMEZONE_LEN - (zi - tz)); + goto END; + } while (0); + + + TdFilePtr pFile = taosOpenFile("/etc/timezone", TD_FILE_READ); + if (pFile == NULL) { + uWarn("[tz] failed to open /etc/timezone, reason:%s", strerror(errno)); + goto END; + } + int len = taosReadFile(pFile, tz, TD_TIMEZONE_LEN - 1); + TAOS_UNUSED(taosCloseFile(&pFile)); + if (len <= 0) { + uWarn("[tz] failed to read /etc/timezone, len:%d", len); + goto END; + } + if (tz[len - 1] == '\n') { + tz[len - 1] = '\0'; + } + +END: + if (tz[0] == '\0') { + memcpy(tz, TZ_UNKNOWN, sizeof(TZ_UNKNOWN)); + } + uDebug("[tz] system timezone:%s", tz); +} +#endif + +int32_t taosGetSystemTimezone(char *outTimezoneStr) { +#ifdef WINDOWS + char value[100] = {0}; + char keyPath[100] = {0}; DWORD bufferSize = sizeof(value); LONG result = RegGetValue(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", "TimeZoneKeyName", RRF_RT_ANY, NULL, (PVOID)&value, &bufferSize); if (result != ERROR_SUCCESS) { return TAOS_SYSTEM_WINAPI_ERROR(result); } - tstrncpy(outTimezoneStr, "not configured", TD_TIMEZONE_LEN); - *tsTimezone = 0; if (bufferSize > 0) { - for (size_t i = 0; i < 139; i++) { + for (size_t i = 0; i < W_TZ_NUM; i++) { if (strcmp(win_tz[i][0], value) == 0) { tstrncpy(outTimezoneStr, win_tz[i][1], TD_TIMEZONE_LEN); bufferSize = sizeof(value); @@ -884,172 +891,19 @@ int32_t taosGetSystemTimezone(char *outTimezoneStr, enum TdTimezone *tsTimezone) if (result != ERROR_SUCCESS) { return TAOS_SYSTEM_WINAPI_ERROR(result); } - if (bufferSize > 0) { - // value[4] = (value[4] == '+' ? '-' : '+'); - snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (UTC, %c%c%c%c%c)", outTimezoneStr, value[4], value[5], value[6], value[8], - value[9]); - *tsTimezone = taosStr2Int32(&value[4], NULL, 10); + if (bufferSize > 0) { // value like (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi + snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (UTC, %c%c%c%c%c)", outTimezoneStr, + value[4], value[5], value[6], value[8], value[9]); } break; } } } return 0; -#elif defined(_TD_DARWIN_64) - char buf[4096] = {0}; - char *tz = NULL; - { - int n = readlink("/etc/localtime", buf, sizeof(buf)); - if (n < 0) { - return TSDB_CODE_TIME_ERROR; - } - buf[n] = '\0'; - - char *zi = strstr(buf, "zoneinfo"); - if (!zi) { - return TSDB_CODE_TIME_ERROR; - } - tz = zi + strlen("zoneinfo") + 1; - - code = setenv("TZ", tz, 1); - if (-1 == code) { - terrno = TAOS_SYSTEM_ERROR(errno); - return terrno; - } - tzset(); - } - - /* - * NOTE: do not remove it. - * Enforce set the correct daylight saving time(DST) flag according - * to current time - */ - time_t tx1 = taosGetTimestampSec(); - struct tm tm1; - if (taosLocalTime(&tx1, &tm1, NULL, 0) == NULL) { - return TSDB_CODE_TIME_ERROR; - } - daylight = tm1.tm_isdst; - isdst_now = tm1.tm_isdst; - - /* - * format example: - * - * Asia/Shanghai (CST, +0800) - * Europe/London (BST, +0100) - */ - snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (%s, %+03ld00)", tz, tm1.tm_isdst ? tzname[daylight] : tzname[0], - -timezone / 3600); - return 0; #else - - char buf[4096] = {0}; - char *tz = NULL; - { - int n = readlink("/etc/localtime", buf, sizeof(buf)-1); - if (n < 0) { - if (taosCheckExistFile("/etc/timezone")) { - /* - * NOTE: do not remove it. - * Enforce set the correct daylight saving time(DST) flag according - * to current time - */ - time_t tx1 = taosGetTimestampSec(); - struct tm tm1; - if(taosLocalTime(&tx1, &tm1, NULL, 0) == NULL) { - return TSDB_CODE_TIME_ERROR; - } - /* load time zone string from /etc/timezone */ - // FILE *f = fopen("/etc/timezone", "r"); - errno = 0; - TdFilePtr pFile = taosOpenFile("/etc/timezone", TD_FILE_READ); - char buf[68] = {0}; - if (pFile != NULL) { - int len = taosReadFile(pFile, buf, 64); - if (len < 0) { - TAOS_UNUSED(taosCloseFile(&pFile)); - return TSDB_CODE_TIME_ERROR; - } - - TAOS_UNUSED(taosCloseFile(&pFile)); - - buf[sizeof(buf) - 1] = 0; - char *lineEnd = strstr(buf, "\n"); - if (lineEnd != NULL) { - *lineEnd = 0; - } - - // for CentOS system, /etc/timezone does not exist. Ignore the TZ environment variables - if (strlen(buf) > 0) { - code = setenv("TZ", buf, 1); - if (-1 == code) { - terrno = TAOS_SYSTEM_ERROR(errno); - return terrno; - } - } - } - // get and set default timezone - tzset(); - /* - * get CURRENT time zone. - * system current time zone is affected by daylight saving time(DST) - * - * e.g., the local time zone of London in DST is GMT+01:00, - * otherwise is GMT+00:00 - */ - int32_t tz = (-timezone * MILLISECOND_PER_SECOND) / MILLISECOND_PER_HOUR; - *tsTimezone = tz; - tz += daylight; - - /* - * format example: - * - * Asia/Shanghai (CST, +0800) - * Europe/London (BST, +0100) - */ - (void)snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (%s, %s%02d00)", buf, tzname[daylight], tz >= 0 ? "+" : "-", - abs(tz)); - } else { - return TSDB_CODE_TIME_ERROR; - } - return 0; - } - buf[n] = '\0'; - - char *zi = strstr(buf, "zoneinfo"); - if (!zi) { - return TSDB_CODE_TIME_ERROR; - } - tz = zi + strlen("zoneinfo") + 1; - - code = setenv("TZ", tz, 1); - if (-1 == code) { - terrno = TAOS_SYSTEM_ERROR(errno); - return terrno; - } - tzset(); - } - - /* - * NOTE: do not remove it. - * Enforce set the correct daylight saving time(DST) flag according - * to current time - */ + char tz[TD_TIMEZONE_LEN] = {0}; + getTimezoneStr(tz); time_t tx1 = taosGetTimestampSec(); - struct tm tm1; - if(taosLocalTime(&tx1, &tm1, NULL, 0) == NULL) { - return TSDB_CODE_TIME_ERROR; - } - isdst_now = tm1.tm_isdst; - - /* - * format example: - * - * Asia/Shanghai (CST, +0800) - * Europe/London (BST, +0100) - */ - (void)snprintf(outTimezoneStr, TD_TIMEZONE_LEN, "%s (%s, %+03ld00)", tz, tm1.tm_isdst ? tzname[daylight] : tzname[0], - -timezone / 3600); - return 0; + return taosFormatTimezoneStr(tx1, tz, NULL, outTimezoneStr); #endif -} +} \ No newline at end of file diff --git a/source/os/test/osTimeTests.cpp b/source/os/test/osTimeTests.cpp index 42837cc537..5c8c837dca 100644 --- a/source/os/test/osTimeTests.cpp +++ b/source/os/test/osTimeTests.cpp @@ -29,30 +29,11 @@ #include "os.h" #include "tlog.h" -TEST(osTimeTests, taosLocalTimeNolock) { - time_t currentTime; - // Test when result is not NULL - struct tm expectedTime; - struct tm* result = taosLocalTimeNolock(&expectedTime, ¤tTime, 1); - if (result) { - EXPECT_EQ(expectedTime.tm_year, result->tm_year); - EXPECT_EQ(expectedTime.tm_mon, result->tm_mon); - EXPECT_EQ(expectedTime.tm_mday, result->tm_mday); - EXPECT_EQ(expectedTime.tm_hour, result->tm_hour); - EXPECT_EQ(expectedTime.tm_min, result->tm_min); - EXPECT_EQ(expectedTime.tm_sec, result->tm_sec); - EXPECT_EQ(expectedTime.tm_wday, result->tm_wday); - EXPECT_EQ(expectedTime.tm_yday, result->tm_yday); - EXPECT_EQ(expectedTime.tm_isdst, result->tm_isdst); - } -} - - TEST(osTimeTests, taosLocalTime) { // Test 1: Test when both timep and result are not NULL time_t timep = 1617531000; // 2021-04-04 18:10:00 struct tm result; - struct tm* local_time = taosLocalTime(&timep, &result, NULL, 0); + struct tm* local_time = taosLocalTime(&timep, &result, NULL, 0, NULL); ASSERT_NE(local_time, nullptr); ASSERT_EQ(local_time->tm_year, 121); ASSERT_EQ(local_time->tm_mon, 3); @@ -62,13 +43,13 @@ TEST(osTimeTests, taosLocalTime) { ASSERT_EQ(local_time->tm_sec, 00); // Test 2: Test when timep is NULL - local_time = taosLocalTime(NULL, &result, NULL, 0); + local_time = taosLocalTime(NULL, &result, NULL, 0, NULL); ASSERT_EQ(local_time, nullptr); // Test 4: Test when timep is negative on Windows #ifdef WINDOWS time_t pos_timep = 1609459200; // 2021-01-01 08:00:00 - local_time = taosLocalTime(&pos_timep, &result, NULL, 0); + local_time = taosLocalTime(&pos_timep, &result, NULL, 0, NULL); ASSERT_NE(local_time, nullptr); ASSERT_EQ(local_time->tm_year, 121); ASSERT_EQ(local_time->tm_mon, 0); @@ -78,7 +59,7 @@ TEST(osTimeTests, taosLocalTime) { ASSERT_EQ(local_time->tm_sec, 0); time_t neg_timep = -1617531000; // 1918-09-29 21:50:00 - local_time = taosLocalTime(&neg_timep, &result, NULL, 0); + local_time = taosLocalTime(&neg_timep, &result, NULL, 0, NULL); ASSERT_NE(local_time, nullptr); ASSERT_EQ(local_time->tm_year, 18); ASSERT_EQ(local_time->tm_mon, 8); @@ -88,7 +69,7 @@ TEST(osTimeTests, taosLocalTime) { ASSERT_EQ(local_time->tm_sec, 0); time_t neg_timep2 = -315619200; // 1960-01-01 08:00:00 - local_time = taosLocalTime(&neg_timep2, &result, NULL, 0); + local_time = taosLocalTime(&neg_timep2, &result, NULL, 0, NULL); ASSERT_NE(local_time, nullptr); ASSERT_EQ(local_time->tm_year, 60); ASSERT_EQ(local_time->tm_mon, 0); @@ -98,7 +79,7 @@ TEST(osTimeTests, taosLocalTime) { ASSERT_EQ(local_time->tm_sec, 0); time_t zero_timep = 0; // 1970-01-01 08:00:00 - local_time = taosLocalTime(&zero_timep, &result, NULL, 0); + local_time = taosLocalTime(&zero_timep, &result, NULL, 0, NULL); ASSERT_NE(local_time, nullptr); ASSERT_EQ(local_time->tm_year, 70); ASSERT_EQ(local_time->tm_mon, 0); @@ -108,7 +89,7 @@ TEST(osTimeTests, taosLocalTime) { ASSERT_EQ(local_time->tm_sec, 0); time_t neg_timep3 = -78115158887; - local_time = taosLocalTime(&neg_timep3, &result, NULL, 0); + local_time = taosLocalTime(&neg_timep3, &result, NULL, 0, NULL); ASSERT_EQ(local_time, nullptr); #endif } \ No newline at end of file diff --git a/source/util/src/tcompare.c b/source/util/src/tcompare.c index ebc379897f..c95030b06e 100644 --- a/source/util/src/tcompare.c +++ b/source/util/src/tcompare.c @@ -1508,7 +1508,7 @@ int32_t comparewcsRegexMatch(const void *pString, const void *pPattern) { return 1; // terrno has been set } - int convertLen = taosUcs4ToMbs((TdUcs4 *)varDataVal(pPattern), len, pattern); + int convertLen = taosUcs4ToMbs((TdUcs4 *)varDataVal(pPattern), len, pattern, NULL); if (convertLen < 0) { taosMemoryFree(pattern); return 1; // terrno has been set @@ -1523,7 +1523,7 @@ int32_t comparewcsRegexMatch(const void *pString, const void *pPattern) { return 1; // terrno has been set } - convertLen = taosUcs4ToMbs((TdUcs4 *)varDataVal(pString), len, str); + convertLen = taosUcs4ToMbs((TdUcs4 *)varDataVal(pString), len, str, NULL); if (convertLen < 0) { taosMemoryFree(str); taosMemoryFree(pattern); diff --git a/source/util/src/tconfig.c b/source/util/src/tconfig.c index d2a2b1fb9a..f12f17853a 100644 --- a/source/util/src/tconfig.c +++ b/source/util/src/tconfig.c @@ -24,6 +24,7 @@ #include "tlog.h" #include "tunit.h" #include "tutil.h" +#include "tconv.h" #define CFG_NAME_PRINT_LEN 32 #define CFG_SRC_PRINT_LEN 12 @@ -245,14 +246,63 @@ static int32_t doSetConf(SConfigItem *pItem, const char *value, ECfgSrcType styp } static int32_t cfgSetTimezone(SConfigItem *pItem, const char *value, ECfgSrcType stype) { - TAOS_CHECK_RETURN(doSetConf(pItem, value, stype)); - if (strlen(value) == 0) { - uError("cfg:%s, type:%s src:%s, value:%s, skip to set timezone", pItem->name, cfgDtypeStr(pItem->dtype), - cfgStypeStr(stype), value); - TAOS_RETURN(TSDB_CODE_SUCCESS); + if (stype == CFG_STYPE_ALTER_SERVER_CMD || (pItem->dynScope & CFG_DYN_CLIENT) == 0){ + uError("failed to config timezone, not support"); + TAOS_RETURN(TSDB_CODE_INVALID_CFG); } + if (value == NULL) { + uError("cfg:%s, type:%s src:%s, value is null, skip to set timezone", pItem->name, cfgDtypeStr(pItem->dtype), + cfgStypeStr(stype)); + TAOS_RETURN(TSDB_CODE_INVALID_CFG); + } TAOS_CHECK_RETURN(osSetTimezone(value)); + + TAOS_CHECK_RETURN(doSetConf(pItem, tsTimezoneStr, stype)); + + TAOS_RETURN(TSDB_CODE_SUCCESS); +} + +static int32_t cfgSetCharset(SConfigItem *pItem, const char *value, ECfgSrcType stype) { + if (stype == CFG_STYPE_ALTER_SERVER_CMD || stype == CFG_STYPE_ALTER_CLIENT_CMD){ + uError("failed to config charset, not support"); + TAOS_RETURN(TSDB_CODE_INVALID_CFG); + } + + if (value == NULL || strlen(value) == 0) { + uError("cfg:%s, type:%s src:%s, value:%s, skip to set charset", pItem->name, cfgDtypeStr(pItem->dtype), + cfgStypeStr(stype), value); + TAOS_RETURN(TSDB_CODE_INVALID_CFG); + } + + if (!taosValidateEncodec(value)) { + uError("invalid charset:%s", value); + TAOS_RETURN(terrno); + } + + if ((tsCharsetCxt = taosConvInit(value)) == NULL) { + TAOS_RETURN(terrno); + } + (void)memcpy(tsCharset, value, strlen(value) + 1); + TAOS_CHECK_RETURN(doSetConf(pItem, value, stype)); + + TAOS_RETURN(TSDB_CODE_SUCCESS); +} + +static int32_t cfgSetLocale(SConfigItem *pItem, const char *value, ECfgSrcType stype) { + if (stype == CFG_STYPE_ALTER_SERVER_CMD || (pItem->dynScope & CFG_DYN_CLIENT) == 0){ + uError("failed to config locale, not support"); + TAOS_RETURN(TSDB_CODE_INVALID_CFG); + } + + if (value == NULL || strlen(value) == 0 || taosSetSystemLocale(value) != 0) { + uError("cfg:%s, type:%s src:%s, value:%s, skip to set locale", pItem->name, cfgDtypeStr(pItem->dtype), + cfgStypeStr(stype), value); + TAOS_RETURN(TSDB_CODE_INVALID_CFG); + } + + TAOS_CHECK_RETURN(doSetConf(pItem, value, stype)); + TAOS_RETURN(TSDB_CODE_SUCCESS); } @@ -368,11 +418,11 @@ int32_t cfgSetItem(SConfig *pCfg, const char *name, const char *value, ECfgSrcTy break; } case CFG_DTYPE_CHARSET: { - code = doSetConf(pItem, value, stype); + code = cfgSetCharset(pItem, value, stype); break; } case CFG_DTYPE_LOCALE: { - code = doSetConf(pItem, value, stype); + code = cfgSetLocale(pItem, value, stype); break; } case CFG_DTYPE_NONE: @@ -634,6 +684,10 @@ const char *cfgStypeStr(ECfgSrcType type) { return "taos_options"; case CFG_STYPE_ENV_CMD: return "env_cmd"; + case CFG_STYPE_ALTER_CLIENT_CMD: + return "alter_client_cmd"; + case CFG_STYPE_ALTER_SERVER_CMD: + return "alter_server_cmd"; default: return "invalid"; } @@ -684,11 +738,19 @@ int32_t cfgDumpItemValue(SConfigItem *pItem, char *buf, int32_t bufSize, int32_t case CFG_DTYPE_DOUBLE: len = tsnprintf(buf, bufSize, "%f", pItem->fval); break; + case CFG_DTYPE_TIMEZONE:{ +// char str1[TD_TIMEZONE_LEN] = {0}; +// time_t tx1 = taosGetTimestampSec(); +// if (taosFormatTimezoneStr(tx1, buf, NULL, str1) != 0) { +// tstrncpy(str1, "tz error", sizeof(str1)); +// } +// len = tsnprintf(buf, bufSize, "%s", str1); +// break; + } case CFG_DTYPE_STRING: case CFG_DTYPE_DIR: case CFG_DTYPE_LOCALE: case CFG_DTYPE_CHARSET: - case CFG_DTYPE_TIMEZONE: case CFG_DTYPE_NONE: len = tsnprintf(buf, bufSize, "%s", pItem->str); break; diff --git a/source/util/src/tconv.c b/source/util/src/tconv.c new file mode 100644 index 0000000000..d9932489f8 --- /dev/null +++ b/source/util/src/tconv.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * This program is free software: you can use, redistribute, and/or modify + * it under the terms of the GNU Affero General Public License, version 3 + * or later ("AGPL"), as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#define ALLOW_FORBID_FUNC + +#include "tconv.h" +#include "thash.h" +#include "osString.h" + +#define CONV_MAX_NUM 32 +SHashObj *gConvInfo = NULL; + +// M2C: Mbs --> Ucs4 +// C2M: Ucs4--> Mbs + +static void taosConvDestroyInner(void *arg) { + SConvInfo *info = (SConvInfo *)arg; + if (info == NULL) { + return; + } + for (int32_t i = 0; i < info->gConvMaxNum[M2C]; ++i) { + (void)iconv_close(info->gConv[M2C][i].conv); + } + for (int32_t i = 0; i < info->gConvMaxNum[C2M]; ++i) { + (void)iconv_close(info->gConv[C2M][i].conv); + } + taosMemoryFreeClear(info->gConv[M2C]); + taosMemoryFreeClear(info->gConv[C2M]); + + info->gConvMaxNum[M2C] = -1; + info->gConvMaxNum[C2M] = -1; +} + +void* taosConvInit(const char* charset) { + if (charset == NULL){ + terrno = TSDB_CODE_INVALID_PARA; + return NULL; + } + + void* conv = NULL; + static int32_t lock_c = 0; + + for (int i = 1; atomic_val_compare_exchange_32(&lock_c, 0, 1) != 0; ++i) { + if (i % 1000 == 0) { + uInfo("haven't acquire lock after spin %d times.", i); + (void)sched_yield(); + } + } + + if (gConvInfo == NULL){ + gConvInfo = taosHashInit(0, MurmurHash3_32, false, HASH_ENTRY_LOCK); + if (gConvInfo == NULL) { + atomic_store_32(&lock_c, 0); + goto END; + } + taosHashSetFreeFp(gConvInfo, taosConvDestroyInner); + } + + conv = taosHashGet(gConvInfo, charset, strlen(charset)); + if (conv != NULL){ + goto END; + } + + SConvInfo info = {0}; + info.gConvMaxNum[M2C] = CONV_MAX_NUM; + info.gConvMaxNum[C2M] = CONV_MAX_NUM; + tstrncpy(info.charset, charset, sizeof(info.charset)); + + info.gConv[M2C] = taosMemoryCalloc(info.gConvMaxNum[M2C], sizeof(SConv)); + if (info.gConv[M2C] == NULL) { + goto FAILED; + } + + info.gConv[C2M] = taosMemoryCalloc(info.gConvMaxNum[C2M], sizeof(SConv)); + if (info.gConv[C2M] == NULL) { + goto FAILED; + } + + for (int32_t i = 0; i < info.gConvMaxNum[M2C]; ++i) { + info.gConv[M2C][i].conv = iconv_open(DEFAULT_UNICODE_ENCODEC, charset); + if ((iconv_t)-1 == info.gConv[M2C][i].conv) { + terrno = TAOS_SYSTEM_ERROR(errno); + goto FAILED; + } + } + for (int32_t i = 0; i < info.gConvMaxNum[C2M]; ++i) { + info.gConv[C2M][i].conv = iconv_open(charset, DEFAULT_UNICODE_ENCODEC); + if ((iconv_t)-1 == info.gConv[C2M][i].conv) { + terrno = TAOS_SYSTEM_ERROR(errno); + goto FAILED; + } + } + + int32_t code = taosHashPut(gConvInfo, charset, strlen(charset), &info, sizeof(info)); + if (code != 0){ + goto FAILED; + } + conv = taosHashGet(gConvInfo, charset, strlen(charset)); + goto END; + +FAILED: + taosConvDestroyInner(&info); + +END: + atomic_store_32(&lock_c, 0); + return conv; +} + +void taosConvDestroy() { + taosHashCleanup(gConvInfo); +} diff --git a/source/util/src/terror.c b/source/util/src/terror.c index e32b93b028..b00fa49349 100644 --- a/source/util/src/terror.c +++ b/source/util/src/terror.c @@ -58,12 +58,12 @@ TAOS_DEFINE_ERROR(TSDB_CODE_RPC_MAX_SESSIONS, "rpc open too many ses TAOS_DEFINE_ERROR(TSDB_CODE_RPC_NETWORK_ERROR, "rpc network error") TAOS_DEFINE_ERROR(TSDB_CODE_RPC_NETWORK_BUSY, "rpc network busy") TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_MODULE_QUIT, "http-report already quit") -TAOS_DEFINE_ERROR(TSDB_CODE_RPC_MODULE_QUIT, "rpc module already quit") -TAOS_DEFINE_ERROR(TSDB_CODE_RPC_ASYNC_MODULE_QUIT, "rpc async module already quit") -TAOS_DEFINE_ERROR(TSDB_CODE_RPC_ASYNC_IN_PROCESS, "rpc async in process") -TAOS_DEFINE_ERROR(TSDB_CODE_RPC_NO_STATE, "rpc no state") -TAOS_DEFINE_ERROR(TSDB_CODE_RPC_STATE_DROPED, "rpc state already dropped") -TAOS_DEFINE_ERROR(TSDB_CODE_RPC_MSG_EXCCED_LIMIT, "rpc msg exceed limit") +TAOS_DEFINE_ERROR(TSDB_CODE_RPC_MODULE_QUIT, "rpc module already quit") +TAOS_DEFINE_ERROR(TSDB_CODE_RPC_ASYNC_MODULE_QUIT, "rpc async module already quit") +TAOS_DEFINE_ERROR(TSDB_CODE_RPC_ASYNC_IN_PROCESS, "rpc async in process") +TAOS_DEFINE_ERROR(TSDB_CODE_RPC_NO_STATE, "rpc no state") +TAOS_DEFINE_ERROR(TSDB_CODE_RPC_STATE_DROPED, "rpc state already dropped") +TAOS_DEFINE_ERROR(TSDB_CODE_RPC_MSG_EXCCED_LIMIT, "rpc msg exceed limit") //common & util TAOS_DEFINE_ERROR(TSDB_CODE_TIME_UNSYNCED, "Client and server's time is not synchronized") @@ -167,7 +167,7 @@ TAOS_DEFINE_ERROR(TSDB_CODE_TSC_COMPRESS_PARAM_ERROR, "Invalid compress para TAOS_DEFINE_ERROR(TSDB_CODE_TSC_COMPRESS_LEVEL_ERROR, "Invalid compress level param") TAOS_DEFINE_ERROR(TSDB_CODE_TSC_FAIL_GENERATE_JSON, "failed to generate JSON") TAOS_DEFINE_ERROR(TSDB_CODE_TSC_STMT_BIND_NUMBER_ERROR, "bind number out of range or not match") - +TAOS_DEFINE_ERROR(TSDB_CODE_NOT_SUPPORTTED_IN_WINDOWS, "Operation not supported in windows") TAOS_DEFINE_ERROR(TSDB_CODE_TSC_INTERNAL_ERROR, "Internal error") @@ -873,6 +873,7 @@ TAOS_DEFINE_ERROR(TSDB_CODE_UTIL_QUEUE_OUT_OF_MEMORY, "Queue out of memory TAOS_DEFINE_ERROR(TSDB_CODE_AUDIT_NOT_FORMAT_TO_JSON, "can't format to json") TAOS_DEFINE_ERROR(TSDB_CODE_AUDIT_FAIL_SEND_AUDIT_RECORD, "Failed to send out audit record") TAOS_DEFINE_ERROR(TSDB_CODE_AUDIT_FAIL_GENERATE_JSON, "Failed to generate json") + #ifdef TAOS_ERROR_C }; #endif diff --git a/source/util/src/tlog.c b/source/util/src/tlog.c index 693935575a..7a5852f329 100644 --- a/source/util/src/tlog.c +++ b/source/util/src/tlog.c @@ -20,6 +20,7 @@ #include "tglobal.h" #include "tjson.h" #include "tutil.h" +#include "ttime.h" #define LOG_MAX_LINE_SIZE (10024) #define LOG_MAX_LINE_BUFFER_SIZE (LOG_MAX_LINE_SIZE + 3) @@ -171,30 +172,12 @@ static int32_t getDay(char *buf, int32_t bufSize) { return code; } struct tm tmInfo; - if (taosLocalTime(&t, &tmInfo, buf, bufSize) != NULL) { - TAOS_UNUSED(strftime(buf, bufSize, "%Y-%m-%d", &tmInfo)); + if (taosLocalTime(&t, &tmInfo, buf, bufSize, NULL) != NULL) { + TAOS_UNUSED(taosStrfTime(buf, bufSize, "%Y-%m-%d", &tmInfo)); } return 0; } -static int64_t getTimestampToday() { - time_t t; - int32_t code = taosTime(&t); - if (code != 0) { - uError("failed to get time, reason:%s", tstrerror(code)); - return 0; - } - struct tm tm; - if (taosLocalTime(&t, &tm, NULL, 0) == NULL) { - return 0; - } - tm.tm_hour = 0; - tm.tm_min = 0; - tm.tm_sec = 0; - - return (int64_t)taosMktime(&tm); -} - static void getFullPathName(char *fullName, const char *logName) { if (strlen(tsLogDir) != 0) { char lastC = tsLogDir[strlen(tsLogDir) - 1]; @@ -230,7 +213,7 @@ int32_t taosInitSlowLog() { } (void)snprintf(name, PATH_MAX + TD_TIME_STR_LEN, "%s.%s", tsLogObj.slowLogName, day); - tsLogObj.timestampToday = getTimestampToday(); + tsLogObj.timestampToday = taosGetTimestampToday(TSDB_TIME_PRECISION_SECONDS, NULL); tsLogObj.slowHandle = taosLogBuffNew(LOG_SLOW_BUF_SIZE); if (tsLogObj.slowHandle == NULL) return terrno; @@ -536,7 +519,7 @@ static void taosOpenNewSlowLogFile() { TdFilePtr pOldFile = tsLogObj.slowHandle->pFile; tsLogObj.slowHandle->pFile = pFile; (void)taosCloseFile(&pOldFile); - tsLogObj.timestampToday = getTimestampToday(); + tsLogObj.timestampToday = taosGetTimestampToday(TSDB_TIME_PRECISION_SECONDS, NULL); (void)taosThreadMutexUnlock(&tsLogObj.logMutex); } @@ -722,8 +705,11 @@ static inline int32_t taosBuildLogHead(char *buffer, const char *flags) { TAOS_UNUSED(taosGetTimeOfDay(&timeSecs)); time_t curTime = timeSecs.tv_sec; - ptm = taosLocalTime(&curTime, &Tm, NULL, 0); - + ptm = taosLocalTime(&curTime, &Tm, NULL, 0, NULL); + if (ptm == NULL){ + uError("%s failed to get local time, code:%d", __FUNCTION__ , errno); + return 0; + } return sprintf(buffer, "%02d/%02d %02d:%02d:%02d.%06d %08" PRId64 " %s %s", ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, (int32_t)timeSecs.tv_usec, taosGetSelfPthreadId(), LOG_EDITION_FLG, flags); diff --git a/source/util/src/tutil.c b/source/util/src/tutil.c index dd3c6ece40..0862b5000c 100644 --- a/source/util/src/tutil.c +++ b/source/util/src/tutil.c @@ -417,25 +417,6 @@ int32_t taosHexStrToByteArray(char hexstr[], char bytes[]) { return 0; } -char *taosIpStr(uint32_t ipInt) { - static char ipStrArray[3][30]; - static int32_t ipStrIndex = 0; - - char *ipStr = ipStrArray[(ipStrIndex++) % 3]; - // sprintf(ipStr, "0x%x:%u.%u.%u.%u", ipInt, ipInt & 0xFF, (ipInt >> 8) & 0xFF, (ipInt >> 16) & 0xFF, (uint8_t)(ipInt - // >> 24)); - sprintf(ipStr, "%u.%u.%u.%u", ipInt & 0xFF, (ipInt >> 8) & 0xFF, (ipInt >> 16) & 0xFF, (uint8_t)(ipInt >> 24)); - return ipStr; -} - -void taosIp2String(uint32_t ip, char *str) { - sprintf(str, "%u.%u.%u.%u", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (uint8_t)(ip >> 24)); -} - -void taosIpPort2String(uint32_t ip, uint16_t port, char *str) { - sprintf(str, "%u.%u.%u.%u:%u", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (uint8_t)(ip >> 24), port); -} - size_t tstrncspn(const char *str, size_t size, const char *reject, size_t rsize) { if (rsize == 0 || rsize == 1) { char *p = strnchr(str, reject[0], size, false); diff --git a/source/util/test/encodeTest.cpp b/source/util/test/encodeTest.cpp index 974677d26c..074fee07ea 100644 --- a/source/util/test/encodeTest.cpp +++ b/source/util/test/encodeTest.cpp @@ -230,8 +230,8 @@ static int32_t tSStructA_v1_decode(SCoder *pCoder, SStructA_v1 *pSAV1) { if (tDecodeI32(pCoder, &pSAV1->A_a) < 0) return -1; if (tDecodeI64(pCoder, &pSAV1->A_b) < 0) return -1; - const char *tstr; - uint64_t len; + const char *tstr = NULL; + uint64_t len = 0; if (tDecodeCStrAndLen(pCoder, &tstr, &len) < 0) return -1; pSAV1->A_c = (char *)tCoderMalloc(pCoder, len + 1); memcpy(pSAV1->A_c, tstr, len + 1); @@ -269,8 +269,8 @@ static int32_t tSStructA_v2_decode(SCoder *pCoder, SStructA_v2 *pSAV2) { if (tDecodeI32(pCoder, &pSAV2->A_a) < 0) return -1; if (tDecodeI64(pCoder, &pSAV2->A_b) < 0) return -1; - const char *tstr; - uint64_t len; + const char *tstr = NULL; + uint64_t len = 0; if (tDecodeCStrAndLen(pCoder, &tstr, &len) < 0) return -1; pSAV2->A_c = (char *)tCoderMalloc(pCoder, len + 1); memcpy(pSAV2->A_c, tstr, len + 1); diff --git a/tests/army/whole/checkErrorCode.py b/tests/army/whole/checkErrorCode.py index 156cacb482..b24c2ae7b5 100644 --- a/tests/army/whole/checkErrorCode.py +++ b/tests/army/whole/checkErrorCode.py @@ -61,7 +61,7 @@ ignoreCodes = [ '0x80003107', '0x80003108', '0x80003109', '0x80003110', '0x80003111', '0x80003112', '0x80003250', '0x80004003', '0x80004004', '0x80004005', '0x80004006', '0x80004007', '0x80004008', '0x80004009', '0x80004010', '0x80004011', '0x80004012', '0x80004013', '0x80004014', '0x80004015', '0x80004016', '0x80004102', '0x80004103', '0x80004104', '0x80004105', '0x80004106', '0x80004107', '0x80004108', '0x80004109', '0x80005100', - '0x80005101', '0x80006000', '0x80006100', '0x80006101', '0x80006102', '0x80000019', '0x80002639', '0x80002666'] + '0x80005101', '0x80006000', '0x80006100', '0x80006101', '0x80006102', '0x80000019', '0x80002639', '0x80002666', '0x80000237'] class TDTestCase(TBase): diff --git a/tests/system-test/0-others/information_schema.py b/tests/system-test/0-others/information_schema.py index 984dc73642..45d3342571 100644 --- a/tests/system-test/0-others/information_schema.py +++ b/tests/system-test/0-others/information_schema.py @@ -225,7 +225,7 @@ class TDTestCase: tdSql.checkEqual(True, len(tdSql.queryResult) in range(292, 293)) tdSql.query("select * from information_schema.ins_columns where db_name ='performance_schema'") - tdSql.checkEqual(56, len(tdSql.queryResult)) + tdSql.checkEqual(60, len(tdSql.queryResult)) def ins_dnodes_check(self): tdSql.execute('drop database if exists db2') diff --git a/tests/system-test/2-query/timezone.py b/tests/system-test/2-query/timezone.py index 33bcb16595..dbb4d2187e 100644 --- a/tests/system-test/2-query/timezone.py +++ b/tests/system-test/2-query/timezone.py @@ -142,26 +142,69 @@ class TDTestCase: tdSql.query(f"select ts from {self.dbname}.d5") tdSql.checkData(0, 0, "2021-07-01 20:00:00.000") - tdSql.execute(f"insert into {self.dbname}.d6 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-115',1)") - tdSql.query(f"select ts from {self.dbname}.d6") - tdSql.checkData(0, 0, "2021-07-01 19:05:00.000") + tdSql.error(f"insert into {self.dbname}.d6 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-115',1)") tdSql.execute(f"insert into {self.dbname}.d7 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-1105',1)") tdSql.query(f"select ts from {self.dbname}.d7") tdSql.checkData(0, 0, "2021-07-01 19:05:00.000") - tdSql.error(f"insert into {self.dbname}.d21 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000+12:10',1)") - tdSql.error(f"insert into {self.dbname}.d22 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-24:10',1)") - tdSql.error(f"insert into {self.dbname}.d23 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000+12:10',1)") - tdSql.error(f"insert into {self.dbname}.d24 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-24:10',1)") - tdSql.error(f"insert into {self.dbname}.d24 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-24100',1)") - tdSql.error(f"insert into {self.dbname}.d24 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-1210',1)") + # tdSql.error(f"insert into {self.dbname}.d21 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000+12:10',1)") + # tdSql.error(f"insert into {self.dbname}.d22 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-24:10',1)") + # tdSql.error(f"insert into {self.dbname}.d23 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000+12:10',1)") + # tdSql.error(f"insert into {self.dbname}.d24 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-24:10',1)") + # tdSql.error(f"insert into {self.dbname}.d24 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-24100',1)") + # tdSql.error(f"insert into {self.dbname}.d24 using {self.dbname}.stb tags (1) values ('2021-07-01T00:00:00.000-1210',1)") tdSql.execute(f'drop database {self.dbname}') + # def timezone_check(self, cursor, timezone): + # cursor.execute("show local variables") + # res = cursor.fetchall() + # for i in range(cursor.rowcount): + # if res[i][0] == "timezone" : + # if res[i][1].find(timezone) == -1: + # tdLog.exit("show timezone:%s != %s"%(res[i][1],timezone)) + # + # def timezone_check_set_options(self): + # buildPath = tdCom.getBuildPath() + # cmdStr = '%s/build/bin/timezone_test'%(buildPath) + # print("cmdStr:", cmdStr) + # tdLog.info(cmdStr) + # ret = os.system(cmdStr) + # if ret != 0: + # tdLog.exit("timezone_test error") + # + # def timezone_check_conf(self, timezone): + # updateCfgDict = ({"clientCfg" : {'timezone': 'UTC'} },) + # tdDnodes.sim.deploy(updateCfgDict) + # conn = taos.connect(config=tdDnodes.getSimCfgPath()) + # cursor = conn.cursor() + # self.timezone_check(cursor, 'UTC') + # cursor.close() + def timezone_check(self, sql, timezone): + tdSql.query(sql) + rows = tdSql.getRows() + for i in range(rows): + if tdSql.getData(i, 0) == "timezone" : + if tdSql.getData(i, 1).find(timezone) == -1: + tdLog.exit("show timezone:%s != %s"%(tdSql.getData(i, 1), timezone)) + + def charset_check(self, sql, charset): + tdSql.query(sql) + rows = tdSql.getRows() + for i in range(rows): + if tdSql.getData(i, 0) == "charset" : + if tdSql.getData(i, 1).find(charset) == -1: + tdLog.exit("show charset:%s != %s"%(tdSql.getData(i, 1), charset)) def run(self): # sourcery skip: extract-duplicate-method timezone = self.get_system_timezone() + # timezone = "Asia/Shanghai" + self.charset_check("show local variables", "UTF-8") + self.timezone_check("show dnode 1 variables", "UTF-8") + self.timezone_check("show local variables", timezone) + self.timezone_check("show dnode 1 variables", timezone) + self.timezone_check_ntb(timezone) self.timezone_check_stb(timezone) self.timezone_format_test() diff --git a/tests/system-test/2-query/timezone_conf.py b/tests/system-test/2-query/timezone_conf.py new file mode 100644 index 0000000000..da45e2c5bd --- /dev/null +++ b/tests/system-test/2-query/timezone_conf.py @@ -0,0 +1,44 @@ + +from util.log import * +from util.sql import * +from util.cases import * +from util.sqlset import * +from util.cluster import * + +class TDTestCase: + updatecfgDict = {"clientCfg" : {'timezone': 'UTC', 'charset': 'gbk'}, 'timezone': 'UTC-8', 'charset': 'gbk'} + def init(self, conn, logSql, replicaVar=1): + self.replicaVar = int(replicaVar) + tdLog.debug(f"start to excute {__file__}") + tdSql.init(conn.cursor()) + + def timezone_check(self, timezone, sql): + tdSql.query(sql) + rows = tdSql.getRows() + for i in range(rows): + if tdSql.getData(i, 0) == "timezone" : + if tdSql.getData(i, 1).find(timezone) == -1: + tdLog.exit("show timezone:%s != %s"%(tdSql.getData(i, 1), timezone)) + + def charset_check(self, charset, sql): + tdSql.query(sql) + rows = tdSql.getRows() + for i in range(rows): + if tdSql.getData(i, 0) == "charset" : + if tdSql.getData(i, 1).find(charset) == -1: + tdLog.exit("show charset:%s != %s"%(tdSql.getData(i, 1), charset)) + + def run(self): + self.charset_check('gbk', "show local variables") + self.charset_check('gbk', "show dnode 1 variables") + self.timezone_check('UTC', "show local variables") + # time.sleep(50) + self.timezone_check('UTC-8', "show dnode 1 variables") + + def stop(self): + tdSql.close() + tdLog.success(f"{__file__} successfully executed") + + +tdCases.addLinux(__file__, TDTestCase()) +tdCases.addWindows(__file__, TDTestCase()) diff --git a/tools/shell/src/shellEngine.c b/tools/shell/src/shellEngine.c index 6fcebd667d..6c1a972f7e 100644 --- a/tools/shell/src/shellEngine.c +++ b/tools/shell/src/shellEngine.c @@ -337,7 +337,7 @@ char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t prec } struct tm ptm = {0}; - if (taosLocalTime(&tt, &ptm, buf, bufSize) == NULL) { + if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) { return buf; } size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm); diff --git a/utils/test/c/CMakeLists.txt b/utils/test/c/CMakeLists.txt index 7054eb218f..cb0410e9bf 100644 --- a/utils/test/c/CMakeLists.txt +++ b/utils/test/c/CMakeLists.txt @@ -15,6 +15,7 @@ add_executable(tmq_multi_thread_test tmq_multi_thread_test.c) add_executable(tmq_offset_test tmq_offset_test.c) add_executable(varbinary_test varbinary_test.c) add_executable(replay_test replay_test.c) +add_executable(timezone_test timezone_test.c) if(${TD_LINUX}) add_executable(tsz_test tsz_test.c) @@ -142,6 +143,14 @@ target_link_libraries( PUBLIC os ) +target_link_libraries( + timezone_test + PUBLIC taos + PUBLIC util + PUBLIC common + PUBLIC os +) + if(${TD_LINUX}) target_link_libraries( tsz_test diff --git a/utils/test/c/timezone_test.c b/utils/test/c/timezone_test.c new file mode 100644 index 0000000000..5a3fa87976 --- /dev/null +++ b/utils/test/c/timezone_test.c @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * This program is free software: you can use, redistribute, and/or modify + * it under the terms of the GNU Affero General Public License, version 3 + * or later ("AGPL"), as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include "taos.h" +#include "types.h" +#include "tlog.h" + +char* timezone_name = "America/New_York"; +void check_timezone(const char* tzName){ + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + ASSERT(pConn != NULL); + TAOS_RES *pRes = taos_query(pConn, "show local variables"); + ASSERT(taos_errno(pRes) == 0); + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(pRes)) != NULL) { + if (strcmp(row[0], "timezone") == 0){ + ASSERT(strstr(row[1], tzName) != NULL); + } + } + taos_free_result(pRes); + taos_close(pConn); +} + +void timezone_set_options_test(){ + taos_options(TSDB_OPTION_TIMEZONE, timezone_name); + check_timezone(timezone_name); +} + +void timezone_insert_test(){ + TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 0); + + TAOS_RES *pRes = taos_query(taos, "drop database if exists tz_db"); + taos_free_result(pRes); + + pRes = taos_query(taos, "create database if not exists tz_db"); + taos_free_result(pRes); + + pRes = taos_query(taos, "use tz_db"); + int code = taos_errno(pRes); + taos_free_result(pRes); + ASSERT(code == 0); + + pRes = taos_query(taos, "create stable stb (ts timestamp, c1 int) tags (t1 timestamp, t2 binary(32))"); + taos_free_result(pRes); + + pRes = taos_query(taos, "create table ntb (ts timestamp, c1 int)"); + taos_free_result(pRes); + + pRes = taos_query(taos, "insert into tb1 using stb tags (1, 'test') values (1, 2)"); + taos_free_result(pRes); + + pRes = taos_query(taos, "insert into tb1 using stb tags ('2013-04-12T10:52:01', 'test') values ('2013-04-12T10:52:01', 2)"); + taos_free_result(pRes); + + pRes = taos_query(taos, "insert into ntb values ('2013-04-12T10:52:01', 2)"); + taos_free_result(pRes); + + pRes = taos_query(taos, "insert into ntb values (1, 2)"); + taos_free_result(pRes); + + + /* + select today(); + tsConver.sim + "COMPACT DATABASE test START WITH '2023-03-07 14:01:23' END WITH '2023-03-08 14:01:23'" + TK_TIMEZONE + + ts > c1('2013-04-12T10:52:01') + in ('2013-04-12T10:52:01') + + offsetFromTz hash join + */ +} + +int main(int argc, char *argv[]) { + int ret = 0; + timezone_set_options_test(); + return ret; +} diff --git a/utils/test/c/tmqDemo.c b/utils/test/c/tmqDemo.c index 40ed98132c..550613ee9a 100644 --- a/utils/test/c/tmqDemo.c +++ b/utils/test/c/tmqDemo.c @@ -597,7 +597,7 @@ void printParaIntoFile() { time_t tTime = taosGetTimestampSec(); struct tm tm; - taosLocalTime(&tTime, &tm, NULL, 0); + taosLocalTime(&tTime, &tm, NULL, 0, NULL); taosFprintfFile(pFile, "###################################################################\n"); taosFprintfFile(pFile, "# configDir: %s\n", configDir); diff --git a/utils/test/c/tmqSim.c b/utils/test/c/tmqSim.c index c045629d1f..1ed9af00f2 100644 --- a/utils/test/c/tmqSim.c +++ b/utils/test/c/tmqSim.c @@ -166,7 +166,7 @@ static void printHelp() { char* getCurrentTimeString(char* timeString) { time_t tTime = taosGetTimestampSec(); struct tm tm; - taosLocalTime(&tTime, &tm, NULL, 0); + taosLocalTime(&tTime, &tm, NULL, 0, NULL); sprintf(timeString, "%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); @@ -472,10 +472,10 @@ static char* shellFormatTimestamp(char* buf, int32_t bufSize, int64_t val, int32 } struct tm ptm; - if (taosLocalTime(&tt, &ptm, buf, bufSize) == NULL) { + if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) { return buf; } - size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm); + size_t pos = taosStrfTime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm); if (precision == TSDB_TIME_PRECISION_NANO) { sprintf(buf + pos, ".%09d", ms); diff --git a/utils/tsim/src/simExe.c b/utils/tsim/src/simExe.c index c7cec64dec..a9772addbb 100644 --- a/utils/tsim/src/simExe.c +++ b/utils/tsim/src/simExe.c @@ -797,10 +797,10 @@ bool simExecuteNativeSqlCommand(SScript *script, char *rest, bool isSlow) { tt = (*(int64_t *)row[i]) / 1000000000; } - if (taosLocalTime(&tt, &tp, timeStr, sizeof(timeStr)) == NULL) { + if (taosLocalTime(&tt, &tp, timeStr, sizeof(timeStr), NULL) == NULL) { break; } - strftime(timeStr, 64, "%y-%m-%d %H:%M:%S", &tp); + taosStrfTime(timeStr, 64, "%y-%m-%d %H:%M:%S", &tp); if (precision == TSDB_TIME_PRECISION_MILLI) { sprintf(value, "%s.%03d", timeStr, (int32_t)(*((int64_t *)row[i]) % 1000)); } else if (precision == TSDB_TIME_PRECISION_MICRO) {