diff --git a/Jenkinsfile b/Jenkinsfile index 72882f9891fa148aed927871187174298d3dfe17..a715cf347a711bc11c05c05b89f0d18b8cb96063 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,9 +1,7 @@ import hudson.model.Result import hudson.model.*; import jenkins.model.CauseOfInterruption -properties([pipelineTriggers([githubPush()])]) node { - git url: 'https://github.com/taosdata/TDengine.git' } def skipbuild=0 @@ -194,6 +192,7 @@ def pre_test_win(){ } pipeline { agent none + options { skipDefaultCheckout() } environment{ WK = '/var/lib/jenkins/workspace/TDinternal' WKC= '/var/lib/jenkins/workspace/TDinternal/community' @@ -201,67 +200,67 @@ pipeline { stages { stage('pre_build'){ agent{label 'master'} - when { - changeRequest() + options { skipDefaultCheckout() } + when{ + changeRequest() } steps { script{ abort_previous() abortPreviousBuilds() } - sh''' - rm -rf ${WORKSPACE}.tes - cp -r ${WORKSPACE} ${WORKSPACE}.tes - cd ${WORKSPACE}.tes - git fetch - ''' - script { - if (env.CHANGE_TARGET == 'master') { - sh ''' - git checkout master - ''' - } - else if(env.CHANGE_TARGET == '2.0'){ - sh ''' - git checkout 2.0 - ''' - } - else{ - sh ''' - git checkout develop - ''' - } - } - sh''' - git fetch origin +refs/pull/${CHANGE_ID}/merge - git checkout -qf FETCH_HEAD - ''' + // sh''' + // rm -rf ${WORKSPACE}.tes + // cp -r ${WORKSPACE} ${WORKSPACE}.tes + // cd ${WORKSPACE}.tes + // git fetch + // ''' + // script { + // if (env.CHANGE_TARGET == 'master') { + // sh ''' + // git checkout master + // ''' + // } + // else if(env.CHANGE_TARGET == '2.0'){ + // sh ''' + // git checkout 2.0 + // ''' + // } + // else{ + // sh ''' + // git checkout develop + // ''' + // } + // } + // sh''' + // git fetch origin +refs/pull/${CHANGE_ID}/merge + // git checkout -qf FETCH_HEAD + // ''' - script{ - skipbuild='2' - skipbuild=sh(script: "git log -2 --pretty=%B | fgrep -ie '[skip ci]' -e '[ci skip]' && echo 1 || echo 2", returnStdout:true) - println skipbuild - } - sh''' - rm -rf ${WORKSPACE}.tes - ''' + // script{ + // skipbuild='2' + // skipbuild=sh(script: "git log -2 --pretty=%B | fgrep -ie '[skip ci]' -e '[ci skip]' && echo 1 || echo 2", returnStdout:true) + // println skipbuild + // } + // sh''' + // rm -rf ${WORKSPACE}.tes + // ''' + // } } } stage('Parallel test stage') { //only build pr + options { skipDefaultCheckout() } when { allOf{ changeRequest() - expression{ - return skipbuild.trim() == '2' - } + not{ expression { env.CHANGE_BRANCH =~ /docs\// }} } } parallel { stage('python_1_s1') { agent{label " slave1 || slave11 "} steps { - pre_test() timeout(time: 55, unit: 'MINUTES'){ sh ''' diff --git a/cmake/define.inc b/cmake/define.inc index 10134a94d2e5d40b7528af1ca205105d3235c6d2..e0cdfd3efc6be2673dc60a53f035e132f5a20a55 100755 --- a/cmake/define.inc +++ b/cmake/define.inc @@ -124,17 +124,25 @@ IF (TD_APLHINE) MESSAGE(STATUS "aplhine is defined") ENDIF () -IF (TD_LINUX) - IF (TD_ARM_32) - SET(TD_BUILD_HTTP TRUE) - ADD_DEFINITIONS(-DHTTP_EMBEDDED) - ELSE () - IF (TD_BUILD_HTTP) - ADD_DEFINITIONS(-DHTTP_EMBEDDED) +MESSAGE("before BUILD_HTTP: " ${BUILD_HTTP}) +IF ("${BUILD_HTTP}" STREQUAL "") + IF (TD_LINUX) + IF (TD_ARM_32) + SET(BUILD_HTTP "true") + ELSE () + SET(BUILD_HTTP "false") ENDIF () + ELSE () + SET(BUILD_HTTP "true") ENDIF () -ELSE () +ENDIF () +MESSAGE("after BUILD_HTTP: " ${BUILD_HTTP}) + +IF (${BUILD_HTTP} MATCHES "true") SET(TD_BUILD_HTTP TRUE) +ENDIF () + +IF (TD_BUILD_HTTP) ADD_DEFINITIONS(-DHTTP_EMBEDDED) ENDIF () diff --git a/cmake/input.inc b/cmake/input.inc index a6eaaa97898bbba5b4ba79fac35b0d96c6a9391f..5bd1a7bed6fe9b0c7dc51c46870d8109462eae81 100755 --- a/cmake/input.inc +++ b/cmake/input.inc @@ -92,10 +92,6 @@ ENDIF () SET(TD_BUILD_HTTP FALSE) -IF (${BUILD_HTTP} MATCHES "true") - SET(TD_BUILD_HTTP TRUE) -ENDIF () - SET(TD_MEMORY_SANITIZER FALSE) IF (${MEMORY_SANITIZER} MATCHES "true") SET(TD_MEMORY_SANITIZER TRUE) diff --git a/deps/lz4/inc/lz4.h b/deps/lz4/inc/lz4.h index 43ccb22c9cdb7006b7dab515613580ae4fb8b7a4..7ab1e483a9f53798f6160bd8aaaabd3852e2c146 100644 --- a/deps/lz4/inc/lz4.h +++ b/deps/lz4/inc/lz4.h @@ -1,7 +1,7 @@ /* * LZ4 - Fast LZ compression algorithm * Header File - * Copyright (C) 2011-2017, Yann Collet. + * Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) @@ -46,24 +46,31 @@ extern "C" { /** Introduction - LZ4 is lossless compression algorithm, providing compression speed at 400 MB/s per core, + LZ4 is lossless compression algorithm, providing compression speed >500 MB/s per core, scalable with multi-cores CPU. It features an extremely fast decoder, with speed in multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. The LZ4 compression library provides in-memory compression and decompression functions. + It gives full buffer control to user. Compression can be done in: - a single step (described as Simple Functions) - a single step, reusing a context (described in Advanced Functions) - unbounded multiple steps (described as Streaming compression) - lz4.h provides block compression functions. It gives full buffer control to user. - Decompressing an lz4-compressed block also requires metadata (such as compressed size). - Each application is free to encode such metadata in whichever way it wants. + lz4.h generates and decodes LZ4-compressed blocks (doc/lz4_Block_format.md). + Decompressing such a compressed block requires additional metadata. + Exact metadata depends on exact decompression function. + For the typical case of LZ4_decompress_safe(), + metadata includes block's compressed size, and maximum bound of decompressed size. + Each application is free to encode and pass such metadata in whichever way it wants. - An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md), - take care of encoding standard metadata alongside LZ4-compressed blocks. - If your application requires interoperability, it's recommended to use it. - A library is provided to take care of it, see lz4frame.h. + lz4.h only handle blocks, it can not generate Frames. + + Blocks are different from Frames (doc/lz4_Frame_format.md). + Frames bundle both blocks and metadata in a specified manner. + Embedding metadata is required for compressed data to be self-contained and portable. + Frame format is delivered through a companion API, declared in lz4frame.h. + The `lz4` CLI can only manage frames. */ /*^*************************************************************** @@ -72,27 +79,28 @@ extern "C" { /* * LZ4_DLL_EXPORT : * Enable exporting of functions when building a Windows DLL -* LZ4LIB_API : +* LZ4LIB_VISIBILITY : * Control library symbols visibility. */ - -#include - +#ifndef LZ4LIB_VISIBILITY +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default"))) +# else +# define LZ4LIB_VISIBILITY +# endif +#endif #if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) -# define LZ4LIB_API __declspec(dllexport) +# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY #elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) -# define LZ4LIB_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ -#elif defined(__GNUC__) && (__GNUC__ >= 4) -# define LZ4LIB_API __attribute__ ((__visibility__ ("default"))) +# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ #else -# define LZ4LIB_API +# define LZ4LIB_API LZ4LIB_VISIBILITY #endif - /*------ Version ------*/ #define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ -#define LZ4_VERSION_MINOR 8 /* for new (non-breaking) interface capabilities */ -#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */ +#define LZ4_VERSION_MINOR 9 /* for new (non-breaking) interface capabilities */ +#define LZ4_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */ #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) @@ -101,8 +109,8 @@ extern "C" { #define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) #define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) -LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; to be used when checking dll version */ -LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; to be used when checking dll version */ +LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; useful to check dll version */ +LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; useful to check dll version */ /*-************************************ @@ -111,42 +119,49 @@ LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; /*! * LZ4_MEMORY_USAGE : * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect + * Increasing memory usage improves compression ratio. + * Reduced memory usage may improve speed, thanks to better cache locality. * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ #ifndef LZ4_MEMORY_USAGE # define LZ4_MEMORY_USAGE 14 #endif + /*-************************************ * Simple Functions **************************************/ /*! LZ4_compress_default() : - Compresses 'sourceSize' bytes from buffer 'source' - into already allocated 'dest' buffer of size 'maxDestSize'. - Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize). - It also runs faster, so it's a recommended setting. - If the function cannot compress 'source' into a more limited 'dest' budget, - compression stops *immediately*, and the function result is zero. - As a consequence, 'dest' content is not valid. - This function never writes outside 'dest' buffer, nor read outside 'source' buffer. - sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE - maxDestSize : full or partial size of buffer 'dest' (which must be already allocated) - return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize) - or 0 if compression fails */ -LZ4LIB_API int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize); + * Compresses 'srcSize' bytes from buffer 'src' + * into already allocated 'dst' buffer of size 'dstCapacity'. + * Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize). + * It also runs faster, so it's a recommended setting. + * If the function cannot compress 'src' into a more limited 'dst' budget, + * compression stops *immediately*, and the function result is zero. + * In which case, 'dst' content is undefined (invalid). + * srcSize : max supported value is LZ4_MAX_INPUT_SIZE. + * dstCapacity : size of buffer 'dst' (which must be already allocated) + * @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity) + * or 0 if compression fails + * Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer). + */ +LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity); /*! LZ4_decompress_safe() : - compressedSize : is the precise full size of the compressed block. - maxDecompressedSize : is the size of destination buffer, which must be already allocated. - return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize) - If destination buffer is not large enough, decoding will stop and output an error code (<0). - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function is protected against buffer overflow exploits, including malicious data packets. - It never writes outside output buffer, nor reads outside input buffer. -*/ -LZ4LIB_API int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize); + * compressedSize : is the exact complete size of the compressed block. + * dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size. + * @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity) + * If destination buffer is not large enough, decoding will stop and output an error code (negative value). + * If the source stream is detected malformed, the function will stop decoding and return a negative result. + * Note 1 : This function is protected against malicious data packets : + * it will never writes outside 'dst' buffer, nor read outside 'source' buffer, + * even if the compressed block is maliciously modified to order the decoder to do these actions. + * In such case, the decoder stops immediately, and considers the compressed block malformed. + * Note 2 : compressedSize and dstCapacity must be provided to the function, the compressed block does not contain them. + * The implementation is free to send / store / derive this information in whichever way is most beneficial. + * If there is a need for a different format which bundles together both compressed data and its metadata, consider looking at lz4frame.h instead. + */ +LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity); /*-************************************ @@ -155,322 +170,603 @@ LZ4LIB_API int LZ4_decompress_safe (const char* source, char* dest, int compress #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) -/*! -LZ4_compressBound() : +/*! LZ4_compressBound() : Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) This function is primarily useful for memory allocation purposes (destination buffer size). Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). - Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize) + Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize) inputSize : max supported value is LZ4_MAX_INPUT_SIZE return : maximum output size in a "worst case" scenario - or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE) + or 0, if input size is incorrect (too large or negative) */ LZ4LIB_API int LZ4_compressBound(int inputSize); -/*! -LZ4_compress_fast() : - Same as LZ4_compress_default(), but allows to select an "acceleration" factor. +/*! LZ4_compress_fast() : + Same as LZ4_compress_default(), but allows selection of "acceleration" factor. The larger the acceleration value, the faster the algorithm, but also the lesser the compression. It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. An acceleration value of "1" is the same as regular LZ4_compress_default() - Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1. + Values <= 0 will be replaced by LZ4_ACCELERATION_DEFAULT (currently == 1, see lz4.c). + Values > LZ4_ACCELERATION_MAX will be replaced by LZ4_ACCELERATION_MAX (currently == 65537, see lz4.c). */ -LZ4LIB_API int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration); +LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); -/*! -LZ4_compress_fast_extState() : - Same compression function, just using an externally allocated memory space to store compression state. - Use LZ4_sizeofState() to know how much memory must be allocated, - and allocate it on 8-bytes boundaries (using malloc() typically). - Then, provide it as 'void* state' to compression function. -*/ +/*! LZ4_compress_fast_extState() : + * Same as LZ4_compress_fast(), using an externally allocated memory space for its state. + * Use LZ4_sizeofState() to know how much memory must be allocated, + * and allocate it on 8-bytes boundaries (using `malloc()` typically). + * Then, provide this buffer as `void* state` to compression function. + */ LZ4LIB_API int LZ4_sizeofState(void); -LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration); +LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); -/*! -LZ4_compress_destSize() : - Reverse the logic, by compressing as much data as possible from 'source' buffer - into already allocated buffer 'dest' of size 'targetDestSize'. - This function either compresses the entire 'source' content into 'dest' if it's large enough, - or fill 'dest' buffer completely with as much data as possible from 'source'. - *sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'. - New value is necessarily <= old value. - return : Nb bytes written into 'dest' (necessarily <= targetDestSize) - or 0 if compression fails -*/ -LZ4LIB_API int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize); - +/*! LZ4_compress_destSize() : + * Reverse the logic : compresses as much data as possible from 'src' buffer + * into already allocated buffer 'dst', of size >= 'targetDestSize'. + * This function either compresses the entire 'src' content into 'dst' if it's large enough, + * or fill 'dst' buffer completely with as much data as possible from 'src'. + * note: acceleration parameter is fixed to "default". + * + * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'. + * New value is necessarily <= input value. + * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize) + * or 0 if compression fails. + * + * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+): + * the produced compressed content could, in specific circumstances, + * require to be decompressed into a destination buffer larger + * by at least 1 byte than the content to decompress. + * If an application uses `LZ4_compress_destSize()`, + * it's highly recommended to update liblz4 to v1.9.2 or better. + * If this can't be done or ensured, + * the receiving decompression function should provide + * a dstCapacity which is > decompressedSize, by at least 1 byte. + * See https://github.com/lz4/lz4/issues/859 for details + */ +LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize); -/*! -LZ4_decompress_fast() : - originalSize : is the original and therefore uncompressed size - return : the number of bytes read from the source buffer (in other words, the compressed size) - If the source stream is detected malformed, the function will stop decoding and return a negative result. - Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes. - note : This function fully respect memory boundaries for properly formed compressed data. - It is a bit faster than LZ4_decompress_safe(). - However, it does not provide any protection against intentionally modified data stream (malicious input). - Use this function in trusted environment only (data to decode comes from a trusted source). -*/ -LZ4LIB_API int LZ4_decompress_fast (const char* source, char* dest, int originalSize); -/*! -LZ4_decompress_safe_partial() : - This function decompress a compressed block of size 'compressedSize' at position 'source' - into destination buffer 'dest' of size 'maxDecompressedSize'. - The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached, - reducing decompression time. - return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize) - Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller. - Always control how many bytes were decoded. - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets -*/ -LZ4LIB_API int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize); +/*! LZ4_decompress_safe_partial() : + * Decompress an LZ4 compressed block, of size 'srcSize' at position 'src', + * into destination buffer 'dst' of size 'dstCapacity'. + * Up to 'targetOutputSize' bytes will be decoded. + * The function stops decoding on reaching this objective. + * This can be useful to boost performance + * whenever only the beginning of a block is required. + * + * @return : the number of bytes decoded in `dst` (necessarily <= targetOutputSize) + * If source stream is detected malformed, function returns a negative result. + * + * Note 1 : @return can be < targetOutputSize, if compressed block contains less data. + * + * Note 2 : targetOutputSize must be <= dstCapacity + * + * Note 3 : this function effectively stops decoding on reaching targetOutputSize, + * so dstCapacity is kind of redundant. + * This is because in older versions of this function, + * decoding operation would still write complete sequences. + * Therefore, there was no guarantee that it would stop writing at exactly targetOutputSize, + * it could write more bytes, though only up to dstCapacity. + * Some "margin" used to be required for this operation to work properly. + * Thankfully, this is no longer necessary. + * The function nonetheless keeps the same signature, in an effort to preserve API compatibility. + * + * Note 4 : If srcSize is the exact size of the block, + * then targetOutputSize can be any value, + * including larger than the block's decompressed size. + * The function will, at most, generate block's decompressed size. + * + * Note 5 : If srcSize is _larger_ than block's compressed size, + * then targetOutputSize **MUST** be <= block's decompressed size. + * Otherwise, *silent corruption will occur*. + */ +LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity); /*-********************************************* * Streaming Compression Functions ***********************************************/ -typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ +typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ -/*! LZ4_createStream() and LZ4_freeStream() : - * LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure. - * LZ4_freeStream() releases its memory. - */ LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr); -/*! LZ4_resetStream() : - * An LZ4_stream_t structure can be allocated once and re-used multiple times. - * Use this function to start compressing a new stream. +/*! LZ4_resetStream_fast() : v1.9.0+ + * Use this to prepare an LZ4_stream_t for a new chain of dependent blocks + * (e.g., LZ4_compress_fast_continue()). + * + * An LZ4_stream_t must be initialized once before usage. + * This is automatically done when created by LZ4_createStream(). + * However, should the LZ4_stream_t be simply declared on stack (for example), + * it's necessary to initialize it first, using LZ4_initStream(). + * + * After init, start any new stream with LZ4_resetStream_fast(). + * A same LZ4_stream_t can be re-used multiple times consecutively + * and compress multiple streams, + * provided that it starts each new stream with LZ4_resetStream_fast(). + * + * LZ4_resetStream_fast() is much faster than LZ4_initStream(), + * but is not compatible with memory regions containing garbage data. + * + * Note: it's only useful to call LZ4_resetStream_fast() + * in the context of streaming compression. + * The *extState* functions perform their own resets. + * Invoking LZ4_resetStream_fast() before is redundant, and even counterproductive. */ -LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); +LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr); /*! LZ4_loadDict() : - * Use this function to load a static dictionary into LZ4_stream_t. - * Any previous data will be forgotten, only 'dictionary' will remain in memory. + * Use this function to reference a static dictionary into LZ4_stream_t. + * The dictionary must remain available during compression. + * LZ4_loadDict() triggers a reset, so any previous data will be forgotten. + * The same dictionary will have to be loaded on decompression side for successful decoding. + * Dictionary are useful for better compression of small data (KB range). + * While LZ4 accept any input as dictionary, + * results are generally better when using Zstandard's Dictionary Builder. * Loading a size of 0 is allowed, and is the same as reset. - * @return : dictionary size, in bytes (necessarily <= 64 KB) + * @return : loaded dictionary size, in bytes (necessarily <= 64 KB) */ LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); /*! LZ4_compress_fast_continue() : - * Compress content into 'src' using data from previously compressed blocks, improving compression ratio. - * 'dst' buffer must be already allocated. + * Compress 'src' content using data from previously compressed blocks, for better compression ratio. + * 'dst' buffer must be already allocated. * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. * - * Important : Up to 64KB of previously compressed data is assumed to remain present and unmodified in memory ! - * Special 1 : If input buffer is a double-buffer, it can have any size, including < 64 KB. - * Special 2 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. - * * @return : size of compressed block - * or 0 if there is an error (typically, compressed data cannot fit into 'dst') - * After an error, the stream status is invalid, it can only be reset or freed. + * or 0 if there is an error (typically, cannot fit into 'dst'). + * + * Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block. + * Each block has precise boundaries. + * Each block must be decompressed separately, calling LZ4_decompress_*() with relevant metadata. + * It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together. + * + * Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory ! + * + * Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB. + * Make sure that buffers are separated, by at least one byte. + * This construction ensures that each block only depends on previous block. + * + * Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. + * + * Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed. */ LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); /*! LZ4_saveDict() : - * If previously compressed data block is not guaranteed to remain available at its current memory location, + * If last 64KB data cannot be guaranteed to remain available at its current memory location, * save it into a safer place (char* safeBuffer). - * Note : it's not necessary to call LZ4_loadDict() after LZ4_saveDict(), dictionary is immediately usable. - * @return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. + * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(), + * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables. + * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error. */ -LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize); +LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize); /*-********************************************** * Streaming Decompression Functions * Bufferless synchronous API ************************************************/ -typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* incomplete type (defined later) */ +typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */ /*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : - * creation / destruction of streaming decompression tracking structure. - * A tracking structure can be re-used multiple times sequentially. */ + * creation / destruction of streaming decompression tracking context. + * A tracking context can be re-used multiple times. + */ LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); /*! LZ4_setStreamDecode() : - * An LZ4_streamDecode_t structure can be allocated once and re-used multiple times. + * An LZ4_streamDecode_t context can be allocated once and re-used multiple times. * Use this function to start decompression of a new stream of blocks. - * A dictionary can optionnally be set. Use NULL or size 0 for a simple reset order. + * A dictionary can optionally be set. Use NULL or size 0 for a reset order. + * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. * @return : 1 if OK, 0 if error */ LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); +/*! LZ4_decoderRingBufferSize() : v1.8.2+ + * Note : in a ring buffer scenario (optional), + * blocks are presumed decompressed next to each other + * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize), + * at which stage it resumes from beginning of ring buffer. + * When setting such a ring buffer for streaming decompression, + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize); +#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize)) /* for static allocation; maxBlockSize presumed valid */ + /*! LZ4_decompress_*_continue() : * These decoding functions allow decompression of consecutive blocks in "streaming" mode. * A block is an unsplittable entity, it must be presented entirely to a decompression function. - * Decompression functions only accept one block at a time. - * Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB). - * - * Special : if application sets a ring buffer for decompression, it must respect one of the following conditions : - * - Exactly same size as encoding buffer, with same update rule (block boundaries at same positions) - * In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB). - * - Larger than encoding buffer, by a minimum of maxBlockSize more bytes. - * maxBlockSize is implementation dependent. It's the maximum size of any single block. + * Decompression functions only accepts one block at a time. + * The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded. + * If less than 64KB of data has been decoded, all the data must be present. + * + * Special : if decompression side sets a ring buffer, it must respect one of the following conditions : + * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize). + * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes. + * In which case, encoding and decoding buffers do not need to be synchronized. + * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize. + * - Synchronized mode : + * Decompression buffer size is _exactly_ the same as compression buffer size, + * and follows exactly same update rule (block boundaries at same positions), + * and decoding function is provided with exact decompressed size of each block (exception for last block of the stream), + * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB). + * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes. * In which case, encoding and decoding buffers do not need to be synchronized, * and encoding ring buffer can have any size, including small ones ( < 64 KB). - * - _At least_ 64 KB + 8 bytes + maxBlockSize. - * In which case, encoding and decoding buffers do not need to be synchronized, - * and encoding ring buffer can have any size, including larger than decoding buffer. - * Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer, - * and indicate where it is saved using LZ4_setStreamDecode() before decompressing next block. + * + * Whenever these conditions are not possible, + * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression, + * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block. */ -LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize); -LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize); +LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity); /*! LZ4_decompress_*_usingDict() : * These decoding functions work the same as * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() * They are stand-alone, and don't need an LZ4_streamDecode_t structure. + * Dictionary is presumed stable : it must remain accessible and unmodified during decompression. + * Performance tip : Decompression speed can be substantially increased + * when dst == dictStart + dictSize. */ -LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize); -LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize); +LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* src, char* dst, int srcSize, int dstCapcity, const char* dictStart, int dictSize); + +#endif /* LZ4_H_2983827168210 */ -/*^********************************************** +/*^************************************* * !!!!!! STATIC LINKING ONLY !!!!!! - ***********************************************/ -/*-************************************ - * Private definitions - ************************************** - * Do not use these definitions. - * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. - * Using these definitions will expose code to API and/or ABI break in future versions of the library. - **************************************/ + ***************************************/ + +/*-**************************************************************************** + * Experimental section + * + * Symbols declared in this section must be considered unstable. Their + * signatures or semantics may change, or they may be removed altogether in the + * future. They are therefore only safe to depend on when the caller is + * statically linked against the library. + * + * To protect against unsafe usage, not only are the declarations guarded, + * the definitions are hidden by default + * when building LZ4 as a shared/dynamic library. + * + * In order to access these declarations, + * define LZ4_STATIC_LINKING_ONLY in your application + * before including LZ4's headers. + * + * In order to make their implementations accessible dynamically, you must + * define LZ4_PUBLISH_STATIC_FUNCTIONS when building the LZ4 library. + ******************************************************************************/ + +#ifdef LZ4_STATIC_LINKING_ONLY + +#ifndef LZ4_STATIC_3504398509 +#define LZ4_STATIC_3504398509 + +#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS +#define LZ4LIB_STATIC_API LZ4LIB_API +#else +#define LZ4LIB_STATIC_API +#endif + + +/*! LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. + * It is only safe to call if the state buffer is known to be correctly initialized already + * (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized"). + * From a high level, the difference is that + * this function initializes the provided state with a call to something like LZ4_resetStream_fast() + * while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream(). + */ +LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_attach_dictionary() : + * This is an experimental API that allows + * efficient use of a static dictionary many times. + * + * Rather than re-loading the dictionary buffer into a working context before + * each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a + * working LZ4_stream_t, this function introduces a no-copy setup mechanism, + * in which the working stream references the dictionary stream in-place. + * + * Several assumptions are made about the state of the dictionary stream. + * Currently, only streams which have been prepared by LZ4_loadDict() should + * be expected to work. + * + * Alternatively, the provided dictionaryStream may be NULL, + * in which case any existing dictionary stream is unset. + * + * If a dictionary is provided, it replaces any pre-existing stream history. + * The dictionary contents are the only history that can be referenced and + * logically immediately precede the data compressed in the first subsequent + * compression call. + * + * The dictionary will only remain attached to the working stream through the + * first compression call, at the end of which it is cleared. The dictionary + * stream (and source buffer) must remain in-place / accessible / unchanged + * through the completion of the first compression call on the stream. + */ +LZ4LIB_STATIC_API void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream); + + +/*! In-place compression and decompression + * + * It's possible to have input and output sharing the same buffer, + * for highly contrained memory environments. + * In both cases, it requires input to lay at the end of the buffer, + * and decompression to start at beginning of the buffer. + * Buffer size must feature some margin, hence be larger than final size. + * + * |<------------------------buffer--------------------------------->| + * |<-----------compressed data--------->| + * |<-----------decompressed size------------------>| + * |<----margin---->| + * + * This technique is more useful for decompression, + * since decompressed size is typically larger, + * and margin is short. + * + * In-place decompression will work inside any buffer + * which size is >= LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize). + * This presumes that decompressedSize > compressedSize. + * Otherwise, it means compression actually expanded data, + * and it would be more efficient to store such data with a flag indicating it's not compressed. + * This can happen when data is not compressible (already compressed, or encrypted). + * + * For in-place compression, margin is larger, as it must be able to cope with both + * history preservation, requiring input data to remain unmodified up to LZ4_DISTANCE_MAX, + * and data expansion, which can happen when input is not compressible. + * As a consequence, buffer size requirements are much higher, + * and memory savings offered by in-place compression are more limited. + * + * There are ways to limit this cost for compression : + * - Reduce history size, by modifying LZ4_DISTANCE_MAX. + * Note that it is a compile-time constant, so all compressions will apply this limit. + * Lower values will reduce compression ratio, except when input_size < LZ4_DISTANCE_MAX, + * so it's a reasonable trick when inputs are known to be small. + * - Require the compressor to deliver a "maximum compressed size". + * This is the `dstCapacity` parameter in `LZ4_compress*()`. + * When this size is < LZ4_COMPRESSBOUND(inputSize), then compression can fail, + * in which case, the return code will be 0 (zero). + * The caller must be ready for these cases to happen, + * and typically design a backup scheme to send data uncompressed. + * The combination of both techniques can significantly reduce + * the amount of margin required for in-place compression. + * + * In-place compression can work in any buffer + * which size is >= (maxCompressedSize) + * with maxCompressedSize == LZ4_COMPRESSBOUND(srcSize) for guaranteed compression success. + * LZ4_COMPRESS_INPLACE_BUFFER_SIZE() depends on both maxCompressedSize and LZ4_DISTANCE_MAX, + * so it's possible to reduce memory requirements by playing with them. + */ + +#define LZ4_DECOMPRESS_INPLACE_MARGIN(compressedSize) (((compressedSize) >> 8) + 32) +#define LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize) ((decompressedSize) + LZ4_DECOMPRESS_INPLACE_MARGIN(decompressedSize)) /**< note: presumes that compressedSize < decompressedSize. note2: margin is overestimated a bit, since it could use compressedSize instead */ + +#ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */ +# define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */ +#endif + +#define LZ4_COMPRESS_INPLACE_MARGIN (LZ4_DISTANCE_MAX + 32) /* LZ4_DISTANCE_MAX can be safely replaced by srcSize when it's smaller */ +#define LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCompressedSize) ((maxCompressedSize) + LZ4_COMPRESS_INPLACE_MARGIN) /**< maxCompressedSize is generally LZ4_COMPRESSBOUND(inputSize), but can be set to any lower value, with the risk that compression can fail (return code 0(zero)) */ + +#endif /* LZ4_STATIC_3504398509 */ +#endif /* LZ4_STATIC_LINKING_ONLY */ + + + +#ifndef LZ4_H_98237428734687 +#define LZ4_H_98237428734687 + +/*-************************************************************ + * Private Definitions + ************************************************************** + * Do not use these definitions directly. + * They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. + * Accessing members will expose user code to API and/or ABI break in future versions of the library. + **************************************************************/ #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) #define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) #define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -#include - -typedef struct { - uint32_t hashTable[LZ4_HASH_SIZE_U32]; - uint32_t currentOffset; - uint32_t initCheck; - const uint8_t* dictionary; - uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */ - uint32_t dictSize; -} LZ4_stream_t_internal; - -typedef struct { - const uint8_t* externalDict; - size_t extDictSize; - const uint8_t* prefixEnd; - size_t prefixSize; -} LZ4_streamDecode_t_internal; - +# include + typedef int8_t LZ4_i8; + typedef uint8_t LZ4_byte; + typedef uint16_t LZ4_u16; + typedef uint32_t LZ4_u32; #else + typedef signed char LZ4_i8; + typedef unsigned char LZ4_byte; + typedef unsigned short LZ4_u16; + typedef unsigned int LZ4_u32; +#endif -typedef struct { - unsigned int hashTable[LZ4_HASH_SIZE_U32]; - unsigned int currentOffset; - unsigned int initCheck; - const unsigned char* dictionary; - unsigned char* bufferStart; /* obsolete, used for slideInputBuffer */ - unsigned int dictSize; -} LZ4_stream_t_internal; +typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; +struct LZ4_stream_t_internal { + LZ4_u32 hashTable[LZ4_HASH_SIZE_U32]; + LZ4_u32 currentOffset; + LZ4_u32 tableType; + const LZ4_byte* dictionary; + const LZ4_stream_t_internal* dictCtx; + LZ4_u32 dictSize; +}; typedef struct { - const unsigned char* externalDict; + const LZ4_byte* externalDict; size_t extDictSize; - const unsigned char* prefixEnd; + const LZ4_byte* prefixEnd; size_t prefixSize; } LZ4_streamDecode_t_internal; -#endif -/*! - * LZ4_stream_t : - * information structure to track an LZ4 stream. - * init this structure before first use. - * note : only use in association with static linking ! - * this definition is not API/ABI safe, - * it may change in a future version ! +/*! LZ4_stream_t : + * Do not use below internal definitions directly ! + * Declare or allocate an LZ4_stream_t instead. + * LZ4_stream_t can also be created using LZ4_createStream(), which is recommended. + * The structure definition can be convenient for static allocation + * (on stack, or as part of larger structure). + * Init this structure with LZ4_initStream() before first use. + * note : only use this definition in association with static linking ! + * this definition is not API/ABI safe, and may change in future versions. */ -#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) -#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(uint64_t)) +#define LZ4_STREAMSIZE 16416 /* static size, for inter-version compatibility */ +#define LZ4_STREAMSIZE_VOIDP (LZ4_STREAMSIZE / sizeof(void*)) union LZ4_stream_u { - uint64_t table[LZ4_STREAMSIZE_U64]; + void* table[LZ4_STREAMSIZE_VOIDP]; LZ4_stream_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_stream_t */ +}; /* previously typedef'd to LZ4_stream_t */ -/*! - * LZ4_streamDecode_t : - * information structure to track an LZ4 stream during decompression. - * init this structure using LZ4_setStreamDecode (or memset()) before first use - * note : only use in association with static linking ! - * this definition is not API/ABI safe, - * and may change in a future version ! +/*! LZ4_initStream() : v1.9.0+ + * An LZ4_stream_t structure must be initialized at least once. + * This is automatically done when invoking LZ4_createStream(), + * but it's not when the structure is simply declared on stack (for example). + * + * Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t. + * It can also initialize any arbitrary buffer of sufficient size, + * and will @return a pointer of proper type upon initialization. + * + * Note : initialization fails if size and alignment conditions are not respected. + * In which case, the function will @return NULL. + * Note2: An LZ4_stream_t structure guarantees correct alignment and size. + * Note3: Before v1.9.0, use LZ4_resetStream() instead + */ +LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size); + + +/*! LZ4_streamDecode_t : + * information structure to track an LZ4 stream during decompression. + * init this structure using LZ4_setStreamDecode() before first use. + * note : only use in association with static linking ! + * this definition is not API/ABI safe, + * and may change in a future version ! */ -#define LZ4_STREAMDECODESIZE_U64 4 -#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(uint64_t)) +#define LZ4_STREAMDECODESIZE_U64 (4 + ((sizeof(void*)==16) ? 2 : 0) /*AS-400*/ ) +#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) union LZ4_streamDecode_u { - uint64_t table[LZ4_STREAMDECODESIZE_U64]; + unsigned long long table[LZ4_STREAMDECODESIZE_U64]; LZ4_streamDecode_t_internal internal_donotuse; } ; /* previously typedef'd to LZ4_streamDecode_t */ + /*-************************************ * Obsolete Functions **************************************/ /*! Deprecation warnings - Should deprecation warnings be a problem, - it is generally possible to disable them, - typically with -Wno-deprecated-declarations for gcc - or _CRT_SECURE_NO_WARNINGS in Visual. - Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */ + * + * Deprecated functions make the compiler generate a warning when invoked. + * This is meant to invite users to update their source code. + * Should deprecation warnings be a problem, it is generally possible to disable them, + * typically with -Wno-deprecated-declarations for gcc + * or _CRT_SECURE_NO_WARNINGS in Visual. + * + * Another method is to define LZ4_DISABLE_DEPRECATE_WARNINGS + * before including the header file. + */ #ifdef LZ4_DISABLE_DEPRECATE_WARNINGS # define LZ4_DEPRECATED(message) /* disable deprecation warnings */ #else -# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# if defined(__clang__) /* clang doesn't handle mixed C++11 and CNU attributes */ -# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) -# elif defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ +# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ # define LZ4_DEPRECATED(message) [[deprecated(message)]] -# elif (LZ4_GCC_VERSION >= 405) -# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) -# elif (LZ4_GCC_VERSION >= 301) -# define LZ4_DEPRECATED(message) __attribute__((deprecated)) # elif defined(_MSC_VER) # define LZ4_DEPRECATED(message) __declspec(deprecated(message)) +# elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 45)) +# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) +# elif defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 31) +# define LZ4_DEPRECATED(message) __attribute__((deprecated)) # else -# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler") -# define LZ4_DEPRECATED(message) +# pragma message("WARNING: LZ4_DEPRECATED needs custom implementation for this compiler") +# define LZ4_DEPRECATED(message) /* disabled */ # endif #endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ -/* Obsolete compression functions */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_default() instead") int LZ4_compress (const char* source, char* dest, int sourceSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_default() instead") int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); +/*! Obsolete compression functions (since v1.7.3) */ +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress (const char* src, char* dest, int srcSize); +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* src, char* dest, int srcSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); -/* Obsolete decompression functions */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_fast() instead") int LZ4_uncompress (const char* source, char* dest, int outputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_safe() instead") int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); +/*! Obsolete decompression functions (since v1.8.0) */ +LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize); +LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); + +/* Obsolete streaming functions (since v1.7.0) + * degraded functionality; do not use! + * + * In order to perform streaming compression, these functions depended on data + * that is no longer tracked in the state. They have been preserved as well as + * possible: using them will still produce a correct output. However, they don't + * actually retain any history between compression calls. The compression ratio + * achieved will therefore be no better than compressing each chunk + * independently. + */ +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void); +LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer (void* state); + +/*! Obsolete streaming decoding functions (since v1.7.0) */ +LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); +LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); + +/*! Obsolete LZ4_decompress_fast variants (since v1.9.0) : + * These functions used to be faster than LZ4_decompress_safe(), + * but this is no longer the case. They are now slower. + * This is because LZ4_decompress_fast() doesn't know the input size, + * and therefore must progress more cautiously into the input buffer to not read beyond the end of block. + * On top of that `LZ4_decompress_fast()` is not protected vs malformed or malicious inputs, making it a security liability. + * As a consequence, LZ4_decompress_fast() is strongly discouraged, and deprecated. + * + * The last remaining LZ4_decompress_fast() specificity is that + * it can decompress a block without knowing its compressed size. + * Such functionality can be achieved in a more secure manner + * by employing LZ4_decompress_safe_partial(). + * + * Parameters: + * originalSize : is the uncompressed size to regenerate. + * `dst` must be already allocated, its size must be >= 'originalSize' bytes. + * @return : number of bytes read from source buffer (== compressed size). + * The function expects to finish at block's end exactly. + * If the source stream is detected malformed, the function stops decoding and returns a negative result. + * note : LZ4_decompress_fast*() requires originalSize. Thanks to this information, it never writes past the output buffer. + * However, since it doesn't know its 'src' size, it may read an unknown amount of input, past input buffer bounds. + * Also, since match offsets are not validated, match reads from 'src' may underflow too. + * These issues never happen if input (compressed) data is correct. + * But they may happen if input data is invalid (error or intentional tampering). + * As a consequence, use these functions in trusted environments with trusted data **only**. + */ +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead") +LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize); +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead") +LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize); +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead") +LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize); -/* Obsolete streaming functions; use new streaming interface whenever possible */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_createStream() instead") void* LZ4_create (char* inputBuffer); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_createStream() instead") int LZ4_sizeofStreamState(void); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_resetStream() instead") int LZ4_resetStreamState(void* state, char* inputBuffer); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_saveDict() instead") char* LZ4_slideInputBuffer (void* state); +/*! LZ4_resetStream() : + * An LZ4_stream_t structure must be initialized at least once. + * This is done with LZ4_initStream(), or LZ4_resetStream(). + * Consider switching to LZ4_initStream(), + * invoking LZ4_resetStream() will trigger deprecation warnings in the future. + */ +LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); -/* Obsolete streaming decoding functions */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); -#endif /* LZ4_H_2983827168210 */ +#endif /* LZ4_H_98237428734687 */ #if defined (__cplusplus) diff --git a/deps/lz4/src/lz4.c b/deps/lz4/src/lz4.c index c48baa63fc1fd7f666e5e8f183e682e262bb0448..9f5e9bfa0839f8e1347d2abb3d867b21ff740215 100644 --- a/deps/lz4/src/lz4.c +++ b/deps/lz4/src/lz4.c @@ -1,6 +1,6 @@ /* LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2017, Yann Collet. + Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) @@ -32,7 +32,6 @@ - LZ4 source repository : https://github.com/lz4/lz4 */ - /*-************************************ * Tuning parameters **************************************/ @@ -46,10 +45,16 @@ #endif /* - * ACCELERATION_DEFAULT : + * LZ4_ACCELERATION_DEFAULT : * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 */ -#define ACCELERATION_DEFAULT 1 +#define LZ4_ACCELERATION_DEFAULT 1 +/* + * LZ4_ACCELERATION_MAX : + * Any "acceleration" value higher than this threshold + * get treated as LZ4_ACCELERATION_MAX instead (fix #876) + */ +#define LZ4_ACCELERATION_MAX 65537 /*-************************************ @@ -69,9 +74,11 @@ * Prefer these methods in priority order (0 > 1 > 2) */ #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ -# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# if defined(__GNUC__) && \ + ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \ + || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) # define LZ4_FORCE_MEMORY_ACCESS 2 -# elif defined(__INTEL_COMPILER) || defined(__GNUC__) +# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) # define LZ4_FORCE_MEMORY_ACCESS 1 # endif #endif @@ -80,14 +87,33 @@ * LZ4_FORCE_SW_BITCOUNT * Define this parameter if your target system or compiler does not support hardware bit count */ -#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */ +#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */ +# undef LZ4_FORCE_SW_BITCOUNT /* avoid double def */ # define LZ4_FORCE_SW_BITCOUNT #endif + /*-************************************ * Dependency **************************************/ +/* + * LZ4_SRC_INCLUDED: + * Amalgamation flag, whether lz4.c is included + */ +#ifndef LZ4_SRC_INCLUDED +# define LZ4_SRC_INCLUDED 1 +#endif + +#ifndef LZ4_STATIC_LINKING_ONLY +#define LZ4_STATIC_LINKING_ONLY +#endif + +#ifndef LZ4_DISABLE_DEPRECATE_WARNINGS +#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */ +#endif + +#define LZ4_STATIC_LINKING_ONLY /* LZ4_DISTANCE_MAX */ #include "lz4.h" /* see also "memory routines" below */ @@ -95,10 +121,9 @@ /*-************************************ * Compiler Options **************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# include -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) /* Visual Studio 2005+ */ +# include /* only present in VS2005+ */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ #endif /* _MSC_VER */ #ifndef LZ4_FORCE_INLINE @@ -117,29 +142,135 @@ # endif /* _MSC_VER */ #endif /* LZ4_FORCE_INLINE */ +/* LZ4_FORCE_O2 and LZ4_FORCE_INLINE + * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8, + * together with a simple 8-byte copy loop as a fall-back path. + * However, this optimization hurts the decompression speed by >30%, + * because the execution does not go to the optimized loop + * for typical compressible data, and all of the preamble checks + * before going to the fall-back path become useless overhead. + * This optimization happens only with the -O3 flag, and -O2 generates + * a simple 8-byte copy loop. + * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8 + * functions are annotated with __attribute__((optimize("O2"))), + * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute + * of LZ4_wildCopy8 does not affect the compression speed. + */ +#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__) +# define LZ4_FORCE_O2 __attribute__((optimize("O2"))) +# undef LZ4_FORCE_INLINE +# define LZ4_FORCE_INLINE static __inline __attribute__((optimize("O2"),always_inline)) +#else +# define LZ4_FORCE_O2 +#endif + #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) # define expect(expr,value) (__builtin_expect ((expr),(value)) ) #else # define expect(expr,value) (expr) #endif +#ifndef likely #define likely(expr) expect((expr) != 0, 1) +#endif +#ifndef unlikely #define unlikely(expr) expect((expr) != 0, 0) +#endif + +/* Should the alignment test prove unreliable, for some reason, + * it can be disabled by setting LZ4_ALIGN_TEST to 0 */ +#ifndef LZ4_ALIGN_TEST /* can be externally provided */ +# define LZ4_ALIGN_TEST 1 +#endif /*-************************************ * Memory routines **************************************/ -#include /* malloc, calloc, free */ -#define ALLOCATOR(n,s) calloc(n,s) -#define FREEMEM free +#ifdef LZ4_USER_MEMORY_FUNCTIONS +/* memory management functions can be customized by user project. + * Below functions must exist somewhere in the Project + * and be available at link time */ +void* LZ4_malloc(size_t s); +void* LZ4_calloc(size_t n, size_t s); +void LZ4_free(void* p); +# define ALLOC(s) LZ4_malloc(s) +# define ALLOC_AND_ZERO(s) LZ4_calloc(1,s) +# define FREEMEM(p) LZ4_free(p) +#else +# include /* malloc, calloc, free */ +# define ALLOC(s) malloc(s) +# define ALLOC_AND_ZERO(s) calloc(1,s) +# define FREEMEM(p) free(p) +#endif + #include /* memset, memcpy */ -#define MEM_INIT memset +#define MEM_INIT(p,v,s) memset((p),(v),(s)) + + +/*-************************************ +* Common Constants +**************************************/ +#define MINMATCH 4 + +#define WILDCOPYLENGTH 8 +#define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */ +#define FASTLOOP_SAFE_DISTANCE 64 +static const int LZ4_minLength = (MFLIMIT+1); + +#define KB *(1 <<10) +#define MB *(1 <<20) +#define GB *(1U<<30) + +#define LZ4_DISTANCE_ABSOLUTE_MAX 65535 +#if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */ +# error "LZ4_DISTANCE_MAX is too big : must be <= 65535" +#endif + +#define ML_BITS 4 +#define ML_MASK ((1U<=1) +# include +#else +# ifndef assert +# define assert(condition) ((void)0) +# endif +#endif + +#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */ + +#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) +# include + static int g_debuglog_enable = 1; +# define DEBUGLOG(l, ...) { \ + if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ + fprintf(stderr, __FILE__ ": "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, " \n"); \ + } } +#else +# define DEBUGLOG(l, ...) {} /* disabled */ +#endif + +static int LZ4_isAligned(const void* ptr, size_t alignment) +{ + return ((size_t)ptr & (alignment -1)) == 0; +} /*-************************************ -* Basic Types +* Types **************************************/ +#include #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) # include typedef uint8_t BYTE; @@ -149,11 +280,14 @@ typedef uint64_t U64; typedef uintptr_t uptrval; #else +# if UINT_MAX != 4294967295UL +# error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4" +# endif typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; - typedef uint64_t U64; + typedef unsigned long long U64; typedef size_t uptrval; /* generally true, except OpenVMS-64 */ #endif @@ -163,9 +297,31 @@ typedef size_t reg_t; /* 32-bits in x32 mode */ #endif +typedef enum { + notLimited = 0, + limitedOutput = 1, + fillOutput = 2 +} limitedOutput_directive; + + /*-************************************ * Reading and writing into memory **************************************/ + +/** + * LZ4 relies on memcpy with a constant size being inlined. In freestanding + * environments, the compiler can't assume the implementation of memcpy() is + * standard compliant, so it can't apply its specialized memcpy() inlining + * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze + * memcpy() as if it were standard compliant, so it can inline it in freestanding + * environments. This is needed when decompressing the Linux Kernel, for example. + */ +#if defined(__GNUC__) && (__GNUC__ >= 4) +#define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size) +#else +#define LZ4_memcpy(dst, src, size) memcpy(dst, src, size) +#endif + static unsigned LZ4_isLittleEndian(void) { const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ @@ -196,31 +352,31 @@ static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArc static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } -#else /* safe and portable access through memcpy() */ +#else /* safe and portable access using memcpy() */ static U16 LZ4_read16(const void* memPtr) { - U16 val; memcpy(&val, memPtr, sizeof(val)); return val; + U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; } static U32 LZ4_read32(const void* memPtr) { - U32 val; memcpy(&val, memPtr, sizeof(val)); return val; + U32 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; } static reg_t LZ4_read_ARCH(const void* memPtr) { - reg_t val; memcpy(&val, memPtr, sizeof(val)); return val; + reg_t val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; } static void LZ4_write16(void* memPtr, U16 value) { - memcpy(memPtr, &value, sizeof(value)); + LZ4_memcpy(memPtr, &value, sizeof(value)); } static void LZ4_write32(void* memPtr, U32 value) { - memcpy(memPtr, &value, sizeof(value)); + LZ4_memcpy(memPtr, &value, sizeof(value)); } #endif /* LZ4_FORCE_MEMORY_ACCESS */ @@ -247,130 +403,216 @@ static void LZ4_writeLE16(void* memPtr, U16 value) } } -static void LZ4_copy8(void* dst, const void* src) -{ - memcpy(dst,src,8); -} - /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ -static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd) +LZ4_FORCE_INLINE +void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd) { BYTE* d = (BYTE*)dstPtr; const BYTE* s = (const BYTE*)srcPtr; BYTE* const e = (BYTE*)dstEnd; - do { LZ4_copy8(d,s); d+=8; s+=8; } while (d= 16. */ +LZ4_FORCE_INLINE void +LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd) +{ + BYTE* d = (BYTE*)dstPtr; + const BYTE* s = (const BYTE*)srcPtr; + BYTE* const e = (BYTE*)dstEnd; -/*-************************************ -* Error detection -**************************************/ -#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ + do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d=2) -# include -# define DEBUGLOG(l, ...) { \ - if (l<=LZ4_DEBUG) { \ - fprintf(stderr, __FILE__ ": "); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, " \n"); \ - } } -#else -# define DEBUGLOG(l, ...) {} /* disabled */ +/* LZ4_memcpy_using_offset() presumes : + * - dstEnd >= dstPtr + MINMATCH + * - there is at least 8 bytes available to write after dstEnd */ +LZ4_FORCE_INLINE void +LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset) +{ + BYTE v[8]; + + assert(dstEnd >= dstPtr + MINMATCH); + + switch(offset) { + case 1: + MEM_INIT(v, *srcPtr, 8); + break; + case 2: + LZ4_memcpy(v, srcPtr, 2); + LZ4_memcpy(&v[2], srcPtr, 2); + LZ4_memcpy(&v[4], v, 4); + break; + case 4: + LZ4_memcpy(v, srcPtr, 4); + LZ4_memcpy(&v[4], srcPtr, 4); + break; + default: + LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset); + return; + } + + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + while (dstPtr < dstEnd) { + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + } +} #endif /*-************************************ * Common functions **************************************/ -static unsigned LZ4_NbCommonBytes (register reg_t val) +static unsigned LZ4_NbCommonBytes (reg_t val) { + assert(val != 0); if (LZ4_isLittleEndian()) { - if (sizeof(val)==8) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - uint64_t r = 0; - _BitScanForward64( &r, (U64)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctzll((U64)val) >> 3); + if (sizeof(val) == 8) { +# if defined(_MSC_VER) && (_MSC_VER >= 1800) && defined(_M_AMD64) && !defined(LZ4_FORCE_SW_BITCOUNT) + /* x64 CPUS without BMI support interpret `TZCNT` as `REP BSF` */ + return (unsigned)_tzcnt_u64(val) >> 3; +# elif defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanForward64(&r, (U64)val); + return (unsigned)r >> 3; +# elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_ctzll((U64)val) >> 3; # else - static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; - return DeBruijnBytePos[((U64)((val & -(int64_t)val) * 0x0218A392CDABBD3FULL)) >> 58]; + const U64 m = 0x0101010101010101ULL; + val ^= val - 1; + return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56); # endif } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - uint64_t r; - _BitScanForward( &r, (U32)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctz((U32)val) >> 3); +# if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r; + _BitScanForward(&r, (U32)val); + return (unsigned)r >> 3; +# elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_ctz((U32)val) >> 3; # else - static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; - return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; + const U32 m = 0x01010101; + return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24; # endif } } else /* Big Endian CPU */ { if (sizeof(val)==8) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - uint64_t r = 0; - _BitScanReverse64( &r, val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clzll((U64)val) >> 3); +# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_clzll((U64)val) >> 3; # else +#if 1 + /* this method is probably faster, + * but adds a 128 bytes lookup table */ + static const unsigned char ctz7_tab[128] = { + 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + }; + U64 const mask = 0x0101010101010101ULL; + U64 const t = (((val >> 8) - mask) | val) & mask; + return ctz7_tab[(t * 0x0080402010080402ULL) >> 57]; +#else + /* this method doesn't consume memory space like the previous one, + * but it contains several branches, + * that may end up slowing execution */ + static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits. + Just to avoid some static analyzer complaining about shift by 32 on 32-bits target. + Note that this code path is never triggered in 32-bits mode. */ unsigned r; - if (!(val>>32)) { r=4; } else { r=0; val>>=32; } + if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; } if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } r += (!val); return r; +#endif # endif } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - uint64_t r = 0; - _BitScanReverse( &r, (uint64_t)val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clz((U32)val) >> 3); +# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_clz((U32)val) >> 3; # else - unsigned r; - if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } - r += (!val); - return r; + val >>= 8; + val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) | + (val + 0x00FF0000)) >> 24; + return (unsigned)val ^ 3; # endif } } } + #define STEPSIZE sizeof(reg_t) -static unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) +LZ4_FORCE_INLINE +unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) { const BYTE* const pStart = pIn; - while (likely(pIn compression ru /*-************************************ * Local Structures and types **************************************/ -typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive; -typedef enum { byPtr, byU32, byU16 } tableType_t; - -typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive; +typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; + +/** + * This enum distinguishes several different modes of accessing previous + * content in the stream. + * + * - noDict : There is no preceding content. + * - withPrefix64k : Table entries up to ctx->dictSize before the current blob + * blob being compressed are valid and refer to the preceding + * content (of length ctx->dictSize), which is available + * contiguously preceding in memory the content currently + * being compressed. + * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere + * else in memory, starting at ctx->dictionary with length + * ctx->dictSize. + * - usingDictCtx : Like usingExtDict, but everything concerning the preceding + * content is in a separate context, pointed to by + * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table + * entries in the current context that refer to positions + * preceding the beginning of the current compression are + * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx + * ->dictSize describe the location and size of the preceding + * content, and matches are found by looking in the ctx + * ->dictCtx->hashTable. + */ +typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; -typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; -typedef enum { full = 0, partial = 1 } earlyEnd_directive; - /*-************************************ * Local Utils @@ -411,13 +672,30 @@ typedef enum { full = 0, partial = 1 } earlyEnd_directive; int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } -int LZ4_sizeofState() { return LZ4_STREAMSIZE; } +int LZ4_sizeofState(void) { return LZ4_STREAMSIZE; } +/*-************************************ +* Internal Definitions used in Tests +**************************************/ +#if defined (__cplusplus) +extern "C" { +#endif + +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize); + +int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, + int compressedSize, int maxOutputSize, + const void* dictStart, size_t dictSize); + +#if defined (__cplusplus) +} +#endif + /*-****************************** * Compression functions ********************************/ -static U32 LZ4_hash4(U32 sequence, tableType_t const tableType) +LZ4_FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType) { if (tableType == byU16) return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); @@ -425,15 +703,16 @@ static U32 LZ4_hash4(U32 sequence, tableType_t const tableType) return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); } -static U32 LZ4_hash5(U64 sequence, tableType_t const tableType) +LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType) { - static const U64 prime5bytes = 889523592379ULL; - static const U64 prime8bytes = 11400714785074694791ULL; const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; - if (LZ4_isLittleEndian()) + if (LZ4_isLittleEndian()) { + const U64 prime5bytes = 889523592379ULL; return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); - else + } else { + const U64 prime8bytes = 11400714785074694791ULL; return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); + } } LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) @@ -442,10 +721,37 @@ LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tab return LZ4_hash4(LZ4_read32(p), tableType); } -static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase) +LZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType) +{ + switch (tableType) + { + default: /* fallthrough */ + case clearedTable: { /* illegal! */ assert(0); return; } + case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = NULL; return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = 0; return; } + case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = 0; return; } + } +} + +LZ4_FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType) +{ + switch (tableType) + { + default: /* fallthrough */ + case clearedTable: /* fallthrough */ + case byPtr: { /* illegal! */ assert(0); return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; } + case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; } + } +} + +LZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h, + void* tableBase, tableType_t const tableType, + const BYTE* srcBase) { switch (tableType) { + case clearedTable: { /* illegal! */ assert(0); return; } case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } @@ -458,71 +764,161 @@ LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_ LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); } -static const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase) +/* LZ4_getIndexOnHash() : + * Index of match position registered in hash table. + * hash position must be calculated by using base+index, or dictBase+index. + * Assumption 1 : only valid if tableType == byU32 or byU16. + * Assumption 2 : h is presumed valid (within limits of hash table) + */ +LZ4_FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType) +{ + LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); + if (tableType == byU32) { + const U32* const hashTable = (const U32*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-2))); + return hashTable[h]; + } + if (tableType == byU16) { + const U16* const hashTable = (const U16*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-1))); + return hashTable[h]; + } + assert(0); return 0; /* forbidden case */ +} + +static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase) { - if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; } - if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; } - { const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ + if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; } + if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; } + { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ } -LZ4_FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +LZ4_FORCE_INLINE const BYTE* +LZ4_getPosition(const BYTE* p, + const void* tableBase, tableType_t tableType, + const BYTE* srcBase) { U32 const h = LZ4_hashPosition(p, tableType); return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); } +LZ4_FORCE_INLINE void +LZ4_prepareTable(LZ4_stream_t_internal* const cctx, + const int inputSize, + const tableType_t tableType) { + /* If the table hasn't been used, it's guaranteed to be zeroed out, and is + * therefore safe to use no matter what mode we're in. Otherwise, we figure + * out if it's safe to leave as is or whether it needs to be reset. + */ + if ((tableType_t)cctx->tableType != clearedTable) { + assert(inputSize >= 0); + if ((tableType_t)cctx->tableType != tableType + || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU) + || ((tableType == byU32) && cctx->currentOffset > 1 GB) + || tableType == byPtr + || inputSize >= 4 KB) + { + DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx); + MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE); + cctx->currentOffset = 0; + cctx->tableType = (U32)clearedTable; + } else { + DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)"); + } + } + + /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, is faster + * than compressing without a gap. However, compressing with + * currentOffset == 0 is faster still, so we preserve that case. + */ + if (cctx->currentOffset != 0 && tableType == byU32) { + DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); + cctx->currentOffset += 64 KB; + } + + /* Finally, clear history */ + cctx->dictCtx = NULL; + cctx->dictionary = NULL; + cctx->dictSize = 0; +} /** LZ4_compress_generic() : - inlined, to ensure branches are decided at compilation time */ -LZ4_FORCE_INLINE int LZ4_compress_generic( + * inlined, to ensure branches are decided at compilation time. + * Presumed already validated at this stage: + * - source != NULL + * - inputSize > 0 + */ +LZ4_FORCE_INLINE int LZ4_compress_generic_validated( LZ4_stream_t_internal* const cctx, const char* const source, char* const dest, const int inputSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ const int maxOutputSize, - const limitedOutput_directive outputLimited, + const limitedOutput_directive outputDirective, const tableType_t tableType, - const dict_directive dict, + const dict_directive dictDirective, const dictIssue_directive dictIssue, - const U32 acceleration) + const int acceleration) { + int result; const BYTE* ip = (const BYTE*) source; - const BYTE* base; + + U32 const startIndex = cctx->currentOffset; + const BYTE* base = (const BYTE*) source - startIndex; const BYTE* lowLimit; - const BYTE* const lowRefLimit = ip - cctx->dictSize; - const BYTE* const dictionary = cctx->dictionary; - const BYTE* const dictEnd = dictionary + cctx->dictSize; - const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source; + + const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx; + const BYTE* const dictionary = + dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary; + const U32 dictSize = + dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize; + const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */ + + int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx); + U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */ + const BYTE* const dictEnd = dictionary ? dictionary + dictSize : dictionary; const BYTE* anchor = (const BYTE*) source; const BYTE* const iend = ip + inputSize; - const BYTE* const mflimit = iend - MFLIMIT; + const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1; const BYTE* const matchlimit = iend - LASTLITERALS; + /* the dictCtx currentOffset is indexed on the start of the dictionary, + * while a dictionary in the current context precedes the currentOffset */ + const BYTE* dictBase = !dictionary ? NULL : (dictDirective == usingDictCtx) ? + dictionary + dictSize - dictCtx->currentOffset : + dictionary + dictSize - startIndex; + BYTE* op = (BYTE*) dest; BYTE* const olimit = op + maxOutputSize; + U32 offset = 0; U32 forwardH; - /* Init conditions */ - if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ - switch(dict) - { - case noDict: - default: - base = (const BYTE*)source; - lowLimit = (const BYTE*)source; - break; - case withPrefix64k: - base = (const BYTE*)source - cctx->currentOffset; - lowLimit = (const BYTE*)source - cctx->dictSize; - break; - case usingExtDict: - base = (const BYTE*)source - cctx->currentOffset; - lowLimit = (const BYTE*)source; - break; + DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType); + assert(ip != NULL); + /* If init conditions are not met, we don't have to mark stream + * as having dirty context, since no action was taken yet */ + if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */ + if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) { return 0; } /* Size too large (not within 64K limit) */ + if (tableType==byPtr) assert(dictDirective==noDict); /* only supported use case with byPtr */ + assert(acceleration >= 1); + + lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0); + + /* Update context state */ + if (dictDirective == usingDictCtx) { + /* Subsequent linked blocks can't use the dictionary. */ + /* Instead, they use the block we just compressed. */ + cctx->dictCtx = NULL; + cctx->dictSize = (U32)inputSize; + } else { + cctx->dictSize += (U32)inputSize; } - if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (inputSizecurrentOffset += (U32)inputSize; + cctx->tableType = (U32)tableType; + + if (inputSizehashTable, tableType, base); @@ -530,50 +926,112 @@ LZ4_FORCE_INLINE int LZ4_compress_generic( /* Main Loop */ for ( ; ; ) { - ptrdiff_t refDelta = 0; const BYTE* match; BYTE* token; + const BYTE* filledIp; /* Find a match */ - { const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = acceleration << LZ4_skipTrigger; + if (tableType == byPtr) { + const BYTE* forwardIp = ip; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; do { U32 const h = forwardH; ip = forwardIp; forwardIp += step; step = (searchMatchNb++ >> LZ4_skipTrigger); - if (unlikely(forwardIp > mflimit)) goto _last_literals; + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); - if (dict==usingExtDict) { - if (match < (const BYTE*)source) { - refDelta = dictDelta; + forwardH = LZ4_hashPosition(forwardIp, tableType); + LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); + + } while ( (match+LZ4_DISTANCE_MAX < ip) + || (LZ4_read32(match) != LZ4_read32(ip)) ); + + } else { /* byU32, byU16 */ + + const BYTE* forwardIp = ip; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + U32 const current = (U32)(forwardIp - base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex <= current); + assert(forwardIp - base < (ptrdiff_t)(2 GB - 1)); + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); + + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + assert(tableType == byU32); + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + matchIndex += dictDelta; /* make dictCtx index comparable with current context */ lowLimit = dictionary; } else { - refDelta = 0; + match = base + matchIndex; lowLimit = (const BYTE*)source; - } } + } + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex); + assert(startIndex - matchIndex >= MINMATCH); + match = dictBase + matchIndex; + lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; + } + } else { /* single continuous memory segment */ + match = base + matchIndex; + } forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + + DEBUGLOG(7, "candidate at pos=%u (offset=%u \n", matchIndex, current - matchIndex); + if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; } /* match outside of valid area */ + assert(matchIndex < current); + if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX)) + && (matchIndex+LZ4_DISTANCE_MAX < current)) { + continue; + } /* too far */ + assert((current - matchIndex) <= LZ4_DISTANCE_MAX); /* match now expected within distance */ + + if (LZ4_read32(match) == LZ4_read32(ip)) { + if (maybe_extMem) offset = current - matchIndex; + break; /* match found */ + } - } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0) - || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) ); + } while(1); } /* Catch up */ - while (((ip>anchor) & (match+refDelta > lowLimit)) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; } + filledIp = ip; + while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } /* Encode Literals */ { unsigned const litLength = (unsigned)(ip - anchor); token = op++; - if ((outputLimited) && /* Check output buffer overflow */ - (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) - return 0; + if ((outputDirective == limitedOutput) && /* Check output buffer overflow */ + (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)) ) { + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + if ((outputDirective == fillOutput) && + (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) { + op--; + goto _last_literals; + } if (litLength >= RUN_MASK) { - int len = (int)litLength-RUN_MASK; + int len = (int)(litLength - RUN_MASK); *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; *op++ = (BYTE)len; @@ -581,37 +1039,87 @@ LZ4_FORCE_INLINE int LZ4_compress_generic( else *token = (BYTE)(litLength< olimit)) { + /* the match was too close to the end, rewind and go to last literals */ + op = token; + goto _last_literals; + } + /* Encode Offset */ - LZ4_writeLE16(op, (U16)(ip-match)); op+=2; + if (maybe_extMem) { /* static test */ + DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source)); + assert(offset <= LZ4_DISTANCE_MAX && offset > 0); + LZ4_writeLE16(op, (U16)offset); op+=2; + } else { + DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match)); + assert(ip-match <= LZ4_DISTANCE_MAX); + LZ4_writeLE16(op, (U16)(ip - match)); op+=2; + } /* Encode MatchLength */ { unsigned matchCode; - if ((dict==usingExtDict) && (lowLimit==dictionary)) { - const BYTE* limit; - match += refDelta; - limit = ip + (dictEnd-match); + if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx) + && (lowLimit==dictionary) /* match within extDict */ ) { + const BYTE* limit = ip + (dictEnd-match); + assert(dictEnd > match); if (limit > matchlimit) limit = matchlimit; matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); - ip += MINMATCH + matchCode; + ip += (size_t)matchCode + MINMATCH; if (ip==limit) { - unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit); + unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit); matchCode += more; ip += more; } + DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH); } else { matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); - ip += MINMATCH + matchCode; + ip += (size_t)matchCode + MINMATCH; + DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH); } - if ( outputLimited && /* Check output buffer overflow */ - (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) - return 0; + if ((outputDirective) && /* Check output buffer overflow */ + (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) { + if (outputDirective == fillOutput) { + /* Match description too long : reduce it */ + U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255; + ip -= matchCode - newMatchCode; + assert(newMatchCode < matchCode); + matchCode = newMatchCode; + if (unlikely(ip <= filledIp)) { + /* We have already filled up to filledIp so if ip ends up less than filledIp + * we have positions in the hash table beyond the current position. This is + * a problem if we reuse the hash table. So we have to remove these positions + * from the hash table. + */ + const BYTE* ptr; + DEBUGLOG(5, "Clearing %u positions", (U32)(filledIp - ip)); + for (ptr = ip; ptr <= filledIp; ++ptr) { + U32 const h = LZ4_hashPosition(ptr, tableType); + LZ4_clearHash(h, cctx->hashTable, tableType); + } + } + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } if (matchCode >= ML_MASK) { *token += ML_MASK; matchCode -= ML_MASK; @@ -626,41 +1134,89 @@ _next_match: } else *token += (BYTE)(matchCode); } + /* Ensure we have enough space for the last literals. */ + assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit)); anchor = ip; /* Test end of chunk */ - if (ip > mflimit) break; + if (ip >= mflimitPlusOne) break; /* Fill table */ LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); /* Test next position */ - match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); - if (dict==usingExtDict) { - if (match < (const BYTE*)source) { - refDelta = dictDelta; - lowLimit = dictionary; - } else { - refDelta = 0; - lowLimit = (const BYTE*)source; - } } - LZ4_putPosition(ip, cctx->hashTable, tableType, base); - if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1) - && (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } + if (tableType == byPtr) { + + match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); + LZ4_putPosition(ip, cctx->hashTable, tableType, base); + if ( (match+LZ4_DISTANCE_MAX >= ip) + && (LZ4_read32(match) == LZ4_read32(ip)) ) + { token=op++; *token=0; goto _next_match; } + + } else { /* byU32, byU16 */ + + U32 const h = LZ4_hashPosition(ip, tableType); + U32 const current = (U32)(ip-base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex < current); + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + matchIndex += dictDelta; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else { /* single memory segment */ + match = base + matchIndex; + } + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + assert(matchIndex < current); + if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) + && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current)) + && (LZ4_read32(match) == LZ4_read32(ip)) ) { + token=op++; + *token=0; + if (maybe_extMem) offset = current - matchIndex; + DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", + (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source)); + goto _next_match; + } + } /* Prepare next loop */ forwardH = LZ4_hashPosition(++ip, tableType); + } _last_literals: /* Encode Last Literals */ - { size_t const lastRun = (size_t)(iend - anchor); - if ( (outputLimited) && /* Check output buffer overflow */ - ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) ) - return 0; + { size_t lastRun = (size_t)(iend - anchor); + if ( (outputDirective) && /* Check output buffer overflow */ + (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) { + if (outputDirective == fillOutput) { + /* adapt lastRun to fill 'dst' */ + assert(olimit >= op); + lastRun = (size_t)(olimit-op) - 1/*token*/; + lastRun -= (lastRun + 256 - RUN_MASK) / 256; /*additional length tokens*/ + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } + DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun); if (lastRun >= RUN_MASK) { size_t accumulator = lastRun - RUN_MASK; *op++ = RUN_MASK << ML_BITS; @@ -669,252 +1225,182 @@ _last_literals: } else { *op++ = (BYTE)(lastRun< 0); + DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, result); + return result; +} + +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time; + * takes care of src == (NULL, 0) + * and forward the rest to LZ4_compress_generic_validated */ +LZ4_FORCE_INLINE int LZ4_compress_generic( + LZ4_stream_t_internal* const cctx, + const char* const src, + char* const dst, + const int srcSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ + const int dstCapacity, + const limitedOutput_directive outputDirective, + const tableType_t tableType, + const dict_directive dictDirective, + const dictIssue_directive dictIssue, + const int acceleration) +{ + DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i", + srcSize, dstCapacity); + + if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; } /* Unsupported srcSize, too large (or negative) */ + if (srcSize == 0) { /* src == NULL supported if srcSize == 0 */ + if (outputDirective != notLimited && dstCapacity <= 0) return 0; /* no output, can't write anything */ + DEBUGLOG(5, "Generating an empty block"); + assert(outputDirective == notLimited || dstCapacity >= 1); + assert(dst != NULL); + dst[0] = 0; + if (outputDirective == fillOutput) { + assert (inputConsumed != NULL); + *inputConsumed = 0; + } + return 1; + } + assert(src != NULL); + + return LZ4_compress_generic_validated(cctx, src, dst, srcSize, + inputConsumed, /* only written into if outputDirective == fillOutput */ + dstCapacity, outputDirective, + tableType, dictDirective, dictIssue, acceleration); } int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) { - LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; - LZ4_resetStream((LZ4_stream_t*)state); - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; - + LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse; + assert(ctx != NULL); + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; if (maxOutputSize >= LZ4_compressBound(inputSize)) { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } } else { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } } } - -int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +/** + * LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. It is only safe + * to call if the state buffer is known to be correctly initialized already + * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of + * "correctly initialized"). + */ +int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration) { -#if (LZ4_HEAPMODE) - void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ -#else - LZ4_stream_t ctx; - void* const ctxPtr = &ctx; -#endif - - int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); - -#if (LZ4_HEAPMODE) - FREEMEM(ctxPtr); -#endif - return result; -} - - -int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize) -{ - return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1); -} - - -/* hidden debug function */ -/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */ -int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - LZ4_stream_t ctx; - LZ4_resetStream(&ctx); - - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration); -} - - -/*-****************************** -* *_destSize() variant -********************************/ - -static int LZ4_compress_destSize_generic( - LZ4_stream_t_internal* const ctx, - const char* const src, - char* const dst, - int* const srcSizePtr, - const int targetDstSize, - const tableType_t tableType) -{ - const BYTE* ip = (const BYTE*) src; - const BYTE* base = (const BYTE*) src; - const BYTE* lowLimit = (const BYTE*) src; - const BYTE* anchor = ip; - const BYTE* const iend = ip + *srcSizePtr; - const BYTE* const mflimit = iend - MFLIMIT; - const BYTE* const matchlimit = iend - LASTLITERALS; - - BYTE* op = (BYTE*) dst; - BYTE* const oend = op + targetDstSize; - BYTE* const oMaxLit = op + targetDstSize - 2 /* offset */ - 8 /* because 8+MINMATCH==MFLIMIT */ - 1 /* token */; - BYTE* const oMaxMatch = op + targetDstSize - (LASTLITERALS + 1 /* token */); - BYTE* const oMaxSeq = oMaxLit - 1 /* token */; - - U32 forwardH; - - - /* Init conditions */ - if (targetDstSize < 1) return 0; /* Impossible to store anything */ - if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */ - if ((tableType == byU16) && (*srcSizePtr>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (*srcSizePtrhashTable, tableType, base); - ip++; forwardH = LZ4_hashPosition(ip, tableType); - - /* Main Loop */ - for ( ; ; ) { - const BYTE* match; - BYTE* token; - - /* Find a match */ - { const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = 1 << LZ4_skipTrigger; - - do { - U32 h = forwardH; - ip = forwardIp; - forwardIp += step; - step = (searchMatchNb++ >> LZ4_skipTrigger); - - if (unlikely(forwardIp > mflimit)) goto _last_literals; - - match = LZ4_getPositionOnHash(h, ctx->hashTable, tableType, base); - forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, ctx->hashTable, tableType, base); - - } while ( ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match) != LZ4_read32(ip)) ); - } - - /* Catch up */ - while ((ip>anchor) && (match > lowLimit) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } - - /* Encode Literal length */ - { unsigned litLength = (unsigned)(ip - anchor); - token = op++; - if (op + ((litLength+240)/255) + litLength > oMaxLit) { - /* Not enough space for a last match */ - op--; - goto _last_literals; - } - if (litLength>=RUN_MASK) { - unsigned len = litLength - RUN_MASK; - *token=(RUN_MASK<= 255 ; len-=255) *op++ = 255; - *op++ = (BYTE)len; + LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + + if (dstCapacity >= LZ4_compressBound(srcSize)) { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } - else *token = (BYTE)(litLength< LZ4_DISTANCE_MAX)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } - -_next_match: - /* Encode Offset */ - LZ4_writeLE16(op, (U16)(ip-match)); op+=2; - - /* Encode MatchLength */ - { size_t matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); - - if (op + ((matchLength+240)/255) > oMaxMatch) { - /* Match description too long : reduce it */ - matchLength = (15-1) + (oMaxMatch-op) * 255; - } - ip += MINMATCH + matchLength; - - if (matchLength>=ML_MASK) { - *token += ML_MASK; - matchLength -= ML_MASK; - while (matchLength >= 255) { matchLength-=255; *op++ = 255; } - *op++ = (BYTE)matchLength; + } else { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); } - else *token += (BYTE)(matchLength); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); } + } +} - anchor = ip; - - /* Test end of block */ - if (ip > mflimit) break; - if (op > oMaxSeq) break; - - /* Fill table */ - LZ4_putPosition(ip-2, ctx->hashTable, tableType, base); - - /* Test next position */ - match = LZ4_getPosition(ip, ctx->hashTable, tableType, base); - LZ4_putPosition(ip, ctx->hashTable, tableType, base); - if ( (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } - /* Prepare next loop */ - forwardH = LZ4_hashPosition(++ip, tableType); - } +int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + int result; +#if (LZ4_HEAPMODE) + LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctxPtr == NULL) return 0; +#else + LZ4_stream_t ctx; + LZ4_stream_t* const ctxPtr = &ctx; +#endif + result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); -_last_literals: - /* Encode Last Literals */ - { size_t lastRunSize = (size_t)(iend - anchor); - if (op + 1 /* token */ + ((lastRunSize+240)/255) /* litLength */ + lastRunSize /* literals */ > oend) { - /* adapt lastRunSize to fill 'dst' */ - lastRunSize = (oend-op) - 1; - lastRunSize -= (lastRunSize+240)/255; - } - ip = anchor + lastRunSize; +#if (LZ4_HEAPMODE) + FREEMEM(ctxPtr); +#endif + return result; +} - if (lastRunSize >= RUN_MASK) { - size_t accumulator = lastRunSize - RUN_MASK; - *op++ = RUN_MASK << ML_BITS; - for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; - *op++ = (BYTE) accumulator; - } else { - *op++ = (BYTE)(lastRunSize<= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); } else { - if (*srcSizePtr < LZ4_64Klimit) - return LZ4_compress_destSize_generic(&state->internal_donotuse, src, dst, srcSizePtr, targetDstSize, byU16); - else - return LZ4_compress_destSize_generic(&state->internal_donotuse, src, dst, srcSizePtr, targetDstSize, sizeof(void*)==8 ? byU32 : byPtr); - } + if (*srcSizePtr < LZ4_64Klimit) { + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1); + } else { + tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1); + } } } int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) { #if (LZ4_HEAPMODE) - LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctx == NULL) return 0; #else LZ4_stream_t ctxBody; LZ4_stream_t* ctx = &ctxBody; @@ -936,20 +1422,50 @@ int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targe LZ4_stream_t* LZ4_createStream(void) { - LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64); + LZ4_stream_t* const lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */ - LZ4_resetStream(lz4s); + DEBUGLOG(4, "LZ4_createStream %p", lz4s); + if (lz4s == NULL) return NULL; + LZ4_initStream(lz4s, sizeof(*lz4s)); return lz4s; } +static size_t LZ4_stream_t_alignment(void) +{ +#if LZ4_ALIGN_TEST + typedef struct { char c; LZ4_stream_t t; } t_a; + return sizeof(t_a) - sizeof(LZ4_stream_t); +#else + return 1; /* effectively disabled */ +#endif +} + +LZ4_stream_t* LZ4_initStream (void* buffer, size_t size) +{ + DEBUGLOG(5, "LZ4_initStream"); + if (buffer == NULL) { return NULL; } + if (size < sizeof(LZ4_stream_t)) { return NULL; } + if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) return NULL; + MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal)); + return (LZ4_stream_t*)buffer; +} + +/* resetStream is now deprecated, + * prefer initStream() which is more general */ void LZ4_resetStream (LZ4_stream_t* LZ4_stream) { - MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t)); + DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream); + MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t_internal)); +} + +void LZ4_resetStream_fast(LZ4_stream_t* ctx) { + LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32); } int LZ4_freeStream (LZ4_stream_t* LZ4_stream) { if (!LZ4_stream) return 0; /* support free on NULL */ + DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream); FREEMEM(LZ4_stream); return (0); } @@ -959,43 +1475,82 @@ int LZ4_freeStream (LZ4_stream_t* LZ4_stream) int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) { LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse; + const tableType_t tableType = byU32; const BYTE* p = (const BYTE*)dictionary; const BYTE* const dictEnd = p + dictSize; const BYTE* base; - if ((dict->initCheck) || (dict->currentOffset > 1 GB)) /* Uninitialized structure, or reuse overflow */ - LZ4_resetStream(LZ4_dict); + DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict); + + /* It's necessary to reset the context, + * and not just continue it with prepareTable() + * to avoid any risk of generating overflowing matchIndex + * when compressing using this dictionary */ + LZ4_resetStream(LZ4_dict); + + /* We always increment the offset by 64 KB, since, if the dict is longer, + * we truncate it to the last 64k, and if it's shorter, we still want to + * advance by a whole window length so we can provide the guarantee that + * there are only valid offsets in the window, which allows an optimization + * in LZ4_compress_fast_continue() where it uses noDictIssue even when the + * dictionary isn't a full 64k. */ + dict->currentOffset += 64 KB; if (dictSize < (int)HASH_UNIT) { - dict->dictionary = NULL; - dict->dictSize = 0; return 0; } if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; - dict->currentOffset += 64 KB; - base = p - dict->currentOffset; + base = dictEnd - dict->currentOffset; dict->dictionary = p; dict->dictSize = (U32)(dictEnd - p); - dict->currentOffset += dict->dictSize; + dict->tableType = (U32)tableType; while (p <= dictEnd-HASH_UNIT) { - LZ4_putPosition(p, dict->hashTable, byU32, base); + LZ4_putPosition(p, dict->hashTable, tableType, base); p+=3; } - return dict->dictSize; + return (int)dict->dictSize; +} + +void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream) { + const LZ4_stream_t_internal* dictCtx = dictionaryStream == NULL ? NULL : + &(dictionaryStream->internal_donotuse); + + DEBUGLOG(4, "LZ4_attach_dictionary (%p, %p, size %u)", + workingStream, dictionaryStream, + dictCtx != NULL ? dictCtx->dictSize : 0); + + if (dictCtx != NULL) { + /* If the current offset is zero, we will never look in the + * external dictionary context, since there is no value a table + * entry can take that indicate a miss. In that case, we need + * to bump the offset to something non-zero. + */ + if (workingStream->internal_donotuse.currentOffset == 0) { + workingStream->internal_donotuse.currentOffset = 64 KB; + } + + /* Don't actually attach an empty dictionary. + */ + if (dictCtx->dictSize == 0) { + dictCtx = NULL; + } + } + workingStream->internal_donotuse.dictCtx = dictCtx; } -static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src) +static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize) { - if ((LZ4_dict->currentOffset > 0x80000000) || - ((uptrval)LZ4_dict->currentOffset > (uptrval)src)) { /* address space overflow */ + assert(nextSize >= 0); + if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ /* rescale hash table */ U32 const delta = LZ4_dict->currentOffset - 64 KB; const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; int i; + DEBUGLOG(4, "LZ4_renormDictT"); for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0; else LZ4_dict->hashTable[i] -= delta; @@ -1007,16 +1562,29 @@ static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src) } -int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, + const char* source, char* dest, + int inputSize, int maxOutputSize, + int acceleration) { + const tableType_t tableType = byU32; LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse; - const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize; + const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize; - const BYTE* smallest = (const BYTE*) source; - if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */ - if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd; - LZ4_renormDictT(streamPtr, smallest); - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; + DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize); + + LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */ + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + + /* invalidate tiny dictionaries */ + if ( (streamPtr->dictSize-1 < 4-1) /* intentional underflow */ + && (dictEnd != (const BYTE*)source) ) { + DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary); + streamPtr->dictSize = 0; + streamPtr->dictionary = (const BYTE*)source; + dictEnd = (const BYTE*)source; + } /* Check overlapping input/dictionary space */ { const BYTE* sourceEnd = (const BYTE*) source + inputSize; @@ -1030,46 +1598,61 @@ int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, ch /* prefix mode : source data follows dictionary */ if (dictEnd == (const BYTE*)source) { - int result; if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, dictSmall, acceleration); + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); else - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, noDictIssue, acceleration); - streamPtr->dictSize += (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; - return result; + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); } /* external dictionary mode */ { int result; - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, dictSmall, acceleration); - else - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, noDictIssue, acceleration); + if (streamPtr->dictCtx) { + /* We depend here on the fact that dictCtx'es (produced by + * LZ4_loadDict) guarantee that their tables contain no references + * to offsets between dictCtx->currentOffset - 64 KB and + * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe + * to use noDictIssue even when the dict isn't a full 64 KB. + */ + if (inputSize > 4 KB) { + /* For compressing large blobs, it is faster to pay the setup + * cost to copy the dictionary's tables into the active context, + * so that the compression loop is only looking into one table. + */ + LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr)); + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration); + } + } else { + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } + } streamPtr->dictionary = (const BYTE*)source; streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; return result; } } -/* Hidden debug function, to force external dictionary mode */ -int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize) +/* Hidden debug function, to force-test external dictionary mode */ +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize) { LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse; int result; - const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize; - const BYTE* smallest = dictEnd; - if (smallest > (const BYTE*) source) smallest = (const BYTE*) source; - LZ4_renormDictT(streamPtr, smallest); + LZ4_renormDictT(streamPtr, srcSize); - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); + } streamPtr->dictionary = (const BYTE*)source; - streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; + streamPtr->dictSize = (U32)srcSize; return result; } @@ -1087,10 +1670,12 @@ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; - if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */ - if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize; + if ((U32)dictSize > 64 KB) { dictSize = 64 KB; } /* useless to define a dictionary > 64 KB */ + if ((U32)dictSize > dict->dictSize) { dictSize = (int)dict->dictSize; } - memmove(safeBuffer, previousDictEnd - dictSize, dictSize); + if (safeBuffer == NULL) assert(dictSize == 0); + if (dictSize > 0) + memmove(safeBuffer, previousDictEnd - dictSize, dictSize); dict->dictionary = (const BYTE*)safeBuffer; dict->dictSize = (U32)dictSize; @@ -1100,212 +1685,602 @@ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) -/*-***************************** -* Decompression functions -*******************************/ +/*-******************************* + * Decompression functions + ********************************/ + +typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; +typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; + +#undef MIN +#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) + +/* Read the variable-length literal or match length. + * + * ip - pointer to use as input. + * lencheck - end ip. Return an error if ip advances >= lencheck. + * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so. + * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so. + * error (output) - error code. Should be set to 0 before call. + */ +typedef enum { loop_error = -2, initial_error = -1, ok = 0 } variable_length_error; +LZ4_FORCE_INLINE unsigned +read_variable_length(const BYTE**ip, const BYTE* lencheck, + int loop_check, int initial_check, + variable_length_error* error) +{ + U32 length = 0; + U32 s; + if (initial_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ + *error = initial_error; + return length; + } + do { + s = **ip; + (*ip)++; + length += s; + if (loop_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ + *error = loop_error; + return length; + } + } while (s==255); + + return length; +} + /*! LZ4_decompress_generic() : * This generic decompression function covers all use cases. * It shall be instantiated several times, using different sets of directives. * Note that it is important for performance that this function really get inlined, * in order to remove useless branches during compilation optimization. */ -LZ4_FORCE_INLINE int LZ4_decompress_generic( +LZ4_FORCE_INLINE int +LZ4_decompress_generic( const char* const src, char* const dst, int srcSize, int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ - int endOnInput, /* endOnOutputSize, endOnInputSize */ - int partialDecoding, /* full, partial */ - int targetOutputSize, /* only used if partialDecoding==partial */ - int dict, /* noDict, withPrefix64k, usingExtDict */ - const BYTE* const lowPrefix, /* == dst when no prefix */ + endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */ + earlyEnd_directive partialDecoding, /* full, partial */ + dict_directive dict, /* noDict, withPrefix64k, usingExtDict */ + const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ const BYTE* const dictStart, /* only if dict==usingExtDict */ const size_t dictSize /* note : = 0 if noDict */ ) { - const BYTE* ip = (const BYTE*) src; - const BYTE* const iend = ip + srcSize; + if (src == NULL) { return -1; } - BYTE* op = (BYTE*) dst; - BYTE* const oend = op + outputSize; - BYTE* cpy; - BYTE* oexit = op + targetOutputSize; + { const BYTE* ip = (const BYTE*) src; + const BYTE* const iend = ip + srcSize; - const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize; - const unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; - const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3}; + BYTE* op = (BYTE*) dst; + BYTE* const oend = op + outputSize; + BYTE* cpy; - const int safeDecode = (endOnInput==endOnInputSize); - const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); + const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize; + const int safeDecode = (endOnInput==endOnInputSize); + const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); - /* Special cases */ - if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */ - if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ - if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); - /* Main Loop : decode sequences */ - while (1) { - size_t length; + /* Set up the "end" pointers for the shortcut. */ + const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; + const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; + const BYTE* match; size_t offset; + unsigned token; + size_t length; - /* get literal length */ - unsigned const token = *ip++; - if ((length=(token>>ML_BITS)) == RUN_MASK) { - unsigned s; - do { - s = *ip++; - length += s; - } while ( likely(endOnInput ? ip(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) - || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) - { - if (partialDecoding) { - if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ - if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ + /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */ + while (1) { + /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ + assert(oend - op >= FASTLOOP_SAFE_DISTANCE); + if (endOnInput) { assert(ip < iend); } + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ + + /* decode literal length */ + if (length == RUN_MASK) { + variable_length_error error = ok; + length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error); + if (error == initial_error) { goto _output_error; } + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ + if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ + + /* copy literals */ + cpy = op+length; + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if (endOnInput) { /* LZ4_decompress_safe() */ + if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; } + LZ4_wildCopy32(op, ip, cpy); + } else { /* LZ4_decompress_fast() */ + if (cpy>oend-8) { goto safe_literal_copy; } + LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : + * it doesn't know input length, and only relies on end-of-block properties */ + } + ip += length; op = cpy; } else { - if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ - if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ + cpy = op+length; + if (endOnInput) { /* LZ4_decompress_safe() */ + DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length); + /* We don't need to check oend, since we check it once for each loop below */ + if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; } + /* Literals can only be 14, but hope compilers optimize if we copy by a register size */ + LZ4_memcpy(op, ip, 16); + } else { /* LZ4_decompress_fast() */ + /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : + * it doesn't know input length, and relies on end-of-block properties */ + LZ4_memcpy(op, ip, 8); + if (length > 8) { LZ4_memcpy(op+8, ip+8, 8); } + } + ip += length; op = cpy; } - memcpy(op, ip, length); - ip += length; - op += length; - break; /* Necessarily EOF, due to parsing restrictions */ - } - LZ4_wildCopy(op, ip, cpy); - ip += length; op = cpy; - - /* get offset */ - offset = LZ4_readLE16(ip); ip+=2; - match = op - offset; - if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ - LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */ - - /* get matchlength */ - length = token & ML_MASK; - if (length == ML_MASK) { - unsigned s; - do { - s = *ip++; - if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; - length += s; - } while (s==255); - if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + match = op - offset; + assert(match <= op); + + /* get matchlength */ + length = token & ML_MASK; + + if (length == ML_MASK) { + variable_length_error error = ok; + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */ + length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error); + if (error != ok) { goto _output_error; } + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */ + length += MINMATCH; + if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + } else { + length += MINMATCH; + if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + + /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */ + if ((dict == withPrefix64k) || (match >= lowPrefix)) { + if (offset >= 8) { + assert(match >= lowPrefix); + assert(match <= op); + assert(op + 18 <= oend); + + LZ4_memcpy(op, match, 8); + LZ4_memcpy(op+8, match+8, 8); + LZ4_memcpy(op+16, match+16, 2); + op += length; + continue; + } } } + + if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) { + DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd"); + length = MIN(length, (size_t)(oend-op)); + } else { + goto _output_error; /* end-of-block condition violated */ + } } + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + memmove(op, dictEnd - (lowPrefix-match), length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + LZ4_memcpy(op, dictEnd - copySize, copySize); + op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) { *op++ = *copyFrom++; } + } else { + LZ4_memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; + } + + /* copy match within block */ + cpy = op + length; + + assert((op <= oend) && (oend-op >= 32)); + if (unlikely(offset<16)) { + LZ4_memcpy_using_offset(op, match, cpy, offset); + } else { + LZ4_wildCopy32(op, match, cpy); + } + + op = cpy; /* wildcopy correction */ } - length += MINMATCH; + safe_decode: +#endif - /* check external dictionary */ - if ((dict==usingExtDict) && (match < lowPrefix)) { - if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ + /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */ + while (1) { + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ + + /* A two-stage shortcut for the most common case: + * 1) If the literal length is 0..14, and there is enough space, + * enter the shortcut and copy 16 bytes on behalf of the literals + * (in the fast mode, only 8 bytes can be safely copied this way). + * 2) Further if the match length is 4..18, copy 18 bytes in a similar + * manner; but we ensure that there's enough space in the output for + * those 18 bytes earlier, upon entering the shortcut (in other words, + * there is a combined check for both stages). + */ + if ( (endOnInput ? length != RUN_MASK : length <= 8) + /* strictly "less than" on input, to re-enter the loop with at least one byte */ + && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) { + /* Copy the literals */ + LZ4_memcpy(op, ip, endOnInput ? 16 : 8); + op += length; ip += length; + + /* The second stage: prepare for match copying, decode full info. + * If it doesn't work out, the info won't be wasted. */ + length = token & ML_MASK; /* match length */ + offset = LZ4_readLE16(ip); ip += 2; + match = op - offset; + assert(match <= op); /* check overflow */ + + /* Do not deal with overlapping matches. */ + if ( (length != ML_MASK) + && (offset >= 8) + && (dict==withPrefix64k || match >= lowPrefix) ) { + /* Copy the match. */ + LZ4_memcpy(op + 0, match + 0, 8); + LZ4_memcpy(op + 8, match + 8, 8); + LZ4_memcpy(op +16, match +16, 2); + op += length + MINMATCH; + /* Both stages worked, load the next token. */ + continue; + } + + /* The second stage didn't work out, but the info is ready. + * Propel it right to the point of match copying. */ + goto _copy_match; + } - if (length <= (size_t)(lowPrefix-match)) { - /* match can be copied as a single segment from external dictionary */ - memmove(op, dictEnd - (lowPrefix-match), length); + /* decode literal length */ + if (length == RUN_MASK) { + variable_length_error error = ok; + length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error); + if (error == initial_error) { goto _output_error; } + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ + if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ + } + + /* copy literals */ + cpy = op+length; +#if LZ4_FAST_DEC_LOOP + safe_literal_copy: +#endif + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) ) + || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) + { + /* We've either hit the input parsing restriction or the output parsing restriction. + * In the normal scenario, decoding a full block, it must be the last sequence, + * otherwise it's an error (invalid input or dimensions). + * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow. + */ + if (partialDecoding) { + /* Since we are partial decoding we may be in this block because of the output parsing + * restriction, which is not valid since the output buffer is allowed to be undersized. + */ + assert(endOnInput); + DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end") + DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length); + DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op)); + DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip)); + /* Finishing in the middle of a literals segment, + * due to lack of input. + */ + if (ip+length > iend) { + length = (size_t)(iend-ip); + cpy = op + length; + } + /* Finishing in the middle of a literals segment, + * due to lack of output space. + */ + if (cpy > oend) { + cpy = oend; + assert(op<=oend); + length = (size_t)(oend-op); + } + } else { + /* We must be on the last sequence because of the parsing limitations so check + * that we exactly regenerate the original size (must be exact when !endOnInput). + */ + if ((!endOnInput) && (cpy != oend)) { goto _output_error; } + /* We must be on the last sequence (or invalid) because of the parsing limitations + * so check that we exactly consume the input and don't overrun the output buffer. + */ + if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) { + DEBUGLOG(6, "should have been last run of literals") + DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend); + DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend); + goto _output_error; + } + } + memmove(op, ip, length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */ + ip += length; op += length; + /* Necessarily EOF when !partialDecoding. + * When partialDecoding, it is EOF if we've either + * filled the output buffer or + * can't proceed with reading an offset for following match. + */ + if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) { + break; + } } else { - /* match encompass external dictionary and current block */ - size_t const copySize = (size_t)(lowPrefix-match); - size_t const restSize = length - copySize; - memcpy(op, dictEnd - copySize, copySize); - op += copySize; - if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */ - BYTE* const endOfMatch = op + restSize; - const BYTE* copyFrom = lowPrefix; - while (op < endOfMatch) *op++ = *copyFrom++; + LZ4_wildCopy8(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ + ip += length; op = cpy; + } + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + match = op - offset; + + /* get matchlength */ + length = token & ML_MASK; + + _copy_match: + if (length == ML_MASK) { + variable_length_error error = ok; + length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error); + if (error != ok) goto _output_error; + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ + } + length += MINMATCH; + +#if LZ4_FAST_DEC_LOOP + safe_match_copy: +#endif + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) length = MIN(length, (size_t)(oend-op)); + else goto _output_error; /* doesn't respect parsing restriction */ + } + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + memmove(op, dictEnd - (lowPrefix-match), length); + op += length; } else { - memcpy(op, lowPrefix, restSize); - op += restSize; - } } - continue; - } + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + LZ4_memcpy(op, dictEnd - copySize, copySize); + op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) *op++ = *copyFrom++; + } else { + LZ4_memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; + } + assert(match >= lowPrefix); + + /* copy match within block */ + cpy = op + length; + + /* partialDecoding : may end anywhere within the block */ + assert(op<=oend); + if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + size_t const mlen = MIN(length, (size_t)(oend-op)); + const BYTE* const matchEnd = match + mlen; + BYTE* const copyEnd = op + mlen; + if (matchEnd > op) { /* overlap copy */ + while (op < copyEnd) { *op++ = *match++; } + } else { + LZ4_memcpy(op, match, mlen); + } + op = copyEnd; + if (op == oend) { break; } + continue; + } - /* copy match within block */ - cpy = op + length; - if (unlikely(offset<8)) { - const int dec64 = dec64table[offset]; - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += dec32table[offset]; - memcpy(op+4, match, 4); - match -= dec64; - } else { LZ4_copy8(op, match); match+=8; } - op += 8; - - if (unlikely(cpy>oend-12)) { - BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1); - if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ - if (op < oCopyLimit) { - LZ4_wildCopy(op, match, oCopyLimit); - match += oCopyLimit - op; - op = oCopyLimit; + if (unlikely(offset<8)) { + LZ4_write32(op, 0); /* silence msan warning when offset==0 */ + op[0] = match[0]; + op[1] = match[1]; + op[2] = match[2]; + op[3] = match[3]; + match += inc32table[offset]; + LZ4_memcpy(op+4, match, 4); + match -= dec64table[offset]; + } else { + LZ4_memcpy(op, match, 8); + match += 8; } - while (op16) LZ4_wildCopy(op+8, match+8, cpy); + op += 8; + + if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1); + if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ + if (op < oCopyLimit) { + LZ4_wildCopy8(op, match, oCopyLimit); + match += oCopyLimit - op; + op = oCopyLimit; + } + while (op < cpy) { *op++ = *match++; } + } else { + LZ4_memcpy(op, match, 8); + if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); } + } + op = cpy; /* wildcopy correction */ } - op=cpy; /* correction */ - } - - /* end of decoding */ - if (endOnInput) - return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ - else - return (int) (((const char*)ip)-src); /* Nb of input bytes read */ - /* Overflow error detected */ -_output_error: - return (int) (-(((const char*)ip)-src))-1; + /* end of decoding */ + if (endOnInput) { + DEBUGLOG(5, "decoded %i bytes", (int) (((char*)op)-dst)); + return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ + } else { + return (int) (((const char*)ip)-src); /* Nb of input bytes read */ + } + + /* Overflow error detected */ + _output_error: + return (int) (-(((const char*)ip)-src))-1; + } } +/*===== Instantiate the API decoding functions. =====*/ + +LZ4_FORCE_O2 int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize) { - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0); + return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, + endOnInputSize, decode_full_block, noDict, + (BYTE*)dest, NULL, 0); } -int LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize) +LZ4_FORCE_O2 +int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity) { - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, partial, targetOutputSize, noDict, (BYTE*)dest, NULL, 0); + dstCapacity = MIN(targetOutputSize, dstCapacity); + return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity, + endOnInputSize, partial_decode, + noDict, (BYTE*)dst, NULL, 0); } +LZ4_FORCE_O2 int LZ4_decompress_fast(const char* source, char* dest, int originalSize) { - return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)(dest - 64 KB), NULL, 64 KB); + return LZ4_decompress_generic(source, dest, 0, originalSize, + endOnOutputSize, decode_full_block, withPrefix64k, + (BYTE*)dest - 64 KB, NULL, 0); +} + +/*===== Instantiate a few more decoding cases, used more than once. =====*/ + +LZ4_FORCE_O2 /* Exported, an obsolete API function. */ +int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + endOnInputSize, decode_full_block, withPrefix64k, + (BYTE*)dest - 64 KB, NULL, 0); } +/* Another obsolete API function, paired with the previous one. */ +int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) +{ + /* LZ4_decompress_fast doesn't validate match offsets, + * and thus serves well with any prefixed dictionary. */ + return LZ4_decompress_fast(source, dest, originalSize); +} + +LZ4_FORCE_O2 +static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize, + size_t prefixSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + endOnInputSize, decode_full_block, noDict, + (BYTE*)dest-prefixSize, NULL, 0); +} + +LZ4_FORCE_O2 +int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, + int compressedSize, int maxOutputSize, + const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + endOnInputSize, decode_full_block, usingExtDict, + (BYTE*)dest, (const BYTE*)dictStart, dictSize); +} + +LZ4_FORCE_O2 +static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize, + const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, 0, originalSize, + endOnOutputSize, decode_full_block, usingExtDict, + (BYTE*)dest, (const BYTE*)dictStart, dictSize); +} + +/* The "double dictionary" mode, for use with e.g. ring buffers: the first part + * of the dictionary is passed as prefix, and the second via dictStart + dictSize. + * These routines are used only once, in LZ4_decompress_*_continue(). + */ +LZ4_FORCE_INLINE +int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize, + size_t prefixSize, const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + endOnInputSize, decode_full_block, usingExtDict, + (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); +} + +LZ4_FORCE_INLINE +int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize, + size_t prefixSize, const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, 0, originalSize, + endOnOutputSize, decode_full_block, usingExtDict, + (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); +} /*===== streaming decompression functions =====*/ LZ4_streamDecode_t* LZ4_createStreamDecode(void) { - LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOCATOR(1, sizeof(LZ4_streamDecode_t)); + LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t)); + LZ4_STATIC_ASSERT(LZ4_STREAMDECODESIZE >= sizeof(LZ4_streamDecode_t_internal)); /* A compilation error here means LZ4_STREAMDECODESIZE is not large enough */ return lz4s; } int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) { - if (!LZ4_stream) return 0; /* support free on NULL */ + if (LZ4_stream == NULL) { return 0; } /* support free on NULL */ FREEMEM(LZ4_stream); return 0; } -/*! - * LZ4_setStreamDecode() : - * Use this function to instruct where to find the dictionary. - * This function is not necessary if previous data is still available where it was decoded. - * Loading a size of 0 is allowed (same effect as no dictionary). - * Return : 1 if OK, 0 if error +/*! LZ4_setStreamDecode() : + * Use this function to instruct where to find the dictionary. + * This function is not necessary if previous data is still available where it was decoded. + * Loading a size of 0 is allowed (same effect as no dictionary). + * @return : 1 if OK, 0 if error */ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) { @@ -1317,6 +2292,25 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti return 1; } +/*! LZ4_decoderRingBufferSize() : + * when setting a ring buffer for streaming decompression (optional scenario), + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * Note : in a ring buffer scenario, + * blocks are presumed decompressed next to each other. + * When not enough space remains for next block (remainingSize < maxBlockSize), + * decoding resumes from beginning of ring buffer. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +int LZ4_decoderRingBufferSize(int maxBlockSize) +{ + if (maxBlockSize < 0) return 0; + if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0; + if (maxBlockSize < 16) maxBlockSize = 16; + return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize); +} + /* *_continue() : These decoding functions allow decompression of multiple blocks in "streaming" mode. @@ -1324,52 +2318,75 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti If it's not possible, save the relevant part of decoded data into a safe buffer, and indicate where it stands using LZ4_setStreamDecode() */ +LZ4_FORCE_O2 int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize) { LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; int result; - if (lz4sd->prefixEnd == (BYTE*)dest) { - result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, - usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (lz4sd->prefixSize == 0) { + /* The first call, no dictionary yet. */ + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); if (result <= 0) return result; - lz4sd->prefixSize += result; + lz4sd->prefixSize = (size_t)result; + lz4sd->prefixEnd = (BYTE*)dest + result; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + /* They're rolling the current segment. */ + if (lz4sd->prefixSize >= 64 KB - 1) + result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); + else if (lz4sd->extDictSize == 0) + result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize); + else + result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize += (size_t)result; lz4sd->prefixEnd += result; } else { + /* The buffer wraps around, or they're switching to another buffer. */ lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, - usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize); + result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, + lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize = result; + lz4sd->prefixSize = (size_t)result; lz4sd->prefixEnd = (BYTE*)dest + result; } return result; } +LZ4_FORCE_O2 int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize) { LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; int result; + assert(originalSize >= 0); - if (lz4sd->prefixEnd == (BYTE*)dest) { - result = LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, - usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (lz4sd->prefixSize == 0) { + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_fast(source, dest, originalSize); if (result <= 0) return result; - lz4sd->prefixSize += originalSize; + lz4sd->prefixSize = (size_t)originalSize; + lz4sd->prefixEnd = (BYTE*)dest + originalSize; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0) + result = LZ4_decompress_fast(source, dest, originalSize); + else + result = LZ4_decompress_fast_doubleDict(source, dest, originalSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize += (size_t)originalSize; lz4sd->prefixEnd += originalSize; } else { lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, - usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize); + result = LZ4_decompress_fast_extDict(source, dest, originalSize, + lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize = originalSize; + lz4sd->prefixSize = (size_t)originalSize; lz4sd->prefixEnd = (BYTE*)dest + originalSize; } @@ -1384,32 +2401,27 @@ Advanced decoding functions : the dictionary must be explicitly provided within parameters */ -LZ4_FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize) +int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) { if (dictSize==0) - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0); + return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); if (dictStart+dictSize == dest) { - if (dictSize >= (int)(64 KB - 1)) - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0); - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0); + if (dictSize >= 64 KB - 1) { + return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); + } + assert(dictSize >= 0); + return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize); } - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); -} - -int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize); + assert(dictSize >= 0); + return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize); } int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) { - return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize); -} - -/* debug function */ -int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); + if (dictSize==0 || dictStart+dictSize == dest) + return LZ4_decompress_fast(source, dest, originalSize); + assert(dictSize >= 0); + return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize); } @@ -1417,64 +2429,67 @@ int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compres * Obsolete Functions ***************************************************/ /* obsolete compression functions */ -int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); } -int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); } -int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); } -int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); } -int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, maxDstSize, 1); } -int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); } +int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) +{ + return LZ4_compress_default(source, dest, inputSize, maxOutputSize); +} +int LZ4_compress(const char* src, char* dest, int srcSize) +{ + return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize)); +} +int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); +} +int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); +} +int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity) +{ + return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1); +} +int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) +{ + return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); +} /* -These function names are deprecated and should no longer be used. +These decompression functions are deprecated and should no longer be used. They are only provided here for compatibility with older user programs. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe */ -int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); } -int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); } - +int LZ4_uncompress (const char* source, char* dest, int outputSize) +{ + return LZ4_decompress_fast(source, dest, outputSize); +} +int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) +{ + return LZ4_decompress_safe(source, dest, isize, maxOutputSize); +} /* Obsolete Streaming functions */ -int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; } - -static void LZ4_init(LZ4_stream_t* lz4ds, BYTE* base) -{ - MEM_INIT(lz4ds, 0, sizeof(LZ4_stream_t)); - lz4ds->internal_donotuse.bufferStart = base; -} +int LZ4_sizeofStreamState(void) { return LZ4_STREAMSIZE; } int LZ4_resetStreamState(void* state, char* inputBuffer) { - if ((((uptrval)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */ - LZ4_init((LZ4_stream_t*)state, (BYTE*)inputBuffer); + (void)inputBuffer; + LZ4_resetStream((LZ4_stream_t*)state); return 0; } void* LZ4_create (char* inputBuffer) { - LZ4_stream_t* lz4ds = (LZ4_stream_t*)ALLOCATOR(8, sizeof(LZ4_stream_t)); - LZ4_init (lz4ds, (BYTE*)inputBuffer); - return lz4ds; + (void)inputBuffer; + return LZ4_createStream(); } -char* LZ4_slideInputBuffer (void* LZ4_Data) -{ - LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)LZ4_Data)->internal_donotuse; - int dictSize = LZ4_saveDict((LZ4_stream_t*)LZ4_Data, (char*)ctx->bufferStart, 64 KB); - return (char*)(ctx->bufferStart + dictSize); -} - -/* Obsolete streaming decompression functions */ - -int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB); -} - -int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) +char* LZ4_slideInputBuffer (void* state) { - return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB); + /* avoid const char * -> char * conversion warning */ + return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary; } #endif /* LZ4_COMMONDEFS_ONLY */ diff --git a/documentation20/cn/05.insert/docs.md b/documentation20/cn/05.insert/docs.md index 57a7521738a857ee681bfaf38858db14f34abe91..9a0e9b388e639d5e6c6e5094682f07a223c01ada 100644 --- a/documentation20/cn/05.insert/docs.md +++ b/documentation20/cn/05.insert/docs.md @@ -243,7 +243,7 @@ repeater 部分添加 { host:'', port: ', port: walFlushSize and walSize > cache*0.5*blocks +# walFlushSize 1024 diff --git a/packaging/docker/Dockerfile b/packaging/docker/Dockerfile index 629f8f9fd6a4167db6f30d29646263710602693a..c49bc0a8a356c960e27f3231c3e901de6d9a72ef 100644 --- a/packaging/docker/Dockerfile +++ b/packaging/docker/Dockerfile @@ -4,21 +4,19 @@ WORKDIR /root ARG pkgFile ARG dirName -RUN echo ${pkgFile} -RUN echo ${dirName} +RUN echo ${pkgFile} && echo ${dirName} COPY ${pkgFile} /root/ RUN tar -zxf ${pkgFile} WORKDIR /root/${dirName}/ RUN /bin/bash install.sh -e no -RUN apt-get clean && apt-get update && apt-get install -y locales -RUN locale-gen en_US.UTF-8 -ENV LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/lib" -ENV LC_CTYPE=en_US.UTF-8 -ENV LANG=en_US.UTF-8 -ENV LC_ALL=en_US.UTF-8 +RUN apt-get clean && apt-get update && apt-get install -y locales && locale-gen en_US.UTF-8 +ENV LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/lib" \ + LC_CTYPE=en_US.UTF-8 \ + LANG=en_US.UTF-8 \ + LC_ALL=en_US.UTF-8 EXPOSE 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 CMD ["taosd"] -VOLUME [ "/var/lib/taos", "/var/log/taos","/etc/taos/" ] +VOLUME [ "/var/lib/taos", "/var/log/taos","/etc/taos/" ] \ No newline at end of file diff --git a/packaging/tools/make_install.sh b/packaging/tools/make_install.sh index 8015b8dfdc2ccfdc27026575abb6259594b793d9..7fbdbab1c798af572fc67cf79f27812ea64d3bae 100755 --- a/packaging/tools/make_install.sh +++ b/packaging/tools/make_install.sh @@ -395,8 +395,9 @@ function install_connector() { ${csudo} cp -rf ${source_dir}/src/connector/python ${install_main_dir}/connector ${csudo} cp ${binary_dir}/build/lib/*.jar ${install_main_dir}/connector &> /dev/null && ${csudo} chmod 777 ${install_main_dir}/connector/*.jar || echo &> /dev/null else - ${csudo} cp -rf ${source_dir}/src/connector/python ${install_main_dir}/connector || ${csudo} cp -rf ${source_dir}/src/connector/python ${install_main_2_dir}/connector} - ${csudo} cp ${binary_dir}/build/lib/*.jar ${install_main_dir}/connector &> /dev/null || cp ${binary_dir}/build/lib/*.jar ${install_main_2_dir}/connector &> /dev/null && ${csudo} chmod 777 ${install_main_dir}/connector/*.jar || ${csudo} chmod 777 ${install_main_2_dir}/connector/*.jar || echo &> /dev/null + ${csudo} cp -rf ${source_dir}/src/connector/python ${install_main_dir}/connector || ${csudo} cp -rf ${source_dir}/src/connector/python ${install_main_2_dir}/connector + ${csudo} cp ${binary_dir}/build/lib/*.jar ${install_main_dir}/connector &> /dev/null && ${csudo} chmod 777 ${install_main_dir}/connector/*.jar || echo &> /dev/null + ${csudo} cp ${binary_dir}/build/lib/*.jar ${install_main_2_dir}/connector &> /dev/null && ${csudo} chmod 777 ${install_main_2_dir}/connector/*.jar || echo &> /dev/null fi } diff --git a/src/client/inc/tscParseLine.h b/src/client/inc/tscParseLine.h index 374e043009d008fb2bcb20a024b864097f3c8917..939ccfb613968620ab1447a7a833277743accb43 100644 --- a/src/client/inc/tscParseLine.h +++ b/src/client/inc/tscParseLine.h @@ -23,6 +23,8 @@ extern "C" { #define SML_TIMESTAMP_SECOND_DIGITS 10 #define SML_TIMESTAMP_MILLI_SECOND_DIGITS 13 +typedef TSDB_SML_PROTOCOL_TYPE SMLProtocolType; + typedef struct { char* key; uint8_t type; @@ -46,27 +48,23 @@ typedef struct { } TAOS_SML_DATA_POINT; typedef enum { - SML_TIME_STAMP_NOW, + SML_TIME_STAMP_NOT_CONFIGURED, SML_TIME_STAMP_HOURS, SML_TIME_STAMP_MINUTES, SML_TIME_STAMP_SECONDS, SML_TIME_STAMP_MILLI_SECONDS, SML_TIME_STAMP_MICRO_SECONDS, SML_TIME_STAMP_NANO_SECONDS, - SML_TIME_STAMP_NOT_CONFIGURED + SML_TIME_STAMP_NOW } SMLTimeStampType; -typedef enum { - SML_LINE_PROTOCOL = 0, - SML_TELNET_PROTOCOL = 1, - SML_JSON_PROTOCOL = 2, -} SMLProtocolType; - typedef struct { uint64_t id; SMLProtocolType protocol; SMLTimeStampType tsType; SHashObj* smlDataToSchema; + + int64_t affectedRows; } SSmlLinesInfo; int tscSmlInsert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint, SSmlLinesInfo* info); @@ -83,12 +81,12 @@ int32_t convertSmlTimeStamp(TAOS_SML_KV *pVal, char *value, void destroySmlDataPoint(TAOS_SML_DATA_POINT* point); -int taos_insert_sml_lines(TAOS* taos, char* lines[], int numLines, - SMLProtocolType protocol, SMLTimeStampType tsType); -int taos_insert_telnet_lines(TAOS* taos, char* lines[], int numLines, - SMLProtocolType protocol, SMLTimeStampType tsType); -int taos_insert_json_payload(TAOS* taos, char* payload, - SMLProtocolType protocol, SMLTimeStampType tsType); +int taos_insert_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType protocol, + SMLTimeStampType tsType, int* affectedRows); +int taos_insert_telnet_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType protocol, + SMLTimeStampType tsType, int* affectedRows); +int taos_insert_json_payload(TAOS* taos, char* payload, SMLProtocolType protocol, + SMLTimeStampType tsType, int* affectedRows); #ifdef __cplusplus diff --git a/src/client/src/TSDBJNIConnector.c b/src/client/src/TSDBJNIConnector.c index 0444c2cb8dd23f2e73179668e6cb7195a030b6be..50fe51e7dac0fc6f5ca4cc0458670f3962942f0e 100644 --- a/src/client/src/TSDBJNIConnector.c +++ b/src/client/src/TSDBJNIConnector.c @@ -1053,7 +1053,8 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsI } JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JNIEnv *env, jobject jobj, - jobjectArray lines, jlong conn) { + jobjectArray lines, jlong conn, + jint protocol, jint precision) { TAOS *taos = (TAOS *)conn; if (taos == NULL) { jniError("jobj:%p, connection already closed", jobj); @@ -1071,7 +1072,8 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(J c_lines[i] = (char *)(*env)->GetStringUTFChars(env, line, 0); } - int code = taos_schemaless_insert(taos, c_lines, numLines, SML_LINE_PROTOCOL, "ms"); + SSqlObj* result = (SSqlObj*)taos_schemaless_insert(taos, c_lines, numLines, protocol, precision); + int code = taos_errno(result); for (int i = 0; i < numLines; ++i) { jstring line = (jstring)((*env)->GetObjectArrayElement(env, lines, i)); @@ -1080,9 +1082,10 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(J tfree(c_lines); if (code != TSDB_CODE_SUCCESS) { - jniError("jobj:%p, conn:%p, code:%s", jobj, taos, tstrerror(code)); + jniError("jobj:%p, conn:%p, code:%s, msg:%s", jobj, taos, tstrerror(code), taos_errstr(result)); return JNI_TDENGINE_ERROR; } - return code; + + return (jlong)result; } diff --git a/src/client/src/tscParseLineProtocol.c b/src/client/src/tscParseLineProtocol.c index 8459ec147959c90e1a049e4849ee0c9913607855..6354ba9e9fe60758dc5b8ddafa618033a4d0ffa1 100644 --- a/src/client/src/tscParseLineProtocol.c +++ b/src/client/src/tscParseLineProtocol.c @@ -761,7 +761,7 @@ static int32_t doInsertChildTableWithStmt(TAOS* taos, char* sql, char* cTableNam code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql)); if (code != 0) { - tscError("SML:0x%"PRIx64" taos_stmt_prepare return %d:%s", info->id, code, tstrerror(code)); + tscError("SML:0x%"PRIx64" taos_stmt_prepare return %d:%s", info->id, code, taos_stmt_errstr(stmt)); taos_stmt_close(stmt); return code; } @@ -771,7 +771,11 @@ static int32_t doInsertChildTableWithStmt(TAOS* taos, char* sql, char* cTableNam do { code = taos_stmt_set_tbname(stmt, cTableName); if (code != 0) { - tscError("SML:0x%"PRIx64" taos_stmt_set_tbname return %d:%s", info->id, code, tstrerror(code)); + tscError("SML:0x%"PRIx64" taos_stmt_set_tbname return %d:%s", info->id, code, taos_stmt_errstr(stmt)); + + int affectedRows = taos_stmt_affected_rows(stmt); + info->affectedRows += affectedRows; + taos_stmt_close(stmt); return code; } @@ -781,13 +785,21 @@ static int32_t doInsertChildTableWithStmt(TAOS* taos, char* sql, char* cTableNam TAOS_BIND* colsBinds = taosArrayGetP(batchBind, i); code = taos_stmt_bind_param(stmt, colsBinds); if (code != 0) { - tscError("SML:0x%"PRIx64" taos_stmt_bind_param return %d:%s", info->id, code, tstrerror(code)); + tscError("SML:0x%"PRIx64" taos_stmt_bind_param return %d:%s", info->id, code, taos_stmt_errstr(stmt)); + + int affectedRows = taos_stmt_affected_rows(stmt); + info->affectedRows += affectedRows; + taos_stmt_close(stmt); return code; } code = taos_stmt_add_batch(stmt); if (code != 0) { - tscError("SML:0x%"PRIx64" taos_stmt_add_batch return %d:%s", info->id, code, tstrerror(code)); + tscError("SML:0x%"PRIx64" taos_stmt_add_batch return %d:%s", info->id, code, taos_stmt_errstr(stmt)); + + int affectedRows = taos_stmt_affected_rows(stmt); + info->affectedRows += affectedRows; + taos_stmt_close(stmt); return code; } @@ -795,9 +807,10 @@ static int32_t doInsertChildTableWithStmt(TAOS* taos, char* sql, char* cTableNam code = taos_stmt_execute(stmt); if (code != 0) { - tscError("SML:0x%"PRIx64" taos_stmt_execute return %d:%s, try:%d", info->id, code, tstrerror(code), try); + tscError("SML:0x%"PRIx64" taos_stmt_execute return %d:%s, try:%d", info->id, code, taos_stmt_errstr(stmt), try); } - + tscDebug("SML:0x%"PRIx64" taos_stmt_execute inserted %d rows", info->id, taos_stmt_affected_rows(stmt)); + tryAgain = false; if ((code == TSDB_CODE_TDB_INVALID_TABLE_ID || code == TSDB_CODE_VND_INVALID_VGROUP_ID @@ -825,6 +838,8 @@ static int32_t doInsertChildTableWithStmt(TAOS* taos, char* sql, char* cTableNam } } while (tryAgain); + int affectedRows = taos_stmt_affected_rows(stmt); + info->affectedRows += affectedRows; taos_stmt_close(stmt); return code; @@ -1069,6 +1084,8 @@ int tscSmlInsert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint, SSmlLine int32_t code = TSDB_CODE_SUCCESS; + info->affectedRows = 0; + tscDebug("SML:0x%"PRIx64" build data point schemas", info->id); SArray* stableSchemas = taosArrayInit(32, sizeof(SSmlSTableSchema)); // SArray code = buildDataPointSchemas(points, numPoint, stableSchemas, info); @@ -1429,13 +1446,13 @@ static bool isTimeStamp(char *pVal, uint16_t len, SMLTimeStampType *tsType, SSml //Default no appendix if (isdigit(pVal[len - 1]) && isdigit(pVal[len - 2])) { - if (info->protocol == SML_LINE_PROTOCOL) { + if (info->protocol == TSDB_SML_LINE_PROTOCOL) { if (info->tsType != SML_TIME_STAMP_NOT_CONFIGURED) { *tsType = info->tsType; } else { *tsType = SML_TIME_STAMP_NANO_SECONDS; } - } else if (info->protocol == SML_TELNET_PROTOCOL) { + } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) { if (len == SML_TIMESTAMP_SECOND_DIGITS) { *tsType = SML_TIME_STAMP_SECONDS; } else if (len == SML_TIMESTAMP_MILLI_SECOND_DIGITS) { @@ -1871,7 +1888,7 @@ static int32_t parseSmlKey(TAOS_SML_KV *pKV, const char **index, SHashObj *pHash //key field cannot start with digit if (isdigit(*cur)) { - tscError("SML:0x%"PRIx64" Tag key cannnot start with digit", info->id); + tscError("SML:0x%"PRIx64" Tag key cannot start with digit", info->id); return TSDB_CODE_TSC_LINE_SYNTAX_ERROR; } while (*cur != '\0') { @@ -1885,6 +1902,8 @@ static int32_t parseSmlKey(TAOS_SML_KV *pKV, const char **index, SHashObj *pHash } //Escape special character if (*cur == '\\') { + //TODO: escape will work after column & tag + //support spcial characters escapeSpecialCharacter(2, &cur); } key[len] = *cur; @@ -1911,13 +1930,42 @@ static int32_t parseSmlKey(TAOS_SML_KV *pKV, const char **index, SHashObj *pHash static int32_t parseSmlValue(TAOS_SML_KV *pKV, const char **index, bool *is_last_kv, SSmlLinesInfo* info, bool isTag) { const char *start, *cur; + int32_t ret = TSDB_CODE_SUCCESS; char *value = NULL; uint16_t len = 0; + bool searchQuote = false; start = cur = *index; + //if field value is string + if (!isTag) { + if (*cur == '"') { + searchQuote = true; + cur += 1; + len += 1; + } else if (*cur == 'L' && *(cur + 1) == '"') { + searchQuote = true; + cur += 2; + len += 2; + } + } + while (1) { // unescaped ',' or ' ' or '\0' identifies a value - if ((*cur == ',' || *cur == ' ' || *cur == '\0') && *(cur - 1) != '\\') { + if (((*cur == ',' || *cur == ' ' ) && *(cur - 1) != '\\') || *cur == '\0') { + if (searchQuote == true) { + //first quote ignored while searching + if (*(cur - 1) == '"' && len != 1 && len != 2) { + *is_last_kv = (*cur == ' ' || *cur == '\0') ? true : false; + break; + } else if (*cur == '\0') { + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } else { + cur++; + len++; + continue; + } + } //unescaped ' ' or '\0' indicates end of value *is_last_kv = (*cur == ' ' || *cur == '\0') ? true : false; if (*cur == ' ' && *(cur + 1) == ' ') { @@ -1929,7 +1977,7 @@ static int32_t parseSmlValue(TAOS_SML_KV *pKV, const char **index, } //Escape special character if (*cur == '\\') { - escapeSpecialCharacter(2, &cur); + escapeSpecialCharacter(isTag ? 2 : 3, &cur); } cur++; len++; @@ -1946,16 +1994,20 @@ static int32_t parseSmlValue(TAOS_SML_KV *pKV, const char **index, if (!convertSmlValueType(pKV, value, len, info, isTag)) { tscError("SML:0x%"PRIx64" Failed to convert sml value string(%s) to any type", info->id, value); - //free previous alocated key field - free(pKV->key); - pKV->key = NULL; free(value); - return TSDB_CODE_TSC_INVALID_VALUE; + ret = TSDB_CODE_TSC_INVALID_VALUE; + goto error; } free(value); *index = (*cur == '\0') ? cur : cur + 1; - return TSDB_CODE_SUCCESS; + return ret; + +error: + //free previous alocated key field + free(pKV->key); + pKV->key = NULL; + return ret; } static int32_t parseSmlMeasurement(TAOS_SML_DATA_POINT *pSml, const char **index, @@ -2221,7 +2273,7 @@ int32_t tscParseLines(char* lines[], int numLines, SArray* points, SArray* faile return TSDB_CODE_SUCCESS; } -int taos_insert_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType protocol, SMLTimeStampType tsType) { +int taos_insert_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType protocol, SMLTimeStampType tsType, int *affectedRows) { int32_t code = 0; SSmlLinesInfo* info = tcalloc(1, sizeof(SSmlLinesInfo)); @@ -2265,6 +2317,9 @@ int taos_insert_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType p if (code != 0) { tscError("SML:0x%"PRIx64" taos_sml_insert error: %s", info->id, tstrerror((code))); } + if (affectedRows != NULL) { + *affectedRows = info->affectedRows; + } cleanup: tscDebug("SML:0x%"PRIx64" taos_insert_lines finish inserting %d lines. code: %d", info->id, numLines, code); @@ -2280,52 +2335,56 @@ cleanup: return code; } -int32_t convertPrecisionStrType(char* precision, SMLTimeStampType *tsType) { - if (precision == NULL) { - *tsType = SML_TIME_STAMP_NOT_CONFIGURED; - return TSDB_CODE_SUCCESS; - } - if (strcmp(precision, "μ") == 0) { - *tsType = SML_TIME_STAMP_MICRO_SECONDS; - return TSDB_CODE_SUCCESS; +static int32_t convertPrecisionType(int precision, SMLTimeStampType *tsType) { + switch (precision) { + case TSDB_SML_TIMESTAMP_NOT_CONFIGURED: + *tsType = SML_TIME_STAMP_NOT_CONFIGURED; + break; + case TSDB_SML_TIMESTAMP_HOURS: + *tsType = SML_TIME_STAMP_HOURS; + break; + case TSDB_SML_TIMESTAMP_MILLI_SECONDS: + *tsType = SML_TIME_STAMP_MILLI_SECONDS; + break; + case TSDB_SML_TIMESTAMP_NANO_SECONDS: + *tsType = SML_TIME_STAMP_NANO_SECONDS; + break; + case TSDB_SML_TIMESTAMP_MICRO_SECONDS: + *tsType = SML_TIME_STAMP_MICRO_SECONDS; + break; + case TSDB_SML_TIMESTAMP_SECONDS: + *tsType = SML_TIME_STAMP_SECONDS; + break; + case TSDB_SML_TIMESTAMP_MINUTES: + *tsType = SML_TIME_STAMP_MINUTES; + break; + default: + return TSDB_CODE_TSC_INVALID_PRECISION_TYPE; } - int32_t len = (int32_t)strlen(precision); - if (len == 1) { - switch (precision[0]) { - case 'u': - *tsType = SML_TIME_STAMP_MICRO_SECONDS; - break; - case 's': - *tsType = SML_TIME_STAMP_SECONDS; - break; - case 'm': - *tsType = SML_TIME_STAMP_MINUTES; - break; - case 'h': - *tsType = SML_TIME_STAMP_HOURS; - break; - default: - return TSDB_CODE_TSC_INVALID_PRECISION_TYPE; - } - } else if (len == 2 && precision[1] == 's') { - switch (precision[0]) { - case 'm': - *tsType = SML_TIME_STAMP_MILLI_SECONDS; - break; - case 'n': - *tsType = SML_TIME_STAMP_NANO_SECONDS; - break; - default: - return TSDB_CODE_TSC_INVALID_PRECISION_TYPE; - } - } else { - return TSDB_CODE_TSC_INVALID_PRECISION_TYPE; + return TSDB_CODE_SUCCESS; +} + +//make a dummy SSqlObj +static SSqlObj* createSmlQueryObj(TAOS* taos, int32_t affected_rows, int32_t code) { + SSqlObj *pNew = (SSqlObj*)calloc(1, sizeof(SSqlObj)); + if (pNew == NULL) { + return NULL; } + pNew->signature = pNew; + pNew->pTscObj = taos; - return TSDB_CODE_SUCCESS; + tsem_init(&pNew->rspSem, 0, 0); + registerSqlObj(pNew); + + pNew->res.numOfRows = affected_rows; + pNew->res.code = code; + + + return pNew; } + /** * taos_schemaless_insert() parse and insert data points into database according to * different protocol. @@ -2347,31 +2406,35 @@ int32_t convertPrecisionStrType(char* precision, SMLTimeStampType *tsType) { * */ -int taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol, char* timePrecision) { - int code; +TAOS_RES* taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol, int precision) { + int code = TSDB_CODE_SUCCESS; + int affected_rows = 0; SMLTimeStampType tsType; - if (protocol == SML_LINE_PROTOCOL) { - code = convertPrecisionStrType(timePrecision, &tsType); + if (protocol == TSDB_SML_LINE_PROTOCOL) { + code = convertPrecisionType(precision, &tsType); if (code != TSDB_CODE_SUCCESS) { - return code; + return NULL; } } switch (protocol) { - case SML_LINE_PROTOCOL: - code = taos_insert_lines(taos, lines, numLines, protocol, tsType); + case TSDB_SML_LINE_PROTOCOL: + code = taos_insert_lines(taos, lines, numLines, protocol, tsType, &affected_rows); break; - case SML_TELNET_PROTOCOL: - code = taos_insert_telnet_lines(taos, lines, numLines, protocol, tsType); + case TSDB_SML_TELNET_PROTOCOL: + code = taos_insert_telnet_lines(taos, lines, numLines, protocol, tsType, &affected_rows); break; - case SML_JSON_PROTOCOL: - code = taos_insert_json_payload(taos, *lines, protocol, tsType); + case TSDB_SML_JSON_PROTOCOL: + code = taos_insert_json_payload(taos, *lines, protocol, tsType, &affected_rows); break; default: code = TSDB_CODE_TSC_INVALID_PROTOCOL_TYPE; break; } - return code; + + SSqlObj *pSql = createSmlQueryObj(taos, affected_rows, code); + + return (TAOS_RES*)pSql; } diff --git a/src/client/src/tscParseOpenTSDB.c b/src/client/src/tscParseOpenTSDB.c index a079198be3f2c192ab175417dd3946fc4e976c54..decef4887819f1467d8345e2f021bc7bc2286dfb 100644 --- a/src/client/src/tscParseOpenTSDB.c +++ b/src/client/src/tscParseOpenTSDB.c @@ -138,21 +138,41 @@ static int32_t parseTelnetMetricValue(TAOS_SML_KV **pKVs, int *num_kvs, const ch const char *start, *cur; int32_t ret = TSDB_CODE_SUCCESS; int len = 0; + bool searchQuote = false; char key[] = OTD_METRIC_VALUE_COLUMN_NAME; char *value = NULL; start = cur = *index; + //if metric value is string + if (*cur == '"') { + searchQuote = true; + cur += 1; + len += 1; + } else if (*cur == 'L' && *(cur + 1) == '"') { + searchQuote = true; + cur += 2; + len += 2; + } + while(*cur != '\0') { if (*cur == ' ') { - if (*cur == ' ') { - if (*(cur + 1) != ' ') { - break; + if (searchQuote == true) { + if (*(cur - 1) == '"' && len != 1 && len != 2) { + searchQuote = false; } else { cur++; + len++; continue; } } + + if (*(cur + 1) != ' ') { + break; + } else { + cur++; + continue; + } } cur++; len++; @@ -389,7 +409,7 @@ static int32_t tscParseTelnetLines(char* lines[], int numLines, SArray* points, return TSDB_CODE_SUCCESS; } -int taos_insert_telnet_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType protocol, SMLTimeStampType tsType) { +int taos_insert_telnet_lines(TAOS* taos, char* lines[], int numLines, SMLProtocolType protocol, SMLTimeStampType tsType, int* affectedRows) { int32_t code = 0; SSmlLinesInfo* info = tcalloc(1, sizeof(SSmlLinesInfo)); @@ -433,6 +453,9 @@ int taos_insert_telnet_lines(TAOS* taos, char* lines[], int numLines, SMLProtoco if (code != 0) { tscError("OTD:0x%"PRIx64" taos_insert_telnet_lines error: %s", info->id, tstrerror((code))); } + if (affectedRows != NULL) { + *affectedRows = info->affectedRows; + } cleanup: tscDebug("OTD:0x%"PRIx64" taos_insert_telnet_lines finish inserting %d lines. code: %d", info->id, numLines, code); @@ -1025,7 +1048,7 @@ PARSE_JSON_OVER: return ret; } -int taos_insert_json_payload(TAOS* taos, char* payload, SMLProtocolType protocol, SMLTimeStampType tsType) { +int taos_insert_json_payload(TAOS* taos, char* payload, SMLProtocolType protocol, SMLTimeStampType tsType, int* affectedRows) { int32_t code = 0; SSmlLinesInfo* info = tcalloc(1, sizeof(SSmlLinesInfo)); @@ -1060,6 +1083,9 @@ int taos_insert_json_payload(TAOS* taos, char* payload, SMLProtocolType protocol if (code != 0) { tscError("OTD:0x%"PRIx64" taos_insert_json_payload error: %s", info->id, tstrerror((code))); } + if (affectedRows != NULL) { + *affectedRows = info->affectedRows; + } cleanup: tscDebug("OTD:0x%"PRIx64" taos_insert_json_payload finish inserting 1 Point. code: %d", info->id, code); diff --git a/src/client/src/tscPrepare.c b/src/client/src/tscPrepare.c index 1fe242d1d1b8fa743fd6d0382610fbe6d925234f..04dd7f57cabe8f01ade992cfe1d4a3122a26d130 100644 --- a/src/client/src/tscPrepare.c +++ b/src/client/src/tscPrepare.c @@ -78,6 +78,8 @@ typedef struct STscStmt { SSqlObj* pSql; SMultiTbStmt mtb; SNormalStmt normal; + + int numOfRows; } STscStmt; #define STMT_RET(c) do { \ @@ -1212,6 +1214,8 @@ static int insertStmtExecute(STscStmt* stmt) { // wait for the callback function to post the semaphore tsem_wait(&pSql->rspSem); + stmt->numOfRows += pSql->res.numOfRows; + // data block reset pCmd->batchSize = 0; for(int32_t i = 0; i < pCmd->insertParam.numOfTables; ++i) { @@ -1284,7 +1288,9 @@ static int insertBatchStmtExecute(STscStmt* pStmt) { tsem_wait(&pStmt->pSql->rspSem); code = pStmt->pSql->res.code; - + + pStmt->numOfRows += pStmt->pSql->res.numOfRows; + insertBatchClean(pStmt); return code; @@ -1516,11 +1522,12 @@ TAOS_STMT* taos_stmt_init(TAOS* taos) { } tsem_init(&pSql->rspSem, 0, 0); - pSql->signature = pSql; - pSql->pTscObj = pObj; - pSql->maxRetry = TSDB_MAX_REPLICA; - pStmt->pSql = pSql; - pStmt->last = STMT_INIT; + pSql->signature = pSql; + pSql->pTscObj = pObj; + pSql->maxRetry = TSDB_MAX_REPLICA; + pStmt->pSql = pSql; + pStmt->last = STMT_INIT; + pStmt->numOfRows = 0; registerSqlObj(pSql); return pStmt; @@ -1564,9 +1571,7 @@ int taos_stmt_prepare(TAOS_STMT* stmt, const char* sql, unsigned long length) { } pRes->qId = 0; - pRes->numOfRows = 1; - - registerSqlObj(pSql); + pRes->numOfRows = 0; strtolower(pSql->sqlstr, sql); tscDebugL("0x%"PRIx64" SQL: %s", pSql->self, pSql->sqlstr); @@ -1981,6 +1986,7 @@ int taos_stmt_execute(TAOS_STMT* stmt) { } else { taosReleaseRef(tscObjRef, pStmt->pSql->self); pStmt->pSql = taos_query((TAOS*)pStmt->taos, sql); + pStmt->numOfRows += taos_affected_rows(pStmt->pSql); ret = taos_errno(pStmt->pSql); free(sql); } @@ -1989,6 +1995,17 @@ int taos_stmt_execute(TAOS_STMT* stmt) { STMT_RET(ret); } +int taos_stmt_affected_rows(TAOS_STMT* stmt) { + STscStmt* pStmt = (STscStmt*)stmt; + + if (pStmt == NULL) { + tscError("statement is invalid"); + return 0; + } + + return pStmt->numOfRows; +} + TAOS_RES *taos_stmt_use_result(TAOS_STMT* stmt) { if (stmt == NULL) { tscError("statement is invalid."); diff --git a/src/client/src/tscSQLParser.c b/src/client/src/tscSQLParser.c index bbfd62570d723a5b0750f23f1ce39711a721afa1..e1ac391bfebb5c8f27b7a0aac853c29428b2e987 100644 --- a/src/client/src/tscSQLParser.c +++ b/src/client/src/tscSQLParser.c @@ -3112,10 +3112,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col memset(pExpr->base.aliasName, 0, tListLen(pExpr->base.aliasName)); getColumnName(pItem, pExpr->base.aliasName, pExpr->base.token, sizeof(pExpr->base.aliasName) - 1); - SSchema s = {0}; - s.type = (uint8_t)resType; - s.bytes = bytes; - s.colId = pExpr->base.colInfo.colId; + SSchema* pSchema = tscGetTableColumnSchema(pTableMetaInfo->pTableMeta, index.columnIndex); uint64_t uid = pTableMetaInfo->pTableMeta->id.uid; SColumnList ids = createColumnList(1, index.tableIndex, index.columnIndex); @@ -3123,7 +3120,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col insertResultField(pQueryInfo, colIndex, &ids, pUdfInfo->resBytes, pUdfInfo->resType, pExpr->base.aliasName, pExpr); } else { for (int32_t i = 0; i < ids.num; ++i) { - tscColumnListInsert(pQueryInfo->colList, index.columnIndex, uid, &s); + tscColumnListInsert(pQueryInfo->colList, index.columnIndex, uid, pSchema); } } tscInsertPrimaryTsSourceColumn(pQueryInfo, pTableMetaInfo->pTableMeta->id.uid); @@ -4227,7 +4224,11 @@ static int32_t validateSQLExpr(SSqlCmd* pCmd, tSqlExpr* pExpr, SQueryInfo* pQuer // Append the sqlExpr into exprList of pQueryInfo structure sequentially pExpr->functionId = isValidFunction(pExpr->Expr.operand.z, pExpr->Expr.operand.n); if (pExpr->functionId < 0) { - return TSDB_CODE_TSC_INVALID_OPERATION; + SUdfInfo* pUdfInfo = NULL; + pUdfInfo = isValidUdf(pQueryInfo->pUdfInfo, pExpr->Expr.operand.z, pExpr->Expr.operand.n); + if (pUdfInfo == NULL) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), "invalid function name"); + } } if (addExprAndResultField(pCmd, pQueryInfo, outputIndex, &item, false, NULL) != TSDB_CODE_SUCCESS) { @@ -5738,6 +5739,7 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq const char* msg8 = "only column in groupby clause allowed as order column"; const char* msg9 = "orderby column must projected in subquery"; const char* msg10 = "not support distinct mixed with order by"; + const char* msg11 = "not support order with udf"; setDefaultOrderInfo(pQueryInfo); STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0); @@ -5777,6 +5779,19 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq SStrToken columnName = {pVar->nLen, pVar->nType, pVar->pz}; SColumnIndex index = COLUMN_INDEX_INITIALIZER; + bool udf = false; + + if (pQueryInfo->pUdfInfo && taosArrayGetSize(pQueryInfo->pUdfInfo) > 0) { + int32_t usize = taosArrayGetSize(pQueryInfo->pUdfInfo); + + for (int32_t i = 0; i < usize; ++i) { + SUdfInfo* pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, i); + if (pUdfInfo->funcType == TSDB_UDF_TYPE_SCALAR) { + udf = true; + break; + } + } + } if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) { // super table query if (getColumnIndexByName(&columnName, pQueryInfo, &index, tscGetErrorMsgPayload(pCmd)) != TSDB_CODE_SUCCESS) { @@ -5832,6 +5847,9 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq pQueryInfo->groupbyExpr.orderType = p1->sortOrder; pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId; + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } } else if (isTopBottomQuery(pQueryInfo)) { /* order of top/bottom query in interval is not valid */ @@ -5853,6 +5871,10 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq } else { tVariantListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0); + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } + pQueryInfo->order.order = p1->sortOrder; pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX; @@ -5880,9 +5902,15 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq } else if (orderByGroupbyCol){ pQueryInfo->order.order = pItem->sortOrder; pQueryInfo->order.orderColId = index.columnIndex; + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } } else { pQueryInfo->order.order = pItem->sortOrder; pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX; + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } } pItem = taosArrayGet(pSqlNode->pSortOrder, 1); @@ -5918,6 +5946,10 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq return invalidOperationMsg(pMsgBuf, msg7); } + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } + tVariantListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0); pQueryInfo->groupbyExpr.orderIndex = pSchema[index.columnIndex].colId; pQueryInfo->groupbyExpr.orderType = p1->sortOrder; @@ -5951,6 +5983,10 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq return TSDB_CODE_SUCCESS; } + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } + tVariantListItem* pItem = taosArrayGet(pSqlNode->pSortOrder, 0); pQueryInfo->order.order = pItem->sortOrder; pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId; @@ -5963,6 +5999,10 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq return invalidOperationMsg(pMsgBuf, msg1); } + if (udf) { + return invalidOperationMsg(pMsgBuf, msg11); + } + tVariantListItem* pItem = taosArrayGet(pSqlNode->pSortOrder, 0); pQueryInfo->order.order = pItem->sortOrder; pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId; @@ -7250,7 +7290,7 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* const char* msg3 = "group by/session/state_window not allowed on projection query"; const char* msg4 = "retrieve tags not compatible with group by or interval query"; const char* msg5 = "functions can not be mixed up"; - const char* msg6 = "TWA/Diff/Derivative/Irate only support group by tbname"; + const char* msg6 = "TWA/Diff/Derivative/Irate/CSum/MAvg only support group by tbname"; // only retrieve tags, group by is not supportted if (tscQueryTags(pQueryInfo)) { @@ -7303,10 +7343,16 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* } if (f < 0) { + SUdfInfo* pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, -1 * f - 1); + if (pUdfInfo->funcType == TSDB_UDF_TYPE_SCALAR) { + return invalidOperationMsg(msg, msg1); + } + continue; } - if ((!pQueryInfo->stateWindow) && (f == TSDB_FUNC_DIFF || f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || f == TSDB_FUNC_IRATE)) { + if ((!pQueryInfo->stateWindow) && (f == TSDB_FUNC_DIFF || f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || + f == TSDB_FUNC_IRATE || f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG)) { for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) { SColIndex* pColIndex = taosArrayGet(pQueryInfo->groupbyExpr.columnInfo, j); if (j == 0) { @@ -7325,6 +7371,10 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* return invalidOperationMsg(msg, msg1); } + if (IS_SCALAR_FUNCTION(aAggs[f].status)) { + return invalidOperationMsg(msg, msg1); + } + if (f == TSDB_FUNC_COUNT && pExpr->base.colInfo.colIndex == TSDB_TBNAME_COLUMN_INDEX) { return invalidOperationMsg(msg, msg1); } @@ -8563,12 +8613,33 @@ int32_t loadAllTableMeta(SSqlObj* pSql, struct SSqlInfo* pInfo) { if (functionId < 0) { struct SUdfInfo info = {0}; info.name = strndup(t->z, t->n); + info.keep = true; if (pQueryInfo->pUdfInfo == NULL) { pQueryInfo->pUdfInfo = taosArrayInit(4, sizeof(struct SUdfInfo)); + } else if (taosArrayGetSize(pQueryInfo->pUdfInfo) > 0) { + int32_t usize = (int32_t)taosArrayGetSize(pQueryInfo->pUdfInfo); + int32_t exist = 0; + + for (int32_t j = 0; j < usize; ++j) { + SUdfInfo* pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, j); + int32_t len = strlen(pUdfInfo->name); + if (len == t->n && strncasecmp(info.name, pUdfInfo->name, t->n) == 0) { + exist = 1; + break; + } + } + + if (exist) { + continue; + } } info.functionId = (int32_t)taosArrayGetSize(pQueryInfo->pUdfInfo) * (-1) - 1;; taosArrayPush(pQueryInfo->pUdfInfo, &info); + if (taosArrayGetSize(pQueryInfo->pUdfInfo) > 1) { + code = tscInvalidOperationMsg(pCmd->payload, "only one udf allowed", NULL); + goto _end; + } } } } diff --git a/src/client/src/tscServer.c b/src/client/src/tscServer.c index 2ed8ea94b53955a2061ffe763cb0521daab30fd9..b19af46a0c7f191b84d1ea8658f13456624179c9 100644 --- a/src/client/src/tscServer.c +++ b/src/client/src/tscServer.c @@ -1102,6 +1102,11 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) { // support only one udf if (pQueryInfo->pUdfInfo != NULL && taosArrayGetSize(pQueryInfo->pUdfInfo) > 0) { + if (taosArrayGetSize(pQueryInfo->pUdfInfo) > 1) { + code = tscInvalidOperationMsg(pCmd->payload, "only one udf allowed", NULL); + goto _end; + } + pQueryMsg->udfContentOffset = htonl((int32_t) (pMsg - pCmd->payload)); for(int32_t i = 0; i < taosArrayGetSize(pQueryInfo->pUdfInfo); ++i) { SUdfInfo* pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, i); diff --git a/src/client/src/tscUtil.c b/src/client/src/tscUtil.c index f880cb11760dfdbb269ee5674a73d8e50333f905..b14c5af47a54e8917c97cec4d1e31acebda9f602 100644 --- a/src/client/src/tscUtil.c +++ b/src/client/src/tscUtil.c @@ -1271,6 +1271,28 @@ void handleDownstreamOperator(SSqlObj** pSqlObjList, int32_t numOfUpstream, SQue .pGroupList = taosArrayInit(1, POINTER_BYTES), }; + SUdfInfo* pUdfInfo = NULL; + + size_t size = tscNumOfExprs(px); + for (int32_t j = 0; j < size; ++j) { + SExprInfo* pExprInfo = tscExprGet(px, j); + + int32_t functionId = pExprInfo->base.functionId; + if (functionId < 0) { + if (pUdfInfo) { + pSql->res.code = tscInvalidOperationMsg(pSql->cmd.payload, "only one udf allowed", NULL); + return; + } + + pUdfInfo = taosArrayGet(px->pUdfInfo, -1 * functionId - 1); + int32_t code = initUdfInfo(pUdfInfo); + if (code != TSDB_CODE_SUCCESS) { + pSql->res.code = code; + return; + } + } + } + tableGroupInfo.map = taosHashInit(1, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK); STableKeyInfo tableKeyInfo = {.pTable = NULL, .lastKey = INT64_MIN}; @@ -1352,6 +1374,9 @@ void handleDownstreamOperator(SSqlObj** pSqlObjList, int32_t numOfUpstream, SQue tscDebug("0x%"PRIx64" create QInfo 0x%"PRIx64" to execute the main query while all nest queries are ready", pSql->self, pSql->self); px->pQInfo = createQInfoFromQueryNode(px, &tableGroupInfo, pSourceOperator, NULL, NULL, MASTER_SCAN, pSql->self); + px->pQInfo->runtimeEnv.udfIsCopy = true; + px->pQInfo->runtimeEnv.pUdfInfo = pUdfInfo; + tfree(pColumnInfo); tfree(schema); @@ -4800,9 +4825,14 @@ int32_t createProjectionExpr(SQueryInfo* pQueryInfo, STableMetaInfo* pTableMetaI functionId = TSDB_FUNC_STDDEV; } + SUdfInfo* pUdfInfo = NULL; + if (functionId < 0) { + pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, -1 * functionId - 1); + } + int32_t inter = 0; getResultDataInfo(pSource->base.colType, pSource->base.colBytes, functionId, 0, &pse->resType, - &pse->resBytes, &inter, 0, false, NULL); + &pse->resBytes, &inter, 0, false, pUdfInfo); pse->colType = pse->resType; pse->colBytes = pse->resBytes; @@ -5095,7 +5125,6 @@ static int32_t doAddTableName(char* nextStr, char** str, SArray* pNameArray, SSq if (nextStr == NULL) { tstrncpy(tablename, *str, TSDB_TABLE_FNAME_LEN); - len = (int32_t) strlen(tablename); } else { len = (int32_t)(nextStr - (*str)); if (len >= TSDB_TABLE_NAME_LEN) { diff --git a/src/common/inc/tglobal.h b/src/common/inc/tglobal.h index 8a82aa00a4cbc1e209b6425b4584fc0751c854f0..c91637b1e85d54fb53c55e8fab09c666263345bf 100644 --- a/src/common/inc/tglobal.h +++ b/src/common/inc/tglobal.h @@ -108,9 +108,10 @@ extern int32_t tsQuorum; extern int8_t tsUpdate; extern int8_t tsCacheLastRow; -//tsdb -extern bool tsdbForceKeepFile; -extern bool tsdbForceCompactFile; +//tsdb +extern bool tsdbForceKeepFile; +extern bool tsdbForceCompactFile; +extern int32_t tsdbWalFlushSize; // balance extern int8_t tsEnableBalance; diff --git a/src/common/src/tglobal.c b/src/common/src/tglobal.c index 0bff138fbb903cb910cd7c86b1628cf2b4f77c4e..f3ba69ec40d8ac76f8db0fc84667a1cf402bc4d0 100644 --- a/src/common/src/tglobal.c +++ b/src/common/src/tglobal.c @@ -155,8 +155,9 @@ int32_t tsTsdbMetaCompactRatio = TSDB_META_COMPACT_RATIO; // tsdb config // For backward compatibility -bool tsdbForceKeepFile = false; -bool tsdbForceCompactFile = false; // compact TSDB fileset forcibly +bool tsdbForceKeepFile = false; +bool tsdbForceCompactFile = false; // compact TSDB fileset forcibly +int32_t tsdbWalFlushSize = TSDB_DEFAULT_WAL_FLUSH_SIZE; // MB // balance int8_t tsEnableBalance = 1; @@ -1652,6 +1653,17 @@ static void doInitGlobalConfig(void) { cfg.unitType = TAOS_CFG_UTYPE_NONE; taosInitConfigOption(cfg); + // flush vnode wal file if walSize > walFlushSize and walSize > cache*0.5*blocks + cfg.option = "walFlushSize"; + cfg.ptr = &tsdbWalFlushSize; + cfg.valType = TAOS_CFG_VTYPE_INT32; + cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW | TSDB_CFG_CTYPE_B_CLIENT; + cfg.minValue = TSDB_MIN_WAL_FLUSH_SIZE; + cfg.maxValue = TSDB_MAX_WAL_FLUSH_SIZE; + cfg.ptrLength = 0; + cfg.unitType = TAOS_CFG_UTYPE_MB; + taosInitConfigOption(cfg); + #ifdef TD_TSZ // lossy compress cfg.option = "lossyColumns"; diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java index 7dbb62d8496e9ae9b758c1a6440531e15e352dc9..f6ec70fbac555b97b2cb342edfaa5fde56245c5a 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java @@ -562,25 +562,27 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da List rowDataList = new ArrayList<>(); try (Statement stmt = connection.createStatement()) { stmt.execute("use " + catalog); - ResultSet tables = stmt.executeQuery("show tables"); - while (tables.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); - rowData.setStringValue(1, catalog); //TABLE_CAT - rowData.setStringValue(2, null); //TABLE_SCHEM - rowData.setStringValue(3, tables.getString("table_name")); //TABLE_NAME - rowData.setStringValue(4, "TABLE"); //TABLE_TYPE - rowData.setStringValue(5, ""); //REMARKS - rowDataList.add(rowData); + try (ResultSet tables = stmt.executeQuery("show tables")) { + while (tables.next()) { + TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); + rowData.setStringValue(1, catalog); //TABLE_CAT + rowData.setStringValue(2, null); //TABLE_SCHEM + rowData.setStringValue(3, tables.getString("table_name")); //TABLE_NAME + rowData.setStringValue(4, "TABLE"); //TABLE_TYPE + rowData.setStringValue(5, ""); //REMARKS + rowDataList.add(rowData); + } } - ResultSet stables = stmt.executeQuery("show stables"); - while (stables.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); - rowData.setStringValue(1, catalog); //TABLE_CAT - rowData.setStringValue(2, null); //TABLE_SCHEM - rowData.setStringValue(3, stables.getString("name")); //TABLE_NAME - rowData.setStringValue(4, "TABLE"); //TABLE_TYPE - rowData.setStringValue(5, "STABLE"); //REMARKS - rowDataList.add(rowData); + try (ResultSet stables = stmt.executeQuery("show stables")) { + while (stables.next()) { + TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); + rowData.setStringValue(1, catalog); //TABLE_CAT + rowData.setStringValue(2, null); //TABLE_SCHEM + rowData.setStringValue(3, stables.getString("name")); //TABLE_NAME + rowData.setStringValue(4, "TABLE"); //TABLE_TYPE + rowData.setStringValue(5, "STABLE"); //REMARKS + rowDataList.add(rowData); + } } resultSet.setRowDataList(rowDataList); } @@ -638,8 +640,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da resultSet.setColumnMetaDataList(buildGetColumnsColumnMetaDataList()); // set up rowDataList List rowDataList = new ArrayList<>(); - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("describe " + catalog + "." + tableNamePattern)) { + int rowIndex = 0; while (rs.next()) { TSDBResultSetRowData rowData = new TSDBResultSetRowData(24); @@ -1147,9 +1150,9 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da columnMetaDataList.add(buildTableCatalogMeta(1)); // 1. TABLE_CAT resultSet.setColumnMetaDataList(columnMetaDataList); - try (Statement stmt = conn.createStatement()) { + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("show databases")) { List rowDataList = new ArrayList<>(); - ResultSet rs = stmt.executeQuery("show databases"); while (rs.next()) { TSDBResultSetRowData rowData = new TSDBResultSetRowData(1); rowData.setStringValue(1, rs.getString("name")); @@ -1168,12 +1171,13 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da return new EmptyResultSet(); DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); - try (Statement stmt = conn.createStatement()) { + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table)) { // set up ColumnMetaDataList resultSet.setColumnMetaDataList(buildGetPrimaryKeysMetadataList()); // set rowData List rowDataList = new ArrayList<>(); - ResultSet rs = stmt.executeQuery("describe " + catalog + "." + table); + rs.next(); TSDBResultSetRowData rowData = new TSDBResultSetRowData(6); rowData.setStringValue(1, catalog); @@ -1217,15 +1221,14 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da } private boolean isAvailableCatalog(Connection connection, String catalog) { - try (Statement stmt = connection.createStatement()) { - ResultSet databases = stmt.executeQuery("show databases"); + try (Statement stmt = connection.createStatement(); + ResultSet databases = stmt.executeQuery("show databases")) { while (databases.next()) { String dbname = databases.getString("name"); this.precision = databases.getString("precision"); if (dbname.equalsIgnoreCase(catalog)) return true; } - databases.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -1246,17 +1249,18 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da resultSet.setColumnMetaDataList(buildGetSuperTablesColumnMetaDataList()); // set result set row data stmt.execute("use " + catalog); - ResultSet rs = stmt.executeQuery("show tables like '" + tableNamePattern + "'"); - List rowDataList = new ArrayList<>(); - while (rs.next()) { - TSDBResultSetRowData rowData = new TSDBResultSetRowData(4); - rowData.setStringValue(1, catalog); - rowData.setStringValue(2, null); - rowData.setStringValue(3, rs.getString("table_name")); - rowData.setStringValue(4, rs.getString("stable_name")); - rowDataList.add(rowData); + try (ResultSet rs = stmt.executeQuery("show tables like '" + tableNamePattern + "'")) { + List rowDataList = new ArrayList<>(); + while (rs.next()) { + TSDBResultSetRowData rowData = new TSDBResultSetRowData(4); + rowData.setStringValue(1, catalog); + rowData.setStringValue(2, null); + rowData.setStringValue(3, rs.getString("table_name")); + rowData.setStringValue(4, rs.getString("stable_name")); + rowDataList.add(rowData); + } + resultSet.setRowDataList(rowDataList); } - resultSet.setRowDataList(rowDataList); } return resultSet; } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java index a801f5a674acdd23f1ca7f949cbb7092f4633bda..12641087fb774a82e80c8339f752ff5f514524a0 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractStatement.java @@ -9,6 +9,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement protected List batchedArgs; private int fetchSize; + protected int affectedRows = -1; @Override public abstract ResultSet executeQuery(String sql) throws SQLException; @@ -247,6 +248,7 @@ public abstract class AbstractStatement extends WrapperImpl implements Statement public boolean getMoreResults(int current) throws SQLException { if (isClosed()) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); + this.affectedRows = -1; switch (current) { case Statement.CLOSE_CURRENT_RESULT: return false; diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java index 2ff0d86c920aa0aae67f71448bf9112564293350..6565a8151e6b16d7f04b184e93dbe89d85466533 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java @@ -189,7 +189,7 @@ public class TSDBResultSetRowData { long value = (long) obj; if (value < 0) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_NUMERIC_VALUE_OUT_OF_RANGE); - return Long.valueOf(value).intValue(); + return (int) value; } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java index e1ebc4ab3cf498168181dbea08a3ac28194a5c7d..436bdcf582b821292c5f4e69f51688f9bf84b870 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java @@ -23,7 +23,6 @@ public class TSDBStatement extends AbstractStatement { * Status of current statement */ private boolean isClosed; - private int affectedRows = -1; private TSDBConnection connection; private TSDBResultSet resultSet; @@ -80,12 +79,13 @@ public class TSDBStatement extends AbstractStatement { if (isClosed()) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); } - + // execute query long pSql = this.connection.getConnector().executeQuery(sql); // if pSql is create/insert/update/delete/alter SQL if (this.connection.getConnector().isUpdateQuery(pSql)) { - this.affectedRows = this.connection.getConnector().getAffectedRows(pSql); + int rows = this.connection.getConnector().getAffectedRows(pSql); + this.affectedRows = rows == 0 ? -1 : this.connection.getConnector().getAffectedRows(pSql); this.connection.getConnector().freeResultSet(pSql); return false; } @@ -99,7 +99,7 @@ public class TSDBStatement extends AbstractStatement { if (isClosed()) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); } - + return this.resultSet; } @@ -113,14 +113,14 @@ public class TSDBStatement extends AbstractStatement { if (isClosed()) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); } - + if (this.connection.getConnector() == null) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); } - + return this.connection; } - + public void setConnection(TSDBConnection connection) { this.connection = connection; } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java index 0a8809e84f92f1e948ea5306648610dfeca57c8f..d5985756ee1851407bf19a568657fa2127d0be43 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulDriver.java @@ -64,9 +64,9 @@ public class RestfulDriver extends AbstractDriver { RestfulConnection conn = new RestfulConnection(host, port, props, database, url, token); if (database != null && !database.trim().replaceAll("\\s", "").isEmpty()) { - Statement stmt = conn.createStatement(); - stmt.execute("use " + database); - stmt.close(); + try (Statement stmt = conn.createStatement()) { + stmt.execute("use " + database); + } } return conn; } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java index 21c76f73b287e55ef14f5d70cf6a911a9cb543db..b7f5fe8006368295753a366aa218a6cc17aa0588 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulStatement.java @@ -22,7 +22,6 @@ public class RestfulStatement extends AbstractStatement { private final RestfulConnection conn; private volatile RestfulResultSet resultSet; - private volatile int affectedRows; public RestfulStatement(RestfulConnection conn, String database) { this.conn = conn; @@ -118,7 +117,7 @@ public class RestfulStatement extends AbstractStatement { throw TSDBError.createSQLException(resultJson.getInteger("code"), resultJson.getString("desc")); } this.resultSet = new RestfulResultSet(database, this, resultJson); - this.affectedRows = 0; + this.affectedRows = -1; return resultSet; } @@ -140,9 +139,10 @@ public class RestfulStatement extends AbstractStatement { if (head.size() != 1 || !"affected_rows".equals(head.getString(0))) throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); JSONArray data = jsonObject.getJSONArray("data"); - if (data != null) - return data.getJSONArray(0).getInteger(0); - + if (data != null) { + int rows = data.getJSONArray(0).getInteger(0); + return rows == 0 ? -1 : data.getJSONArray(0).getInteger(0); + } throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_VARIABLE); } diff --git a/src/connector/python/taos/cinterface.py b/src/connector/python/taos/cinterface.py index 1fcbf678b6a2a3f51bd757b84c08a7693166556c..1223b4544899dd83d3f1ea1a519def035de8ebcf 100644 --- a/src/connector/python/taos/cinterface.py +++ b/src/connector/python/taos/cinterface.py @@ -822,11 +822,16 @@ def taos_schemaless_insert(connection, lines, protocol, precision): lines = (c_char_p(line.encode("utf-8")) for line in lines) lines_type = ctypes.c_char_p * num_of_lines p_lines = lines_type(*lines) - if precision != None: - precision = c_char_p(precision.encode("utf-8")) - errno = _libtaos.taos_schemaless_insert(connection, p_lines, num_of_lines, protocol, precision) + res = c_void_p(_libtaos.taos_schemaless_insert(connection, p_lines, num_of_lines, protocol, precision)) + errno = taos_errno(res) if errno != 0: - raise SchemalessError("schemaless insert error", errno) + errstr = taos_errstr(res) + taos_free_result(res) + print("schemaless_insert error affected rows: {}".format(taos_affected_rows(res))) + raise SchemalessError(errstr, errno) + + taos_free_result(res) + return errno class CTaosInterface(object): def __init__(self, config=None): diff --git a/src/inc/taos.h b/src/inc/taos.h index 4a7f3ae99b7c543a1dd6d20d66eeb3b2a69f38ce..4afec942ff991ce1009cb8c54113562f93f9c92d 100644 --- a/src/inc/taos.h +++ b/src/inc/taos.h @@ -72,6 +72,23 @@ typedef enum { SET_CONF_RET_ERR_TOO_LONG = -6 } SET_CONF_RET_CODE; +typedef enum { + TSDB_SML_UNKNOWN_PROTOCOL = 0, + TSDB_SML_LINE_PROTOCOL = 1, + TSDB_SML_TELNET_PROTOCOL = 2, + TSDB_SML_JSON_PROTOCOL = 3, +} TSDB_SML_PROTOCOL_TYPE; + +typedef enum { + TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0, + TSDB_SML_TIMESTAMP_HOURS, + TSDB_SML_TIMESTAMP_MINUTES, + TSDB_SML_TIMESTAMP_SECONDS, + TSDB_SML_TIMESTAMP_MILLI_SECONDS, + TSDB_SML_TIMESTAMP_MICRO_SECONDS, + TSDB_SML_TIMESTAMP_NANO_SECONDS, +} TSDB_SML_TIMESTAMP_TYPE; + #define RET_MSG_LENGTH 1024 typedef struct setConfRet { SET_CONF_RET_CODE retCode; @@ -141,6 +158,7 @@ DLL_EXPORT int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIN DLL_EXPORT int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, int colIdx); DLL_EXPORT int taos_stmt_add_batch(TAOS_STMT *stmt); DLL_EXPORT int taos_stmt_execute(TAOS_STMT *stmt); +DLL_EXPORT int taos_stmt_affected_rows(TAOS_STMT *stmt); DLL_EXPORT TAOS_RES * taos_stmt_use_result(TAOS_STMT *stmt); DLL_EXPORT int taos_stmt_close(TAOS_STMT *stmt); DLL_EXPORT char * taos_stmt_errstr(TAOS_STMT *stmt); @@ -187,7 +205,7 @@ DLL_EXPORT void taos_close_stream(TAOS_STREAM *tstr); DLL_EXPORT int taos_load_table_info(TAOS *taos, const char* tableNameList); -DLL_EXPORT int taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol, char* precision); +DLL_EXPORT TAOS_RES *taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol, int precision); #ifdef __cplusplus } diff --git a/src/inc/taosdef.h b/src/inc/taosdef.h index 3f68a8600f22bd6ddb1def72be82d453698b43a8..cc4df80952c90d30836c56bc3cc189be8ffc121f 100644 --- a/src/inc/taosdef.h +++ b/src/inc/taosdef.h @@ -279,6 +279,10 @@ do { \ #define TSDB_MAX_TOTAL_BLOCKS 10000 #define TSDB_DEFAULT_TOTAL_BLOCKS 6 +#define TSDB_MIN_WAL_FLUSH_SIZE 128 // MB +#define TSDB_MAX_WAL_FLUSH_SIZE 10000000 // MB +#define TSDB_DEFAULT_WAL_FLUSH_SIZE 1024 // MB + #define TSDB_MIN_TABLES 4 #define TSDB_MAX_TABLES 10000000 #define TSDB_DEFAULT_TABLES 1000000 diff --git a/src/inc/tsdb.h b/src/inc/tsdb.h index 4e11e4f2478fe0616701e0d183d38455b9526514..ad7eaef8cbda7a52f9e2340969d7ab95791d127d 100644 --- a/src/inc/tsdb.h +++ b/src/inc/tsdb.h @@ -418,6 +418,12 @@ int tsdbCompact(STsdbRepo *pRepo); // no problem return true bool tsdbNoProblem(STsdbRepo* pRepo); +// unit of walSize: MB +int tsdbCheckWal(STsdbRepo *pRepo, uint32_t walSize); + +// not commit if other instances in committing state or waiting to commit +bool tsdbIsNeedCommit(STsdbRepo *pRepo); + #ifdef __cplusplus } #endif diff --git a/src/inc/twal.h b/src/inc/twal.h index 868a1fbd780232303b42e58185ffc00730c17546..daea34daed43a7a47ca0c50aaf759e3cb905cfef 100644 --- a/src/inc/twal.h +++ b/src/inc/twal.h @@ -66,6 +66,7 @@ int32_t walRestore(twalh, void *pVnode, FWalWrite writeFp); int32_t walGetWalFile(twalh, char *fileName, int64_t *fileId); uint64_t walGetVersion(twalh); void walResetVersion(twalh, uint64_t newVer); +int64_t walGetFSize(twalh); #ifdef __cplusplus } diff --git a/src/kit/taosdemo/taosdemo.c b/src/kit/taosdemo/taosdemo.c index 067c3a2300d1c502bee74941f982d2fbe0813784..761593f6768d4f5017e9fd48b13ec7eb58a948ec 100644 --- a/src/kit/taosdemo/taosdemo.c +++ b/src/kit/taosdemo/taosdemo.c @@ -56,6 +56,7 @@ #define REQ_EXTRA_BUF_LEN 1024 #define RESP_BUF_LEN 4096 +#define SQL_BUFF_LEN 1024 extern char configDir[]; @@ -66,6 +67,7 @@ extern char configDir[]; #define HEAD_BUFF_LEN TSDB_MAX_COLUMNS*24 // 16*MAX_COLUMNS + (192+32)*2 + insert into .. #define BUFFER_SIZE TSDB_MAX_ALLOWED_SQL_LEN +#define FETCH_BUFFER_SIZE 100 * TSDB_MAX_ALLOWED_SQL_LEN #define COND_BUF_LEN (BUFFER_SIZE - 30) #define COL_BUFFER_LEN ((TSDB_COL_NAME_LEN + 15) * TSDB_MAX_COLUMNS) @@ -87,6 +89,7 @@ extern char configDir[]; #define FLOAT_BUFF_LEN 22 #define DOUBLE_BUFF_LEN 42 #define TIMESTAMP_BUFF_LEN 21 +#define PRINT_STAT_INTERVAL 30*1000 #define MAX_SAMPLES 10000 #define MAX_NUM_COLUMNS (TSDB_MAX_COLUMNS - 1) // exclude first column timestamp @@ -97,8 +100,10 @@ extern char configDir[]; #define MAX_QUERY_SQL_COUNT 100 #define MAX_DATABASE_COUNT 256 -#define INPUT_BUF_LEN 256 +#define MAX_JSON_BUFF 6400000 +#define INPUT_BUF_LEN 256 +#define EXTRA_SQL_LEN 256 #define TBNAME_PREFIX_LEN (TSDB_TABLE_NAME_LEN - 20) // 20 characters reserved for seq #define SMALL_BUFF_LEN 8 #define DATATYPE_BUFF_LEN (SMALL_BUFF_LEN*3) @@ -109,6 +114,45 @@ extern char configDir[]; #define DEFAULT_INTERLACE_ROWS 0 #define DEFAULT_DATATYPE_NUM 1 #define DEFAULT_CHILDTABLES 10000 +#define DEFAULT_TEST_MODE 0 +#define DEFAULT_METAFILE NULL +#define DEFAULT_SQLFILE NULL +#define DEFAULT_HOST "localhost" +#define DEFAULT_PORT 6030 +#define DEFAULT_IFACE INTERFACE_BUT +#define DEFAULT_DATABASE "test" +#define DEFAULT_REPLICA 1 +#define DEFAULT_TB_PREFIX "d" +#define DEFAULT_ESCAPE_CHAR false +#define DEFAULT_USE_METRIC true +#define DEFAULT_DROP_DB true +#define DEFAULT_AGGR_FUNC false +#define DEFAULT_DEBUG false +#define DEFAULT_VERBOSE false +#define DEFAULT_PERF_STAT false +#define DEFAULT_ANS_YES false +#define DEFAULT_OUTPUT "./output.txt" +#define DEFAULT_SYNC_MODE 0 +#define DEFAULT_DATA_TYPE {TSDB_DATA_TYPE_FLOAT,TSDB_DATA_TYPE_INT,TSDB_DATA_TYPE_FLOAT} +#define DEFAULT_DATATYPE {"FLOAT","INT","FLOAT"} +#define DEFAULT_BINWIDTH 64 +#define DEFAULT_COL_COUNT 4 +#define DEFAULT_LEN_ONE_ROW 76 +#define DEFAULT_INSERT_INTERVAL 0 +#define DEFAULT_QUERY_TIME 1 +#define DEFAULT_PREPARED_RAND 10000 +#define DEFAULT_REQ_PER_REQ 30000 +#define DEFAULT_INSERT_ROWS 10000 +#define DEFAULT_ABORT 0 +#define DEFAULT_RATIO 0 +#define DEFAULT_DISORDER_RANGE 1000 +#define DEFAULT_METHOD_DEL 1 +#define DEFAULT_TOTAL_INSERT 0 +#define DEFAULT_TOTAL_AFFECT 0 +#define DEFAULT_DEMO_MODE true +#define DEFAULT_CREATE_BATCH 10 +#define DEFAULT_SUB_INTERVAL 10000 +#define DEFAULT_QUERY_INTERVAL 10000 #define STMT_BIND_PARAM_BATCH 1 @@ -147,6 +191,7 @@ enum enum_TAOS_INTERFACE { TAOSC_IFACE, REST_IFACE, STMT_IFACE, + SML_IFACE, INTERFACE_BUT }; @@ -245,6 +290,7 @@ typedef struct SArguments_S { uint64_t insert_interval; uint64_t timestamp_step; int64_t query_times; + int64_t prepared_rand; uint32_t interlaceRows; uint32_t reqPerReq; // num_of_records_per_req uint64_t max_sql_len; @@ -366,7 +412,7 @@ typedef struct SDataBase_S { bool drop; // 0: use exists, 1: if exists, drop then new create SDbCfg dbCfg; uint64_t superTblCount; - SSuperTable superTbls[MAX_SUPER_TABLE_COUNT]; + SSuperTable* superTbls; } SDataBase; typedef struct SDbs_S { @@ -385,12 +431,11 @@ typedef struct SDbs_S { uint32_t threadCount; uint32_t threadCountForCreateTbl; uint32_t dbCount; - SDataBase db[MAX_DB_COUNT]; - // statistics uint64_t totalInsertRows; uint64_t totalAffectedRows; + SDataBase* db; } SDbs; typedef struct SpecifiedQueryInfo_S { @@ -466,7 +511,7 @@ typedef struct SThreadInfo_S { int threadID; char db_name[TSDB_DB_NAME_LEN]; uint32_t time_precision; - char filePath[4096]; + char filePath[TSDB_FILENAME_LEN]; FILE *fp; char tb_prefix[TSDB_TABLE_NAME_LEN]; uint64_t start_table_from; @@ -504,6 +549,7 @@ typedef struct SThreadInfo_S { uint64_t querySeq; // sequence number of sql command TAOS_SUB* tsub; + char** lines; int sockfd; } threadInfo; @@ -593,12 +639,12 @@ static int regexMatch(const char *s, const char *reg, int cflags); /* ************ Global variables ************ */ -int32_t g_randint[MAX_PREPARED_RAND]; -uint32_t g_randuint[MAX_PREPARED_RAND]; -int64_t g_randbigint[MAX_PREPARED_RAND]; -uint64_t g_randubigint[MAX_PREPARED_RAND]; -float g_randfloat[MAX_PREPARED_RAND]; -double g_randdouble[MAX_PREPARED_RAND]; +int32_t* g_randint; +uint32_t* g_randuint; +int64_t* g_randbigint; +uint64_t* g_randubigint; +float* g_randfloat; +double* g_randdouble; char *g_randbool_buff = NULL; char *g_randint_buff = NULL; @@ -622,62 +668,49 @@ char *g_aggreFunc[] = {"*", "count(*)", "avg(C0)", "sum(C0)", "max(C0)", "min(C0)", "first(C0)", "last(C0)"}; SArguments g_args = { - NULL, // metaFile - 0, // test_mode - "localhost", // host - 6030, // port - INTERFACE_BUT, // iface - "root", // user -#ifdef _TD_POWER_ - "powerdb", // password -#elif (_TD_TQ_ == true) - "tqueue", // password -#elif (_TD_PRO_ == true) - "prodb", // password -#else - "taosdata", // password -#endif - "test", // database - 1, // replica - "d", // tb_prefix - false, // escapeChar - NULL, // sqlFile - true, // use_metric - true, // drop_database - false, // aggr_func - false, // debug_print - false, // verbose_print - false, // performance statistic print - false, // answer_yes; - "./output.txt", // output_file - 0, // mode : sync or async - {TSDB_DATA_TYPE_FLOAT, - TSDB_DATA_TYPE_INT, - TSDB_DATA_TYPE_FLOAT}, - { - "FLOAT", // dataType - "INT", // dataType - "FLOAT", // dataType. demo mode has 3 columns - }, - 64, // binwidth - 4, // columnCount, timestamp + float + int + float - 20 + FLOAT_BUFF_LEN + INT_BUFF_LEN + FLOAT_BUFF_LEN, // lenOfOneRow - DEFAULT_NTHREADS,// nthreads - 0, // insert_interval - DEFAULT_TIMESTAMP_STEP, // timestamp_step - 1, // query_times - DEFAULT_INTERLACE_ROWS, // interlaceRows; - 30000, // reqPerReq - (1024*1024), // max_sql_len - DEFAULT_CHILDTABLES, // ntables - 10000, // insertRows - 0, // abort - 0, // disorderRatio - 1000, // disorderRange - 1, // method_of_delete - 0, // totalInsertRows; - 0, // totalAffectedRows; - true, // demo_mode; + DEFAULT_METAFILE, // metaFile + DEFAULT_TEST_MODE, // test_mode + DEFAULT_HOST, // host + DEFAULT_PORT, // port + DEFAULT_IFACE, // iface + TSDB_DEFAULT_USER, // user + TSDB_DEFAULT_PASS, // password + DEFAULT_DATABASE, // database + DEFAULT_REPLICA, // replica + DEFAULT_TB_PREFIX, // tb_prefix + DEFAULT_ESCAPE_CHAR, // escapeChar + DEFAULT_SQLFILE, // sqlFile + DEFAULT_USE_METRIC, // use_metric + DEFAULT_DROP_DB, // drop_database + DEFAULT_AGGR_FUNC, // aggr_func + DEFAULT_DEBUG, // debug_print + DEFAULT_VERBOSE, // verbose_print + DEFAULT_PERF_STAT, // performance statistic print + DEFAULT_ANS_YES, // answer_yes; + DEFAULT_OUTPUT, // output_file + DEFAULT_SYNC_MODE, // mode : sync or async + DEFAULT_DATA_TYPE, // data_type + DEFAULT_DATATYPE, // dataType + DEFAULT_BINWIDTH, // binwidth + DEFAULT_COL_COUNT, // columnCount, timestamp + float + int + float + DEFAULT_LEN_ONE_ROW, // lenOfOneRow + DEFAULT_NTHREADS, // nthreads + DEFAULT_INSERT_INTERVAL, // insert_interval + DEFAULT_TIMESTAMP_STEP, // timestamp_step + DEFAULT_QUERY_TIME, // query_times + DEFAULT_PREPARED_RAND, // prepared_rand + DEFAULT_INTERLACE_ROWS, // interlaceRows; + DEFAULT_REQ_PER_REQ, // reqPerReq + TSDB_MAX_ALLOWED_SQL_LEN, // max_sql_len + DEFAULT_CHILDTABLES, // ntables + DEFAULT_INSERT_ROWS, // insertRows + DEFAULT_ABORT, // abort + DEFAULT_RATIO, // disorderRatio + DEFAULT_DISORDER_RANGE, // disorderRange + DEFAULT_METHOD_DEL, // method_of_delete + DEFAULT_TOTAL_INSERT, // totalInsertRows; + DEFAULT_TOTAL_AFFECT, // totalAffectedRows; + DEFAULT_DEMO_MODE, // demo_mode; }; static SDbs g_Dbs; @@ -732,7 +765,7 @@ static FILE * g_fpOfInsertResult = NULL; /////////////////////////////////////////////////// -static void ERROR_EXIT(const char *msg) { errorPrint("%s", msg); exit(-1); } +static void ERROR_EXIT(const char *msg) { errorPrint("%s", msg); exit(EXIT_FAILURE); } #ifndef TAOSDEMO_COMMIT_SHA1 #define TAOSDEMO_COMMIT_SHA1 "unknown" @@ -1054,6 +1087,8 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { arguments->iface = REST_IFACE; } else if (0 == strcasecmp(argv[i+1], "stmt")) { arguments->iface = STMT_IFACE; + } else if (0 == strcasecmp(argv[i+1], "sml")) { + arguments->iface = SML_IFACE; } else { errorWrongValue(argv[0], "-I", argv[i+1]); exit(EXIT_FAILURE); @@ -1066,6 +1101,8 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { arguments->iface = REST_IFACE; } else if (0 == strcasecmp((char *)(argv[i] + strlen("--interface=")), "stmt")) { arguments->iface = STMT_IFACE; + } else if (0 == strcasecmp((char *)(argv[i] + strlen("--interface=")), "sml")) { + arguments->iface = SML_IFACE; } else { errorPrintReqArg3(argv[0], "--interface"); exit(EXIT_FAILURE); @@ -1077,6 +1114,8 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { arguments->iface = REST_IFACE; } else if (0 == strcasecmp((char *)(argv[i] + strlen("-I")), "stmt")) { arguments->iface = STMT_IFACE; + } else if (0 == strcasecmp((char *)(argv[i] + strlen("-I")), "sml")) { + arguments->iface = SML_IFACE; } else { errorWrongValue(argv[0], "-I", (char *)(argv[i] + strlen("-I"))); @@ -1093,6 +1132,8 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { arguments->iface = REST_IFACE; } else if (0 == strcasecmp(argv[i+1], "stmt")) { arguments->iface = STMT_IFACE; + } else if (0 == strcasecmp(argv[i+1], "sml")) { + arguments->iface = SML_IFACE; } else { errorWrongValue(argv[0], "--interface", argv[i+1]); exit(EXIT_FAILURE); @@ -1999,7 +2040,7 @@ static void parse_args(int argc, char *argv[], SArguments *arguments) { } g_args.columnCount = columnCount; - g_args.lenOfOneRow = 20; // timestamp + g_args.lenOfOneRow = TIMESTAMP_BUFF_LEN; // timestamp for (int c = 0; c < g_args.columnCount; c++) { switch(g_args.data_type[c]) { case TSDB_DATA_TYPE_BINARY: @@ -2106,7 +2147,7 @@ static void tmfclose(FILE *fp) { } } -static void tmfree(char *buf) { +static void tmfree(void *buf) { if (NULL != buf) { free(buf); buf = NULL; @@ -2161,7 +2202,7 @@ static void fetchResult(TAOS_RES *res, threadInfo* pThreadInfo) { int num_fields = taos_field_count(res); TAOS_FIELD *fields = taos_fetch_fields(res); - char* databuf = (char*) calloc(1, 100*1024*1024); + char* databuf = (char*) calloc(1, FETCH_BUFFER_SIZE); if (databuf == NULL) { errorPrint2("%s() LN%d, failed to malloc, warning: save result to file slowly!\n", __func__, __LINE__); @@ -2172,11 +2213,11 @@ static void fetchResult(TAOS_RES *res, threadInfo* pThreadInfo) { // fetch the records row by row while((row = taos_fetch_row(res))) { - if (totalLen >= (100*1024*1024 - HEAD_BUFF_LEN*2)) { + if (totalLen >= (FETCH_BUFFER_SIZE - HEAD_BUFF_LEN*2)) { if (strlen(pThreadInfo->filePath) > 0) appendResultBufToFile(databuf, pThreadInfo); totalLen = 0; - memset(databuf, 0, 100*1024*1024); + memset(databuf, 0, FETCH_BUFFER_SIZE); } num_rows++; char temp[HEAD_BUFF_LEN] = {0}; @@ -2230,157 +2271,157 @@ static void selectAndGetResult( static char *rand_bool_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randbool_buff + ((cursor % MAX_PREPARED_RAND) * BOOL_BUFF_LEN); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randbool_buff + ((cursor % g_args.prepared_rand) * BOOL_BUFF_LEN); } static int32_t rand_bool() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randint[cursor % MAX_PREPARED_RAND] % 2; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randint[cursor % g_args.prepared_rand] % TSDB_DATA_BOOL_NULL; } static char *rand_tinyint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randtinyint_buff + - ((cursor % MAX_PREPARED_RAND) * TINYINT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * TINYINT_BUFF_LEN); } static int32_t rand_tinyint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randint[cursor % MAX_PREPARED_RAND] % 128; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randint[cursor % g_args.prepared_rand] % TSDB_DATA_TINYINT_NULL; } static char *rand_utinyint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randutinyint_buff + - ((cursor % MAX_PREPARED_RAND) * TINYINT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * TINYINT_BUFF_LEN); } static int32_t rand_utinyint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randuint[cursor % MAX_PREPARED_RAND] % 255; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randuint[cursor % g_args.prepared_rand] % TSDB_DATA_UTINYINT_NULL; } static char *rand_smallint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randsmallint_buff + - ((cursor % MAX_PREPARED_RAND) * SMALLINT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * SMALLINT_BUFF_LEN); } static int32_t rand_smallint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randint[cursor % MAX_PREPARED_RAND] % 32768; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randint[cursor % g_args.prepared_rand] % TSDB_DATA_SMALLINT_NULL; } static char *rand_usmallint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randusmallint_buff + - ((cursor % MAX_PREPARED_RAND) * SMALLINT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * SMALLINT_BUFF_LEN); } static int32_t rand_usmallint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randuint[cursor % MAX_PREPARED_RAND] % 65535; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randuint[cursor % g_args.prepared_rand] % TSDB_DATA_USMALLINT_NULL; } static char *rand_int_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randint_buff + ((cursor % MAX_PREPARED_RAND) * INT_BUFF_LEN); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randint_buff + ((cursor % g_args.prepared_rand) * INT_BUFF_LEN); } static int32_t rand_int() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randint[cursor % MAX_PREPARED_RAND]; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randint[cursor % g_args.prepared_rand]; } static char *rand_uint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randuint_buff + ((cursor % MAX_PREPARED_RAND) * INT_BUFF_LEN); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randuint_buff + ((cursor % g_args.prepared_rand) * INT_BUFF_LEN); } static int32_t rand_uint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randuint[cursor % MAX_PREPARED_RAND]; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randuint[cursor % g_args.prepared_rand]; } static char *rand_bigint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randbigint_buff + - ((cursor % MAX_PREPARED_RAND) * BIGINT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * BIGINT_BUFF_LEN); } static int64_t rand_bigint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randbigint[cursor % MAX_PREPARED_RAND]; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randbigint[cursor % g_args.prepared_rand]; } static char *rand_ubigint_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randubigint_buff + - ((cursor % MAX_PREPARED_RAND) * BIGINT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * BIGINT_BUFF_LEN); } static int64_t rand_ubigint() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randubigint[cursor % MAX_PREPARED_RAND]; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randubigint[cursor % g_args.prepared_rand]; } static char *rand_float_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randfloat_buff + ((cursor % MAX_PREPARED_RAND) * FLOAT_BUFF_LEN); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randfloat_buff + ((cursor % g_args.prepared_rand) * FLOAT_BUFF_LEN); } @@ -2388,58 +2429,58 @@ static float rand_float() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_randfloat[cursor % MAX_PREPARED_RAND]; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_randfloat[cursor % g_args.prepared_rand]; } static char *demo_current_float_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_rand_current_buff + - ((cursor % MAX_PREPARED_RAND) * FLOAT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * FLOAT_BUFF_LEN); } static float UNUSED_FUNC demo_current_float() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return (float)(9.8 + 0.04 * (g_randint[cursor % MAX_PREPARED_RAND] % 10) - + g_randfloat[cursor % MAX_PREPARED_RAND]/1000000000); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return (float)(9.8 + 0.04 * (g_randint[cursor % g_args.prepared_rand] % 10) + + g_randfloat[cursor % g_args.prepared_rand]/1000000000); } static char *demo_voltage_int_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_rand_voltage_buff + - ((cursor % MAX_PREPARED_RAND) * INT_BUFF_LEN); + ((cursor % g_args.prepared_rand) * INT_BUFF_LEN); } static int32_t UNUSED_FUNC demo_voltage_int() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return 215 + g_randint[cursor % MAX_PREPARED_RAND] % 10; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return 215 + g_randint[cursor % g_args.prepared_rand] % 10; } static char *demo_phase_float_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return g_rand_phase_buff + ((cursor % MAX_PREPARED_RAND) * FLOAT_BUFF_LEN); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return g_rand_phase_buff + ((cursor % g_args.prepared_rand) * FLOAT_BUFF_LEN); } static float UNUSED_FUNC demo_phase_float() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; - return (float)((115 + g_randint[cursor % MAX_PREPARED_RAND] % 10 - + g_randfloat[cursor % MAX_PREPARED_RAND]/1000000000)/360); + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; + return (float)((115 + g_randint[cursor % g_args.prepared_rand] % 10 + + g_randfloat[cursor % g_args.prepared_rand]/1000000000)/360); } #if 0 @@ -2467,7 +2508,7 @@ static void rand_string(char *str, int size) { //--size; int n; for (n = 0; n < size; n++) { - int key = abs(rand_tinyint()) % (int)(sizeof(charset) - 1); + int key = abs(taosRandom()) % (int)(sizeof(charset) - 1); str[n] = charset[key]; } str[n] = 0; @@ -2478,7 +2519,7 @@ static char *rand_double_str() { static int cursor; cursor++; - if (cursor > (MAX_PREPARED_RAND - 1)) cursor = 0; + if (cursor > (g_args.prepared_rand - 1)) cursor = 0; return g_randdouble_buff + (cursor * DOUBLE_BUFF_LEN); } @@ -2486,42 +2527,54 @@ static double rand_double() { static int cursor; cursor++; - cursor = cursor % MAX_PREPARED_RAND; + cursor = cursor % g_args.prepared_rand; return g_randdouble[cursor]; } static void init_rand_data() { - g_randint_buff = calloc(1, INT_BUFF_LEN * MAX_PREPARED_RAND); + g_randint_buff = calloc(1, INT_BUFF_LEN * g_args.prepared_rand); assert(g_randint_buff); - g_rand_voltage_buff = calloc(1, INT_BUFF_LEN * MAX_PREPARED_RAND); + g_rand_voltage_buff = calloc(1, INT_BUFF_LEN * g_args.prepared_rand); assert(g_rand_voltage_buff); - g_randbigint_buff = calloc(1, BIGINT_BUFF_LEN * MAX_PREPARED_RAND); + g_randbigint_buff = calloc(1, BIGINT_BUFF_LEN * g_args.prepared_rand); assert(g_randbigint_buff); - g_randsmallint_buff = calloc(1, SMALLINT_BUFF_LEN * MAX_PREPARED_RAND); + g_randsmallint_buff = calloc(1, SMALLINT_BUFF_LEN * g_args.prepared_rand); assert(g_randsmallint_buff); - g_randtinyint_buff = calloc(1, TINYINT_BUFF_LEN * MAX_PREPARED_RAND); + g_randtinyint_buff = calloc(1, TINYINT_BUFF_LEN * g_args.prepared_rand); assert(g_randtinyint_buff); - g_randbool_buff = calloc(1, BOOL_BUFF_LEN * MAX_PREPARED_RAND); + g_randbool_buff = calloc(1, BOOL_BUFF_LEN * g_args.prepared_rand); assert(g_randbool_buff); - g_randfloat_buff = calloc(1, FLOAT_BUFF_LEN * MAX_PREPARED_RAND); + g_randfloat_buff = calloc(1, FLOAT_BUFF_LEN * g_args.prepared_rand); assert(g_randfloat_buff); - g_rand_current_buff = calloc(1, FLOAT_BUFF_LEN * MAX_PREPARED_RAND); + g_rand_current_buff = calloc(1, FLOAT_BUFF_LEN * g_args.prepared_rand); assert(g_rand_current_buff); - g_rand_phase_buff = calloc(1, FLOAT_BUFF_LEN * MAX_PREPARED_RAND); + g_rand_phase_buff = calloc(1, FLOAT_BUFF_LEN * g_args.prepared_rand); assert(g_rand_phase_buff); - g_randdouble_buff = calloc(1, DOUBLE_BUFF_LEN * MAX_PREPARED_RAND); + g_randdouble_buff = calloc(1, DOUBLE_BUFF_LEN * g_args.prepared_rand); assert(g_randdouble_buff); - g_randuint_buff = calloc(1, INT_BUFF_LEN * MAX_PREPARED_RAND); + g_randuint_buff = calloc(1, INT_BUFF_LEN * g_args.prepared_rand); assert(g_randuint_buff); - g_randutinyint_buff = calloc(1, TINYINT_BUFF_LEN * MAX_PREPARED_RAND); + g_randutinyint_buff = calloc(1, TINYINT_BUFF_LEN * g_args.prepared_rand); assert(g_randutinyint_buff); - g_randusmallint_buff = calloc(1, SMALLINT_BUFF_LEN * MAX_PREPARED_RAND); + g_randusmallint_buff = calloc(1, SMALLINT_BUFF_LEN * g_args.prepared_rand); assert(g_randusmallint_buff); - g_randubigint_buff = calloc(1, BIGINT_BUFF_LEN * MAX_PREPARED_RAND); + g_randubigint_buff = calloc(1, BIGINT_BUFF_LEN * g_args.prepared_rand); assert(g_randubigint_buff); - - for (int i = 0; i < MAX_PREPARED_RAND; i++) { + g_randint = calloc(1, sizeof(int32_t) * g_args.prepared_rand); + assert(g_randint); + g_randuint = calloc(1, sizeof(uint32_t) * g_args.prepared_rand); + assert(g_randuint); + g_randbigint = calloc(1, sizeof(int64_t) * g_args.prepared_rand); + assert(g_randbigint); + g_randubigint = calloc(1, sizeof(uint64_t) * g_args.prepared_rand); + assert(g_randubigint); + g_randfloat = calloc(1, sizeof(float) * g_args.prepared_rand); + assert(g_randfloat); + g_randdouble = calloc(1, sizeof(double) * g_args.prepared_rand); + assert(g_randdouble); + + for (int i = 0; i < g_args.prepared_rand; i++) { g_randint[i] = (int)(taosRandom() % RAND_MAX - (RAND_MAX >> 1)); g_randuint[i] = (int)(taosRandom()); sprintf(g_randint_buff + i * INT_BUFF_LEN, "%d", @@ -2598,7 +2651,8 @@ static int printfInsertMeta() { // first time if no iface specified printf("interface: \033[33m%s\033[0m\n", (g_args.iface==TAOSC_IFACE)?"taosc": - (g_args.iface==REST_IFACE)?"rest":"stmt"); + (g_args.iface==REST_IFACE)?"rest": + (g_args.iface==STMT_IFACE)?"stmt":"sml"); } printf("host: \033[33m%s:%u\033[0m\n", @@ -2724,7 +2778,8 @@ static int printfInsertMeta() { g_Dbs.db[i].superTbls[j].dataSource); printf(" iface: \033[33m%s\033[0m\n", (g_Dbs.db[i].superTbls[j].iface==TAOSC_IFACE)?"taosc": - (g_Dbs.db[i].superTbls[j].iface==REST_IFACE)?"rest":"stmt"); + (g_Dbs.db[i].superTbls[j].iface==REST_IFACE)?"rest": + (g_Dbs.db[i].superTbls[j].iface==STMT_IFACE)?"stmt":"sml"); if (g_Dbs.db[i].superTbls[j].childTblLimit > 0) { printf(" childTblLimit: \033[33m%"PRId64"\033[0m\n", g_Dbs.db[i].superTbls[j].childTblLimit); @@ -2923,7 +2978,8 @@ static void printfInsertMetaToFile(FILE* fp) { g_Dbs.db[i].superTbls[j].dataSource); fprintf(fp, " iface: %s\n", (g_Dbs.db[i].superTbls[j].iface==TAOSC_IFACE)?"taosc": - (g_Dbs.db[i].superTbls[j].iface==REST_IFACE)?"rest":"stmt"); + (g_Dbs.db[i].superTbls[j].iface==REST_IFACE)?"rest": + (g_Dbs.db[i].superTbls[j].iface==STMT_IFACE)?"stmt":"sml"); fprintf(fp, " insertRows: %"PRId64"\n", g_Dbs.db[i].superTbls[j].insertRows); fprintf(fp, " interlace rows: %u\n", @@ -3340,7 +3396,7 @@ static void printfDbInfoForQueryToFile( static void printfQuerySystemInfo(TAOS * taos) { char filename[MAX_FILE_NAME_LEN] = {0}; - char buffer[1024] = {0}; + char buffer[SQL_BUFF_LEN] = {0}; TAOS_RES* res; time_t t; @@ -3379,12 +3435,12 @@ static void printfQuerySystemInfo(TAOS * taos) { printfDbInfoForQueryToFile(filename, dbInfos[i], i); // show db.vgroups - snprintf(buffer, 1024, "show %s.vgroups;", dbInfos[i]->name); + snprintf(buffer, SQL_BUFF_LEN, "show %s.vgroups;", dbInfos[i]->name); res = taos_query(taos, buffer); xDumpResultToFile(filename, res); // show db.stables - snprintf(buffer, 1024, "show %s.stables;", dbInfos[i]->name); + snprintf(buffer, SQL_BUFF_LEN, "show %s.stables;", dbInfos[i]->name); res = taos_query(taos, buffer); xDumpResultToFile(filename, res); free(dbInfos[i]); @@ -3504,18 +3560,22 @@ static int postProceSql(char *host, uint16_t port, break; received += bytes; - verbosePrint("%s() LN%d: received:%d resp_len:%d, response_buf:\n%s\n", - __func__, __LINE__, received, resp_len, response_buf); + response_buf[RESP_BUF_LEN - 1] = '\0'; - if (((NULL != strstr(response_buf, resEncodingChunk)) - && (NULL != strstr(response_buf, resHttp))) - || ((NULL != strstr(response_buf, resHttpOk)) - && (NULL != strstr(response_buf, "\"status\":")))) { - debugPrint( - "%s() LN%d: received:%d resp_len:%d, response_buf:\n%s\n", + if (strlen(response_buf)) { + verbosePrint("%s() LN%d: received:%d resp_len:%d, response_buf:\n%s\n", __func__, __LINE__, received, resp_len, response_buf); - break; - } + + if (((NULL != strstr(response_buf, resEncodingChunk)) + && (NULL != strstr(response_buf, resHttp))) + || ((NULL != strstr(response_buf, resHttpOk)) + && (NULL != strstr(response_buf, "\"status\":")))) { + debugPrint( + "%s() LN%d: received:%d resp_len:%d, response_buf:\n%s\n", + __func__, __LINE__, received, resp_len, response_buf); + break; + } + } } while(received < resp_len); if (received == resp_len) { @@ -3523,8 +3583,6 @@ static int postProceSql(char *host, uint16_t port, ERROR_EXIT("storing complete response from socket"); } - response_buf[RESP_BUF_LEN - 1] = '\0'; - if (strlen(pThreadInfo->filePath) > 0) { appendResultBufToFile(response_buf, pThreadInfo); } @@ -3727,7 +3785,7 @@ static int calcRowLen(SSuperTable* superTbls) { } } - superTbls->lenOfOneRow = lenOfOneRow + 20; // timestamp + superTbls->lenOfOneRow = lenOfOneRow + TIMESTAMP_BUFF_LEN; // timestamp int tagIndex; int lenOfTagOfOneRow = 0; @@ -3781,7 +3839,7 @@ static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos, char* dbName, char* stbName, char** childTblNameOfSuperTbl, int64_t* childTblCountOfSuperTbl, int64_t limit, uint64_t offset, bool escapChar) { - char command[1024] = "\0"; + char command[SQL_BUFF_LEN] = "\0"; char limitBuf[100] = "\0"; TAOS_RES * res; @@ -3793,7 +3851,7 @@ static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos, limit, offset); //get all child table name use cmd: select tbname from superTblName; - snprintf(command, 1024, escapChar ? "select tbname from %s.`%s` %s" : + snprintf(command, SQL_BUFF_LEN, escapChar ? "select tbname from %s.`%s` %s" : "select tbname from %s.%s %s", dbName, stbName, limitBuf); res = taos_query(taos, command); @@ -3801,12 +3859,12 @@ static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos, if (code != 0) { taos_free_result(res); taos_close(taos); - errorPrint2("%s() LN%d, failed to run command %s\n", - __func__, __LINE__, command); + errorPrint2("%s() LN%d, failed to run command %s, reason: %s\n", + __func__, __LINE__, command, taos_errstr(res)); exit(EXIT_FAILURE); } - int64_t childTblCount = (limit < 0)?10000:limit; + int64_t childTblCount = (limit < 0)?DEFAULT_CHILDTABLES:limit; int64_t count = 0; if (childTblName == NULL) { childTblName = (char*)calloc(1, childTblCount * TSDB_TABLE_NAME_LEN); @@ -3871,17 +3929,17 @@ static int getAllChildNameOfSuperTable(TAOS * taos, char* dbName, static int getSuperTableFromServer(TAOS * taos, char* dbName, SSuperTable* superTbls) { - char command[1024] = "\0"; + char command[SQL_BUFF_LEN] = "\0"; TAOS_RES * res; TAOS_ROW row = NULL; int count = 0; //get schema use cmd: describe superTblName; - snprintf(command, 1024, "describe %s.%s", dbName, superTbls->stbName); + snprintf(command, SQL_BUFF_LEN, "describe %s.%s", dbName, superTbls->stbName); res = taos_query(taos, command); int32_t code = taos_errno(res); if (code != 0) { - printf("failed to run command %s\n", command); + printf("failed to run command %s, reason: %s\n", command, taos_errstr(res)); taos_free_result(res); return -1; } @@ -4207,10 +4265,10 @@ static int createSuperTable( } } - superTbl->lenOfOneRow = lenOfOneRow + 20; // timestamp + superTbl->lenOfOneRow = lenOfOneRow + TIMESTAMP_BUFF_LEN; // timestamp // save for creating child table - superTbl->colsOfCreateChildTable = (char*)calloc(len+20, 1); + superTbl->colsOfCreateChildTable = (char*)calloc(len+TIMESTAMP_BUFF_LEN, 1); if (NULL == superTbl->colsOfCreateChildTable) { taos_close(taos); free(command); @@ -4219,7 +4277,7 @@ static int createSuperTable( exit(EXIT_FAILURE); } - snprintf(superTbl->colsOfCreateChildTable, len+20, "(ts timestamp%s)", cols); + snprintf(superTbl->colsOfCreateChildTable, len+TIMESTAMP_BUFF_LEN, "(ts timestamp%s)", cols); verbosePrint("%s() LN%d: %s\n", __func__, __LINE__, superTbl->colsOfCreateChildTable); @@ -4454,6 +4512,10 @@ int createDatabasesAndStables(char *command) { int validStbCount = 0; for (uint64_t j = 0; j < g_Dbs.db[i].superTblCount; j++) { + if (g_Dbs.db[i].superTbls[j].iface == SML_IFACE) { + goto skip; + } + sprintf(command, "describe %s.%s;", g_Dbs.db[i].dbName, g_Dbs.db[i].superTbls[j].stbName); ret = queryDbExec(taos, command, NO_INSERT_TYPE, true); @@ -4475,6 +4537,7 @@ int createDatabasesAndStables(char *command) { continue; } } + skip: validStbCount ++; } g_Dbs.db[i].superTblCount = validStbCount; @@ -4561,7 +4624,7 @@ static void* createTable(void *sarg) batchNum++; if ((batchNum < stbInfo->batchCreateTableNum) && ((buff_len - len) - >= (stbInfo->lenOfTagOfOneRow + 256))) { + >= (stbInfo->lenOfTagOfOneRow + EXTRA_SQL_LEN))) { continue; } } @@ -4577,7 +4640,7 @@ static void* createTable(void *sarg) } pThreadInfo->tables_created += batchNum; uint64_t currentPrintTime = taosGetTimestampMs(); - if (currentPrintTime - lastPrintTime > 30*1000) { + if (currentPrintTime - lastPrintTime > PRINT_STAT_INTERVAL) { printf("thread[%d] already create %"PRIu64" - %"PRIu64" tables\n", pThreadInfo->threadID, pThreadInfo->start_table_from, i); lastPrintTime = currentPrintTime; @@ -4749,7 +4812,7 @@ static int readTagFromCsvFileToMem(SSuperTable * stbInfo) { stbInfo->tagDataBuf = NULL; } - int tagCount = 10000; + int tagCount = MAX_SAMPLES; int count = 0; char* tagDataBuf = calloc(1, stbInfo->lenOfTagOfOneRow * tagCount); if (tagDataBuf == NULL) { @@ -5155,35 +5218,35 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (port && port->type == cJSON_Number) { g_Dbs.port = port->valueint; } else if (!port) { - g_Dbs.port = 6030; + g_Dbs.port = DEFAULT_PORT; } cJSON* user = cJSON_GetObjectItem(root, "user"); if (user && user->type == cJSON_String && user->valuestring != NULL) { tstrncpy(g_Dbs.user, user->valuestring, MAX_USERNAME_SIZE); } else if (!user) { - tstrncpy(g_Dbs.user, "root", MAX_USERNAME_SIZE); + tstrncpy(g_Dbs.user, TSDB_DEFAULT_USER, MAX_USERNAME_SIZE); } cJSON* password = cJSON_GetObjectItem(root, "password"); if (password && password->type == cJSON_String && password->valuestring != NULL) { tstrncpy(g_Dbs.password, password->valuestring, SHELL_MAX_PASSWORD_LEN); } else if (!password) { - tstrncpy(g_Dbs.password, "taosdata", SHELL_MAX_PASSWORD_LEN); + tstrncpy(g_Dbs.password, TSDB_DEFAULT_PASS, SHELL_MAX_PASSWORD_LEN); } cJSON* resultfile = cJSON_GetObjectItem(root, "result_file"); if (resultfile && resultfile->type == cJSON_String && resultfile->valuestring != NULL) { tstrncpy(g_Dbs.resultFile, resultfile->valuestring, MAX_FILE_NAME_LEN); } else if (!resultfile) { - tstrncpy(g_Dbs.resultFile, "./insert_res.txt", MAX_FILE_NAME_LEN); + tstrncpy(g_Dbs.resultFile, DEFAULT_OUTPUT, MAX_FILE_NAME_LEN); } cJSON* threads = cJSON_GetObjectItem(root, "thread_count"); if (threads && threads->type == cJSON_Number) { g_Dbs.threadCount = threads->valueint; } else if (!threads) { - g_Dbs.threadCount = 1; + g_Dbs.threadCount = DEFAULT_NTHREADS; } else { errorPrint("%s", "failed to read json, threads not found\n"); goto PARSE_OVER; @@ -5193,7 +5256,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (threads2 && threads2->type == cJSON_Number) { g_Dbs.threadCountForCreateTbl = threads2->valueint; } else if (!threads2) { - g_Dbs.threadCountForCreateTbl = 1; + g_Dbs.threadCountForCreateTbl = DEFAULT_NTHREADS; } else { errorPrint("%s", "failed to read json, threads2 not found\n"); goto PARSE_OVER; @@ -5207,7 +5270,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { } g_args.insert_interval = gInsertInterval->valueint; } else if (!gInsertInterval) { - g_args.insert_interval = 0; + g_args.insert_interval = DEFAULT_INSERT_INTERVAL; } else { errorPrint("%s", "failed to read json, insert_interval input mistake\n"); goto PARSE_OVER; @@ -5222,7 +5285,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { } g_args.interlaceRows = interlaceRows->valueint; } else if (!interlaceRows) { - g_args.interlaceRows = 0; // 0 means progressive mode, > 0 mean interlace mode. max value is less or equ num_of_records_per_req + g_args.interlaceRows = DEFAULT_INTERLACE_ROWS; // 0 means progressive mode, > 0 mean interlace mode. max value is less or equ num_of_records_per_req } else { errorPrint("%s", "failed to read json, interlaceRows input mistake\n"); goto PARSE_OVER; @@ -5237,7 +5300,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { } g_args.max_sql_len = maxSqlLen->valueint; } else if (!maxSqlLen) { - g_args.max_sql_len = (1024*1024); + g_args.max_sql_len = TSDB_MAX_ALLOWED_SQL_LEN; } else { errorPrint("%s() LN%d, failed to read json, max_sql_len input mistake\n", __func__, __LINE__); @@ -5267,6 +5330,22 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { goto PARSE_OVER; } + cJSON* prepareRand = cJSON_GetObjectItem(root, "prepared_rand"); + if (prepareRand && prepareRand->type == cJSON_Number) { + if (prepareRand->valueint <= 0) { + errorPrint("%s() LN%d, failed to read json, prepared_rand input mistake\n", + __func__, __LINE__); + goto PARSE_OVER; + } + g_args.prepared_rand = prepareRand->valueint; + } else if (!prepareRand) { + g_args.prepared_rand = DEFAULT_PREPARED_RAND; + } else { + errorPrint("%s() LN%d, failed to read json, prepared_rand not found\n", + __func__, __LINE__); + goto PARSE_OVER; + } + cJSON *answerPrompt = cJSON_GetObjectItem(root, "confirm_parameter_prompt"); // yes, no, if (answerPrompt && answerPrompt->type == cJSON_String @@ -5276,7 +5355,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { } else if (0 == strncasecmp(answerPrompt->valuestring, "no", 2)) { g_args.answer_yes = true; } else { - g_args.answer_yes = false; + g_args.answer_yes = DEFAULT_ANS_YES; } } else if (!answerPrompt) { g_args.answer_yes = true; // default is no, mean answer_yes. @@ -5308,7 +5387,8 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { MAX_DB_COUNT); goto PARSE_OVER; } - + g_Dbs.db = calloc(1, sizeof(SDataBase)*dbSize); + assert(g_Dbs.db); g_Dbs.dbCount = dbSize; for (int i = 0; i < dbSize; ++i) { cJSON* dbinfos = cJSON_GetArrayItem(dbs, i); @@ -5508,7 +5588,8 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { MAX_SUPER_TABLE_COUNT); goto PARSE_OVER; } - + g_Dbs.db[i].superTbls = calloc(1, stbSize * sizeof(SSuperTable)); + assert(g_Dbs.db[i].superTbls); g_Dbs.db[i].superTblCount = stbSize; for (int j = 0; j < stbSize; ++j) { cJSON* stbInfo = cJSON_GetArrayItem(stables, j); @@ -5573,7 +5654,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (batchCreateTbl && batchCreateTbl->type == cJSON_Number) { g_Dbs.db[i].superTbls[j].batchCreateTableNum = batchCreateTbl->valueint; } else if (!batchCreateTbl) { - g_Dbs.db[i].superTbls[j].batchCreateTableNum = 10; + g_Dbs.db[i].superTbls[j].batchCreateTableNum = DEFAULT_CREATE_BATCH; } else { errorPrint("%s", "failed to read json, batch_create_tbl_num not found\n"); goto PARSE_OVER; @@ -5636,6 +5717,9 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { g_Dbs.db[i].superTbls[j].iface= REST_IFACE; } else if (0 == strcasecmp(stbIface->valuestring, "stmt")) { g_Dbs.db[i].superTbls[j].iface= STMT_IFACE; + } else if (0 == strcasecmp(stbIface->valuestring, "sml")) { + g_Dbs.db[i].superTbls[j].iface= SML_IFACE; + g_args.iface = SML_IFACE; } else { errorPrint("failed to read json, insert_mode %s not recognized\n", stbIface->valuestring); @@ -5852,7 +5936,7 @@ static bool getMetaFromInsertJsonFile(cJSON* root) { if (disorderRange && disorderRange->type == cJSON_Number) { g_Dbs.db[i].superTbls[j].disorderRange = disorderRange->valueint; } else if (!disorderRange) { - g_Dbs.db[i].superTbls[j].disorderRange = 1000; + g_Dbs.db[i].superTbls[j].disorderRange = DEFAULT_DISORDER_RANGE; } else { errorPrint("%s", "failed to read json, disorderRange not found\n"); goto PARSE_OVER; @@ -5900,7 +5984,7 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { if (host && host->type == cJSON_String && host->valuestring != NULL) { tstrncpy(g_queryInfo.host, host->valuestring, MAX_HOSTNAME_SIZE); } else if (!host) { - tstrncpy(g_queryInfo.host, "127.0.0.1", MAX_HOSTNAME_SIZE); + tstrncpy(g_queryInfo.host, DEFAULT_HOST, MAX_HOSTNAME_SIZE); } else { errorPrint("%s", "failed to read json, host not found\n"); goto PARSE_OVER; @@ -5910,21 +5994,21 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { if (port && port->type == cJSON_Number) { g_queryInfo.port = port->valueint; } else if (!port) { - g_queryInfo.port = 6030; + g_queryInfo.port = DEFAULT_PORT; } cJSON* user = cJSON_GetObjectItem(root, "user"); if (user && user->type == cJSON_String && user->valuestring != NULL) { tstrncpy(g_queryInfo.user, user->valuestring, MAX_USERNAME_SIZE); } else if (!user) { - tstrncpy(g_queryInfo.user, "root", MAX_USERNAME_SIZE); ; + tstrncpy(g_queryInfo.user, TSDB_DEFAULT_USER, MAX_USERNAME_SIZE); ; } cJSON* password = cJSON_GetObjectItem(root, "password"); if (password && password->type == cJSON_String && password->valuestring != NULL) { tstrncpy(g_queryInfo.password, password->valuestring, SHELL_MAX_PASSWORD_LEN); } else if (!password) { - tstrncpy(g_queryInfo.password, "taosdata", SHELL_MAX_PASSWORD_LEN);; + tstrncpy(g_queryInfo.password, TSDB_DEFAULT_PASS, SHELL_MAX_PASSWORD_LEN);; } cJSON *answerPrompt = cJSON_GetObjectItem(root, "confirm_parameter_prompt"); // yes, no, @@ -5952,7 +6036,7 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { } g_args.query_times = gQueryTimes->valueint; } else if (!gQueryTimes) { - g_args.query_times = 1; + g_args.query_times = DEFAULT_QUERY_TIME; } else { errorPrint("%s", "failed to read json, query_times input mistake\n"); goto PARSE_OVER; @@ -6050,7 +6134,7 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { } else if (!interval) { //printf("failed to read json, subscribe interval no found\n"); //goto PARSE_OVER; - g_queryInfo.specifiedQueryInfo.subscribeInterval = 10000; + g_queryInfo.specifiedQueryInfo.subscribeInterval = DEFAULT_SUB_INTERVAL; } cJSON* restart = cJSON_GetObjectItem(specifiedQuery, "restart"); @@ -6197,7 +6281,7 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { } g_queryInfo.superQueryInfo.threadCnt = threads->valueint; } else if (!threads) { - g_queryInfo.superQueryInfo.threadCnt = 1; + g_queryInfo.superQueryInfo.threadCnt = DEFAULT_NTHREADS; } //cJSON* subTblCnt = cJSON_GetObjectItem(superQuery, "childtable_count"); @@ -6242,7 +6326,7 @@ static bool getMetaFromQueryJsonFile(cJSON* root) { } else if (!superInterval) { //printf("failed to read json, subscribe interval no found\n"); //goto PARSE_OVER; - g_queryInfo.superQueryInfo.subscribeInterval = 10000; + g_queryInfo.superQueryInfo.subscribeInterval = DEFAULT_QUERY_INTERVAL; } cJSON* subrestart = cJSON_GetObjectItem(superQuery, "restart"); @@ -6362,7 +6446,7 @@ static bool getInfoFromJsonFile(char* file) { } bool ret = false; - int maxLen = 6400000; + int maxLen = MAX_JSON_BUFF; char *content = calloc(1, maxLen + 1); int len = fread(content, 1, maxLen, fp); if (len <= 0) { @@ -6399,9 +6483,12 @@ static bool getInfoFromJsonFile(char* file) { } if (INSERT_TEST == g_args.test_mode) { + memset(&g_Dbs, 0, sizeof(SDbs)); + g_Dbs.use_metric = g_args.use_metric; ret = getMetaFromInsertJsonFile(root); } else if ((QUERY_TEST == g_args.test_mode) || (SUBSCRIBE_TEST == g_args.test_mode)) { + memset(&g_queryInfo, 0, sizeof(SQueryMetaInfo)); ret = getMetaFromQueryJsonFile(root); } else { errorPrint("%s", @@ -6466,8 +6553,9 @@ static void postFreeResource() { g_Dbs.db[i].superTbls[j].childTblName = NULL; } } + tmfree(g_Dbs.db[i].superTbls); } - + tmfree(g_Dbs.db); tmfree(g_randbool_buff); tmfree(g_randint_buff); tmfree(g_rand_voltage_buff); @@ -6490,6 +6578,7 @@ static void postFreeResource() { } } tmfree(g_sampleBindBatchArray); + #endif } @@ -6971,7 +7060,8 @@ static int32_t execInsert(threadInfo *pThreadInfo, uint32_t k) { int32_t affectedRows; SSuperTable* stbInfo = pThreadInfo->stbInfo; - + TAOS_RES* res; + int32_t code; uint16_t iface; if (stbInfo) iface = stbInfo->iface; @@ -7023,7 +7113,16 @@ static int32_t execInsert(threadInfo *pThreadInfo, uint32_t k) } affectedRows = k; break; - + case SML_IFACE: + res = taos_schemaless_insert(pThreadInfo->taos, pThreadInfo->lines, k, 0, pThreadInfo->time_precision); + code = taos_errno(res); + affectedRows = taos_affected_rows(res); + if (code != TSDB_CODE_SUCCESS) { + errorPrint2("%s() LN%d, failed to execute schemaless insert. reason: %s\n", + __func__, __LINE__, taos_errstr(res)); + exit(EXIT_FAILURE); + } + break; default: errorPrint2("%s() LN%d: unknown insert mode: %d\n", __func__, __LINE__, stbInfo->iface); @@ -9509,6 +9608,441 @@ free_of_interlace_stmt: #endif +static void generateSmlHead(char* smlHead, SSuperTable* stbInfo, threadInfo* pThreadInfo, int tbSeq) { + int64_t dataLen = 0; + dataLen += snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "%s,id=%s%" PRIu64 "", stbInfo->stbName, + stbInfo->childTblPrefix, + tbSeq + pThreadInfo->start_table_from); + for (int j = 0; j < stbInfo->tagCount; j++) { + tstrncpy(smlHead + dataLen, ",", 2); + dataLen += 1; + switch (stbInfo->tags[j].data_type) { + case TSDB_DATA_TYPE_TIMESTAMP: + errorPrint2( + "%s() LN%d, Does not support data type %s as tag\n", + __func__, __LINE__, stbInfo->tags[j].dataType); + exit(EXIT_FAILURE); + case TSDB_DATA_TYPE_BOOL: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%s", j, rand_bool_str()); + break; + case TSDB_DATA_TYPE_TINYINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%si8", j, rand_tinyint_str()); + break; + case TSDB_DATA_TYPE_UTINYINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%su8", j, rand_utinyint_str()); + break; + case TSDB_DATA_TYPE_SMALLINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%si16", j, rand_smallint_str()); + break; + case TSDB_DATA_TYPE_USMALLINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%su16", j, rand_usmallint_str()); + break; + case TSDB_DATA_TYPE_INT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%si32", j, rand_int_str()); + break; + case TSDB_DATA_TYPE_UINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%su32", j, rand_uint_str()); + break; + case TSDB_DATA_TYPE_BIGINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%si64", j, rand_bigint_str()); + break; + case TSDB_DATA_TYPE_UBIGINT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%su64", j, rand_ubigint_str()); + break; + case TSDB_DATA_TYPE_FLOAT: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%sf32", j, rand_float_str()); + break; + case TSDB_DATA_TYPE_DOUBLE: + dataLen += + snprintf(smlHead + dataLen, HEAD_BUFF_LEN - dataLen, + "T%d=%sf64", j, rand_double_str()); + break; + case TSDB_DATA_TYPE_BINARY: + case TSDB_DATA_TYPE_NCHAR: + if (stbInfo->tags[j].dataLen > TSDB_MAX_BINARY_LEN) { + errorPrint2( + "binary or nchar length overflow, maxsize:%u\n", + (uint32_t)TSDB_MAX_BINARY_LEN); + exit(EXIT_FAILURE); + } + char *buf = (char *)calloc(stbInfo->tags[j].dataLen + 1, 1); + if (NULL == buf) { + errorPrint2("calloc failed! size:%d\n", + stbInfo->tags[j].dataLen); + exit(EXIT_FAILURE); + } + rand_string(buf, stbInfo->tags[j].dataLen); + if (stbInfo->tags[j].data_type == TSDB_DATA_TYPE_BINARY) { + dataLen += snprintf(smlHead + dataLen, + HEAD_BUFF_LEN - dataLen, + "T%d=\"%s\"", j, buf); + } else { + dataLen += snprintf(smlHead + dataLen, + HEAD_BUFF_LEN - dataLen, + "T%d=L\"%s\"", j, buf); + } + tmfree(buf); + break; + + default: + errorPrint2("%s() LN%d, Unknown data type %s\n", __func__, + __LINE__, stbInfo->tags[j].dataType); + exit(EXIT_FAILURE); + } + } +} + +static void generateSmlTail(char* line, char* smlHead, SSuperTable* stbInfo, + threadInfo* pThreadInfo, int64_t timestamp) { + int dataLen = 0; + dataLen = snprintf(line, BUFFER_SIZE, "%s ", smlHead); + for (uint32_t c = 0; c < stbInfo->columnCount; c++) { + if (c != 0) { + tstrncpy(line + dataLen, ",", 2); + dataLen += 1; + } + switch (stbInfo->columns[c].data_type) { + case TSDB_DATA_TYPE_TIMESTAMP: + errorPrint2( + "%s() LN%d, Does not support data type %s as tag\n", + __func__, __LINE__, stbInfo->columns[c].dataType); + exit(EXIT_FAILURE); + case TSDB_DATA_TYPE_BOOL: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, "c%d=%s", + c, rand_bool_str()); + break; + case TSDB_DATA_TYPE_TINYINT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, "c%d=%si8", + c, rand_tinyint_str()); + break; + case TSDB_DATA_TYPE_UTINYINT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, "c%d=%su8", + c, rand_utinyint_str()); + break; + case TSDB_DATA_TYPE_SMALLINT: + dataLen += snprintf( + line + dataLen, BUFFER_SIZE - dataLen, + "c%d=%si16", c, rand_smallint_str()); + break; + case TSDB_DATA_TYPE_USMALLINT: + dataLen += snprintf( + line + dataLen, BUFFER_SIZE - dataLen, + "c%d=%su16", c, rand_usmallint_str()); + break; + case TSDB_DATA_TYPE_INT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=%si32", c, rand_int_str()); + break; + case TSDB_DATA_TYPE_UINT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=%su32", c, rand_uint_str()); + break; + case TSDB_DATA_TYPE_BIGINT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=%si64", c, rand_bigint_str()); + break; + case TSDB_DATA_TYPE_UBIGINT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=%su64", c, rand_ubigint_str()); + break; + case TSDB_DATA_TYPE_FLOAT: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=%sf32", c, rand_float_str()); + break; + case TSDB_DATA_TYPE_DOUBLE: + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=%sf64", c, rand_double_str()); + break; + case TSDB_DATA_TYPE_BINARY: + case TSDB_DATA_TYPE_NCHAR: + if (stbInfo->columns[c].dataLen > TSDB_MAX_BINARY_LEN) { + errorPrint2( + "binary or nchar length overflow, maxsize:%u\n", + (uint32_t)TSDB_MAX_BINARY_LEN); + exit(EXIT_FAILURE); + } + char *buf = + (char *)calloc(stbInfo->columns[c].dataLen + 1, 1); + if (NULL == buf) { + errorPrint2("calloc failed! size:%d\n", + stbInfo->columns[c].dataLen); + exit(EXIT_FAILURE); + } + rand_string(buf, stbInfo->columns[c].dataLen); + if (stbInfo->columns[c].data_type == + TSDB_DATA_TYPE_BINARY) { + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=\"%s\"", c, buf); + } else { + dataLen += snprintf(line + dataLen, + BUFFER_SIZE - dataLen, + "c%d=L\"%s\"", c, buf); + } + tmfree(buf); + break; + default: + errorPrint2("%s() LN%d, Unknown data type %s\n", + __func__, __LINE__, + stbInfo->columns[c].dataType); + exit(EXIT_FAILURE); + } + } + dataLen += snprintf(line + dataLen, BUFFER_SIZE - dataLen," %" PRId64 "", timestamp); +} + +static void* syncWriteInterlaceSml(threadInfo *pThreadInfo, uint32_t interlaceRows) { + debugPrint("[%d] %s() LN%d: ### interlace schemaless write\n", + pThreadInfo->threadID, __func__, __LINE__); + int64_t insertRows; + uint64_t maxSqlLen; + int64_t timeStampStep; + uint64_t insert_interval; + + SSuperTable* stbInfo = pThreadInfo->stbInfo; + + if (stbInfo) { + insertRows = stbInfo->insertRows; + maxSqlLen = stbInfo->maxSqlLen; + timeStampStep = stbInfo->timeStampStep; + insert_interval = stbInfo->insertInterval; + } else { + insertRows = g_args.insertRows; + maxSqlLen = g_args.max_sql_len; + timeStampStep = g_args.timestamp_step; + insert_interval = g_args.insert_interval; + } + + debugPrint("[%d] %s() LN%d: start_table_from=%"PRIu64" ntables=%"PRId64" insertRows=%"PRIu64"\n", + pThreadInfo->threadID, __func__, __LINE__, + pThreadInfo->start_table_from, + pThreadInfo->ntables, insertRows); + + if (interlaceRows > g_args.reqPerReq) + interlaceRows = g_args.reqPerReq; + + uint32_t batchPerTbl = interlaceRows; + uint32_t batchPerTblTimes; + + if ((interlaceRows > 0) && (pThreadInfo->ntables > 1)) { + batchPerTblTimes = + g_args.reqPerReq / interlaceRows; + } else { + batchPerTblTimes = 1; + } + + char *smlHead[pThreadInfo->ntables]; + for (int t = 0; t < pThreadInfo->ntables; t++) { + smlHead[t] = (char *)calloc(HEAD_BUFF_LEN, 1); + if (NULL == smlHead[t]) { + errorPrint2("calloc failed! size:%d\n", HEAD_BUFF_LEN); + exit(EXIT_FAILURE); + } + generateSmlHead(smlHead[t], stbInfo, pThreadInfo, t); + + } + + pThreadInfo->totalInsertRows = 0; + pThreadInfo->totalAffectedRows = 0; + + uint64_t st = 0; + uint64_t et = UINT64_MAX; + + uint64_t lastPrintTime = taosGetTimestampMs(); + uint64_t startTs = taosGetTimestampMs(); + uint64_t endTs; + + uint64_t tableSeq = pThreadInfo->start_table_from; + int64_t startTime = pThreadInfo->start_time; + + uint64_t generatedRecPerTbl = 0; + bool flagSleep = true; + uint64_t sleepTimeTotal = 0; + + int percentComplete = 0; + int64_t totalRows = insertRows * pThreadInfo->ntables; + + pThreadInfo->lines = calloc(g_args.reqPerReq, sizeof(char *)); + if (NULL == pThreadInfo->lines) { + errorPrint2("Failed to alloc %"PRIu64" bytes, reason:%s\n", + g_args.reqPerReq * sizeof(char *), + strerror(errno)); + return NULL; + } + + while(pThreadInfo->totalInsertRows < pThreadInfo->ntables * insertRows) { + if ((flagSleep) && (insert_interval)) { + st = taosGetTimestampMs(); + flagSleep = false; + } + + // generate data + + uint32_t recOfBatch = 0; + + for (uint64_t i = 0; i < batchPerTblTimes; i++) { + int64_t timestamp = startTime; + for (int j = recOfBatch; j < recOfBatch + batchPerTbl; j++) { + pThreadInfo->lines[j] = calloc(BUFFER_SIZE, 1); + if (NULL == pThreadInfo->lines[j]) { + errorPrint2("Failed to alloc %d bytes, reason:%s\n", + BUFFER_SIZE, strerror(errno)); + } + generateSmlTail(pThreadInfo->lines[j], smlHead[i], stbInfo, pThreadInfo, timestamp); + timestamp += timeStampStep; + } + tableSeq ++; + recOfBatch += batchPerTbl; + + pThreadInfo->totalInsertRows += batchPerTbl; + + verbosePrint("[%d] %s() LN%d batchPerTbl=%d recOfBatch=%d\n", + pThreadInfo->threadID, __func__, __LINE__, + batchPerTbl, recOfBatch); + + if (tableSeq == pThreadInfo->start_table_from + pThreadInfo->ntables) { + // turn to first table + tableSeq = pThreadInfo->start_table_from; + generatedRecPerTbl += batchPerTbl; + + startTime = pThreadInfo->start_time + + generatedRecPerTbl * timeStampStep; + + flagSleep = true; + if (generatedRecPerTbl >= insertRows) + break; + + int64_t remainRows = insertRows - generatedRecPerTbl; + if ((remainRows > 0) && (batchPerTbl > remainRows)) + batchPerTbl = remainRows; + + if (pThreadInfo->ntables * batchPerTbl < g_args.reqPerReq) + break; + } + + verbosePrint("[%d] %s() LN%d generatedRecPerTbl=%"PRId64" insertRows=%"PRId64"\n", + pThreadInfo->threadID, __func__, __LINE__, + generatedRecPerTbl, insertRows); + + if ((g_args.reqPerReq - recOfBatch) < batchPerTbl) + break; + } + + verbosePrint("[%d] %s() LN%d recOfBatch=%d totalInsertRows=%"PRIu64"\n", + pThreadInfo->threadID, __func__, __LINE__, recOfBatch, + pThreadInfo->totalInsertRows); + verbosePrint("[%d] %s() LN%d, buffer=%s\n", + pThreadInfo->threadID, __func__, __LINE__, pThreadInfo->buffer); + + startTs = taosGetTimestampUs(); + + if (recOfBatch == 0) { + errorPrint2("[%d] %s() LN%d Failed to insert records of batch %d\n", + pThreadInfo->threadID, __func__, __LINE__, + batchPerTbl); + if (batchPerTbl > 0) { + errorPrint("\tIf the batch is %d, the length of the SQL to insert a row must be less then %"PRId64"\n", + batchPerTbl, maxSqlLen / batchPerTbl); + } + errorPrint("\tPlease check if the buffer length(%"PRId64") or batch(%d) is set with proper value!\n", + maxSqlLen, batchPerTbl); + goto free_of_interlace; + } + int64_t affectedRows = execInsert(pThreadInfo, recOfBatch); + + endTs = taosGetTimestampUs(); + uint64_t delay = endTs - startTs; + performancePrint("%s() LN%d, insert execution time is %10.2f ms\n", + __func__, __LINE__, delay / 1000.0); + verbosePrint("[%d] %s() LN%d affectedRows=%"PRId64"\n", + pThreadInfo->threadID, + __func__, __LINE__, affectedRows); + + if (delay > pThreadInfo->maxDelay) pThreadInfo->maxDelay = delay; + if (delay < pThreadInfo->minDelay) pThreadInfo->minDelay = delay; + pThreadInfo->cntDelay++; + pThreadInfo->totalDelay += delay; + + if (recOfBatch != affectedRows) { + errorPrint2("[%d] %s() LN%d execInsert insert %d, affected rows: %"PRId64"\n%s\n", + pThreadInfo->threadID, __func__, __LINE__, + recOfBatch, affectedRows, pThreadInfo->buffer); + goto free_of_interlace; + } + + pThreadInfo->totalAffectedRows += affectedRows; + + int currentPercent = pThreadInfo->totalAffectedRows * 100 / totalRows; + if (currentPercent > percentComplete ) { + printf("[%d]:%d%%\n", pThreadInfo->threadID, currentPercent); + percentComplete = currentPercent; + } + int64_t currentPrintTime = taosGetTimestampMs(); + if (currentPrintTime - lastPrintTime > 30*1000) { + printf("thread[%d] has currently inserted rows: %"PRIu64 ", affected rows: %"PRIu64 "\n", + pThreadInfo->threadID, + pThreadInfo->totalInsertRows, + pThreadInfo->totalAffectedRows); + lastPrintTime = currentPrintTime; + } + + if ((insert_interval) && flagSleep) { + et = taosGetTimestampMs(); + + if (insert_interval > (et - st) ) { + uint64_t sleepTime = insert_interval - (et -st); + performancePrint("%s() LN%d sleep: %"PRId64" ms for insert interval\n", + __func__, __LINE__, sleepTime); + taosMsleep(sleepTime); // ms + sleepTimeTotal += insert_interval; + } + } + for (int index = 0; index < g_args.reqPerReq; index++) { + free(pThreadInfo->lines[index]); + } + } + if (percentComplete < 100) + printf("[%d]:%d%%\n", pThreadInfo->threadID, percentComplete); + +free_of_interlace: + tmfree(pThreadInfo->lines); + for (int index = 0; index < pThreadInfo->ntables; index++) { + free(smlHead[index]); + } + printStatPerThread(pThreadInfo); + return NULL; +} + // sync write interlace data static void* syncWriteInterlace(threadInfo *pThreadInfo, uint32_t interlaceRows) { debugPrint("[%d] %s() LN%d: ### interlace write\n", @@ -9911,6 +10445,118 @@ free_of_stmt_progressive: printStatPerThread(pThreadInfo); return NULL; } + +static void* syncWriteProgressiveSml(threadInfo *pThreadInfo) { + debugPrint("%s() LN%d: ### sml progressive write\n", __func__, __LINE__); + + SSuperTable* stbInfo = pThreadInfo->stbInfo; + int64_t timeStampStep = stbInfo->timeStampStep; + int64_t insertRows = stbInfo->insertRows; + verbosePrint("%s() LN%d insertRows=%"PRId64"\n", + __func__, __LINE__, insertRows); + + uint64_t lastPrintTime = taosGetTimestampMs(); + + pThreadInfo->totalInsertRows = 0; + pThreadInfo->totalAffectedRows = 0; + + pThreadInfo->samplePos = 0; + + char *smlHead[pThreadInfo->ntables]; + for (int t = 0; t < pThreadInfo->ntables; t++) { + smlHead[t] = (char *)calloc(HEAD_BUFF_LEN, 1); + if (NULL == smlHead[t]) { + errorPrint2("calloc failed! size:%d\n", HEAD_BUFF_LEN); + exit(EXIT_FAILURE); + } + generateSmlHead(smlHead[t], stbInfo, pThreadInfo, t); + + } + int currentPercent = 0; + int percentComplete = 0; + + if (insertRows < g_args.reqPerReq) { + g_args.reqPerReq = insertRows; + } + pThreadInfo->lines = calloc(g_args.reqPerReq, sizeof(char *)); + if (NULL == pThreadInfo->lines) { + errorPrint2("Failed to alloc %"PRIu64" bytes, reason:%s\n", + g_args.reqPerReq * sizeof(char *), + strerror(errno)); + return NULL; + } + + for (uint64_t i = 0; i < pThreadInfo->ntables; i++) { + int64_t timestamp = pThreadInfo->start_time; + + for (uint64_t j = 0; j < insertRows;) { + for (int k = 0; k < g_args.reqPerReq; k++) { + pThreadInfo->lines[k] = calloc(BUFFER_SIZE, 1); + if (NULL == pThreadInfo->lines[k]) { + errorPrint2("Failed to alloc %d bytes, reason:%s\n", + BUFFER_SIZE, strerror(errno)); + } + generateSmlTail(pThreadInfo->lines[k], smlHead[i], stbInfo, pThreadInfo, timestamp); + timestamp += timeStampStep; + j++; + if (j == insertRows) { + break; + } + } + uint64_t startTs = taosGetTimestampUs(); + int32_t affectedRows = execInsert(pThreadInfo, g_args.reqPerReq); + uint64_t endTs = taosGetTimestampUs(); + uint64_t delay = endTs - startTs; + + performancePrint("%s() LN%d, insert execution time is %10.f ms\n", + __func__, __LINE__, delay/1000.0); + verbosePrint("[%d] %s() LN%d affectedRows=%d\n", + pThreadInfo->threadID, + __func__, __LINE__, affectedRows); + + if (delay > pThreadInfo->maxDelay){ + pThreadInfo->maxDelay = delay; + } + if (delay < pThreadInfo->minDelay){ + pThreadInfo->minDelay = delay; + } + pThreadInfo->cntDelay++; + pThreadInfo->totalDelay += delay; + + pThreadInfo->totalAffectedRows += affectedRows; + pThreadInfo->totalInsertRows += g_args.reqPerReq; + currentPercent = + pThreadInfo->totalAffectedRows * g_Dbs.threadCount / insertRows; + if (currentPercent > percentComplete) { + printf("[%d]:%d%%\n", pThreadInfo->threadID, + currentPercent); + percentComplete = currentPercent; + } + + int64_t currentPrintTime = taosGetTimestampMs(); + if (currentPrintTime - lastPrintTime > 30*1000) { + printf("thread[%d] has currently inserted rows: %"PRId64 ", affected rows: %"PRId64 "\n", + pThreadInfo->threadID, + pThreadInfo->totalInsertRows, + pThreadInfo->totalAffectedRows); + lastPrintTime = currentPrintTime; + } + + for (int index = 0; index < g_args.reqPerReq; index++) { + free(pThreadInfo->lines[index]); + } + if (j == insertRows) { + break; + } + } + } + tmfree(pThreadInfo->lines); + for (int index = 0; index < pThreadInfo->ntables; index++) { + free(smlHead[index]); + } + return NULL; +} + // sync insertion progressive data static void* syncWriteProgressive(threadInfo *pThreadInfo) { debugPrint("%s() LN%d: ### progressive write\n", __func__, __LINE__); @@ -10116,6 +10762,8 @@ static void* syncWrite(void *sarg) { #else return syncWriteInterlaceStmt(pThreadInfo, interlaceRows); #endif + } else if (SML_IFACE == stbInfo->iface) { + return syncWriteInterlaceSml(pThreadInfo, interlaceRows); } else { return syncWriteInterlace(pThreadInfo, interlaceRows); } @@ -10125,6 +10773,9 @@ static void* syncWrite(void *sarg) { if (((stbInfo) && (STMT_IFACE == stbInfo->iface)) || (STMT_IFACE == g_args.iface)) { return syncWriteProgressiveStmt(pThreadInfo); + } else if (((stbInfo) && (SML_IFACE == stbInfo->iface)) + || (SML_IFACE == g_args.iface)) { + return syncWriteProgressiveSml(pThreadInfo); } else { return syncWriteProgressive(pThreadInfo); } @@ -10282,7 +10933,7 @@ static void startMultiThreadInsertData(int threads, char* db_name, // read sample data from file first int ret; - if (stbInfo) { + if (stbInfo && stbInfo->iface != SML_IFACE) { ret = prepareSampleForStb(stbInfo); } else { ret = prepareSampleForNtb(); @@ -10305,72 +10956,76 @@ static void startMultiThreadInsertData(int threads, char* db_name, int64_t ntables = 0; uint64_t tableFrom; - + if (stbInfo) { - int64_t limit; - uint64_t offset; + if (stbInfo->iface != SML_IFACE) { + int64_t limit; + uint64_t offset; - if ((NULL != g_args.sqlFile) - && (stbInfo->childTblExists == TBL_NO_EXISTS) - && ((stbInfo->childTblOffset != 0) - || (stbInfo->childTblLimit >= 0))) { - printf("WARNING: offset and limit will not be used since the child tables not exists!\n"); - } + if ((NULL != g_args.sqlFile) + && (stbInfo->childTblExists == TBL_NO_EXISTS) + && ((stbInfo->childTblOffset != 0) + || (stbInfo->childTblLimit >= 0))) { + printf("WARNING: offset and limit will not be used since the child tables not exists!\n"); + } - if (stbInfo->childTblExists == TBL_ALREADY_EXISTS) { - if ((stbInfo->childTblLimit < 0) - || ((stbInfo->childTblOffset - + stbInfo->childTblLimit) - > (stbInfo->childTblCount))) { + if (stbInfo->childTblExists == TBL_ALREADY_EXISTS) { + if ((stbInfo->childTblLimit < 0) + || ((stbInfo->childTblOffset + + stbInfo->childTblLimit) + > (stbInfo->childTblCount))) { - if (stbInfo->childTblCount < stbInfo->childTblOffset) { - printf("WARNING: offset will not be used since the child tables count is less then offset!\n"); + if (stbInfo->childTblCount < stbInfo->childTblOffset) { + printf("WARNING: offset will not be used since the child tables count is less then offset!\n"); - stbInfo->childTblOffset = 0; + stbInfo->childTblOffset = 0; + } + stbInfo->childTblLimit = + stbInfo->childTblCount - stbInfo->childTblOffset; } - stbInfo->childTblLimit = - stbInfo->childTblCount - stbInfo->childTblOffset; + + offset = stbInfo->childTblOffset; + limit = stbInfo->childTblLimit; + } else { + limit = stbInfo->childTblCount; + offset = 0; } - offset = stbInfo->childTblOffset; - limit = stbInfo->childTblLimit; - } else { - limit = stbInfo->childTblCount; - offset = 0; - } + ntables = limit; + tableFrom = offset; - ntables = limit; - tableFrom = offset; + if ((stbInfo->childTblExists != TBL_NO_EXISTS) + && ((stbInfo->childTblOffset + stbInfo->childTblLimit) + > stbInfo->childTblCount)) { + printf("WARNING: specified offset + limit > child table count!\n"); + prompt(); + } - if ((stbInfo->childTblExists != TBL_NO_EXISTS) - && ((stbInfo->childTblOffset + stbInfo->childTblLimit) - > stbInfo->childTblCount)) { - printf("WARNING: specified offset + limit > child table count!\n"); - prompt(); - } + if ((stbInfo->childTblExists != TBL_NO_EXISTS) + && (0 == stbInfo->childTblLimit)) { + printf("WARNING: specified limit = 0, which cannot find table name to insert or query! \n"); + prompt(); + } - if ((stbInfo->childTblExists != TBL_NO_EXISTS) - && (0 == stbInfo->childTblLimit)) { - printf("WARNING: specified limit = 0, which cannot find table name to insert or query! \n"); - prompt(); - } + stbInfo->childTblName = (char*)calloc(1, + limit * TSDB_TABLE_NAME_LEN); + if (stbInfo->childTblName == NULL) { + taos_close(taos0); + errorPrint2("%s() LN%d, alloc memory failed!\n", __func__, __LINE__); + exit(EXIT_FAILURE); + } - stbInfo->childTblName = (char*)calloc(1, - limit * TSDB_TABLE_NAME_LEN); - if (stbInfo->childTblName == NULL) { - taos_close(taos0); - errorPrint2("%s() LN%d, alloc memory failed!\n", __func__, __LINE__); - exit(EXIT_FAILURE); + int64_t childTblCount; + getChildNameOfSuperTableWithLimitAndOffset( + taos0, + db_name, stbInfo->stbName, + &stbInfo->childTblName, &childTblCount, + limit, + offset, stbInfo->escapeChar); + ntables = childTblCount; + } else { + ntables = stbInfo->childTblCount; } - - int64_t childTblCount; - getChildNameOfSuperTableWithLimitAndOffset( - taos0, - db_name, stbInfo->stbName, - &stbInfo->childTblName, &childTblCount, - limit, - offset, stbInfo->escapeChar); - ntables = childTblCount; } else { ntables = g_args.ntables; tableFrom = 0; @@ -10954,33 +11609,34 @@ static int insertTestProcess() { double start; double end; - if (g_totalChildTables > 0) { - fprintf(stderr, - "creating %"PRId64" table(s) with %d thread(s)\n\n", - g_totalChildTables, g_Dbs.threadCountForCreateTbl); - if (g_fpOfInsertResult) { - fprintf(g_fpOfInsertResult, - "creating %"PRId64" table(s) with %d thread(s)\n\n", - g_totalChildTables, g_Dbs.threadCountForCreateTbl); - } + if (g_args.iface != SML_IFACE) { + if (g_totalChildTables > 0) { + fprintf(stderr, + "creating %"PRId64" table(s) with %d thread(s)\n\n", + g_totalChildTables, g_Dbs.threadCountForCreateTbl); + if (g_fpOfInsertResult) { + fprintf(g_fpOfInsertResult, + "creating %"PRId64" table(s) with %d thread(s)\n\n", + g_totalChildTables, g_Dbs.threadCountForCreateTbl); + } - // create child tables - start = taosGetTimestampMs(); - createChildTables(); - end = taosGetTimestampMs(); + // create child tables + start = taosGetTimestampMs(); + createChildTables(); + end = taosGetTimestampMs(); - fprintf(stderr, - "\nSpent %.4f seconds to create %"PRId64" table(s) with %d thread(s), actual %"PRId64" table(s) created\n\n", - (end - start)/1000.0, g_totalChildTables, - g_Dbs.threadCountForCreateTbl, g_actualChildTables); - if (g_fpOfInsertResult) { - fprintf(g_fpOfInsertResult, - "\nSpent %.4f seconds to create %"PRId64" table(s) with %d thread(s), actual %"PRId64" table(s) created\n\n", - (end - start)/1000.0, g_totalChildTables, - g_Dbs.threadCountForCreateTbl, g_actualChildTables); + fprintf(stderr, + "\nSpent %.4f seconds to create %"PRId64" table(s) with %d thread(s), actual %"PRId64" table(s) created\n\n", + (end - start)/1000.0, g_totalChildTables, + g_Dbs.threadCountForCreateTbl, g_actualChildTables); + if (g_fpOfInsertResult) { + fprintf(g_fpOfInsertResult, + "\nSpent %.4f seconds to create %"PRId64" table(s) with %d thread(s), actual %"PRId64" table(s) created\n\n", + (end - start)/1000.0, g_totalChildTables, + g_Dbs.threadCountForCreateTbl, g_actualChildTables); + } } } - // create sub threads for inserting data //start = taosGetTimestampMs(); for (int i = 0; i < g_Dbs.dbCount; i++) { @@ -11000,11 +11656,16 @@ static int insertTestProcess() { } } } else { - startMultiThreadInsertData( + if (SML_IFACE == g_args.iface) { + errorPrint2("%s\n", "Schemaless insertion must include stable"); + exit(EXIT_FAILURE); + } else { + startMultiThreadInsertData( g_Dbs.threadCount, g_Dbs.db[i].dbName, g_Dbs.db[i].dbCfg.precision, NULL); + } } } //end = taosGetTimestampMs(); @@ -11919,29 +12580,6 @@ static int subscribeTestProcess() { return 0; } -static void initOfInsertMeta() { - memset(&g_Dbs, 0, sizeof(SDbs)); - - // set default values - tstrncpy(g_Dbs.host, "127.0.0.1", MAX_HOSTNAME_SIZE); - g_Dbs.port = 6030; - tstrncpy(g_Dbs.user, TSDB_DEFAULT_USER, MAX_USERNAME_SIZE); - tstrncpy(g_Dbs.password, TSDB_DEFAULT_PASS, SHELL_MAX_PASSWORD_LEN); - g_Dbs.threadCount = 2; - - g_Dbs.use_metric = g_args.use_metric; -} - -static void initOfQueryMeta() { - memset(&g_queryInfo, 0, sizeof(SQueryMetaInfo)); - - // set default values - tstrncpy(g_queryInfo.host, "127.0.0.1", MAX_HOSTNAME_SIZE); - g_queryInfo.port = 6030; - tstrncpy(g_queryInfo.user, TSDB_DEFAULT_USER, MAX_USERNAME_SIZE); - tstrncpy(g_queryInfo.password, TSDB_DEFAULT_PASS, SHELL_MAX_PASSWORD_LEN); -} - static void setParaFromArg() { char type[20]; char length[20]; @@ -11974,7 +12612,7 @@ static void setParaFromArg() { tstrncpy(g_Dbs.resultFile, g_args.output_file, MAX_FILE_NAME_LEN); g_Dbs.use_metric = g_args.use_metric; - + g_args.prepared_rand = min(g_args.insertRows, MAX_PREPARED_RAND); g_Dbs.aggr_func = g_args.aggr_func; char dataString[TSDB_MAX_BYTES_PER_ROW]; @@ -12056,10 +12694,12 @@ static void setParaFromArg() { tstrncpy(g_Dbs.db[0].superTbls[0].tags[0].dataType, "INT", min(DATATYPE_BUFF_LEN, strlen("INT") + 1)); + g_Dbs.db[0].superTbls[0].tags[0].data_type = TSDB_DATA_TYPE_INT; g_Dbs.db[0].superTbls[0].tags[0].dataLen = 0; tstrncpy(g_Dbs.db[0].superTbls[0].tags[1].dataType, "BINARY", min(DATATYPE_BUFF_LEN, strlen("BINARY") + 1)); + g_Dbs.db[0].superTbls[0].tags[1].data_type = TSDB_DATA_TYPE_BINARY; g_Dbs.db[0].superTbls[0].tags[1].dataLen = g_args.binwidth; g_Dbs.db[0].superTbls[0].tagCount = 2; } else { @@ -12251,8 +12891,6 @@ int main(int argc, char *argv[]) { if (g_args.metaFile) { g_totalChildTables = 0; - initOfInsertMeta(); - initOfQueryMeta(); if (false == getInfoFromJsonFile(g_args.metaFile)) { printf("Failed to read %s\n", g_args.metaFile); @@ -12262,6 +12900,10 @@ int main(int argc, char *argv[]) { testMetaFile(); } else { memset(&g_Dbs, 0, sizeof(SDbs)); + g_Dbs.db = calloc(1, sizeof(SDataBase)); + assert(g_Dbs.db); + g_Dbs.db[0].superTbls = calloc(1, sizeof(SSuperTable)); + assert(g_Dbs.db[0].superTbls); setParaFromArg(); if (NULL != g_args.sqlFile) { diff --git a/src/kit/taosdump/taosdump.c b/src/kit/taosdump/taosdump.c index 34d9956c642c5c91aa72c6a4386dc675ad48dc98..317722ada99392965ff07cb2921a6acb6b92ef01 100644 --- a/src/kit/taosdump/taosdump.c +++ b/src/kit/taosdump/taosdump.c @@ -3005,7 +3005,13 @@ int main(int argc, char *argv[]) { printf("debug_print: %d\n", g_args.debug_print); for (int32_t i = 0; i < g_args.arg_list_len; i++) { - printf("arg_list[%d]: %s\n", i, g_args.arg_list[i]); + if (g_args.databases || g_args.all_databases) { + errorPrint("%s is an invalid input if database(s) be already specified.\n", + g_args.arg_list[i]); + exit(EXIT_FAILURE); + } else { + printf("arg_list[%d]: %s\n", i, g_args.arg_list[i]); + } } printf("==============================\n"); diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt index 83e54b97965f9dd0f8c1b484979cfd2e8919dbb1..4cf444bab2f05816c1af55d96156334800d758d5 100644 --- a/src/plugins/CMakeLists.txt +++ b/src/plugins/CMakeLists.txt @@ -32,7 +32,7 @@ ELSE () MESSAGE("") MESSAGE("${Green} use blm3 as httpd ${ColourReset}") EXECUTE_PROCESS( - COMMAND cd blm3 + COMMAND cd ${CMAKE_CURRENT_SOURCE_DIR}/blm3 ) EXECUTE_PROCESS( COMMAND git rev-parse --short HEAD diff --git a/src/plugins/blm3 b/src/plugins/blm3 index 4bfae86dcabea0d5a40ff81a72be7c822737269b..f56aa0f485d7bb6aebbcefc2007eeecdccb767c8 160000 --- a/src/plugins/blm3 +++ b/src/plugins/blm3 @@ -1 +1 @@ -Subproject commit 4bfae86dcabea0d5a40ff81a72be7c822737269b +Subproject commit f56aa0f485d7bb6aebbcefc2007eeecdccb767c8 diff --git a/src/query/inc/qAggMain.h b/src/query/inc/qAggMain.h index 548b03e1108f87feac0af5f93be69d4ee5569477..8bcd8fea42aa46ad3dd2f0857d88a9b4bb76dd4d 100644 --- a/src/query/inc/qAggMain.h +++ b/src/query/inc/qAggMain.h @@ -233,6 +233,7 @@ int32_t isValidFunction(const char* name, int32_t len); #define IS_MULTIOUTPUT(x) (((x)&TSDB_FUNCSTATE_MO) != 0) #define IS_SINGLEOUTPUT(x) (((x)&TSDB_FUNCSTATE_SO) != 0) #define IS_OUTER_FORWARD(x) (((x)&TSDB_FUNCSTATE_OF) != 0) +#define IS_SCALAR_FUNCTION(x) (((x)&TSDB_FUNCSTATE_SCALAR) != 0) // determine the real data need to calculated the result enum { diff --git a/src/query/inc/qExecutor.h b/src/query/inc/qExecutor.h index 82f4f34a57c7d6d10a021fb2e426ff83cb3604e6..1bbc8a363ba3af678b42530db48eebb92deece48 100644 --- a/src/query/inc/qExecutor.h +++ b/src/query/inc/qExecutor.h @@ -312,7 +312,8 @@ typedef struct SQueryRuntimeEnv { STableQueryInfo *current; SRspResultInfo resultInfo; SHashObj *pTableRetrieveTsMap; - SUdfInfo *pUdfInfo; + SUdfInfo *pUdfInfo; + bool udfIsCopy; } SQueryRuntimeEnv; enum { diff --git a/src/query/inc/qUdf.h b/src/query/inc/qUdf.h index 1083b1e698f7591aae4586c7722e5343cd9c4d86..77da4b668ae08d10a6154cdece59ec62f5114be9 100644 --- a/src/query/inc/qUdf.h +++ b/src/query/inc/qUdf.h @@ -51,6 +51,7 @@ typedef struct SUdfInfo { SUdfInit init; char *content; char *path; + bool keep; } SUdfInfo; //script diff --git a/src/query/src/qExecutor.c b/src/query/src/qExecutor.c index 0f1764817c5129de460680b5f8766c826a8517fe..9457483714310c9ada01148345927f44718a28e8 100644 --- a/src/query/src/qExecutor.c +++ b/src/query/src/qExecutor.c @@ -365,7 +365,8 @@ int32_t getNumOfResult(SQueryRuntimeEnv *pRuntimeEnv, SQLFunctionCtx* pCtx, int3 * ts, tag, tagprj function can not decide the output number of current query * the number of output result is decided by main output */ - if (hasMainFunction && (id == TSDB_FUNC_TS || id == TSDB_FUNC_TAG || id == TSDB_FUNC_TAGPRJ)) { + if (hasMainFunction && (id == TSDB_FUNC_TS || id == TSDB_FUNC_TAG || id == TSDB_FUNC_TAGPRJ || + id == TSDB_FUNC_TS_DUMMY || id == TSDB_FUNC_TAG_DUMMY)) { continue; } @@ -987,13 +988,12 @@ void doInvokeUdf(SUdfInfo* pUdfInfo, SQLFunctionCtx *pCtx, int32_t idx, int32_t SResultRowCellInfo *pResInfo = GET_RES_INFO(pCtx); void *interBuf = (void *)GET_ROWCELL_INTERBUF(pResInfo); if (pUdfInfo->isScript) { - (*(scriptFinalizeFunc)pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE])(pUdfInfo->pScriptCtx, pCtx->startTs, pCtx->pOutput, &output); + (*(scriptFinalizeFunc)pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE])(pUdfInfo->pScriptCtx, pCtx->startTs, pCtx->pOutput, (int32_t *)&pCtx->resultInfo->numOfRes); } else { - (*(udfFinalizeFunc)pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE])(pCtx->pOutput, interBuf, &output, &pUdfInfo->init); + (*(udfFinalizeFunc)pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE])(pCtx->pOutput, interBuf, (int32_t *)&pCtx->resultInfo->numOfRes, &pUdfInfo->init); } - // set the output value exist - pCtx->resultInfo->numOfRes = output; - if (output > 0) { + + if (pCtx->resultInfo->numOfRes > 0) { pCtx->resultInfo->hasResult = DATA_SET_FLAG; } @@ -2408,8 +2408,10 @@ static void teardownQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv) { tfree(pRuntimeEnv->sasArray); } - destroyUdfInfo(pRuntimeEnv->pUdfInfo); - + if (!pRuntimeEnv->udfIsCopy) { + destroyUdfInfo(pRuntimeEnv->pUdfInfo); + } + destroyResultBuf(pRuntimeEnv->pResultBuf); doFreeQueryHandle(pRuntimeEnv); @@ -8038,7 +8040,7 @@ static char* getUdfFuncName(char* funcname, char* name, int type) { } int32_t initUdfInfo(SUdfInfo* pUdfInfo) { - if (pUdfInfo == NULL) { + if (pUdfInfo == NULL || pUdfInfo->handle) { return TSDB_CODE_SUCCESS; } //qError("script len: %d", pUdfInfo->contLen); @@ -8073,10 +8075,21 @@ int32_t initUdfInfo(SUdfInfo* pUdfInfo) { // TODO check for failure of flush to disk /*size_t t = */ fwrite(pUdfInfo->content, pUdfInfo->contLen, 1, file); fclose(file); - tfree(pUdfInfo->content); + if (!pUdfInfo->keep) { + tfree(pUdfInfo->content); + } + if (pUdfInfo->path) { + unlink(pUdfInfo->path); + } + + tfree(pUdfInfo->path); pUdfInfo->path = strdup(path); + if (pUdfInfo->handle) { + taosCloseDll(pUdfInfo->handle); + } + pUdfInfo->handle = taosLoadDll(path); if (NULL == pUdfInfo->handle) { @@ -8091,9 +8104,17 @@ int32_t initUdfInfo(SUdfInfo* pUdfInfo) { pUdfInfo->funcs[TSDB_UDF_FUNC_INIT] = taosLoadSym(pUdfInfo->handle, getUdfFuncName(funcname, pUdfInfo->name, TSDB_UDF_FUNC_INIT)); + pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE] = taosLoadSym(pUdfInfo->handle, getUdfFuncName(funcname, pUdfInfo->name, TSDB_UDF_FUNC_FINALIZE)); + pUdfInfo->funcs[TSDB_UDF_FUNC_MERGE] = taosLoadSym(pUdfInfo->handle, getUdfFuncName(funcname, pUdfInfo->name, TSDB_UDF_FUNC_MERGE)); + if (pUdfInfo->funcType == TSDB_UDF_TYPE_AGGREGATE) { - pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE] = taosLoadSym(pUdfInfo->handle, getUdfFuncName(funcname, pUdfInfo->name, TSDB_UDF_FUNC_FINALIZE)); - pUdfInfo->funcs[TSDB_UDF_FUNC_MERGE] = taosLoadSym(pUdfInfo->handle, getUdfFuncName(funcname, pUdfInfo->name, TSDB_UDF_FUNC_MERGE)); + if (NULL == pUdfInfo->funcs[TSDB_UDF_FUNC_MERGE] || NULL == pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE]) { + return TSDB_CODE_QRY_SYS_ERROR; + } + } else { + if (pUdfInfo->funcs[TSDB_UDF_FUNC_MERGE] || pUdfInfo->funcs[TSDB_UDF_FUNC_FINALIZE]) { + return TSDB_CODE_QRY_SYS_ERROR; + } } pUdfInfo->funcs[TSDB_UDF_FUNC_DESTROY] = taosLoadSym(pUdfInfo->handle, getUdfFuncName(funcname, pUdfInfo->name, TSDB_UDF_FUNC_DESTROY)); @@ -8200,7 +8221,7 @@ int32_t createQueryFunc(SQueriedTableInfo* pTableInfo, int32_t numOfOutput, SExp } int32_t param = (int32_t)pExprs[i].base.param[0].i64; - if (pExprs[i].base.functionId != TSDB_FUNC_ARITHM && + if (pExprs[i].base.functionId > 0 && pExprs[i].base.functionId != TSDB_FUNC_ARITHM && (type != pExprs[i].base.colType || bytes != pExprs[i].base.colBytes)) { tfree(pExprs); return TSDB_CODE_QRY_INVALID_MSG; diff --git a/src/tsdb/inc/tsdbReadImpl.h b/src/tsdb/inc/tsdbReadImpl.h index f067905f5c0dcf4fde64dfc066d4d1a1dbabb25d..20d8b88c839411136793556de55450577ffecaec 100644 --- a/src/tsdb/inc/tsdbReadImpl.h +++ b/src/tsdb/inc/tsdbReadImpl.h @@ -71,11 +71,10 @@ typedef struct { * blkVer; // 0 - original block, 1 - block since importing .smad/.smal * aggrOffset; // only valid when blkVer > 0 and aggrStat > 0 */ -#define SBlockFieldsP1 \ - uint64_t aggrStat : 3; \ - uint64_t blkVer : 5; \ - uint64_t aggrOffset : 56; \ - uint32_t aggrLen +#define SBlockFieldsP1 \ + uint64_t aggrStat : 1; \ + uint64_t blkVer : 7; \ + uint64_t aggrOffset : 56 typedef struct { SBlockFieldsP0; @@ -125,7 +124,6 @@ typedef struct { int32_t len; uint32_t type : 8; uint32_t offset : 24; - // char padding[]; } SBlockColV1; #define SBlockCol SBlockColV1 // latest SBlockCol definition @@ -160,10 +158,8 @@ typedef struct { uint64_t uid; // For recovery usage SBlockCol cols[]; } SBlockData; -typedef struct { - int32_t numOfCols; // For recovery usage - SAggrBlkCol cols[]; -} SAggrBlkData; + +typedef void SAggrBlkData; // SBlockCol cols[]; struct SReadH { STsdbRepo * pRepo; @@ -207,8 +203,7 @@ static FORCE_INLINE size_t tsdbBlockStatisSize(int nCols, uint32_t blkVer) { } } -#define TSDB_BLOCK_AGGR_SIZE(ncols, blkVer) \ - (sizeof(SAggrBlkData) + sizeof(SAggrBlkColV##blkVer) * (ncols) + sizeof(TSCKSUM)) +#define TSDB_BLOCK_AGGR_SIZE(ncols, blkVer) (sizeof(SAggrBlkColV##blkVer) * (ncols) + sizeof(TSCKSUM)) static FORCE_INLINE size_t tsdbBlockAggrSize(int nCols, uint32_t blkVer) { switch (blkVer) { diff --git a/src/tsdb/src/tsdbCommit.c b/src/tsdb/src/tsdbCommit.c index 53ca51004fc406b05028d13be7cd2bf054771c0d..eccdcbdbf6155ca37dc35bc171189de3781e8642 100644 --- a/src/tsdb/src/tsdbCommit.c +++ b/src/tsdb/src/tsdbCommit.c @@ -1080,11 +1080,10 @@ int tsdbWriteBlockImpl(STsdbRepo *pRepo, STable *pTable, SDFile *pDFile, SDFile // Get # of cols not all NULL(not including key column) int nColsNotAllNull = 0; - int nAggrCols = 0; for (int ncol = 1; ncol < pDataCols->numOfCols; ncol++) { // ncol from 1, we skip the timestamp column SDataCol * pDataCol = pDataCols->cols + ncol; SBlockCol * pBlockCol = pBlockData->cols + nColsNotAllNull; - SAggrBlkCol *pAggrBlkCol = pAggrBlkData->cols + nColsNotAllNull; + SAggrBlkCol *pAggrBlkCol = (SAggrBlkCol *)pAggrBlkData + nColsNotAllNull; if (isAllRowsNull(pDataCol)) { // all data to commit are NULL, just ignore it continue; @@ -1106,7 +1105,6 @@ int tsdbWriteBlockImpl(STsdbRepo *pRepo, STable *pTable, SDFile *pDFile, SDFile (*tDataTypes[pDataCol->type].statisFunc)(pDataCol->pData, rowsToWrite, &(pAggrBlkCol->min), &(pAggrBlkCol->max), &(pAggrBlkCol->sum), &(pAggrBlkCol->minIndex), &(pAggrBlkCol->maxIndex), &(pAggrBlkCol->numOfNull)); - ++nAggrCols; } nColsNotAllNull++; } @@ -1188,9 +1186,8 @@ int tsdbWriteBlockImpl(STsdbRepo *pRepo, STable *pTable, SDFile *pDFile, SDFile return -1; } - uint32_t aggrStatus = ((nAggrCols > 0) && (rowsToWrite > 8)) ? 1 : 0; // TODO: How to make the decision? + uint32_t aggrStatus = ((nColsNotAllNull > 0) && (rowsToWrite > 8)) ? 1 : 0; // TODO: How to make the decision? if (aggrStatus > 0) { - pAggrBlkData->numOfCols = nColsNotAllNull; taosCalcChecksumAppend(0, (uint8_t *)pAggrBlkData, tsizeAggr); tsdbUpdateDFileMagic(pDFileAggr, POINTER_SHIFT(pAggrBlkData, tsizeAggr - sizeof(TSCKSUM))); @@ -1216,7 +1213,6 @@ int tsdbWriteBlockImpl(STsdbRepo *pRepo, STable *pTable, SDFile *pDFile, SDFile pBlock->aggrStat = aggrStatus; pBlock->blkVer = SBlockVerLatest; pBlock->aggrOffset = (uint64_t)offsetAggr; - pBlock->aggrLen = tsizeAggr; tsdbDebug("vgId:%d tid:%d a block of data is written to file %s, offset %" PRId64 " numOfRows %d len %d numOfCols %" PRId16 " keyFirst %" PRId64 " keyLast %" PRId64, diff --git a/src/tsdb/src/tsdbCompact.c b/src/tsdb/src/tsdbCompact.c index 6415c9a649ec08e4db442a321565e15e5df2e4a7..3b5e8ce56dab297c5b6cc4a9b07d8150445917b9 100644 --- a/src/tsdb/src/tsdbCompact.c +++ b/src/tsdb/src/tsdbCompact.c @@ -441,6 +441,7 @@ static int tsdbCompactMeta(STsdbRepo *pRepo) { if ((tdInitDataCols(pComph->pDataCols, pSchema) < 0) || (tdInitDataCols(pReadh->pDCols[0], pSchema) < 0) || (tdInitDataCols(pReadh->pDCols[1], pSchema) < 0)) { terrno = TSDB_CODE_TDB_OUT_OF_MEMORY; + tdFreeSchema(pSchema); return -1; } tdFreeSchema(pSchema); diff --git a/src/tsdb/src/tsdbMain.c b/src/tsdb/src/tsdbMain.c index 62160c2f36762e1c55e858a7026360b8287f6c3f..23835d659d3157b789f61bd7e50f21861d863433 100644 --- a/src/tsdb/src/tsdbMain.c +++ b/src/tsdb/src/tsdbMain.c @@ -185,6 +185,23 @@ int tsdbUnlockRepo(STsdbRepo *pRepo) { return 0; } +bool tsdbIsNeedCommit(STsdbRepo *pRepo) { + int nVal = 0; + if (sem_getvalue(&pRepo->readyToCommit, &nVal) != 0) { + tsdbError("vgId:%d failed to sem_getvalue of readyToCommit", REPO_ID(pRepo)); + return false; + } + return nVal > 0; +} + +int tsdbCheckWal(STsdbRepo *pRepo, uint32_t walSize) { // MB + STsdbCfg *pCfg = &(pRepo->config); + if ((walSize > tsdbWalFlushSize) && (walSize > (pCfg->totalBlocks / 2 * pCfg->cacheBlockSize))) { + if (tsdbIsNeedCommit(pRepo) && (tsdbAsyncCommit(pRepo) < 0)) return -1; + } + return 0; +} + int tsdbCheckCommit(STsdbRepo *pRepo) { ASSERT(pRepo->mem != NULL); STsdbCfg *pCfg = &(pRepo->config); @@ -194,9 +211,8 @@ int tsdbCheckCommit(STsdbRepo *pRepo) { if ((pRepo->mem->extraBuffList != NULL) || ((listNEles(pRepo->mem->bufBlockList) >= pCfg->totalBlocks / 3) && (pBufBlock->remain < TSDB_BUFFER_RESERVE))) { // trigger commit - if (tsdbAsyncCommit(pRepo) < 0) return -1; + if (tsdbIsNeedCommit(pRepo) && (tsdbAsyncCommit(pRepo) < 0)) return -1; } - return 0; } diff --git a/src/tsdb/src/tsdbRead.c b/src/tsdb/src/tsdbRead.c index ca6912cdd887a1fdb200bee82cbf542c517f08a3..5e4ab00b4158d2f1c15b3fe47e3a296ff429edfa 100644 --- a/src/tsdb/src/tsdbRead.c +++ b/src/tsdb/src/tsdbRead.c @@ -1620,7 +1620,7 @@ static void mergeTwoRowFromMem(STsdbQueryHandle* pQueryHandle, int32_t capacity, SColIdx *pColIdx = kvRowColIdxAt(rowBody, chosen_itr); colId = pColIdx->colId; offset = pColIdx->offset; - value = tdGetKvRowDataOfCol(rowBody, pColIdx->offset); + value = tdGetKvRowDataOfCol(rowBody, offset); } diff --git a/src/tsdb/src/tsdbReadImpl.c b/src/tsdb/src/tsdbReadImpl.c index e55944d5bb83ca614da862f9c350a41690b0ca6e..4976e8b8fb8213b6a9cdedbf380d812e117f1fc8 100644 --- a/src/tsdb/src/tsdbReadImpl.c +++ b/src/tsdb/src/tsdbReadImpl.c @@ -580,12 +580,12 @@ void tsdbGetBlockStatis(SReadH *pReadh, SDataStatis *pStatis, int numOfCols, SBl SAggrBlkData *pAggrBlkData = pReadh->pAggrBlkData; for (int i = 0, j = 0; i < numOfCols;) { - if (j >= pAggrBlkData->numOfCols) { + if (j >= pBlock->numOfCols) { pStatis[i].numOfNull = -1; i++; continue; } - SAggrBlkCol *pAggrBlkCol = ((SAggrBlkCol *)(pAggrBlkData->cols)) + j; + SAggrBlkCol *pAggrBlkCol = ((SAggrBlkCol *)(pAggrBlkData)) + j; if (pStatis[i].colId == pAggrBlkCol->colId) { pStatis[i].sum = pAggrBlkCol->sum; pStatis[i].max = pAggrBlkCol->max; diff --git a/src/util/inc/tconfig.h b/src/util/inc/tconfig.h index 2ba4b964c04b0a1ca9f883cd619aae2b7fcbe1d7..3ba0031a07a83d7374b3f940cf51bf31478cfd38 100644 --- a/src/util/inc/tconfig.h +++ b/src/util/inc/tconfig.h @@ -20,7 +20,7 @@ extern "C" { #endif -#define TSDB_CFG_MAX_NUM 124 +#define TSDB_CFG_MAX_NUM 125 #define TSDB_CFG_PRINT_LEN 23 #define TSDB_CFG_OPTION_LEN 24 #define TSDB_CFG_VALUE_LEN 41 diff --git a/src/util/inc/tfile.h b/src/util/inc/tfile.h index 066040170e44c24539e29b5de5acd438e8b9b9d0..11a04cdf9480927131a92753a56bb67b462500ab 100644 --- a/src/util/inc/tfile.h +++ b/src/util/inc/tfile.h @@ -37,6 +37,7 @@ int32_t tfFsync(int64_t tfd); bool tfValid(int64_t tfd); int64_t tfLseek(int64_t tfd, int64_t offset, int32_t whence); int32_t tfFtruncate(int64_t tfd, int64_t length); +int32_t tfStat(int64_t tfd, struct stat *pFstat); #ifdef __cplusplus } diff --git a/src/util/src/tfile.c b/src/util/src/tfile.c index 455c885e753e35724d27ec223f86ebf04751286f..d975995b2149297d2ae53584bcf36b6c74b7b529 100644 --- a/src/util/src/tfile.c +++ b/src/util/src/tfile.c @@ -133,3 +133,14 @@ int32_t tfFtruncate(int64_t tfd, int64_t length) { taosReleaseRef(tsFileRsetId, tfd); return code; } + +int32_t tfStat(int64_t tfd, struct stat *pFstat) { + void *p = taosAcquireRef(tsFileRsetId, tfd); + if (p == NULL) return -1; + + int32_t fd = (int32_t)(uintptr_t)p; + int32_t code = fstat(fd, pFstat); + + taosReleaseRef(tsFileRsetId, tfd); + return code; +} diff --git a/src/vnode/inc/vnodeInt.h b/src/vnode/inc/vnodeInt.h index 4864b79dc4ee7c718ad7c023277793f21e74446d..1deceebb0ad3bd146a3cd81fab4cabb2d290b037 100644 --- a/src/vnode/inc/vnodeInt.h +++ b/src/vnode/inc/vnodeInt.h @@ -56,6 +56,7 @@ typedef struct { uint64_t version; // current version uint64_t cversion; // version while commit start uint64_t fversion; // version on saved data file + uint32_t tblMsgVer; // create table msg version void * wqueue; // write queue void * qqueue; // read query queue void * fqueue; // read fetch/cancel queue diff --git a/src/vnode/src/vnodeWrite.c b/src/vnode/src/vnodeWrite.c index e8ac978bb2d163ff0a8eda78015efae9f817ac34..7f7d37a255ff42ab47be94507a33647fce853e8e 100644 --- a/src/vnode/src/vnodeWrite.c +++ b/src/vnode/src/vnodeWrite.c @@ -36,6 +36,7 @@ static int32_t vnodeProcessAlterTableMsg(SVnodeObj *pVnode, void *pCont, SRspRet static int32_t vnodeProcessDropStableMsg(SVnodeObj *pVnode, void *pCont, SRspRet *); static int32_t vnodeProcessUpdateTagValMsg(SVnodeObj *pVnode, void *pCont, SRspRet *); static int32_t vnodePerformFlowCtrl(SVWriteMsg *pWrite); +static int32_t vnodeCheckWal(SVnodeObj *pVnode); int32_t vnodeInitWrite(void) { vnodeProcessWriteMsgFp[TSDB_MSG_TYPE_SUBMIT] = vnodeProcessSubmitMsg; @@ -167,6 +168,13 @@ static int32_t vnodeProcessSubmitMsg(SVnodeObj *pVnode, void *pCont, SRspRet *pR return code; } +static int32_t vnodeCheckWal(SVnodeObj *pVnode) { + if (tsdbIsNeedCommit(pVnode->tsdb)) { + return tsdbCheckWal(pVnode->tsdb, walGetFSize(pVnode->wal) >> 20); + } + return 0; +} + static int32_t vnodeProcessCreateTableMsg(SVnodeObj *pVnode, void *pCont, SRspRet *pRet) { int code = TSDB_CODE_SUCCESS; @@ -181,6 +189,10 @@ static int32_t vnodeProcessCreateTableMsg(SVnodeObj *pVnode, void *pCont, SRspRe ASSERT(code != 0); } + if (((++pVnode->tblMsgVer) & 16383) == 0) { // lazy check + vnodeCheckWal(pVnode); + } + tsdbClearTableCfg(pCfg); return code; } diff --git a/src/wal/src/walWrite.c b/src/wal/src/walWrite.c index e991bf02aa68c92d7cf4dfdb09982ebaa6541bdc..3f2df3f6243c3291602ceb0c7fcd93d475927485 100644 --- a/src/wal/src/walWrite.c +++ b/src/wal/src/walWrite.c @@ -576,4 +576,14 @@ void walResetVersion(twalh param, uint64_t newVer) { wInfo("vgId:%d, version reset from %" PRIu64 " to %" PRIu64, pWal->vgId, pWal->version, newVer); pWal->version = newVer; +} + +int64_t walGetFSize(twalh handle) { + SWal *pWal = handle; + if (pWal == NULL) return 0; + struct stat _fstat; + if (tfStat(pWal->tfd, &_fstat) == 0) { + return _fstat.st_size; + }; + return 0; } \ No newline at end of file diff --git a/tests/examples/c/apitest.c b/tests/examples/c/apitest.c index d9d2a41cb2782f1e919857d3a94c5f83946bb277..2510035e9217f4907ac8fdd3d11d7fc123a2bfa6 100644 --- a/tests/examples/c/apitest.c +++ b/tests/examples/c/apitest.c @@ -288,7 +288,7 @@ void verify_stream(TAOS* taos) { taos_close_stream(strm); } -int32_t verify_schema_less(TAOS* taos) { +void verify_schema_less(TAOS* taos) { TAOS_RES* result; result = taos_query(taos, "drop database if exists test;"); taos_free_result(result); @@ -302,7 +302,7 @@ int32_t verify_schema_less(TAOS* taos) { taos_free_result(result); usleep(100000); - int code = 0; + int code = 0, affected_rows = 0; char* lines[] = { "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", @@ -316,41 +316,91 @@ int32_t verify_schema_less(TAOS* taos) { "stf,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641000000" }; - code = taos_schemaless_insert(taos, lines , sizeof(lines)/sizeof(char*), 0, "ns"); + result = taos_schemaless_insert(taos, lines , sizeof(lines)/sizeof(char*), TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines1]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); char* lines2[] = { "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000" }; - code = taos_schemaless_insert(taos, &lines2[0], 1, 0, "ns"); - code = taos_schemaless_insert(taos, &lines2[1], 1, 0, "ns"); + result = taos_schemaless_insert(taos, &lines2[0], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines2_0]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); + + result = taos_schemaless_insert(taos, &lines2[1], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines2_1]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); char* lines3[] = { "sth,t1=4i64,t2=5f64,t4=5f64,ID=childTable c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641", "sth,t1=4i64,t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933654" }; - code = taos_schemaless_insert(taos, lines3, 2, 0, "ms"); + result = taos_schemaless_insert(taos, lines3, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines3]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); char* lines4[] = { "st123456,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", "dgtyqodr,t2=5f64,t3=L\"ste\" c1=tRue,c2=4i64,c3=\"iam\" 1626056811823316532" }; - code = taos_schemaless_insert(taos, lines4, 2, 0, "ns"); + result = taos_schemaless_insert(taos, lines4, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines4]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); + char* lines5[] = { "zqlbgs,id=zqlbgs_39302_21680,t0=f,t1=127i8,t2=32767i16,t3=2147483647i32,t4=9223372036854775807i64,t5=11.12345f32,t6=22.123456789f64,t7=\"binaryTagValue\",t8=L\"ncharTagValue\" c0=f,c1=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=11.12345f32,c6=22.123456789f64,c7=\"binaryColValue\",c8=L\"ncharColValue\",c9=7u64 1626006833639000000", "zqlbgs,t9=f,id=zqlbgs_39302_21680,t0=f,t1=127i8,t11=127i8,t2=32767i16,t3=2147483647i32,t4=9223372036854775807i64,t5=11.12345f32,t6=22.123456789f64,t7=\"binaryTagValue\",t8=L\"ncharTagValue\",t10=L\"ncharTagValue\" c10=f,c0=f,c1=127i8,c12=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=11.12345f32,c6=22.123456789f64,c7=\"binaryColValue\",c8=L\"ncharColValue\",c9=7u64,c11=L\"ncharColValue\" 1626006833639000000" }; - code = taos_schemaless_insert(taos, &lines5[0], 1, 0, "ns"); - code = taos_schemaless_insert(taos, &lines5[1], 1, 0, "ns"); + result = taos_schemaless_insert(taos, &lines5[0], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines5_0]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); + + result = taos_schemaless_insert(taos, &lines5[1], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines5_1]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); char* lines6[] = { "st123456,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", "dgtyqodr,t2=5f64,t3=L\"ste\" c1=tRue,c2=4i64,c3=\"iam\" 1626056811823316532" }; - code = taos_schemaless_insert(taos, lines6, 2, 0, "ns"); + result = taos_schemaless_insert(taos, lines6, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + code = taos_errno(result); + if (code != TSDB_CODE_SUCCESS) { + affected_rows = taos_affected_rows(result); + printf("\033[31m [lines6]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); + } + taos_free_result(result); - return (code); } int main(int argc, char* argv[]) { diff --git a/tests/examples/c/prepare.c b/tests/examples/c/prepare.c index 9842c9639db0857d73756290c18f05432b357b53..b62aca727905f6b632d191e08f87cfeb061266e0 100644 --- a/tests/examples/c/prepare.c +++ b/tests/examples/c/prepare.c @@ -184,6 +184,10 @@ void verify_prepare(TAOS* taos) { taos_stmt_close(stmt); exit(EXIT_FAILURE); } + + int affectedRows = taos_stmt_affected_rows(stmt); + printf("sucessfully inserted %d rows\n", affectedRows); + taos_stmt_close(stmt); // query the records @@ -400,6 +404,9 @@ void verify_prepare2(TAOS* taos) { exit(EXIT_FAILURE); } + int affectedRows = taos_stmt_affected_rows(stmt); + printf("sucessfully inserted %d rows\n", affectedRows); + taos_stmt_close(stmt); // query the records @@ -784,6 +791,10 @@ void verify_prepare3(TAOS* taos) { taos_stmt_close(stmt); exit(EXIT_FAILURE); } + + int affectedRows = taos_stmt_affected_rows(stmt); + printf("successfully inserted %d rows\n", affectedRows); + taos_stmt_close(stmt); // query the records diff --git a/tests/examples/c/schemaless.c b/tests/examples/c/schemaless.c index 0d98acb03a27cd3c72568d8f713cf392e5bd057c..9a2d2f063573d26093bd5032e2f68cc54fc5f908 100644 --- a/tests/examples/c/schemaless.c +++ b/tests/examples/c/schemaless.c @@ -33,6 +33,8 @@ typedef struct { int numBatches; SThreadLinesBatch batches[MAX_THREAD_LINE_BATCHES]; int64_t costTime; + int tsPrecision; + int lineProtocol; } SThreadInsertArgs; static void* insertLines(void* args) { @@ -43,10 +45,12 @@ static void* insertLines(void* args) { SThreadLinesBatch* batch = insertArgs->batches + i; printf("%s, thread: 0x%s\n", "begin taos_insert_lines", tidBuf); int64_t begin = getTimeInUs(); - int32_t code = taos_schemaless_insert(insertArgs->taos, batch->lines, batch->numLines, 0, "ms"); + TAOS_RES *res = taos_schemaless_insert(insertArgs->taos, batch->lines, batch->numLines, insertArgs->lineProtocol, insertArgs->tsPrecision); + int32_t code = taos_errno(res); int64_t end = getTimeInUs(); insertArgs->costTime += end - begin; - printf("code: %d, %s. time used:%"PRId64", thread: 0x%s\n", code, tstrerror(code), end - begin, tidBuf); + printf("code: %d, %s. affected lines:%d time used:%"PRId64", thread: 0x%s\n", code, taos_errstr(res), taos_affected_rows(res), end - begin, tidBuf); + taos_free_result(res); } return NULL; } @@ -95,9 +99,11 @@ int main(int argc, char* argv[]) { int numFields = 13; int maxLinesPerBatch = 16384; + int tsPrecision = TSDB_SML_TIMESTAMP_NOT_CONFIGURED; + int lineProtocol = TSDB_SML_UNKNOWN_PROTOCOL; int opt; - while ((opt = getopt(argc, argv, "s:c:r:f:t:m:h")) != -1) { + while ((opt = getopt(argc, argv, "s:c:r:f:t:m:p:P:h")) != -1) { switch (opt) { case 's': numSuperTables = atoi(optarg); @@ -117,6 +123,12 @@ int main(int argc, char* argv[]) { case 'm': maxLinesPerBatch = atoi(optarg); break; + case 'p': + tsPrecision = atoi(optarg); + break; + case 'P': + lineProtocol = atoi(optarg); + break; case 'h': fprintf(stderr, "Usage: %s -s supertable -c childtable -r rows -f fields -t threads -m maxlines_per_batch\n", argv[0]); @@ -178,6 +190,8 @@ int main(int argc, char* argv[]) { args.taos = taos; args.batches[0].lines = linesStb; args.batches[0].numLines = numSuperTables; + args.tsPrecision = tsPrecision; + args.lineProtocol = lineProtocol; insertLines(&args); for (int i = 0; i < numSuperTables; ++i) { free(linesStb[i]); diff --git a/tests/pytest/fulltest.sh b/tests/pytest/fulltest.sh index 998109a99f659e44e3aaddb9f8f5e17474cb153f..f54a6c4bbd6d7c10d94a59d6eae1f3aff00bf298 100755 --- a/tests/pytest/fulltest.sh +++ b/tests/pytest/fulltest.sh @@ -391,6 +391,7 @@ python3 ./test.py -f tag_lite/alter_tag.py python3 test.py -f tools/taosdemoAllTest/TD-4985/query-limit-offset.py python3 test.py -f tools/taosdemoAllTest/TD-5213/insert4096columns_not_use_taosdemo.py python3 test.py -f tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py +python3 test.py -f tools/taosdemoAllTest/TD-10539/create_taosdemo.py python3 ./test.py -f tag_lite/drop_auto_create.py python3 test.py -f insert/insert_before_use_db.py python3 test.py -f alter/alter_keep.py diff --git a/tests/pytest/insert/insertJSONPayload.py b/tests/pytest/insert/insertJSONPayload.py index c5cd96f86d984bff09dcc3ee40405bf5c2056fea..41d60cd1520e09b94c90083f8b6a361df4556444 100644 --- a/tests/pytest/insert/insertJSONPayload.py +++ b/tests/pytest/insert/insertJSONPayload.py @@ -15,6 +15,7 @@ import sys from util.log import * from util.cases import * from util.sql import * +from util.types import TDSmlProtocolType, TDSmlTimestampType class TDTestCase: @@ -46,7 +47,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe `.stb.0.`") @@ -67,7 +68,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_0") @@ -86,7 +87,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_1") @@ -105,7 +106,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_2") @@ -124,7 +125,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_3") @@ -143,7 +144,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_4") @@ -162,7 +163,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_5") @@ -184,7 +185,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) ### timestamp 10 digits second ### @@ -201,7 +202,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) print("============= step3 : test tags ================") @@ -216,7 +217,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_8") @@ -232,7 +233,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_9") @@ -248,7 +249,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb0_10") @@ -274,7 +275,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select ts from stb1_0") @@ -297,7 +298,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select ts from stb1_1") @@ -320,7 +321,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select ts from stb1_2") @@ -343,7 +344,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select ts from stb1_3") @@ -367,7 +368,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) ### metric value ### @@ -390,7 +391,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_0") @@ -415,7 +416,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_1") @@ -440,7 +441,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_2") @@ -465,7 +466,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_3") @@ -490,7 +491,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_4") @@ -515,7 +516,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_5") @@ -540,7 +541,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_6") @@ -565,7 +566,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_7") @@ -590,7 +591,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb2_8") @@ -649,7 +650,7 @@ class TDTestCase: } } '''] - code = self._conn.schemaless_insert(payload, 2, None) + code = self._conn.schemaless_insert(payload, TDSmlProtocolType.JSON.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("describe stb3_0") diff --git a/tests/pytest/insert/insertTelnetLines.py b/tests/pytest/insert/insertTelnetLines.py index a1809cff2a46d47d7ce2205963fad84950dfa3cd..0ecf93b5a459d2aac2a656543e946173f8309759 100644 --- a/tests/pytest/insert/insertTelnetLines.py +++ b/tests/pytest/insert/insertTelnetLines.py @@ -15,7 +15,7 @@ import sys from util.log import * from util.cases import * from util.sql import * - +from util.types import TDSmlProtocolType, TDSmlTimestampType class TDTestCase: def init(self, conn, logSql): @@ -29,7 +29,6 @@ class TDTestCase: tdSql.execute("create database if not exists test precision 'us'") tdSql.execute('use test') - ### metric ### print("============= step1 : test metric ================") lines0 = [ @@ -39,7 +38,7 @@ class TDTestCase: "`.stb0.3.` 1626006833639000000ns 4i8 host=\"host0\" interface=\"eth0\"", ] - code = self._conn.schemaless_insert(lines0, 1, None) + code = self._conn.schemaless_insert(lines0, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("show stables") @@ -69,7 +68,7 @@ class TDTestCase: "stb1 0 7i8 host=\"host0\"", ] - code = self._conn.schemaless_insert(lines1, 1, None) + code = self._conn.schemaless_insert(lines1, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb1") @@ -83,7 +82,7 @@ class TDTestCase: "stb2_0 1626006833651ms -127i8 host=\"host0\"", "stb2_0 1626006833652ms 127i8 host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_0, 1, None) + code = self._conn.schemaless_insert(lines2_0, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_0") @@ -98,7 +97,7 @@ class TDTestCase: "stb2_1 1626006833651ms -32767i16 host=\"host0\"", "stb2_1 1626006833652ms 32767i16 host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_1, 1, None) + code = self._conn.schemaless_insert(lines2_1, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_1") @@ -114,7 +113,7 @@ class TDTestCase: "stb2_2 1626006833652ms 2147483647i32 host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_2, 1, None) + code = self._conn.schemaless_insert(lines2_2, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_2") @@ -130,7 +129,7 @@ class TDTestCase: "stb2_3 1626006833652ms 9223372036854775807i64 host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_3, 1, None) + code = self._conn.schemaless_insert(lines2_3, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_3") @@ -154,7 +153,7 @@ class TDTestCase: "stb2_4 1626006833710ms -3.4E38f32 host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_4, 1, None) + code = self._conn.schemaless_insert(lines2_4, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_4") @@ -179,7 +178,7 @@ class TDTestCase: "stb2_5 1626006833710ms 3 host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_5, 1, None) + code = self._conn.schemaless_insert(lines2_5, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_5") @@ -203,7 +202,7 @@ class TDTestCase: "stb2_6 1626006833700ms FALSE host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_6, 1, None) + code = self._conn.schemaless_insert(lines2_6, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_6") @@ -215,12 +214,12 @@ class TDTestCase: #binary lines2_7 = [ - "stb2_7 1626006833610ms \"binary_val.!@#$%^&*\" host=\"host0\"", + "stb2_7 1626006833610ms \" binary_val .!@#$%^&* \" host=\"host0\"", "stb2_7 1626006833620ms \"binary_val.:;,./?|+-=\" host=\"host0\"", "stb2_7 1626006833630ms \"binary_val.()[]{}<>\" host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_7, 1, None) + code = self._conn.schemaless_insert(lines2_7, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_7") @@ -232,11 +231,11 @@ class TDTestCase: #nchar lines2_8 = [ - "stb2_8 1626006833610ms L\"nchar_val数值一\" host=\"host0\"", + "stb2_8 1626006833610ms L\" nchar_val 数值一 \" host=\"host0\"", "stb2_8 1626006833620ms L\"nchar_val数值二\" host=\"host0\"" ] - code = self._conn.schemaless_insert(lines2_8, 1, None) + code = self._conn.schemaless_insert(lines2_8, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb2_8") @@ -254,7 +253,7 @@ class TDTestCase: "stb3_0 1626006833610ms 2 t1=-127i8 t2=-32767i16 t3=-2147483647i32 t4=-9223372036854775807i64 t5=-3.4E38f32 t6=-1.7E308f64 t7=false t8=\"binary_val_2\" t9=L\"标签值2\"" ] - code = self._conn.schemaless_insert(lines3_0, 1, None) + code = self._conn.schemaless_insert(lines3_0, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb3_0") @@ -298,7 +297,7 @@ class TDTestCase: "stb3_1 1626006833610ms 3 ID=child_table3 host=host3" ] - code = self._conn.schemaless_insert(lines3_1, 1, None) + code = self._conn.schemaless_insert(lines3_1, TDSmlProtocolType.TELNET.value, TDSmlTimestampType.NOT_CONFIGURED.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from stb3_1") diff --git a/tests/pytest/insert/line_insert.py b/tests/pytest/insert/line_insert.py index fe73fbbb65e4cbb0431bde22d7bf1a5bc7b15c11..334ccd4e6ec8c6058afe2f115fda61bda6428a14 100644 --- a/tests/pytest/insert/line_insert.py +++ b/tests/pytest/insert/line_insert.py @@ -15,13 +15,14 @@ import sys from util.log import * from util.cases import * from util.sql import * +from util.types import TDSmlProtocolType, TDSmlTimestampType class TDTestCase: def init(self, conn, logSql): tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - self._conn = conn + self._conn = conn def run(self): print("running {}".format(__file__)) @@ -31,9 +32,9 @@ class TDTestCase: tdSql.execute('create stable ste(ts timestamp, f int) tags(t1 bigint)') - lines = [ "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", + lines = [ "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"\"\"a pa,\"s si,t \"\"\",c2=false,c4=4f64 1626006833639000000", "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000", - "ste,t2=5f64,t3=L\"ste\" c1=true,c2=4i64,c3=\"iam\" 1626056811823316532", + "ste,t2=5f64,t3=L\"ste\" c1=true,c2=4i64,c3=\" i,\"a \"m,\"\"\" 1626056811823316532", "stf,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000", "st,t1=4i64,t2=5f64,t3=\"t4\" c1=3i64,c3=L\"passitagain\",c2=true,c4=5f64 1626006833642000000", "ste,t2=5f64,t3=L\"ste2\" c3=\"iamszhou\",c4=false 1626056811843316532", @@ -42,17 +43,17 @@ class TDTestCase: "stf,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641000000" ] - code = self._conn.schemaless_insert(lines, 0, "ns") + code = self._conn.schemaless_insert(lines, TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) print("schemaless_insert result {}".format(code)) lines2 = [ "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000" ] - code = self._conn.schemaless_insert([ lines2[0] ], 0, "ns") + code = self._conn.schemaless_insert([ lines2[0] ], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) print("schemaless_insert result {}".format(code)) - self._conn.schemaless_insert([ lines2[1] ], 0, "ns") + code = self._conn.schemaless_insert([ lines2[1] ], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) print("schemaless_insert result {}".format(code)) tdSql.query("select * from st") @@ -76,7 +77,7 @@ class TDTestCase: self._conn.schemaless_insert([ "sth,t1=4i64,t2=5f64,t4=5f64,ID=childtable c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641", "sth,t1=4i64,t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933654" - ], 0, "ms") + ], TDSmlProtocolType.LINE.value, TDSmlTimestampType.MILLI_SECOND.value) tdSql.execute('reset query cache') tdSql.query('select tbname, * from sth') diff --git a/tests/pytest/insert/schemalessInsert.py b/tests/pytest/insert/schemalessInsert.py index 56558ab3be9d74c5abf0987f23b8986a629567b4..94ea0ab79a54cbb7daea1a431fa566567b9de684 100644 --- a/tests/pytest/insert/schemalessInsert.py +++ b/tests/pytest/insert/schemalessInsert.py @@ -21,6 +21,7 @@ import numpy as np from util.log import * from util.cases import * from util.sql import * +from util.types import TDSmlProtocolType, TDSmlTimestampType import threading @@ -294,7 +295,7 @@ class TDTestCase: def resCmp(self, input_sql, stb_name, query_sql="select * from", condition="", ts=None, id=True, none_check_tag=None): expect_list = self.inputHandle(input_sql) - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) query_sql = f"{query_sql} {stb_name} {condition}" res_row_list, res_field_list_without_ts, res_type_list = self.resHandle(query_sql, True) if ts == 0: @@ -409,11 +410,11 @@ class TDTestCase: """ for input_sql in [self.genLongSql(128, 1)[0], self.genLongSql(1, 4094)[0]]: self.cleanStb() - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) for input_sql in [self.genLongSql(129, 1)[0], self.genLongSql(1, 4095)[0]]: self.cleanStb() try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -427,7 +428,7 @@ class TDTestCase: for i in rstr: input_sql = self.genFullTypeSql(tb_name=f"\"aaa{i}bbb\"")[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -438,7 +439,7 @@ class TDTestCase: self.cleanStb() input_sql = self.genFullTypeSql(tb_name=f"\"1aaabbb\"")[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -449,7 +450,7 @@ class TDTestCase: self.cleanStb() input_sql = self.genFullTypeSql(ts="now")[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -460,7 +461,7 @@ class TDTestCase: self.cleanStb() input_sql = self.genFullTypeSql(ts="2021-07-21\ 19:01:46.920")[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -471,7 +472,7 @@ class TDTestCase: self.cleanStb() input_sql = self.genFullTypeSql(ts="16260068336390us19")[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -487,7 +488,7 @@ class TDTestCase: for t1 in ["-128i8", "128i8"]: input_sql = self.genFullTypeSql(t1=t1)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -498,7 +499,7 @@ class TDTestCase: for t2 in ["-32768i16", "32768i16"]: input_sql = self.genFullTypeSql(t2=t2)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -509,7 +510,7 @@ class TDTestCase: for t3 in ["-2147483648i32", "2147483648i32"]: input_sql = self.genFullTypeSql(t3=t3)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -520,7 +521,7 @@ class TDTestCase: for t4 in ["-9223372036854775808i64", "9223372036854775808i64"]: input_sql = self.genFullTypeSql(t4=t4)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError: pass @@ -532,7 +533,7 @@ class TDTestCase: for t5 in [f"{-3.4028234664*(10**38)}f32", f"{3.4028234664*(10**38)}f32"]: input_sql = self.genFullTypeSql(t5=t5)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -546,7 +547,7 @@ class TDTestCase: for c6 in [f'{-1.797693134862316*(10**308)}f64', f'{-1.797693134862316*(10**308)}f64']: input_sql = self.genFullTypeSql(c6=c6)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -554,11 +555,11 @@ class TDTestCase: # binary stb_name = self.getLongName(7, "letters") input_sql = f'{stb_name},t0=t,t1="{self.getLongName(16374, "letters")}" c0=f 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) input_sql = f'{stb_name},t0=t,t1="{self.getLongName(16375, "letters")}" c0=f 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: pass @@ -567,11 +568,11 @@ class TDTestCase: # * legal nchar could not be larger than 16374/4 stb_name = self.getLongName(7, "letters") input_sql = f'{stb_name},t0=t,t1=L"{self.getLongName(4093, "letters")}" c0=f 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) input_sql = f'{stb_name},t0=t,t1=L"{self.getLongName(4094, "letters")}" c0=f 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -589,7 +590,7 @@ class TDTestCase: for c1 in ["-128i8", "128i8"]: input_sql = self.genFullTypeSql(c1=c1)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -600,7 +601,7 @@ class TDTestCase: for c2 in ["-32768i16", "32768i16"]: input_sql = self.genFullTypeSql(c2=c2)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -612,7 +613,7 @@ class TDTestCase: for c3 in ["-2147483648i32", "2147483648i32"]: input_sql = self.genFullTypeSql(c3=c3)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -624,7 +625,7 @@ class TDTestCase: for c4 in ["-9223372036854775808i64", "9223372036854775808i64"]: input_sql = self.genFullTypeSql(c4=c4)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -637,7 +638,7 @@ class TDTestCase: for c5 in [f"{-3.4028234664*(10**38)}f32", f"{3.4028234664*(10**38)}f32"]: input_sql = self.genFullTypeSql(c5=c5)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -650,7 +651,7 @@ class TDTestCase: for c6 in [f'{-1.797693134862316*(10**308)}f64', f'{-1.797693134862316*(10**308)}f64']: input_sql = self.genFullTypeSql(c6=c6)[0] try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -658,11 +659,11 @@ class TDTestCase: # # binary stb_name = self.getLongName(7, "letters") input_sql = f'{stb_name},t0=t c0=f,c1="{self.getLongName(16374, "letters")}" 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) input_sql = f'{stb_name},t0=t c0=f,c1="{self.getLongName(16375, "letters")}" 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -671,11 +672,11 @@ class TDTestCase: # * legal nchar could not be larger than 16374/4 stb_name = self.getLongName(7, "letters") input_sql = f'{stb_name},t0=t c0=f,c1=L"{self.getLongName(4093, "letters")}" 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) input_sql = f'{stb_name},t0=t c0=f,c1=L"{self.getLongName(4094, "letters")}" 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -690,13 +691,13 @@ class TDTestCase: for i in ["TrUe", "tRue", "trUe", "truE", "FalsE", "fAlse", "faLse", "falSe", "falsE"]: input_sql1 = self.genFullTypeSql(t0=i)[0] try: - self._conn.schemaless_insert([input_sql1], 0) + self._conn.schemaless_insert([input_sql1], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) input_sql2 = self.genFullTypeSql(c0=i)[0] try: - self._conn.schemaless_insert([input_sql2], 0) + self._conn.schemaless_insert([input_sql2], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -718,7 +719,7 @@ class TDTestCase: self.genFullTypeSql(c9="1s1u64")[0] ]: try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -731,7 +732,7 @@ class TDTestCase: input_sql4 = f'{stb_name},t0=t,t1=L"abc aaa" c0=f 1626006833639000000ns' for input_sql in [input_sql1, input_sql2, input_sql3, input_sql4]: try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -741,8 +742,8 @@ class TDTestCase: for symbol in list('~!@#$¥%^&*()-+={}|[]、「」:;'): input_sql1 = f'{stb_name},t0=t c0=f,c1="abc{symbol}aaa" 1626006833639000000ns' input_sql2 = f'{stb_name},t0=t,t1="abc{symbol}aaa" c0=f 1626006833639000000ns' - self._conn.schemaless_insert([input_sql1], 0) - self._conn.schemaless_insert([input_sql2], 0) + self._conn.schemaless_insert([input_sql1], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) + self._conn.schemaless_insert([input_sql2], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) def duplicateIdTagColInsertCheckCase(self): @@ -752,7 +753,7 @@ class TDTestCase: self.cleanStb() input_sql_id = self.genFullTypeSql(id_double_tag=True)[0] try: - self._conn.schemaless_insert([input_sql_id], 0) + self._conn.schemaless_insert([input_sql_id], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -760,7 +761,7 @@ class TDTestCase: input_sql = self.genFullTypeSql()[0] input_sql_tag = input_sql.replace("t5", "t6") try: - self._conn.schemaless_insert([input_sql_tag], 0) + self._conn.schemaless_insert([input_sql_tag], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -768,7 +769,7 @@ class TDTestCase: input_sql = self.genFullTypeSql()[0] input_sql_col = input_sql.replace("c5", "c6") try: - self._conn.schemaless_insert([input_sql_col], 0) + self._conn.schemaless_insert([input_sql_col], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -776,7 +777,7 @@ class TDTestCase: input_sql = self.genFullTypeSql()[0] input_sql_col = input_sql.replace("c5", "C6") try: - self._conn.schemaless_insert([input_sql_col], 0) + self._conn.schemaless_insert([input_sql_col], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -802,7 +803,7 @@ class TDTestCase: self.cleanStb() input_sql, stb_name = self.genFullTypeSql() self.resCmp(input_sql, stb_name) - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) self.resCmp(input_sql, stb_name) def tagColBinaryNcharLengthCheckCase(self): @@ -869,7 +870,7 @@ class TDTestCase: tdSql.checkRows(1) tdSql.checkEqual(tb_name1, tb_name2) input_sql, stb_name = self.genFullTypeSql(stb_name=stb_name, t0="f", c0="f", id_noexist_tag=True, ct_add_tag=True) - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) tb_name3 = self.getNoIdTbName(stb_name) tdSql.query(f"select * from {stb_name}") tdSql.checkRows(2) @@ -884,17 +885,17 @@ class TDTestCase: stb_name = self.getLongName(7, "letters") tb_name = f'{stb_name}_1' input_sql = f'{stb_name},id="{tb_name}",t0=t c0=f 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) # * every binary and nchar must be length+2, so here is two tag, max length could not larger than 16384-2*2 input_sql = f'{stb_name},t0=t,t1="{self.getLongName(16374, "letters")}",t2="{self.getLongName(5, "letters")}" c0=f 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) tdSql.query(f"select * from {stb_name}") tdSql.checkRows(2) input_sql = f'{stb_name},t0=t,t1="{self.getLongName(16374, "letters")}",t2="{self.getLongName(6, "letters")}" c0=f 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError: pass @@ -903,13 +904,13 @@ class TDTestCase: # # * check col,col+ts max in describe ---> 16143 input_sql = f'{stb_name},t0=t c0=f,c1="{self.getLongName(16374, "letters")}",c2="{self.getLongName(16374, "letters")}",c3="{self.getLongName(16374, "letters")}",c4="{self.getLongName(12, "letters")}" 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) tdSql.query(f"select * from {stb_name}") tdSql.checkRows(3) input_sql = f'{stb_name},t0=t c0=f,c1="{self.getLongName(16374, "letters")}",c2="{self.getLongName(16374, "letters")}",c3="{self.getLongName(16374, "letters")}",c4="{self.getLongName(13, "letters")}" 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -925,16 +926,16 @@ class TDTestCase: stb_name = self.getLongName(7, "letters") tb_name = f'{stb_name}_1' input_sql = f'{stb_name},id="{tb_name}",t0=t c0=f 1626006833639000000ns' - code = self._conn.schemaless_insert([input_sql], 0) + code = self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) # * legal nchar could not be larger than 16374/4 input_sql = f'{stb_name},t0=t,t1=L"{self.getLongName(4093, "letters")}",t2=L"{self.getLongName(1, "letters")}" c0=f 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) tdSql.query(f"select * from {stb_name}") tdSql.checkRows(2) input_sql = f'{stb_name},t0=t,t1=L"{self.getLongName(4093, "letters")}",t2=L"{self.getLongName(2, "letters")}" c0=f 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -942,12 +943,12 @@ class TDTestCase: tdSql.checkRows(2) input_sql = f'{stb_name},t0=t c0=f,c1=L"{self.getLongName(4093, "letters")}",c2=L"{self.getLongName(4093, "letters")}",c3=L"{self.getLongName(4093, "letters")}",c4=L"{self.getLongName(4, "letters")}" 1626006833639000000ns' - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) tdSql.query(f"select * from {stb_name}") tdSql.checkRows(3) input_sql = f'{stb_name},t0=t c0=f,c1=L"{self.getLongName(4093, "letters")}",c2=L"{self.getLongName(4093, "letters")}",c3=L"{self.getLongName(4093, "letters")}",c4=L"{self.getLongName(5, "letters")}" 1626006833639000000ns' try: - self._conn.schemaless_insert([input_sql], 0) + self._conn.schemaless_insert([input_sql], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -971,7 +972,7 @@ class TDTestCase: "st123456,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000ns", "st123456,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641000000ns" ] - self._conn.schemaless_insert(lines, 0) + self._conn.schemaless_insert(lines, TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) def multiInsertCheckCase(self, count): """ @@ -984,7 +985,7 @@ class TDTestCase: for i in range(count): input_sql = self.genFullTypeSql(stb_name=stb_name, t7=f'"{self.getLongName(8, "letters")}"', c7=f'"{self.getLongName(8, "letters")}"', id_noexist_tag=True)[0] sql_list.append(input_sql) - self._conn.schemaless_insert(sql_list, 0) + self._conn.schemaless_insert(sql_list, TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) def batchErrorInsertCheckCase(self): """ @@ -995,7 +996,7 @@ class TDTestCase: lines = ["st123456,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000ns", f"{stb_name},t2=5f64,t3=L\"ste\" c1=tRue,c2=4i64,c3=\"iam\" 1626056811823316532ns"] try: - self._conn.schemaless_insert(lines, 0) + self._conn.schemaless_insert(lines, TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) raise Exception("should not reach here") except SchemalessError as err: tdSql.checkNotEqual(err.errno, 0) @@ -1049,7 +1050,7 @@ class TDTestCase: def genMultiThreadSeq(self, sql_list): tlist = list() for insert_sql in sql_list: - t = threading.Thread(target=self._conn.schemaless_insert,args=([insert_sql[0]], 0)) + t = threading.Thread(target=self._conn.schemaless_insert,args=([insert_sql[0]], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value)) tlist.append(t) return tlist @@ -1260,8 +1261,8 @@ class TDTestCase: input_sql1 = "rfasta,id=\"rfasta_1\",t0=true,t1=127i8,t2=32767i16,t3=2147483647i32,t4=9223372036854775807i64,t5=11.12345f32,t6=22.123456789f64,t7=\"ddzhiksj\",t8=L\"ncharTagValue\" c0=True,c1=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=11.12345f32,c6=22.123456789f64,c7=\"bnhwlgvj\",c8=L\"ncharTagValue\",c9=7u64 1626006933640000000ns" input_sql2 = "rfasta,id=\"rfasta_1\",t0=true,t1=127i8,t2=32767i16,t3=2147483647i32,t4=9223372036854775807i64,t5=11.12345f32,t6=22.123456789f64 c0=True,c1=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=11.12345f32,c6=22.123456789f64 1626006933640000000ns" try: - self._conn.schemaless_insert([input_sql1], 0) - self._conn.schemaless_insert([input_sql2], 0) + self._conn.schemaless_insert([input_sql1], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) + self._conn.schemaless_insert([input_sql2], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) except SchemalessError as err: print(err.errno) # self._conn.schemaless_insert([input_sql2], 0) diff --git a/tests/pytest/query/udf.py b/tests/pytest/query/udf.py index 5b345643b30856195caab938f59c7e8f7a642784..14429a53f44b1393c9f179cc405ed61fb59e8b02 100644 --- a/tests/pytest/query/udf.py +++ b/tests/pytest/query/udf.py @@ -210,10 +210,10 @@ class TDTestCase: tdSql.query("select max(id) + 5 from tb1") tdSql.query("select max(id) + avg(val) from st") tdSql.query("select max(id) + avg(val) from tb1") - tdSql.error("select abs_max(number) + 5 from st") - tdSql.error("select abs_max(number) + 5 from tb1") + tdSql.query("select abs_max(number) + 5 from st") + tdSql.query("select abs_max(number) + 5 from tb1") tdSql.error("select abs_max(number) + max(id) from st") - tdSql.error("select abs_max(number)*abs_max(val) from st") + tdSql.query("select abs_max(number)*abs_max(val) from st") tdLog.info("======= UDF Nested query test =======") tdSql.query("select sum(id) from (select id from st)") diff --git a/tests/pytest/table/create.py b/tests/pytest/table/create.py index 59044bc52b1bb02a33c0a2087deabf5f43d6c518..ec9179c5e97356f284b8d11ed006c12518142328 100644 --- a/tests/pytest/table/create.py +++ b/tests/pytest/table/create.py @@ -298,8 +298,7 @@ class TDTestCase: print("==============step3,#create regular_table; insert regular_table; show regular_table; select regular_table; drop regular_table") self.regular_table = "regular_table~!@#$%^&*()-_+=[]{}';:,<.>/?stST24680~!@#$%^&*()-_+=[]{}" - #self.regular_table = "regular_table~!@#$%^&*()-_+=[]{}';:,<.>/?stST24680~!@#$%^&*()-_+=[]{}" - + tdSql.execute("create table `%s` (ts timestamp,i int) ;" %self.regular_table) tdSql.query("describe `%s` ; "%self.regular_table) tdSql.checkRows(2) @@ -328,9 +327,9 @@ class TDTestCase: tdSql.checkRows(1) self.crr_tb = "create_r_table~!@#$%^&*()-_+=[]{}';:,<.>/?stST24680~!@#$%^&*()-_+=[]{}" - # tdSql.execute("create table `%s` as select * from `%s` ;" %(self.crr_tb,self.regular_table)) - # tdSql.query("show db.tables like 'create_r_table%' ") - # tdSql.checkRows(1) + tdSql.execute("create table `%s` as select * from `%s` ;" %(self.crr_tb,self.regular_table)) + tdSql.query("show db2.tables like 'create_r_table%' ") + tdSql.checkRows(1) print("==============drop table\stable") try: @@ -340,15 +339,6 @@ class TDTestCase: tdSql.error("select * from `%s`" %self.regular_table) - - #表名:192个字符,还要包含前面的数据库名 - #taosdemo 建数据库表 # 单独放 - # self.tsdemo = "tsdemo~!@#$%^&*()-_+=[]{}" - # os.system("%staosdemo -d test -m `%s` -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) - # tdSql.execute("use #!#!#!") - # tdSql.query("select count (tbname) from #!#!#!") - # tdSql.checkData(0, 0, 1000) - diff --git a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo.py b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo.py new file mode 100644 index 0000000000000000000000000000000000000000..d7926d6e5b5a3db80f3c66df0655266a5c673999 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo.py @@ -0,0 +1,185 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +import taos +import time +import os +from util.log import tdLog +from util.cases import tdCases +from util.sql import tdSql + + +class TDTestCase: + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + + def getBuildPath(self): + selfPath = os.path.dirname(os.path.realpath(__file__)) + + if ("community" in selfPath): + projPath = selfPath[:selfPath.find("community")] + else: + projPath = selfPath[:selfPath.find("tests")] + + for root, dirs, files in os.walk(projPath): + if ("taosd" in files): + rootRealPath = os.path.dirname(os.path.realpath(root)) + if ("packaging" not in rootRealPath): + buildPath = root[:len(root)-len("/build/bin")] + break + return buildPath + + def run(self): + buildPath = self.getBuildPath() + if (buildPath == ""): + tdLog.exit("taosd not found!") + else: + tdLog.info("taosd found in %s" % buildPath) + binPath = buildPath+ "/build/bin/" + + os.system("rm -rf tools/taosdemoAllTest/TD-10539/create_taosdemo.py.sql") + tdSql.prepare() + + #print("==============taosdemo,#create stable,table; insert table; show table; select table; drop table") + self.tsdemo = "tsdemo~!.@#$%^*[]-_=+{,?.}" + #this escape character is not support in shell . include & () <> | / + os.system("%staosdemo -d test -E -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) + tdSql.execute("use test ;" ) + tdSql.query("select count(*) from meters") + tdSql.checkData(0, 0, 1000) + tdSql.query("show test.tables like 'tsdemo%'" ) + tdSql.checkRows(10) + tdSql.query("show test.tables like '%s_'" %self.tsdemo) + tdSql.checkRows(10) + tdSql.query("select _block_dist() from `%s1`" %self.tsdemo) + tdSql.checkRows(1) + tdSql.query("describe test.`%s1` ; " %self.tsdemo) + tdSql.checkRows(13) + tdSql.query("show create table test.`%s1` ; " %self.tsdemo) + tdSql.checkData(0, 0, self.tsdemo+str(1)) + tdSql.checkData(0, 1, "CREATE TABLE `%s1` USING `meters` TAGS (1,\"beijing\")" %self.tsdemo) + + print("==============drop table\stable") + try: + tdSql.execute("drop table test.`%s1` ; " %self.tsdemo) + except Exception as e: + tdLog.exit(e) + + tdSql.error("select * from test.`%s1` ; " %self.tsdemo) + tdSql.query("show test.tables like '%s_'" %self.tsdemo) + tdSql.checkRows(9) + + try: + tdSql.execute("drop table test.meters ") + except Exception as e: + tdLog.exit(e) + + tdSql.error("select * from test.meters ") + tdSql.error("select * from test.`%s2` ; " %self.tsdemo) + + # Exception + os.system("%staosdemo -d test -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) + tdSql.query("show test.tables ") + tdSql.checkRows(0) + + #print("==============taosdemo,#create regular table; insert table; show table; select table; drop table") + self.tsdemo = "tsdemo~!.@#$%^*[]-_=+{,?.}" + #this escape character is not support in shell . include & () <> | / + os.system("%staosdemo -N -E -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) + tdSql.execute("use test ;" ) + tdSql.query("select count(*) from `%s1`" %self.tsdemo) + tdSql.checkData(0, 0, 100) + tdSql.query("show test.tables like 'tsdemo%'" ) + tdSql.checkRows(10) + tdSql.query("show test.tables like '%s_'" %self.tsdemo) + tdSql.checkRows(10) + tdSql.query("select _block_dist() from `%s1`" %self.tsdemo) + tdSql.checkRows(1) + tdSql.query("describe test.`%s1` ; " %self.tsdemo) + tdSql.checkRows(11) + tdSql.query("show create table test.`%s1` ; " %self.tsdemo) + tdSql.checkData(0, 0, self.tsdemo+str(1)) + tdSql.checkData(0, 1, "create table `%s1` (ts TIMESTAMP,c0 FLOAT,c1 INT,c2 INT,c3 INT,c4 INT,c5 INT,c6 INT,c7 INT,c8 INT,c9 INT)" %self.tsdemo) + + print("==============drop table\stable") + try: + tdSql.execute("drop table test.`%s1` ; " %self.tsdemo) + except Exception as e: + tdLog.exit(e) + + tdSql.error("select * from test.`%s1` ; " %self.tsdemo) + tdSql.query("show test.tables like '%s_'" %self.tsdemo) + tdSql.checkRows(9) + + # Exception + os.system("%staosdemo -N -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) + tdSql.query("show test.tables ") + tdSql.checkRows(0) + + + #print("==============taosdemo——json_yes,#create stable,table; insert table; show table; select table; drop table") + os.system("%staosdemo -f tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json -y " % binPath) + tdSql.execute("use dbyes") + + self.tsdemo_stable = "tsdemo_stable~!.@#$%^*[]-_=+{,?.}" + self.tsdemo = "tsdemo~!.@#$%^*[]-_=+{,?.}" + + tdSql.query("select count(*) from dbyes.`%s`" %self.tsdemo_stable) + tdSql.checkData(0, 0, 1000) + tdSql.query("show dbyes.tables like 'tsdemo%'" ) + tdSql.checkRows(10) + tdSql.query("show dbyes.tables like '%s_'" %self.tsdemo) + tdSql.checkRows(10) + tdSql.query("select _block_dist() from `%s1`" %self.tsdemo) + tdSql.checkRows(1) + tdSql.query("describe dbyes.`%s1` ; " %self.tsdemo) + tdSql.checkRows(13) + tdSql.query("show create table dbyes.`%s1` ; " %self.tsdemo) + tdSql.checkData(0, 0, self.tsdemo+str(1)) + tdSql.checkData(0, 1, "CREATE TABLE `%s1` USING `%s` TAGS (1,1)" %(self.tsdemo,self.tsdemo_stable)) + + print("==============drop table\stable") + try: + tdSql.execute("drop table dbyes.`%s1` ; " %self.tsdemo) + except Exception as e: + tdLog.exit(e) + + tdSql.error("select * from dbyes.`%s1` ; " %self.tsdemo) + tdSql.query("show dbyes.tables like '%s_'" %self.tsdemo) + tdSql.checkRows(9) + + try: + tdSql.execute("drop table dbyes.`%s` ; " %self.tsdemo_stable) + except Exception as e: + tdLog.exit(e) + + tdSql.error("select * from dbyes.`%s` ; " %self.tsdemo_stable) + tdSql.error("select * from dbyes.`%s2` ; " %self.tsdemo) + + #print("==============taosdemo——json_no,#create stable,table; insert table; show table; select table; drop table") + + assert os.system("%staosdemo -f tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json -y " % binPath) == 0 + tdSql.query("show dbno.tables ") + tdSql.checkRows(0) + + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json new file mode 100644 index 0000000000000000000000000000000000000000..759a437b448c8c65bf252e859345dd9557cc51c5 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json @@ -0,0 +1,63 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 10, + "thread_count_create_tbl": 10, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": 1, + "max_sql_len": 1024000, + "databases": [{ + "dbinfo": { + "name": "dbno", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 36500, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "meters", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "tsdemo~!.@#$%^*[]-_=+{,?.}", + "escape_character": "no", + "auto_create_table": "no", + "batch_create_tbl_num": 1, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 100, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "", + "tags_file": "", + "columns": [{"type": "INT","count":9}, {"type": "BINARY", "len": 16, "count":1}], + "tags": [{"type": "INT", "count":2}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json new file mode 100644 index 0000000000000000000000000000000000000000..aafc79215fc0b94d037da3a9b229a2f967b51613 --- /dev/null +++ b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json @@ -0,0 +1,63 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 5, + "thread_count_create_tbl": 10, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "insert_interval": 0, + "interlace_rows": 10, + "num_of_records_per_req": 1, + "max_sql_len": 1024000, + "databases": [{ + "dbinfo": { + "name": "dbyes", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 50, + "blocks": 8, + "precision": "ms", + "keep": 36500, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 0 + }, + "super_tables": [{ + "name": "tsdemo_stable~!.@#$%^*[]-_=+{,?.}", + "child_table_exists":"no", + "childtable_count": 10, + "childtable_prefix": "tsdemo~!.@#$%^*[]-_=+{,?.}", + "escape_character": "yes", + "auto_create_table": "no", + "batch_create_tbl_num": 1, + "data_source": "rand", + "insert_mode": "taosc", + "insert_rows": 100, + "childtable_limit": 0, + "childtable_offset":0, + "multi_thread_write_one_tbl": "no", + "interlace_rows": 0, + "insert_interval":0, + "max_sql_len": 1024000, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_format": "csv", + "sample_file": "", + "tags_file": "", + "columns": [{"type": "INT","count":9}, {"type": "BINARY", "len": 16, "count":1}], + "tags": [{"type": "INT", "count":2}] + }] + }] +} diff --git a/tests/pytest/tools/taosdemoAllTest/stmt/nsertColumnsAndTagNumLarge4096-stmt.json b/tests/pytest/tools/taosdemoAllTest/stmt/insertColumnsAndTagNumLarge4096-stmt.json similarity index 100% rename from tests/pytest/tools/taosdemoAllTest/stmt/nsertColumnsAndTagNumLarge4096-stmt.json rename to tests/pytest/tools/taosdemoAllTest/stmt/insertColumnsAndTagNumLarge4096-stmt.json diff --git a/tests/pytest/tools/taosdumpTest3.py b/tests/pytest/tools/taosdumpTest3.py index 6650afa0376cf6f6a38d217c1d1b5838d04d8ed7..d13c502fd5887d47b5094ef5bd08691372f9648b 100644 --- a/tests/pytest/tools/taosdumpTest3.py +++ b/tests/pytest/tools/taosdumpTest3.py @@ -62,8 +62,12 @@ class TDTestCase: os.makedirs("./taosdumptest/tmp3") if not os.path.exists("./taosdumptest/tmp4"): os.makedirs("./taosdumptest/tmp4") - - + if not os.path.exists("./taosdumptest/tmp5"): + os.makedirs("./taosdumptest/tmp5") + if not os.path.exists("./taosdumptest/tmp6"): + os.makedirs("./taosdumptest/tmp6") + if not os.path.exists("./taosdumptest/tmp7"): + os.makedirs("./taosdumptest/tmp7") buildPath = self.getBuildPath() if (buildPath == ""): tdLog.exit("taosdump not found!") @@ -72,6 +76,8 @@ class TDTestCase: binPath = buildPath + "/build/bin/" # create db1 , one stables and one table ; create general tables + tdSql.execute("drop database if exists dp1") + tdSql.execute("drop database if exists dp2") tdSql.execute("create database if not exists dp1") tdSql.execute("use dp1") tdSql.execute("create stable st0(ts timestamp, c1 int, c2 nchar(10)) tags(t1 int)") @@ -82,9 +88,10 @@ class TDTestCase: tdSql.execute("create table if not exists gt1 (ts timestamp, c0 int, c1 double) ") tdSql.execute("insert into gt0 values(1614218412000,637,8.861)") tdSql.execute("insert into gt1 values(1614218413000,638,8.862)") + # create db1 , three stables:stb0,include ctables stb0_0 \ stb0_1,stb1 include ctables stb1_0 and stb1_1 # \stb3,include ctables stb3_0 and stb3_1 - # ; create general three tables gt0 gt1 gt2 + # create general three tables gt0 gt1 gt2 tdSql.execute("create database if not exists dp2") tdSql.execute("use dp2") tdSql.execute("create stable st0(ts timestamp, c01 int, c02 nchar(10)) tags(t1 int)") @@ -102,94 +109,188 @@ class TDTestCase: tdSql.execute("create table if not exists gt0 (ts timestamp, c00 int, c01 float) ") tdSql.execute("create table if not exists gt1 (ts timestamp, c10 int, c11 double) ") tdSql.execute("create table if not exists gt2 (ts timestamp, c20 int, c21 float) ") - tdSql.execute("insert into gt0 values(1614218412000,8637,78.86155)") - tdSql.execute("insert into gt1 values(1614218413000,8638,78.862020199)") - tdSql.execute("insert into gt2 values(1614218413000,8639,78.863)") + tdSql.execute("insert into gt0 values(1614218412700,8637,78.86155)") + tdSql.execute("insert into gt1 values(1614218413800,8638,78.862020199)") + tdSql.execute("insert into gt2 values(1614218413900,8639,78.863)") + + # create + tdSql.execute("create database if not exists dp3 precision 'ns'") + tdSql.execute("use dp3") + tdSql.execute("create stable st0(ts timestamp, c01 int, c02 nchar(10)) tags(t1 int)") + tdSql.execute("create table st0_0 using st0 tags(0) st0_1 using st0 tags(1) ") + tdSql.execute("insert into st0_0 values(1614218412000000001,8600,'R')(1614218422000000002,8600,'E')") + tdSql.execute("insert into st0_1 values(1614218413000000001,8601,'A')(1614218423000000002,8601,'D')") + # tdSql.execute("insert into t0 values(1614218422000,8638,'R')") os.system("rm -rf ./taosdumptest/tmp1/*") os.system("rm -rf ./taosdumptest/tmp2/*") os.system("rm -rf ./taosdumptest/tmp3/*") os.system("rm -rf ./taosdumptest/tmp4/*") + os.system("rm -rf ./taosdumptest/tmp5/*") + # # taosdump stable and general table - # os.system("%staosdump -o ./taosdumptest/tmp1 -D dp1 dp2 " % binPath) - # os.system("%staosdump -o ./taosdumptest/tmp2 dp1 st0 gt0 " % binPath) - # os.system("%staosdump -o ./taosdumptest/tmp3 dp2 st0 st1_0 gt0" % binPath) - # os.system("%staosdump -o ./taosdumptest/tmp4 dp2 st0 st2 gt0 gt2" % binPath)、 + os.system("%staosdump -o ./taosdumptest/tmp1 -D dp1,dp2 " % binPath) + os.system("%staosdump -o ./taosdumptest/tmp2 dp1 st0 gt0 " % binPath) + os.system("%staosdump -o ./taosdumptest/tmp3 dp2 st0 st1_0 gt0" % binPath) + os.system("%staosdump -o ./taosdumptest/tmp4 dp2 st0 st2 gt0 gt2" % binPath) + + # verify ns + os.system("%staosdump -o ./taosdumptest/tmp6 dp3 st0_0" % binPath) + assert os.system("%staosdump -o ./taosdumptest/tmp6 dp3 st0_0 -C ns " % binPath) != 0 + # verify -D:--database - # os.system("%staosdump --databases dp1 -o ./taosdumptest/tmp3 dp2 st0 st1_0 gt0" % binPath) - # os.system("%staosdump --databases dp1,dp2 -o ./taosdumptest/tmp3 " % binPath) - - # #check taosdumptest/tmp1 - # tdSql.execute("drop database dp1") - # tdSql.execute("drop database dp2") - # os.system("%staosdump -i ./taosdumptest/tmp1 -T 2 " % binPath) - # tdSql.execute("use dp1") - # tdSql.query("show stables") - # tdSql.checkRows(1) - # tdSql.query("show tables") - # tdSql.checkRows(4) - # tdSql.execute("use dp2") - # tdSql.query("show stables") - # tdSql.checkRows(3) - # tdSql.query("show tables") - # tdSql.checkRows(9) - # tdSql.query("select c01 from gt0") - # tdSql.checkData(0,0,78.86155) - # tdSql.query("select c11 from gt1") - # tdSql.checkData(0, 0, 78.862020199) - # tdSql.query("select c21 from gt2") - # tdSql.checkData(0, 0, 78.86300) - - # #check taosdumptest/tmp2 - # tdSql.execute("drop database dp1") - # tdSql.execute("drop database dp2") - # os.system("%staosdump -i ./taosdumptest/tmp2 -T 2 " % binPath) - # tdSql.execute("use dp1") - # tdSql.query("show stables") - # tdSql.checkRows(1) - # tdSql.query("show tables") - # tdSql.checkRows(3) - # tdSql.error("use dp2") - # tdSql.query("select c01 from gt0") - # tdSql.checkData(0,0,78.86155) - - # #check taosdumptest/tmp3 - # tdSql.execute("drop database dp1") - # os.system("%staosdump -i ./taosdumptest/tmp3 -T 2 " % binPath) - # tdSql.execute("use dp2") - # tdSql.query("show stables") - # tdSql.checkRows(2) - # tdSql.query("show tables") - # tdSql.checkRows(4) - # tdSql.query("select count(*) from st1_0") - # tdSql.query("select c01 from gt0") - # tdSql.checkData(0,0,78.86155) - # tdSql.error("use dp1") - # tdSql.error("select count(*) from st2_0") - # tdSql.error("select count(*) from gt2") - - # #check taosdumptest/tmp4 - # tdSql.execute("drop database dp2") - # os.system("%staosdump -i ./taosdumptest/tmp4 -T 2 " % binPath) - # tdSql.execute("use dp2") - # tdSql.query("show stables") - # tdSql.checkRows(2) - # tdSql.query("show tables") - # tdSql.checkRows(6) - # tdSql.query("select c21 from gt2") - # tdSql.checkData(0, 0, 78.86300) - # tdSql.query("select count(*) from st2_0") - # tdSql.error("use dp1") - # tdSql.error("select count(*) from st1_0") - # tdSql.error("select count(*) from gt3") - # tdSql.execute("drop database dp2") - - - # os.system("rm -rf ./taosdumptest/tmp1") - # os.system("rm -rf ./taosdumptest/tmp2") - # os.system("rm -rf ./dump_result.txt") - # os.system("rm -rf ./db.csv") + os.system("%staosdump -o ./taosdumptest/tmp5 --databases dp1,dp2 " % binPath) + # verify mixed -D:--database and dbname tbname + assert os.system("%staosdump --databases dp1 -o ./taosdumptest/tmp5 dp2 st0 st1_0 gt0" % binPath) != 0 + + #check taosdumptest/tmp1 + tdSql.execute("drop database dp1") + tdSql.execute("drop database dp2") + os.system("%staosdump -i ./taosdumptest/tmp1 -T 2 " % binPath) + tdSql.execute("use dp1") + tdSql.query("show stables") + tdSql.checkRows(1) + tdSql.query("show tables") + tdSql.checkRows(4) + tdSql.query("select c1 from st0_0 order by ts") + tdSql.checkData(0,0,8537) + tdSql.query("select c2 from st0_1 order by ts") + tdSql.checkData(1,0,"D") + tdSql.query("select * from gt0") + tdSql.checkData(0,0,'2021-02-25 10:00:12.000') + tdSql.checkData(0,1,637) + tdSql.execute("use dp2") + tdSql.query("show stables") + tdSql.checkRows(3) + tdSql.query("show tables") + tdSql.checkRows(9) + tdSql.query("select ts from gt0") + tdSql.checkData(0,0,'2021-02-25 10:00:12.700') + tdSql.query("select c10 from gt1") + tdSql.checkData(0, 0, 8638) + tdSql.query("select c20 from gt2") + tdSql.checkData(0, 0, 8639) + + + #check taosdumptest/tmp2 + tdSql.execute("drop database dp1") + tdSql.execute("drop database dp2") + os.system("%staosdump -i ./taosdumptest/tmp2 -T 2 " % binPath) + tdSql.execute("use dp1") + tdSql.query("show stables") + tdSql.checkRows(1) + tdSql.query("show tables") + tdSql.checkRows(3) + tdSql.query("select c1 from st0_0 order by ts") + tdSql.checkData(0,0,8537) + tdSql.query("select c2 from st0_1 order by ts") + tdSql.checkData(1,0,"D") + tdSql.query("select * from gt0") + tdSql.checkData(0,0,'2021-02-25 10:00:12.000') + tdSql.checkData(0,1,637) + tdSql.error("select count(*) from gt1") + tdSql.error("use dp2") + + + #check taosdumptest/tmp3 + tdSql.execute("drop database dp1") + os.system("%staosdump -i ./taosdumptest/tmp3 -T 2 " % binPath) + tdSql.execute("use dp2") + tdSql.query("show stables") + tdSql.checkRows(2) + tdSql.query("show tables") + tdSql.checkRows(4) + tdSql.query("select count(*) from st1_0") + tdSql.checkData(0,0,2) + tdSql.query("select ts from gt0") + tdSql.checkData(0,0,'2021-02-25 10:00:12.700') + tdSql.error("use dp1") + tdSql.error("select count(*) from st2_0") + tdSql.error("select count(*) from gt2") + + #check taosdumptest/tmp4 + tdSql.execute("drop database dp2") + os.system("%staosdump -i ./taosdumptest/tmp4 -T 2 " % binPath) + tdSql.execute("use dp2") + tdSql.query("show stables") + tdSql.checkRows(2) + tdSql.query("show tables") + tdSql.checkRows(6) + tdSql.query("select c20 from gt2") + tdSql.checkData(0, 0, 8639) + tdSql.query("select count(*) from st0_0") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st0_1") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st2_1") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st2_0") + tdSql.checkData(0, 0, 2) + tdSql.error("use dp1") + tdSql.error("select count(*) from st1_0") + tdSql.error("select count(*) from st1_1") + tdSql.error("select count(*) from gt3") + + + #check taosdumptest/tmp5 + tdSql.execute("drop database dp2") + os.system("%staosdump -i ./taosdumptest/tmp5 -T 2 " % binPath) + tdSql.execute("use dp2") + tdSql.query("show stables") + tdSql.checkRows(3) + tdSql.query("show tables") + tdSql.checkRows(9) + tdSql.query("select c20 from gt2") + tdSql.checkData(0, 0, 8639) + tdSql.query("select count(*) from st0_0") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st0_1") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st2_1") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st2_0") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st1_1") + tdSql.checkData(0, 0, 2) + tdSql.query("select count(*) from st1_0") + tdSql.checkData(0, 0, 2) + tdSql.execute("use dp1") + tdSql.query("show stables") + tdSql.checkRows(1) + tdSql.query("show tables") + tdSql.checkRows(4) + tdSql.query("select c1 from st0_0 order by ts") + tdSql.checkData(0,0,8537) + tdSql.query("select c2 from st0_1 order by ts") + tdSql.checkData(1,0,"D") + tdSql.query("select * from gt0") + tdSql.checkData(0,0,'2021-02-25 10:00:12.000') + tdSql.checkData(0,1,637) + + #check taosdumptest/tmp6 + tdSql.execute("drop database dp1") + tdSql.execute("drop database dp2") + tdSql.execute("drop database dp3") + os.system("%staosdump -i ./taosdumptest/tmp6 -T 2 " % binPath) + tdSql.execute("use dp3") + tdSql.query("show stables") + tdSql.checkRows(1) + tdSql.query("show tables") + tdSql.checkRows(1) + tdSql.query("select count(*) from st0_0") + tdSql.checkData(0, 0, 2) + tdSql.query("select * from st0 order by ts") + tdSql.checkData(0,0,'2021-02-25 10:00:12.000000001') + tdSql.checkData(0,1,8600) + + os.system("rm -rf ./taosdumptest/tmp1") + os.system("rm -rf ./taosdumptest/tmp2") + os.system("rm -rf ./taosdumptest/tmp3") + os.system("rm -rf ./taosdumptest/tmp4") + os.system("rm -rf ./taosdumptest/tmp5") + os.system("rm -rf ./dump_result.txt") + os.system("rm -rf ./db.csv") def stop(self): tdSql.close() diff --git a/tests/pytest/util/types.py b/tests/pytest/util/types.py new file mode 100644 index 0000000000000000000000000000000000000000..218a4770269328a5ef7161cc56c0e0dc0c420f73 --- /dev/null +++ b/tests/pytest/util/types.py @@ -0,0 +1,38 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +from enum import Enum + +class TDSmlProtocolType(Enum): + ''' + Schemaless Protocol types + 0 - unknown + 1 - InfluxDB Line Protocol + 2 - OpenTSDB Telnet Protocl + 3 - OpenTSDB JSON Protocol + ''' + UNKNOWN = 0 + LINE = 1 + TELNET = 2 + JSON = 3 + +class TDSmlTimestampType(Enum): + NOT_CONFIGURED = 0 + HOUR = 1 + MINUTE = 2 + SECOND = 3 + MILLI_SECOND = 4 + MICRO_SECOND = 5 + NANO_SECOND = 6 + + diff --git a/tests/script/api/batchprepare.c b/tests/script/api/batchprepare.c index 72bb9471db8e2c3043306c332c608f1b4f1df836..e1db54e291ac6e02715a80ee852e5d78dc672a87 100644 --- a/tests/script/api/batchprepare.c +++ b/tests/script/api/batchprepare.c @@ -119,7 +119,11 @@ int stmt_scol_func1(TAOS_STMT *stmt) { printf("failed to execute insert statement.\n"); exit(1); } - + + int affectedRows = taos_stmt_affected_rows(stmt); + if (affectedRows != 100) { + printf("failed to insert 100 rows"); + } return 0; } diff --git a/tests/script/api/openTSDBTest.c b/tests/script/api/openTSDBTest.c index 2b9cf986f2f5278f1cfc1c8042d735423fdef312..70048e17fcaf6d609274d561b8d206490c53dd96 100644 --- a/tests/script/api/openTSDBTest.c +++ b/tests/script/api/openTSDBTest.c @@ -26,10 +26,12 @@ void verify_telnet_insert(TAOS* taos) { "stb0_1 1626006833639000000ns 4i8 host=\"host0\" interface=\"eth0\"", "stb0_2 1626006833639000000ns 4i8 host=\"host0\" interface=\"eth0\"", }; - code = taos_schemaless_insert(taos, lines0, 3, 1, NULL); + result = taos_schemaless_insert(taos, lines0, 3, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines0 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); /* timestamp */ char* lines1[] = { @@ -41,10 +43,12 @@ void verify_telnet_insert(TAOS* taos) { "stb1 1626006833651ms 6i8 host=\"host0\"", "stb1 0 7i8 host=\"host0\"", }; - code = taos_schemaless_insert(taos, lines1, 7, 1, NULL); + result = taos_schemaless_insert(taos, lines1, 7, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines1 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); /* metric value */ //tinyint @@ -52,40 +56,48 @@ void verify_telnet_insert(TAOS* taos) { "stb2_0 1626006833651ms -127i8 host=\"host0\"", "stb2_0 1626006833652ms 127i8 host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_0, 2, 1, NULL); + result = taos_schemaless_insert(taos, lines2_0, 2, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_0 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //smallint char* lines2_1[] = { "stb2_1 1626006833651ms -32767i16 host=\"host0\"", "stb2_1 1626006833652ms 32767i16 host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_1, 2, 1, NULL); + result = taos_schemaless_insert(taos, lines2_1, 2, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_1 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //int char* lines2_2[] = { "stb2_2 1626006833651ms -2147483647i32 host=\"host0\"", "stb2_2 1626006833652ms 2147483647i32 host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_2, 2, 1, NULL); + result = taos_schemaless_insert(taos, lines2_2, 2, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_2 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //bigint char* lines2_3[] = { "stb2_3 1626006833651ms -9223372036854775807i64 host=\"host0\"", "stb2_3 1626006833652ms 9223372036854775807i64 host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_3, 2, 1, NULL); + result = taos_schemaless_insert(taos, lines2_3, 2, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_3 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //float char* lines2_4[] = { @@ -100,10 +112,12 @@ void verify_telnet_insert(TAOS* taos) { "stb2_4 1626006833700ms 3.4E38f32 host=\"host0\"", "stb2_4 1626006833710ms -3.4E38f32 host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_4, 10, 1, NULL); + result = taos_schemaless_insert(taos, lines2_4, 10, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_4 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //double char* lines2_5[] = { @@ -119,10 +133,12 @@ void verify_telnet_insert(TAOS* taos) { "stb2_5 1626006833700ms -1.7E308f64 host=\"host0\"", "stb2_5 1626006833710ms 3.15 host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_5, 11, 1, NULL); + result = taos_schemaless_insert(taos, lines2_5, 11, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_5 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //bool char* lines2_6[] = { @@ -137,10 +153,12 @@ void verify_telnet_insert(TAOS* taos) { "stb2_6 1626006833690ms False host=\"host0\"", "stb2_6 1626006833700ms FALSE host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_6, 10, 1, NULL); + result = taos_schemaless_insert(taos, lines2_6, 10, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_6 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //binary char* lines2_7[] = { @@ -148,20 +166,24 @@ void verify_telnet_insert(TAOS* taos) { "stb2_7 1626006833620ms \"binary_val.:;,./?|+-=\" host=\"host0\"", "stb2_7 1626006833630ms \"binary_val.()[]{}<>\" host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_7, 3, 1, NULL); + result = taos_schemaless_insert(taos, lines2_7, 3, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_7 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //nchar char* lines2_8[] = { "stb2_8 1626006833610ms L\"nchar_val数值一\" host=\"host0\"", "stb2_8 1626006833620ms L\"nchar_val数值二\" host=\"host0\"" }; - code = taos_schemaless_insert(taos, lines2_8, 2, 1, NULL); + result = taos_schemaless_insert(taos, lines2_8, 2, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines2_8 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); /* tags */ //tag value types @@ -169,10 +191,12 @@ void verify_telnet_insert(TAOS* taos) { "stb3_0 1626006833610ms 1 t1=127i8 t2=32767i16 t3=2147483647i32 t4=9223372036854775807i64 t5=3.4E38f32 t6=1.7E308f64 t7=true t8=\"binary_val_1\" t9=L\"标签值1\"", "stb3_0 1626006833610ms 2 t1=-127i8 t2=-32767i16 t3=-2147483647i32 t4=-9223372036854775807i64 t5=-3.4E38f32 t6=-1.7E308f64 t7=false t8=\"binary_val_2\" t9=L\"标签值2\"" }; - code = taos_schemaless_insert(taos, lines3_0, 2, 1, NULL); + result = taos_schemaless_insert(taos, lines3_0, 2, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines3_0 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); //tag ID as child table name char* lines3_1[] = { @@ -180,10 +204,12 @@ void verify_telnet_insert(TAOS* taos) { "stb3_1 1626006833610ms 2 host=host2 iD=child_table2", "stb3_1 1626006833610ms 3 ID=child_table3 host=host3" }; - code = taos_schemaless_insert(taos, lines3_1, 3, 1, NULL); + result = taos_schemaless_insert(taos, lines3_1, 3, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("lines3_1 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); return; } @@ -214,10 +240,12 @@ void verify_json_insert(TAOS* taos) { } \ }"}; - code = taos_schemaless_insert(taos, message, 0, 2, NULL); + result = taos_schemaless_insert(taos, message, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload_0 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); char *message1[] = { "[ \ @@ -245,10 +273,12 @@ void verify_json_insert(TAOS* taos) { } \ ]"}; - code = taos_schemaless_insert(taos, message1, 0, 2, NULL); + result = taos_schemaless_insert(taos, message1, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload_1 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); char *message2[] = { "[ \ @@ -296,10 +326,12 @@ void verify_json_insert(TAOS* taos) { } \ } \ ]"}; - code = taos_schemaless_insert(taos, message2, 0, 2, NULL); + result = taos_schemaless_insert(taos, message2, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload_2 code: %d, %s.\n", code, tstrerror(code)); } + taos_free_result(result); cJSON *payload, *tags; @@ -320,12 +352,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload0_0 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //true payload = cJSON_CreateObject(); @@ -341,12 +375,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload0_1 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //false payload = cJSON_CreateObject(); @@ -362,12 +398,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload0_2 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //string payload = cJSON_CreateObject(); @@ -383,12 +421,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload0_3 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //timestamp 0 -> current time payload = cJSON_CreateObject(); @@ -404,12 +444,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload0_4 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); /* Nested format */ //timestamp @@ -433,12 +475,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload1_0 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //milleseconds payload = cJSON_CreateObject(); @@ -459,12 +503,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload1_1 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //microseconds payload = cJSON_CreateObject(); @@ -485,12 +531,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload1_2 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //now payload = cJSON_CreateObject(); @@ -511,12 +559,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload1_4 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //metric value cJSON *metric_val; @@ -543,12 +593,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_0 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //tinyint payload = cJSON_CreateObject(); @@ -573,12 +625,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_1 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //smallint payload = cJSON_CreateObject(); @@ -603,12 +657,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_2 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //int payload = cJSON_CreateObject(); @@ -633,12 +689,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_3 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //bigint payload = cJSON_CreateObject(); @@ -663,12 +721,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_4 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //float payload = cJSON_CreateObject(); @@ -693,12 +753,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_5 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //double payload = cJSON_CreateObject(); @@ -723,12 +785,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_6 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //binary payload = cJSON_CreateObject(); @@ -753,12 +817,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_7 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //nchar payload = cJSON_CreateObject(); @@ -783,12 +849,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload2_8 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); //tag value cJSON *tag; @@ -863,12 +931,14 @@ void verify_json_insert(TAOS* taos) { *payload_str = cJSON_Print(payload); //printf("%s\n", payload_str); - code = taos_schemaless_insert(taos, payload_str, 0, 2, NULL); + result = taos_schemaless_insert(taos, payload_str, 0, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); if (code) { printf("payload3_0 code: %d, %s.\n", code, tstrerror(code)); } free(*payload_str); cJSON_Delete(payload); + taos_free_result(result); } int main(int argc, char *argv[]) { diff --git a/tests/script/api/stmt.c b/tests/script/api/stmt.c index baf40c1421df1de4afcc8570288f642df067130a..f4fb9233a83f930a808eadf2135003d0e644c597 100644 --- a/tests/script/api/stmt.c +++ b/tests/script/api/stmt.c @@ -46,6 +46,7 @@ void taos_stmt_init_test() { } stmt = taos_stmt_init(taos); assert(stmt != NULL); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_close(stmt) == 0); printf("finish taos_stmt_init test\n"); } @@ -127,6 +128,7 @@ void taos_stmt_set_tbname_test() { assert(taos_stmt_set_tbname(stmt, name) == 0); free(name); free(stmt_sql); + assert(taos_stmt_affected_rows(stmt) == 0); taos_stmt_close(stmt); printf("finish taos_stmt_set_tbname test\n"); } @@ -166,6 +168,7 @@ void taos_stmt_set_tbname_tags_test() { free(stmt_sql); free(name); free(tags); + assert(taos_stmt_affected_rows(stmt) == 0); taos_stmt_close(stmt); printf("finish taos_stmt_set_tbname_tags test\n"); } @@ -194,8 +197,10 @@ void taos_stmt_set_sub_tbname_test() { assert(taos_stmt_set_sub_tbname(stmt, name) != 0); sprintf(name, "tb"); assert(taos_stmt_set_sub_tbname(stmt, name) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_load_table_info(taos, "super, tb") == 0); assert(taos_stmt_set_sub_tbname(stmt, name) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); free(name); free(stmt_sql); assert(taos_stmt_close(stmt) == 0); @@ -238,6 +243,7 @@ void taos_stmt_bind_param_test() { assert(taos_stmt_bind_param(stmt, params) != 0); assert(taos_stmt_set_tbname(stmt, "super") == 0); assert(taos_stmt_bind_param(stmt, params) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); free(params); free(stmt_sql); taos_stmt_close(stmt); @@ -249,6 +255,7 @@ void taos_stmt_bind_single_param_batch_test() { TAOS_STMT * stmt = NULL; TAOS_MULTI_BIND *bind = NULL; assert(taos_stmt_bind_single_param_batch(stmt, bind, 0) != 0); + assert(taos_stmt_affected_rows(stmt) == 0); printf("finish taos_stmt_bind_single_param_batch test\n"); } @@ -257,6 +264,7 @@ void taos_stmt_bind_param_batch_test() { TAOS_STMT * stmt = NULL; TAOS_MULTI_BIND *bind = NULL; assert(taos_stmt_bind_param_batch(stmt, bind) != 0); + assert(taos_stmt_affected_rows(stmt) == 0); printf("finish taos_stmt_bind_param_batch test\n"); } @@ -293,10 +301,14 @@ void taos_stmt_add_batch_test() { params[1].length = ¶ms[1].buffer_length; params[1].is_null = NULL; assert(taos_stmt_set_tbname(stmt, "super") == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_bind_param(stmt, params) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_add_batch(stmt) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); free(params); free(stmt_sql); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_close(stmt) == 0); printf("finish taos_stmt_add_batch test\n"); } @@ -317,10 +329,13 @@ void taos_stmt_execute_test() { stmt = taos_stmt_init(taos); assert(stmt != NULL); assert(taos_stmt_execute(stmt) != 0); + assert(taos_stmt_affected_rows(stmt) == 0); char *stmt_sql = calloc(1, 1000); sprintf(stmt_sql, "insert into ? values (?,?)"); assert(taos_stmt_prepare(stmt, stmt_sql, 0) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_execute(stmt) != 0); + assert(taos_stmt_affected_rows(stmt) == 0); TAOS_BIND *params = calloc(2, sizeof(TAOS_BIND)); int64_t ts = (int64_t)1591060628000; params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; @@ -335,11 +350,17 @@ void taos_stmt_execute_test() { params[1].length = ¶ms[1].buffer_length; params[1].is_null = NULL; assert(taos_stmt_set_tbname(stmt, "super") == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_execute(stmt) != 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_bind_param(stmt, params) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_execute(stmt) != 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_add_batch(stmt) == 0); + assert(taos_stmt_affected_rows(stmt) == 0); assert(taos_stmt_execute(stmt) == 0); + assert(taos_stmt_affected_rows(stmt) == 1); free(params); free(stmt_sql); assert(taos_stmt_close(stmt) == 0); @@ -542,4 +563,4 @@ int main(int argc, char *argv[]) { test_api_reliability(); test_query(); return 0; -} \ No newline at end of file +} diff --git a/tests/script/api/stmtTest.c b/tests/script/api/stmtTest.c index 9595fe5b2d72e3291959828badf45abc2f7cb71e..b81e96ba4477bf4f43e0a179d46169b0c8d23558 100644 --- a/tests/script/api/stmtTest.c +++ b/tests/script/api/stmtTest.c @@ -229,6 +229,14 @@ int main(int argc, char *argv[]) { PRINT_SUCCESS printf("Successfully execute insert statement.\n"); + int affectedRows = taos_stmt_affected_rows(stmt); + printf("Successfully inserted %d rows\n", affectedRows); + if (affectedRows != 10) { + PRINT_ERROR + printf("failed to insert 10 rows\n"); + exit(EXIT_FAILURE); + } + taos_stmt_close(stmt); for (int i = 0; i < 10; i++) { check_result(taos, i, 1); diff --git a/tests/script/general/compute/csum2.sim b/tests/script/general/compute/csum2.sim index 506070ae369ccb4c1d2bc28d149c7126079a2b54..48de71df394a6f520ede1a2540ad78e215c57075 100644 --- a/tests/script/general/compute/csum2.sim +++ b/tests/script/general/compute/csum2.sim @@ -78,7 +78,9 @@ print ===> $data11 if $data11 != 1.000000000 then return -1 endi + sql_error select csum(c7) from $tb +sql_error select csum(c7) from $tb group by c8 sql_error select csum(c8) from $tb sql_error select csum(c9) from $tb sql_error select csum(ts) from $tb diff --git a/tests/script/general/compute/mavg2.sim b/tests/script/general/compute/mavg2.sim index 60b170e270505b7c3e8d2ee174a4e3b8a4ad223d..55c1fbb29fa276e0c58eb592d910dce8f01da558 100644 --- a/tests/script/general/compute/mavg2.sim +++ b/tests/script/general/compute/mavg2.sim @@ -80,6 +80,7 @@ if $data11 != 1.500000000 then endi sql_error select mavg(c7,2) from $tb sql_error select mavg(c8,2) from $tb +sql_error select mavg(c8,2) from $tb order by c7 sql_error select mavg(c9,2) from $tb sql_error select mavg(ts,2) from $tb sql_error select mavg(c1,2), mavg(c2,2) from $tb diff --git a/tests/script/general/parser/udf_dll.sim b/tests/script/general/parser/udf_dll.sim index 7168e0a5ddf5502170e6bb22f30b10621795a568..61bf5fee6e54d02ccc08218102a43a37821fdd30 100644 --- a/tests/script/general/parser/udf_dll.sim +++ b/tests/script/general/parser/udf_dll.sim @@ -452,6 +452,7 @@ if $data31 != 2 then return -1 endi +sql_error select add_one(f1) from tb1 order by ts desc; sql select add_one(f1) from tb1 limit 2; if $rows != 2 then diff --git a/tests/script/general/parser/udf_dll_stable.sim b/tests/script/general/parser/udf_dll_stable.sim index 15becaab22476d12829abc62db4de4f914eef271..cd1dbc8b5374779d13decde5bf8a0fce48d90f0a 100644 --- a/tests/script/general/parser/udf_dll_stable.sim +++ b/tests/script/general/parser/udf_dll_stable.sim @@ -10,9 +10,10 @@ sql connect print ======================== dnode1 start sql create function add_one as '/tmp/add_one.so' outputtype int; +sql create function add_one_64232 as '/tmp/add_one_64232.so' outputtype int; sql create aggregate function sum_double as '/tmp/sum_double.so' outputtype int; sql show functions; -if $rows != 2 then +if $rows != 3 then return -1 endi @@ -1154,6 +1155,93 @@ if $data61 != 22 then return -1 endi +sql_error select sum_double(f1),add_one(f1) from tb1 where ts>="2021-03-23 17:00:00.000" and ts<="2021-03-24 20:00:00.000" interval (1h) sliding (30m); + +sql select add_one(f1) from (select * from tb1); +if $rows != 7 then + return -1 +endi + +if $data00 != 2 then + return -1 +endi +if $data10 != 3 then + return -1 +endi +if $data20 != 4 then + return -1 +endi +if $data30 != 5 then + return -1 +endi +if $data40 != 6 then + return -1 +endi +if $data50 != 7 then + return -1 +endi +if $data60 != 8 then + return -1 +endi + +sql select add_one(ff1) from (select add_one(f1) as ff1 from tb1); +if $rows != 7 then + return -1 +endi + +if $data00 != 3 then + return -1 +endi +if $data10 != 4 then + return -1 +endi +if $data20 != 5 then + return -1 +endi +if $data30 != 6 then + return -1 +endi +if $data40 != 7 then + return -1 +endi +if $data50 != 8 then + return -1 +endi +if $data60 != 9 then + return -1 +endi + +sql_error select add_one(f1),sub_one(f1) from tb1; + + +sql create table taaa (ts timestamp, f1 bigint); +sql insert into taaa values (now, 1); +sleep 100 +sql insert into taaa values (now, 10); +sleep 100 +sql insert into taaa values (now, 1000); +sleep 100 +sql insert into taaa values (now, 100); + +sql select add_one_64232(f1) from taaa; +if $rows != 4 then + print $rows + return -1 +endi + +if $data00 != 2 then + return -1 +endi +if $data10 != 11 then + return -1 +endi +if $data20 != 1001 then + return -1 +endi +if $data30 != 101 then + return -1 +endi + system sh/exec.sh -n dnode1 -s stop -x SIGINT diff --git a/tests/script/jenkins/basic.txt b/tests/script/jenkins/basic.txt index a9b2764495095b86c55f56c52c55c74f4e545e96..ae47241ac4b102bc4d788a5bce74d716a4d20b5b 100644 --- a/tests/script/jenkins/basic.txt +++ b/tests/script/jenkins/basic.txt @@ -415,4 +415,8 @@ cd ../../../debug; make ./test.sh -f general/parser/last_cache.sim ./test.sh -f unique/big/balance.sim +./test.sh -f general/parser/udf.sim +./test.sh -f general/parser/udf_dll.sim +./test.sh -f general/parser/udf_dll_stable.sim + #======================b7-end=============== diff --git a/tests/script/sh/abs_max.c b/tests/script/sh/abs_max.c index 2983ad1a43d60494f75d32978ca51c5e385fa0b2..e9f11feb414363eb0e741c722f4d4dd79b87e81e 100644 --- a/tests/script/sh/abs_max.c +++ b/tests/script/sh/abs_max.c @@ -38,6 +38,8 @@ void abs_max(char* data, short itype, short ibytes, int numOfRows, long long* ts *(long *)dataOutput=r; printf("abs_max out, dataoutput:%ld, numOfOutput:%d\n", *(long *)dataOutput, *numOfOutput); + } else { + *numOfOutput=0; } } @@ -47,7 +49,7 @@ void abs_max_finalize(char* dataOutput, char* interBuf, int* numOfOutput, SUdfIn int i; int r = 0; printf("abs_max_finalize dataoutput:%p:%d, numOfOutput:%d, buf:%p\n", dataOutput, *dataOutput, *numOfOutput, buf); - *numOfOutput=1; + printf("abs_max finalize, dataoutput:%ld, numOfOutput:%d\n", *(long *)dataOutput, *numOfOutput); } diff --git a/tests/script/sh/add_one_64232.c b/tests/script/sh/add_one_64232.c new file mode 100644 index 0000000000000000000000000000000000000000..8db87d049d607a7fed60580dcdaf682dcca944b4 --- /dev/null +++ b/tests/script/sh/add_one_64232.c @@ -0,0 +1,33 @@ +#include +#include +#include + +typedef struct SUdfInit{ + int maybe_null; /* 1 if function can return NULL */ + int decimals; /* for real functions */ + long long length; /* For string functions */ + char *ptr; /* free pointer for function data */ + int const_item; /* 0 if result is independent of arguments */ +} SUdfInit; + +void add_one_64232(char* data, short itype, short ibytes, int numOfRows, long long* ts, char* dataOutput, char* interBUf, char* tsOutput, + int* numOfOutput, short otype, short obytes, SUdfInit* buf) { + int i; + int r = 0; + printf("add_one_64232 input data:%p, type:%d, rows:%d, ts:%p,%lld, dataoutput:%p, tsOutput:%p, numOfOutput:%p, buf:%p\n", data, itype, numOfRows, ts, *ts, dataOutput, tsOutput, numOfOutput, buf); + if (itype == 5) { + for(i=0;i +#include +#include + +typedef struct SUdfInit{ + int maybe_null; /* 1 if function can return NULL */ + int decimals; /* for real functions */ + long long length; /* For string functions */ + char *ptr; /* free pointer for function data */ + int const_item; /* 0 if result is independent of arguments */ +} SUdfInit; + +void sub_one(char* data, short itype, short ibytes, int numOfRows, long long* ts, char* dataOutput, char* interBUf, char* tsOutput, + int* numOfOutput, short otype, short obytes, SUdfInit* buf) { + int i; + int r = 0; + printf("sub_one input data:%p, type:%d, rows:%d, ts:%p,%lld, dataoutput:%p, tsOutput:%p, numOfOutput:%p, buf:%p\n", data, itype, numOfRows, ts, *ts, dataOutput, tsOutput, numOfOutput, buf); + if (itype == 4) { + for(i=0;ifileName, rest); simLogSql(buf, true); - char * lines[] = {rest}; - int32_t ret = taos_schemaless_insert(script->taos, lines, 1, 0, "ns"); - if (ret == TSDB_CODE_SUCCESS) { + char* lines[] = {rest}; + TAOS_RES *result = taos_schemaless_insert(script->taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + int32_t code = taos_errno(result); + if (code == TSDB_CODE_SUCCESS) { simDebug("script:%s, taos:%p, %s executed. success.", script->fileName, script->taos, rest); script->linePos++; - return true; + ret = true; } else { - sprintf(script->error, "lineNum: %d. line: %s failed, ret:%d:%s", line->lineNum, rest, - ret & 0XFFFF, tstrerror(ret)); - return false; + sprintf(script->error, "lineNum: %d. line: %s failed, code:%d:%s", line->lineNum, rest, + code & 0XFFFF, taos_errstr(result)); + ret = false; } + taos_free_result(result); + return ret; } bool simExecuteLineInsertErrorCmd(SScript *script, char *rest) { + bool ret; char buf[TSDB_MAX_BINARY_LEN]; simVisuallizeOption(script, rest, buf); @@ -1107,14 +1112,17 @@ bool simExecuteLineInsertErrorCmd(SScript *script, char *rest) { simInfo("script:%s, %s", script->fileName, rest); simLogSql(buf, true); char * lines[] = {rest}; - int32_t ret = taos_schemaless_insert(script->taos, lines, 1, 0, "ns"); - if (ret == TSDB_CODE_SUCCESS) { + TAOS_RES *result = taos_schemaless_insert(script->taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + int32_t code = taos_errno(result); + if (code == TSDB_CODE_SUCCESS) { sprintf(script->error, "script:%s, taos:%p, %s executed. expect failed, but success.", script->fileName, script->taos, rest); script->linePos++; - return false; + ret = false; } else { - simDebug("lineNum: %d. line: %s failed, ret:%d:%s. Expect failed, so success", line->lineNum, rest, - ret & 0XFFFF, tstrerror(ret)); - return true; + simDebug("lineNum: %d. line: %s failed, code:%d:%s. Expect failed, so success", line->lineNum, rest, + code & 0XFFFF, taos_errstr(result)); + ret = true; } + taos_free_result(result); + return ret; }