You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by ji...@apache.org on 2026/06/09 07:06:51 UTC
(iotdb) branch master updated: Refactor/cpp client sdk (#17801)
This is an automated email from the ASF dual-hosted git repository.
jt2594838 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new faba002feb9 Refactor/cpp client sdk (#17801)
faba002feb9 is described below
commit faba002feb9a95a853b6dbec14792e9a42aa1624
Author: Hongzhi Gao <76...@qq.com>
AuthorDate: Tue Jun 9 15:06:44 2026 +0800
Refactor/cpp client sdk (#17801)
* Refactor client-cpp build to single CMake entry with portable third-party cache
Move C++ client dependency resolution and compilation into one top-level
CMakeLists with Fetch* modules, cache tarballs under third-party/<os>/ for
offline copy-the-repo workflows, and slim the Maven POM to a CMake wrapper.
Skip server CI when only client-cpp changes; gate multi-language-client jobs
by language via paths-filter.
* Fix macOS client-cpp CI bison version and add source-build workflow
Install Homebrew bison on macOS package/IT runners so Thrift 0.21.0 builds
(%code requires Bison 2.4+). Add client-cpp-source-build workflow that uses a
minimal toolchain and online CMake fetch to verify zero-to-build compilation.
* Fix client-cpp-source-build: install clang-format-17 on all runners
Align Linux/macOS/Windows toolchain setup with client-cpp-package so
Spotless clang-format check during mvn package succeeds.
* Skip Spotless in client-cpp-source-build; drop clang-format install
Source-build workflow focuses on minimal-toolchain CMake fetch; pass
-Dspotless.skip=true instead of installing clang-format on runners.
* Refactor C++ client SDK: isolate Thrift and ship Windows DLL.
Reorganize sources into include/session/rpc with PIMPL so public headers no longer pull in Thrift or Boost. Embed Thrift in iotdb_session on all platforms; on Windows build a /MD shared library with import lib. Update examples, CI verification, and documentation for the slimmer SDK layout.
* fix(client-cpp): include ctime for std::tm in Common.h
Fixes Linux CI build where convertToTimestamp/int32ToDate declarations require std::tm from <ctime> (C++11).
* fix(client-cpp): CMake 4 Thrift policy and Session.cpp cstring
Pass CMAKE_POLICY_VERSION_MINIMUM=3.5 when configuring Thrift 0.21 on CMake 4.x (VS2026 CI). Include <cstring> in Session.cpp for memcpy/strlen/strstr on strict Linux builds.
* fix(client-cpp): Linux Thrift link and default Boost 1.84
Drop --whole-archive on Linux to avoid libgcc morestack duplicate symbols; build Thrift with -fno-split-stack. Bump default Boost to 1.84.0 for modern Clang on macOS CI.
* fix(client-cpp): Linux Thrift link and macOS Boost 1.84
Linux: keep --whole-archive for Thrift in libiotdb_session.so but add --allow-multiple-definition to avoid libgcc morestack duplicate symbols. macOS: default BOOST_VERSION to 1.84.0 for modern Clang enum checks (other platforms stay on 1.60.0).
* ci(client-cpp): multi-toolchain package matrix for release zips
Add per-classifier SDK packages (glibc 2.17 on CentOS 7, Windows VS2015-2026), workflow_dispatch variant filter, and documentation for choosing the right zip.
* fix(ci): write windows_matrix to GITHUB_OUTPUT without invalid format
* fix(ci): scope C++ triggers, glibc231 arm64, CentOS7 and VS2015 boost
- paths-ignore C++ workflows/scripts on Java IT jobs; narrow C++ path filters (no root pom.xml)
- aarch64 package on Ubuntu 20.04 container (linux-aarch64-glibc231)
- CentOS7 script: vault repos, Adoptium API JDK, devtoolset deps
- VS2015/2017: pin boost-msvc-14.2/14.1 versions instead of missing boost-msvc-14.0
* fix(ci): docker-based glibc builds, CMake 3.28 on arm64, drop VS2015
- glibc217/aarch64: checkout on host, build inside docker (fixes CentOS7 + Node 24)
- aarch64: install Kitware CMake 3.28 (ARCHIVE_EXTRACT needs 3.18+)
- Remove VS2015 package matrix and related docs
* fix(client-cpp): flatten package zip name and layout
- Zip: client-cpp-<version>-<classifier>.zip (remove redundant -cpp- segment)
- Root folder client-cpp-<version>-<classifier>/ with include/ and lib/ inside
- Update examples (strip one dir on unpack), distribution assembly, CI artifact paths
- CentOS7 SCLo vault mirror fix; chown workspace after docker builds
* fix(ci): pin CentOS7 SCLo repos to vault 7.9.2009 for glibc217
centos-sclo-sclo baseurl with releasever=7 404s on vault; rewrite SCLo repo files and refresh yum cache before devtoolset-8 install.
* fix(ci): build glibc217 in manylinux2014 job container
Replace docker run on ubuntu-22.04 with job-level container quay.io/pypa/manylinux2014_x86_64 and checkout@v4, matching PyPA manylinux CI style.
* fix(ci): host checkout + docker manylinux2014 for glibc217
Job container cannot run Node-based actions on glibc 2.17. Run checkout/cache on ubuntu-latest and build inside manylinux2014 via docker run; use preinstalled devtoolset-10 in the image.
* fix(ci): avoid SIGPIPE 141 from head/tail under pipefail
Replace ldd | head -1 with sed -n 1p and find | head -1 with find -quit so glibc checks do not fail after a successful build.
* fix(client-cpp): force x64 for Visual Studio Windows packages
VS2017 generator defaults to Win32; pass -DCMAKE_GENERATOR_PLATFORM=x64 on Windows via Maven profile. Add CI PE check that iotdb_session.dll is x64.
* fix(ci): build linux-aarch64 glibc217 with manylinux2014
Use manylinux2014_aarch64 and the shared packaging script instead of Ubuntu 20.04 glibc231. Extend the script for aarch64 CMake/JDK arch and classifier auto-detection. Update docs and remove the obsolete ubuntu20-arm script.
* fix(client-cpp): PR review follow-ups for SDK branch
Guard checkTemplateExists against a null dataset, document DataIterator lifetime, correct README Maven vs CMake option names, drop unused IotdbResolveTarball.cmake, and skip server CI when only multi-language-client workflow changes.
* chore(ci): slim manylinux glibc217 package path
Rename the Linux packaging helper to a manylinux-specific script, drop unused CentOS7 fallback branches, and keep only build plus GLIBC<=2.17 verification steps. Also add concise C++ workflow comments and unify client-cpp CMake minimum version to 3.15.
* refactor(client-cpp): rename IoTDBDate and move tests
Rename public Date type from IoTdbDate to IoTDBDate across headers, RPC/session code, and ITs. Move tests from src/test to a top-level test directory and update CMake, Maven, and README paths accordingly.
* example: merge C Session demos into client-cpp-example
Move tree_example.c and table_example.c into client-cpp-example, build them from the shared CMake entry, and update EN/ZH docs. Remove the standalone client-c-example module and drop it from the with-cpp profile.
* style(client-cpp): apply spotless to C examples
* fix(ci): use curl for downloads in manylinux glibc217 script
* fix(ci): use curl directly in manylinux glibc217 script
* fix(client-cpp): centralize SessionConfig defaults and align fetchSize with Java
* ci(client-cpp): add glibc224 packages with explicit CXX11 ABI on manylinux_2_24
Add linux-*-glibc224 zips built on manylinux_2_24 with -D_GLIBCXX_USE_CXX11_ABI=1 wired through Session and Thrift. Document glibc224 as recommended over glibc217 for modern distros.
* fix(client-cpp): correct glibc224 CXX11 ABI check and Maven flag wiring
* fix(client-cpp): use CMake ABI tag file instead of nm for glibc224 CI
* ci(client-cpp): remove source-build workflow
Drop client-cpp-source-build.yml; packaging is covered by client-cpp-package.yml.
* fix(ci): harden glibc checks and drop removed source-build workflow refs
Fail manylinux package scripts when GLIBC symbols cannot be parsed, and remove stale client-cpp-source-build.yml path triggers left after that workflow was deleted.
* fix(client-cpp): flatten package zip layout and add SHA512 checksums
Unpack directly to include/ and lib/ at zip root, generate .sha512 via checksum-maven-plugin, and upload checksums from the package workflow.
* fix sessionIT.cpp compilation
* fix(client-cpp): download Catch2 at build time instead of vendoring
Maven wget in generate-test-resources; CMake file(DOWNLOAD) fallback; remove test/catch2/catch.hpp from source tree.
* fix(client-cpp): download Catch2 before CMake compile phase
Run wget in generate-resources (not generate-test-resources, which runs after compile). CMake also downloads catch.hpp when the header is still missing.
* refactor(client-cpp): move SessionPool implementation into session sources
Place SessionPool.cpp under src/session to align with the existing source layout while keeping public headers in src/include.
* refactor(client-cpp): ship SDK tarballs with cmake/pkgconfig and bundled examples
Rename packages to iotdb-session-cpp-* classifiers, move examples into
client-cpp, drop glibc2.24 release matrix, and add CI smoke tests that build
and run examples against a standalone IoTDB server.
* fix(ci): normalize RUNNER_TEMP for Windows tar extract in cpp package smoke test
Git Bash on Windows runners passes D:\a\_temp to tar -C, which MSYS tar cannot
open; convert via cygpath -u before unpack and example build paths.
* chore(client-cpp): trim examples README and formatDatetime dead code
Simplify the SDK layout note in examples README and drop unused-parameter
casts for precision/zoneId in formatDatetime.
* fix(ci): locate Windows standalone scripts under sbin/windows in cpp smoke test
Distribution packages start/stop batch files at sbin/windows/, matching
client-cpp pom.xml; normalize GITHUB_WORKSPACE via cygpath for find on Windows.
* fix(ci): start IoTDB on Windows with cmd //c and wait for RPC port 6667
Git Bash mangles cmd.exe /c so start-standalone.bat never ran; use //c with
quoted paths and poll Test-NetConnection before running packaged examples.
* fix(ci): upload cpp SDK tarball before packaged example smoke tests
Resolve and upload artifacts on macOS and Windows immediately after packaging
so failed verify steps still retain the tarball; reuse pkg path in verify step.
* refactor(client-cpp): use zip for SDK release packages instead of tar.gz
Align Maven assembly, distribution bundle, CI resolve/upload, smoke-test
unpack (unzip), and docs on iotdb-session-cpp-<version>-<classifier>.zip.
* fix(ci): correct Git Bash quoting when starting IoTDB on Windows
Nested escaped quotes made cmd.exe treat the bat path as the command name; use //c with a single quoted path. Add a local script to replay verify steps.
* fix(ci): build packaged examples as x64 for VS2017 on Windows
Visual Studio 15/16 generators default to Win32 while the SDK is x64, causing LNK1112. Pass -A x64 in the verify step and set CMAKE_GENERATOR_PLATFORM in examples CMakeLists.
* Improve C++ session package documentation
* Set CXX11 ABI for glibc217 C++ package
* Fix C++ SDK CXX11 ABI propagation
* Fix C++ SDK package ABI verification
* Fix glibc217 C++ client ABI build
* Use link test for glibc217 C++ ABI check
* Rebuild C++ client when ABI changes
* Fail C++ client build on ABI mismatch
* Use old libstdc++ ABI for glibc217 package
* Use manylinux_2_28 for C++ client packages
* chore(ci): remove unused local Windows C++ example debug scripts
These scripts were one-off helpers for VS2017 x64 CI fixes; verification
logic already lives inline in client-cpp-package.yml.
* Fix MSVC debug C++ client build
* Document C++ client debug builds
* Address C++ client packaging review comments
---
.github/scripts/package-client-cpp-manylinux228.sh | 140 +
.github/workflows/client-cpp-package.yml | 465 +-
.github/workflows/cluster-it-1c1d.yml | 8 +
.github/workflows/cluster-it-1c1d1a.yml | 8 +
.github/workflows/cluster-it-1c3d.yml | 8 +
.github/workflows/compile-check.yml | 8 +
.github/workflows/dependency-check.yml | 8 +
.github/workflows/multi-language-client.yml | 66 +-
.github/workflows/pipe-it.yml | 8 +
.github/workflows/sonar-codecov.yml | 8 +
.github/workflows/table-cluster-it-1c1d.yml | 8 +
.github/workflows/table-cluster-it-1c3d.yml | 8 +
.github/workflows/unit-test.yml | 8 +
.gitignore | 10 +-
CONTRIBUTING.md | 3 -
distribution/pom.xml | 66 +-
distribution/src/assembly/client-cpp.xml | 6 +-
example/client-c-example/README.md | 68 -
example/client-c-example/pom.xml | 150 -
example/client-c-example/src/table_example.c | 152 -
example/client-c-example/src/tree_example.c | 114 -
example/client-cpp-example/pom.xml | 200 -
example/client-cpp-example/src/CMakeLists.txt | 151 -
example/pom.xml | 9 -
iotdb-client/client-cpp/CMakeLists.txt | 305 +
iotdb-client/client-cpp/README.md | 613 +-
iotdb-client/client-cpp/README_zh.md | 277 +
iotdb-client/client-cpp/cmake/CheckCxx11Abi.cmake | 59 +
iotdb-client/client-cpp/cmake/FetchBoost.cmake | 130 +
.../client-cpp/cmake/FetchBuildTools.cmake | 266 +
iotdb-client/client-cpp/cmake/FetchOpenSSL.cmake | 121 +
iotdb-client/client-cpp/cmake/FetchThrift.cmake | 278 +
.../client-cpp/cmake/GenerateThriftSources.cmake | 126 +
.../client-cpp/cmake/iotdb-session-config.cmake.in | 56 +
iotdb-client/client-cpp/cmake/iotdb-session.pc.in | 26 +
.../examples}/AlignedTimeseriesSessionExample.cpp | 25 +-
iotdb-client/client-cpp/examples/CMakeLists.txt | 187 +
.../client-cpp/examples}/MultiSvrNodeClient.cpp | 8 +-
iotdb-client/client-cpp/examples/README.md | 260 +
iotdb-client/client-cpp/examples/README_zh.md | 253 +
.../client-cpp/examples}/SessionExample.cpp | 33 +-
.../examples}/TableModelSessionExample.cpp | 0
iotdb-client/client-cpp/examples/table_example.c | 153 +
iotdb-client/client-cpp/examples/tree_example.c | 114 +
iotdb-client/client-cpp/pom.xml | 370 +-
.../client-cpp/src/assembly/client-cpp.xml | 69 +-
.../package-metadata/third_party/DEPENDENCIES.md | 42 +-
.../src/{main => include}/AbstractSessionBuilder.h | 10 +-
.../client-cpp/src/{main => include}/Column.h | 0
.../src/{main => include}/ColumnDecoder.h | 0
.../client-cpp/src/{main => include}/Common.h | 146 +-
iotdb-client/client-cpp/src/include/Date.h | 74 +
.../client-cpp/src/{main => include}/DeviceID.h | 0
.../{main/TableSession.h => include/Endpoint.h} | 41 +-
.../src/{main/TableSession.h => include/Export.h} | 38 +-
iotdb-client/client-cpp/src/include/Optional.h | 77 +
.../client-cpp/src/{main => include}/Session.h | 328 +-
.../src/{main => include}/SessionBuilder.h | 0
.../client-cpp/src/{main => include}/SessionC.h | 0
.../TableSession.h => include/SessionConfig.h} | 38 +-
.../client-cpp/src/include/SessionDataSet.h | 124 +
.../client-cpp/src/{main => include}/SessionPool.h | 0
.../src/{main/TableSession.h => include/Status.h} | 34 +-
.../src/{main => include}/TableSession.h | 0
.../src/{main => include}/TableSessionBuilder.h | 0
.../client-cpp/src/{main => include}/TsBlock.h | 0
iotdb-client/client-cpp/src/main/CMakeLists.txt | 90 -
iotdb-client/client-cpp/src/main/SessionDataSet.h | 124 -
.../src/{main => rpc}/IoTDBRpcDataSet.cpp | 74 +-
.../client-cpp/src/{main => rpc}/IoTDBRpcDataSet.h | 51 +-
.../client-cpp/src/{main => rpc}/NodesSupplier.cpp | 11 +-
.../client-cpp/src/{main => rpc}/NodesSupplier.h | 9 +-
iotdb-client/client-cpp/src/rpc/RpcCommon.cpp | 214 +
iotdb-client/client-cpp/src/rpc/RpcCommon.h | 81 +
.../src/{main => rpc}/SessionConnection.cpp | 34 +-
.../src/{main => rpc}/SessionConnection.h | 20 +-
.../client-cpp/src/rpc/SessionDataSetFactory.h | 42 +
iotdb-client/client-cpp/src/rpc/SessionImpl.h | 231 +
.../src/{main => rpc}/ThriftConnection.cpp | 16 +-
.../src/{main => rpc}/ThriftConnection.h | 4 +-
iotdb-client/client-cpp/src/rpc/ThriftConvert.cpp | 61 +
.../{main/TableSession.h => rpc/ThriftConvert.h} | 40 +-
.../client-cpp/src/{main => session}/Column.cpp | 0
.../src/{main => session}/ColumnDecoder.cpp | 0
.../client-cpp/src/{main => session}/Common.cpp | 224 +-
iotdb-client/client-cpp/src/session/Date.cpp | 63 +
.../client-cpp/src/{main => session}/Session.cpp | 490 +-
.../client-cpp/src/{main => session}/SessionC.cpp | 0
.../client-cpp/src/session/SessionDataSet.cpp | 320 +
.../src/{main => session}/SessionPool.cpp | 0
.../src/{main => session}/TableSession.cpp | 0
.../client-cpp/src/{main => session}/TsBlock.cpp | 0
iotdb-client/client-cpp/src/test/CMakeLists.txt | 152 -
iotdb-client/client-cpp/src/test/catch2/catch.hpp | 17974 -------------------
iotdb-client/client-cpp/test/CMakeLists.txt | 104 +
iotdb-client/client-cpp/test/catch2/.gitignore | 4 +
.../client-cpp/{src => }/test/cpp/sessionCIT.cpp | 0
.../{src => }/test/cpp/sessionCRelationalIT.cpp | 0
.../client-cpp/{src => }/test/cpp/sessionIT.cpp | 7 +-
.../{src => }/test/cpp/sessionRelationalIT.cpp | 7 +-
iotdb-client/client-cpp/{src => }/test/main.cpp | 0
.../client-cpp/{src => }/test/main_Relational.cpp | 0
iotdb-client/client-cpp/{src => }/test/main_c.cpp | 0
.../{src => }/test/main_c_Relational.cpp | 0
iotdb-client/client-cpp/third-party/.gitignore | 7 +
iotdb-client/client-cpp/third-party/README.md | 75 +
.../client-cpp/third-party/linux/.gitignore | 2 +
iotdb-client/client-cpp/third-party/mac/.gitignore | 2 +
.../client-cpp/third-party/windows/.gitignore | 2 +
109 files changed, 6161 insertions(+), 20735 deletions(-)
diff --git a/.github/scripts/package-client-cpp-manylinux228.sh b/.github/scripts/package-client-cpp-manylinux228.sh
new file mode 100755
index 00000000000..773e835d7ef
--- /dev/null
+++ b/.github/scripts/package-client-cpp-manylinux228.sh
@@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with this
+# work for additional information regarding copyright ownership. The ASF
+# licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Build client-cpp in manylinux_2_28 and verify max required GLIBC symbol <= 2.28.
+set -euxo pipefail
+
+MACHINE=$(uname -m)
+case "${MACHINE}" in
+ x86_64)
+ CMAKE_PKG_ARCH=linux-x86_64
+ JDK_API_ARCH=linux/x64
+ DEFAULT_CLASSIFIER=linux-x86_64-glibc2.28
+ ;;
+ aarch64)
+ CMAKE_PKG_ARCH=linux-aarch64
+ JDK_API_ARCH=linux/aarch64
+ DEFAULT_CLASSIFIER=linux-aarch64-glibc2.28
+ ;;
+ *)
+ echo "Unsupported architecture: ${MACHINE}" >&2
+ exit 1
+ ;;
+esac
+
+PACKAGE_CLASSIFIER="${PACKAGE_CLASSIFIER:-${DEFAULT_CLASSIFIER}}"
+
+CMAKE_VERSION=3.28.4
+CMAKE_DIR="/opt/cmake-${CMAKE_VERSION}"
+if [[ ! -x "${CMAKE_DIR}/bin/cmake" ]]; then
+ curl -fsSL -o /tmp/cmake.tar.gz "https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-${CMAKE_PKG_ARCH}.tar.gz"
+ rm -rf "${CMAKE_DIR}"
+ mkdir -p /opt
+ tar xf /tmp/cmake.tar.gz -C /opt
+ mv "/opt/cmake-${CMAKE_VERSION}-${CMAKE_PKG_ARCH}" "${CMAKE_DIR}"
+fi
+
+JAVA_HOME=/opt/jdk-17
+if [[ ! -x "${JAVA_HOME}/bin/java" ]]; then
+ curl -fsSL -o /tmp/jdk17.tar.gz "https://api.adoptium.net/v3/binary/latest/17/ga/${JDK_API_ARCH}/jdk/hotspot/normal/eclipse?project=jdk"
+ rm -rf /opt/jdk-17*
+ mkdir -p /opt
+ tar xf /tmp/jdk17.tar.gz -C /opt
+ JAVA_HOME=$(find /opt -maxdepth 1 -type d -name 'jdk-17*' -print -quit)
+ ln -sfn "${JAVA_HOME}" /opt/jdk-17
+ JAVA_HOME=/opt/jdk-17
+fi
+
+export PATH="${CMAKE_DIR}/bin:${JAVA_HOME}/bin:${PATH}"
+export JAVA_HOME
+
+gcc --version
+c++ --version
+gcc_major=$(gcc -dumpversion | cut -d. -f1)
+if (( gcc_major < 14 )); then
+ echo "ERROR: GCC >= 14 is required; got $(gcc -dumpversion)"
+ exit 1
+fi
+cmake --version
+java -version
+
+cd "${GITHUB_WORKSPACE:?GITHUB_WORKSPACE is not set}"
+./mvnw clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Dspotless.skip=true \
+ -Dclient.cpp.package.classifier="${PACKAGE_CLASSIFIER}"
+
+SO="iotdb-client/client-cpp/target/install/lib/libiotdb_session.so"
+test -f "${SO}"
+
+echo "=== Build host glibc ==="
+ldd --version 2>&1 | sed -n '1p'
+
+echo "=== Highest GLIBC_* symbols in libiotdb_session.so ==="
+objdump -T "${SO}" | grep GLIBC_ | sed "s/.*GLIBC_/GLIBC_/" | sort -Vu | tail -10
+
+max_glibc=$(objdump -T "${SO}" | grep -oE "GLIBC_[0-9.]+" | sed "s/GLIBC_//" | sort -t. -k1,1n -k2,2n -k3,3n | tail -1)
+echo "max_glibc=${max_glibc}"
+
+if [[ -z "${max_glibc}" ]]; then
+ echo "ERROR: could not determine max GLIBC version from ${SO}"
+ exit 1
+fi
+
+if awk -v max="${max_glibc}" "BEGIN { exit !(max > 2.28) }"; then
+ echo "ERROR: libiotdb_session.so requires glibc > 2.28 (max=${max_glibc})"
+ exit 1
+fi
+
+echo "glibc compatibility check passed (max=${max_glibc} <= 2.28)"
+
+echo "=== Example package build/link/run smoke test ==="
+PKG_ZIP=$(find "${GITHUB_WORKSPACE}/iotdb-client/client-cpp/target" -maxdepth 1 -type f -name "iotdb-session-cpp-*-${PACKAGE_CLASSIFIER}.zip" -print -quit)
+if [[ -z "${PKG_ZIP}" ]]; then
+ echo "ERROR: could not find package zip for ${PACKAGE_CLASSIFIER}"
+ exit 1
+fi
+PKG_UNPACK="/tmp/client-cpp-package-smoke-glibc228"
+rm -rf "${PKG_UNPACK}"
+mkdir -p "${PKG_UNPACK}"
+unzip -q -o "${PKG_ZIP}" -d "${PKG_UNPACK}"
+PKG_ROOT=$(find "${PKG_UNPACK}" -mindepth 1 -maxdepth 1 -type d -name "iotdb-session-cpp-*-${PACKAGE_CLASSIFIER}" -print -quit)
+if [[ -z "${PKG_ROOT}" ]]; then
+ echo "ERROR: could not find unpacked package directory for ${PACKAGE_CLASSIFIER}"
+ exit 1
+fi
+EXAMPLE_BUILD="/tmp/client-cpp-example-smoke-glibc228"
+rm -rf "${EXAMPLE_BUILD}"
+mkdir -p "${EXAMPLE_BUILD}"
+unset CC CXX CFLAGS CXXFLAGS
+"${CMAKE_DIR}/bin/cmake" -S "${PKG_ROOT}/examples" -B "${EXAMPLE_BUILD}" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DIOTDB_SDK_ROOT="${PKG_ROOT}"
+"${CMAKE_DIR}/bin/cmake" --build "${EXAMPLE_BUILD}" -j"$(nproc)"
+
+./mvnw -pl distribution -am -DskipTests -Dspotless.skip=true package
+SERVER_ROOT=$(find "${GITHUB_WORKSPACE}/distribution/target" -path '*/apache-iotdb-*-all-bin/sbin/start-standalone.sh' -print -quit | sed 's#/sbin/start-standalone.sh##')
+if [[ -z "${SERVER_ROOT}" ]]; then
+ echo "ERROR: could not find IoTDB distribution under distribution/target"
+ exit 1
+fi
+"${SERVER_ROOT}/sbin/start-standalone.sh"
+trap '"${SERVER_ROOT}/sbin/stop-standalone.sh" || true' EXIT
+sleep 30
+for example in SessionExample AlignedTimeseriesSessionExample TableModelSessionExample tree_example table_example; do
+ test -x "${EXAMPLE_BUILD}/${example}"
+ "${EXAMPLE_BUILD}/${example}"
+done
+echo "Example package smoke test passed"
diff --git a/.github/workflows/client-cpp-package.yml b/.github/workflows/client-cpp-package.yml
index b403dfad9dd..4eb889b0136 100644
--- a/.github/workflows/client-cpp-package.yml
+++ b/.github/workflows/client-cpp-package.yml
@@ -1,9 +1,26 @@
-# Manual run; Release published; v* tag pushes; rc/** pushes only when C++-related paths change
-# (job should-package). release events use the workflow file from the default branch.
+# Publish-oriented packaging workflow:
+# - manual runs, release:published, v* tags
+# - rc/** pushes only when C++-related paths change (job should-package)
+# release events always use the workflow file from the default branch.
name: C++ Client package
on:
workflow_dispatch:
+ inputs:
+ variants:
+ description: "Which packages to build"
+ required: false
+ default: all
+ type: choice
+ options:
+ - all
+ - linux
+ - macos
+ - windows
+ - windows-vs2017
+ - windows-vs2019
+ - windows-vs2022
+ - windows-vs2026
release:
types: [published]
push:
@@ -22,6 +39,7 @@ env:
jobs:
should-package:
+ # Keep rc branch cost low: skip full matrix when unrelated files change.
runs-on: ubuntu-latest
outputs:
run: ${{ steps.result.outputs.run }}
@@ -34,10 +52,12 @@ jobs:
with:
filters: |
cpp:
- - 'pom.xml'
- - 'iotdb-client/**'
- - 'iotdb-protocol/**'
+ - 'iotdb-client/client-cpp/**'
+ - 'iotdb-client/pom.xml'
+ - 'iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift'
+ - 'iotdb-protocol/thrift-commons/src/main/thrift/common.thrift'
- '.github/workflows/client-cpp-package.yml'
+ - '.github/scripts/package-client-cpp-*.sh'
- id: result
shell: bash
run: |
@@ -62,68 +82,199 @@ jobs:
fi
echo "run=false" >> "$GITHUB_OUTPUT"
- package-linux:
- name: Package (${{ matrix.name }})
+ resolve-matrix:
+ name: Resolve package matrix
needs: should-package
if: needs.should-package.outputs.run == 'true'
- strategy:
- fail-fast: false
- matrix:
- include:
- - name: linux-x86_64
- runs-on: ubuntu-22.04
- - name: linux-aarch64
- runs-on: ubuntu-22.04-arm
- runs-on: ${{ matrix.runs-on }}
+ runs-on: ubuntu-latest
+ outputs:
+ run_linux: ${{ steps.filter.outputs.run_linux }}
+ run_macos: ${{ steps.filter.outputs.run_macos }}
+ run_windows: ${{ steps.filter.outputs.run_windows }}
+ windows_matrix: ${{ steps.filter.outputs.windows_matrix }}
+ steps:
+ - id: filter
+ # Resolve workflow_dispatch variants to a compact matrix payload for fromJSON().
+ shell: bash
+ run: |
+ set -euo pipefail
+ VARIANT="${{ github.event.inputs.variants || 'all' }}"
+
+ run_linux=false
+ run_macos=false
+ run_windows=false
+ case "$VARIANT" in
+ all)
+ run_linux=true
+ run_macos=true
+ run_windows=true
+ ;;
+ linux) run_linux=true ;;
+ macos) run_macos=true ;;
+ windows) run_windows=true ;;
+ windows-vs2017|windows-vs2019|windows-vs2022|windows-vs2026)
+ run_windows=true
+ ;;
+ *)
+ echo "Unknown variant: $VARIANT" >&2
+ exit 1
+ ;;
+ esac
+
+ echo "run_linux=${run_linux}" >> "$GITHUB_OUTPUT"
+ echo "run_macos=${run_macos}" >> "$GITHUB_OUTPUT"
+ echo "run_windows=${run_windows}" >> "$GITHUB_OUTPUT"
+
+ # Compact JSON (no leading whitespace); required for GITHUB_OUTPUT + fromJSON().
+ WINDOWS_MATRIX='[{"name":"windows-vs2026","runs-on":"windows-2025-vs2026","boost_choco":"boost-msvc-14.3","boost_choco_version":"","cmake_generator":"Visual Studio 18 2026","package_classifier":"windows-x86_64-msvc14.4","vs_choco":"","vs_choco_params":""},{"name":"windows-vs2022","runs-on":"windows-2022","boost_choco":"boost-msvc-14.3","boost_choco_version":"","cmake_generator":"","package_classifier":"windows-x86_64-msvc14.3","vs_choco":"","vs_choco_params":""},{"name":"window [...]
+
+ write_windows_matrix_output() {
+ local matrix_json="$1"
+ {
+ echo 'windows_matrix<<__MATRIX_EOF__'
+ echo "${matrix_json}"
+ echo '__MATRIX_EOF__'
+ } >> "$GITHUB_OUTPUT"
+ }
+
+ if [[ "$run_windows" == true ]]; then
+ if [[ "$VARIANT" == all || "$VARIANT" == windows ]]; then
+ FILTERED="$WINDOWS_MATRIX"
+ elif [[ "$VARIANT" =~ ^windows-vs ]]; then
+ FILTERED=$(echo "$WINDOWS_MATRIX" | jq -c --arg v "$VARIANT" '[.[] | select(.name == $v)]')
+ else
+ FILTERED='[]'
+ fi
+ if [[ $(echo "$FILTERED" | jq 'length') -eq 0 ]]; then
+ echo "No Windows matrix rows for variant=${VARIANT}" >&2
+ exit 1
+ fi
+ FILTERED=$(echo "$FILTERED" | jq -c '.')
+ write_windows_matrix_output "${FILTERED}"
+ else
+ write_windows_matrix_output '[]'
+ fi
+
+ package-linux-glibc228:
+ name: Package (linux-x86_64-glibc2.28)
+ needs: [should-package, resolve-matrix]
+ if: needs.should-package.outputs.run == 'true' && needs.resolve-matrix.outputs.run_linux == 'true'
+ # Checkout/cache on host (Node actions need modern glibc); build in manylinux_2_28 via docker run.
+ runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- - name: Set up JDK 17
- uses: actions/setup-java@v5
+ - name: Cache Maven packages
+ uses: actions/cache@v5
with:
- distribution: temurin
- java-version: "17"
- - name: Install C++ dependencies (Linux)
+ path: ~/.m2
+ key: linux-glibc228-m2-${{ hashFiles('**/pom.xml') }}
+ restore-keys: |
+ linux-glibc228-m2-
+ - name: Package client-cpp (glibc 2.28 baseline)
shell: bash
run: |
set -euxo pipefail
- sudo apt-get update
- sudo apt-get install -y libboost-all-dev openssl libssl-dev wget
- . /etc/os-release
- if [[ "${VERSION_CODENAME}" == "jammy" ]]; then
- wget -qO /tmp/llvm.sh https://apt.llvm.org/llvm.sh
- chmod +x /tmp/llvm.sh
- sudo DEBIAN_FRONTEND=noninteractive /tmp/llvm.sh 17
- # llvm.sh installs clang-17/lldb/lld/clangd but not the clang-format-17 package
- sudo apt-get install -y clang-format-17
- else
- sudo apt-get install -y clang-format-17
+ chmod +x .github/scripts/package-client-cpp-manylinux228.sh
+ docker run --rm \
+ -v "${{ github.workspace }}:/workspace" \
+ -v "${HOME}/.m2:/root/.m2" \
+ -w /workspace \
+ -e GITHUB_WORKSPACE=/workspace \
+ quay.io/pypa/manylinux_2_28_x86_64 \
+ bash .github/scripts/package-client-cpp-manylinux228.sh
+ - name: Restore workspace ownership after container build
+ if: always()
+ run: sudo chown -R "$(id -u):$(id -g)" "${{ github.workspace }}"
+ - name: Resolve package zip
+ id: pkg
+ shell: bash
+ run: |
+ set -euo pipefail
+ shopt -s nullglob
+ packages=(iotdb-client/client-cpp/target/iotdb-session-cpp-*-linux-x86_64-glibc2.28.zip)
+ if [ "${#packages[@]}" -ne 1 ]; then
+ echo "Expected exactly one package zip, got: ${packages[*]:-(none)}"
+ exit 1
fi
- sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-17 100
- sudo update-alternatives --set clang-format /usr/bin/clang-format-17
- clang-format --version
+ echo "path=${packages[0]}" >> "$GITHUB_OUTPUT"
+ echo "name=$(basename "${packages[0]}" .zip)" >> "$GITHUB_OUTPUT"
+ sha512="${packages[0]}.sha512"
+ if [ ! -f "${sha512}" ]; then
+ echo "Expected checksum file: ${sha512}"
+ exit 1
+ fi
+ echo "sha512_path=${sha512}" >> "$GITHUB_OUTPUT"
+ - name: Upload zip artifact
+ uses: actions/upload-artifact@v6
+ with:
+ name: ${{ steps.pkg.outputs.name }}
+ path: |
+ ${{ steps.pkg.outputs.path }}
+ ${{ steps.pkg.outputs.sha512_path }}
+ if-no-files-found: error
+
+ package-linux-aarch64-glibc228:
+ name: Package (linux-aarch64-glibc2.28)
+ needs: [should-package, resolve-matrix]
+ if: needs.should-package.outputs.run == 'true' && needs.resolve-matrix.outputs.run_linux == 'true'
+ # Checkout/cache on host; build in manylinux_2_28 aarch64 via docker run (glibc 2.28 baseline).
+ runs-on: ubuntu-22.04-arm
+ steps:
+ - uses: actions/checkout@v5
- name: Cache Maven packages
uses: actions/cache@v5
with:
path: ~/.m2
- key: ${{ runner.os }}-${{ runner.arch }}-m2-${{ hashFiles('**/pom.xml') }}
+ key: linux-aarch64-glibc228-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: |
- ${{ runner.os }}-${{ runner.arch }}-m2-
- - name: Package client-cpp
+ linux-aarch64-glibc228-m2-
+ - name: Package client-cpp (glibc 2.28 baseline)
shell: bash
run: |
set -euxo pipefail
- ./mvnw clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests
+ chmod +x .github/scripts/package-client-cpp-manylinux228.sh
+ docker run --rm \
+ -v "${{ github.workspace }}:/workspace" \
+ -v "${HOME}/.m2:/root/.m2" \
+ -w /workspace \
+ -e GITHUB_WORKSPACE=/workspace \
+ quay.io/pypa/manylinux_2_28_aarch64 \
+ bash .github/scripts/package-client-cpp-manylinux228.sh
+ - name: Restore workspace ownership after container build
+ if: always()
+ run: sudo chown -R "$(id -u):$(id -g)" "${{ github.workspace }}"
+ - name: Resolve package zip
+ id: pkg
+ shell: bash
+ run: |
+ set -euo pipefail
+ shopt -s nullglob
+ packages=(iotdb-client/client-cpp/target/iotdb-session-cpp-*-linux-aarch64-glibc2.28.zip)
+ if [ "${#packages[@]}" -ne 1 ]; then
+ echo "Expected exactly one package zip, got: ${packages[*]:-(none)}"
+ exit 1
+ fi
+ echo "path=${packages[0]}" >> "$GITHUB_OUTPUT"
+ echo "name=$(basename "${packages[0]}" .zip)" >> "$GITHUB_OUTPUT"
+ sha512="${packages[0]}.sha512"
+ if [ ! -f "${sha512}" ]; then
+ echo "Expected checksum file: ${sha512}"
+ exit 1
+ fi
+ echo "sha512_path=${sha512}" >> "$GITHUB_OUTPUT"
- name: Upload zip artifact
uses: actions/upload-artifact@v6
with:
- name: client-cpp-${{ matrix.name }}
- path: iotdb-client/client-cpp/target/client-cpp-*-cpp-*.zip
+ name: ${{ steps.pkg.outputs.name }}
+ path: |
+ ${{ steps.pkg.outputs.path }}
+ ${{ steps.pkg.outputs.sha512_path }}
if-no-files-found: error
package-macos:
name: Package (${{ matrix.name }})
- needs: should-package
- if: needs.should-package.outputs.run == 'true'
+ needs: [should-package, resolve-matrix]
+ if: needs.should-package.outputs.run == 'true' && needs.resolve-matrix.outputs.run_macos == 'true'
strategy:
fail-fast: false
matrix:
@@ -144,49 +295,91 @@ jobs:
shell: bash
run: |
set -euxo pipefail
- brew install boost openssl llvm@17
+ brew install boost openssl llvm@17 bison
ln -sf "$(brew --prefix llvm@17)/bin/clang-format" "$(brew --prefix)/bin/clang-format"
+ echo "$(brew --prefix bison)/bin" >> "$GITHUB_PATH"
echo "$(brew --prefix llvm@17)/bin" >> "$GITHUB_PATH"
clang-format --version
+ bison --version
- name: Cache Maven packages
uses: actions/cache@v5
with:
path: ~/.m2
- key: ${{ runner.os }}-${{ runner.arch }}-m2-${{ hashFiles('**/pom.xml') }}
+ key: macos-${{ matrix.name }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: |
- ${{ runner.os }}-${{ runner.arch }}-m2-
+ macos-${{ matrix.name }}-m2-
- name: Package client-cpp
shell: bash
env:
MACOSX_DEPLOYMENT_TARGET: "12.0"
run: |
set -euxo pipefail
- ./mvnw clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests
+ ./mvnw clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Dspotless.skip=true
+ - name: Resolve package zip
+ id: pkg
+ shell: bash
+ run: |
+ set -euo pipefail
+ shopt -s nullglob
+ packages=(iotdb-client/client-cpp/target/iotdb-session-cpp-*.zip)
+ if [ "${#packages[@]}" -ne 1 ]; then
+ echo "Expected exactly one package zip, got: ${packages[*]:-(none)}"
+ exit 1
+ fi
+ echo "path=${packages[0]}" >> "$GITHUB_OUTPUT"
+ echo "name=$(basename "${packages[0]}" .zip)" >> "$GITHUB_OUTPUT"
+ sha512="${packages[0]}.sha512"
+ if [ ! -f "${sha512}" ]; then
+ echo "Expected checksum file: ${sha512}"
+ exit 1
+ fi
+ echo "sha512_path=${sha512}" >> "$GITHUB_OUTPUT"
- name: Upload zip artifact
uses: actions/upload-artifact@v6
with:
- name: client-cpp-${{ matrix.name }}
- path: iotdb-client/client-cpp/target/client-cpp-*-cpp-*.zip
+ name: ${{ steps.pkg.outputs.name }}
+ path: |
+ ${{ steps.pkg.outputs.path }}
+ ${{ steps.pkg.outputs.sha512_path }}
if-no-files-found: error
+ - name: Verify packaged examples
+ shell: bash
+ run: |
+ set -euxo pipefail
+ PKG_TARBALL="${{ steps.pkg.outputs.path }}"
+ test -n "${PKG_TARBALL}"
+ PKG_UNPACK="${RUNNER_TEMP}/client-cpp-package"
+ rm -rf "${PKG_UNPACK}"
+ mkdir -p "${PKG_UNPACK}"
+ unzip -q -o "${PKG_TARBALL}" -d "${PKG_UNPACK}"
+ PKG_ROOT=$(find "${PKG_UNPACK}" -mindepth 1 -maxdepth 1 -type d -name 'iotdb-session-cpp-*' -print -quit)
+ test -n "${PKG_ROOT}"
+ EXAMPLE_BUILD="${RUNNER_TEMP}/client-cpp-example-smoke"
+ cmake -S "${PKG_ROOT}/examples" -B "${EXAMPLE_BUILD}" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DIOTDB_SDK_ROOT="${PKG_ROOT}"
+ cmake --build "${EXAMPLE_BUILD}" -j"$(sysctl -n hw.ncpu)"
+ ./mvnw -pl distribution -am -DskipTests -Dspotless.skip=true package
+ SERVER_ROOT=$(find "${GITHUB_WORKSPACE}/distribution/target" -path '*/apache-iotdb-*-all-bin/sbin/start-standalone.sh' -print -quit | sed 's#/sbin/start-standalone.sh##')
+ test -n "${SERVER_ROOT}"
+ "${SERVER_ROOT}/sbin/start-standalone.sh"
+ trap '"${SERVER_ROOT}/sbin/stop-standalone.sh" || true' EXIT
+ sleep 30
+ "${EXAMPLE_BUILD}/SessionExample"
+ "${EXAMPLE_BUILD}/AlignedTimeseriesSessionExample"
+ "${EXAMPLE_BUILD}/TableModelSessionExample"
+ "${EXAMPLE_BUILD}/tree_example"
+ "${EXAMPLE_BUILD}/table_example"
package-windows:
name: Package (${{ matrix.name }})
- needs: should-package
- if: needs.should-package.outputs.run == 'true'
+ needs: [should-package, resolve-matrix]
+ if: needs.should-package.outputs.run == 'true' && needs.resolve-matrix.outputs.run_windows == 'true'
strategy:
fail-fast: false
matrix:
- include:
- - name: windows-vs2022
- runs-on: windows-2022
- boost_choco: boost-msvc-14.3
- cmake_generator: ""
- iotdb_tools_thrift_version: ""
- - name: windows-vs2026
- runs-on: windows-2025-vs2026
- boost_choco: boost-msvc-14.3
- cmake_generator: Visual Studio 18 2026
- iotdb_tools_thrift_version: ""
+ include: ${{ fromJSON(needs.resolve-matrix.outputs.windows_matrix) }}
runs-on: ${{ matrix.runs-on }}
steps:
- uses: actions/checkout@v5
@@ -195,44 +388,160 @@ jobs:
with:
distribution: temurin
java-version: "17"
+ - name: Install Visual Studio Build Tools (${{ matrix.name }})
+ if: matrix.vs_choco != ''
+ shell: pwsh
+ run: |
+ $params = '${{ matrix.vs_choco_params }}'
+ if ($params) {
+ choco install ${{ matrix.vs_choco }} -y --package-parameters="$params" --no-progress
+ } else {
+ choco install ${{ matrix.vs_choco }} -y --no-progress
+ }
- name: Install C++ dependencies (Windows)
shell: pwsh
run: |
- choco install winflexbison3 -y
- choco install ${{ matrix.boost_choco }} -y
- $boost_path = (Get-ChildItem -Path 'C:\local\' -Filter 'boost_*').FullName
- echo $boost_path >> $env:GITHUB_PATH
- choco install openssl -y
+ choco install winflexbison3 -y --no-progress
+ $boostArgs = @('install', '${{ matrix.boost_choco }}', '-y', '--no-progress')
+ if ('${{ matrix.boost_choco_version }}' -ne '') {
+ $boostArgs += @("--version=${{ matrix.boost_choco_version }}")
+ }
+ & choco @boostArgs
+ if (-not (Test-Path 'C:\local')) {
+ New-Item -ItemType Directory -Path 'C:\local' -Force | Out-Null
+ }
+ $boostDir = Get-ChildItem -Path 'C:\local\' -Filter 'boost_*' -ErrorAction SilentlyContinue | Select-Object -First 1
+ if (-not $boostDir) {
+ throw "Boost not found under C:\local after installing ${{ matrix.boost_choco }}"
+ }
+ echo $boostDir.FullName >> $env:GITHUB_PATH
+ choco install openssl -y --no-progress
$sslPath = (Get-ChildItem 'C:\Program Files\OpenSSL*' -Directory | Select-Object -First 1).FullName
echo "$sslPath\bin" >> $env:GITHUB_PATH
echo "OPENSSL_ROOT_DIR=$sslPath" >> $env:GITHUB_ENV
- choco install llvm --version=17.0.6 --force -y
- clang-format --version
- name: Cache Maven packages
uses: actions/cache@v5
with:
path: ~/.m2
- key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
+ key: windows-${{ matrix.name }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: |
- ${{ runner.os }}-m2-
+ windows-${{ matrix.name }}-m2-
- name: Package client-cpp
shell: bash
env:
CMAKE_GENERATOR: ${{ matrix.cmake_generator }}
- IOTDB_TOOLS_THRIFT_VERSION: ${{ matrix.iotdb_tools_thrift_version }}
+ PACKAGE_CLASSIFIER: ${{ matrix.package_classifier }}
run: |
set -euxo pipefail
- MVN_ARGS=(./mvnw clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests)
+ MVN_ARGS=(./mvnw clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Dspotless.skip=true \
+ "-Dclient.cpp.package.classifier=${PACKAGE_CLASSIFIER}")
if [ -n "${CMAKE_GENERATOR:-}" ]; then
MVN_ARGS+=("-Dcmake.generator=${CMAKE_GENERATOR}")
fi
- if [ -n "${IOTDB_TOOLS_THRIFT_VERSION:-}" ]; then
- MVN_ARGS+=("-Diotdb-tools-thrift.version=${IOTDB_TOOLS_THRIFT_VERSION}")
- fi
"${MVN_ARGS[@]}"
+ - name: Verify Windows SDK is x64
+ # Guard against accidental Win32 generator defaults on legacy VS matrices.
+ shell: pwsh
+ run: |
+ $dll = "iotdb-client/client-cpp/target/install/lib/iotdb_session.dll"
+ if (-not (Test-Path $dll)) {
+ throw "Missing $dll"
+ }
+ $bytes = [System.IO.File]::ReadAllBytes($dll)
+ $peOffset = [BitConverter]::ToInt32($bytes, 0x3C)
+ $machine = [BitConverter]::ToUInt16($bytes, $peOffset + 4)
+ if ($machine -ne 0x8664) {
+ throw "Expected PE32+ x64 (machine=0x8664), got 0x$($machine.ToString('X4'))"
+ }
+ Write-Host "Verified x64 DLL: $dll"
+ - name: Resolve package zip
+ id: pkg
+ shell: bash
+ run: |
+ set -euo pipefail
+ shopt -s nullglob
+ packages=(iotdb-client/client-cpp/target/iotdb-session-cpp-*-${{ matrix.package_classifier }}.zip)
+ if [ "${#packages[@]}" -ne 1 ]; then
+ echo "Expected exactly one package zip, got: ${packages[*]:-(none)}"
+ exit 1
+ fi
+ echo "path=${packages[0]}" >> "$GITHUB_OUTPUT"
+ echo "name=$(basename "${packages[0]}" .zip)" >> "$GITHUB_OUTPUT"
+ sha512="${packages[0]}.sha512"
+ if [ ! -f "${sha512}" ]; then
+ echo "Expected checksum file: ${sha512}"
+ exit 1
+ fi
+ echo "sha512_path=${sha512}" >> "$GITHUB_OUTPUT"
- name: Upload zip artifact
uses: actions/upload-artifact@v6
with:
- name: client-cpp-${{ matrix.name }}
- path: iotdb-client/client-cpp/target/client-cpp-*-cpp-*.zip
+ name: ${{ steps.pkg.outputs.name }}
+ path: |
+ ${{ steps.pkg.outputs.path }}
+ ${{ steps.pkg.outputs.sha512_path }}
if-no-files-found: error
+ - name: Verify packaged examples
+ shell: bash
+ env:
+ CMAKE_GENERATOR: ${{ matrix.cmake_generator }}
+ run: |
+ set -euxo pipefail
+ PKG_TARBALL="${{ steps.pkg.outputs.path }}"
+ test -n "${PKG_TARBALL}"
+ if [ "${RUNNER_OS}" = "Windows" ]; then
+ TEMP_BASE="$(cygpath -u "${RUNNER_TEMP}")"
+ else
+ TEMP_BASE="${RUNNER_TEMP}"
+ fi
+ PKG_UNPACK="${TEMP_BASE}/client-cpp-package"
+ rm -rf "${PKG_UNPACK}"
+ mkdir -p "${PKG_UNPACK}"
+ unzip -q -o "${PKG_TARBALL}" -d "${PKG_UNPACK}"
+ PKG_ROOT=$(find "${PKG_UNPACK}" -mindepth 1 -maxdepth 1 -type d -name 'iotdb-session-cpp-*' -print -quit)
+ test -n "${PKG_ROOT}"
+ EXAMPLE_BUILD="${TEMP_BASE}/client-cpp-example-smoke"
+ CMAKE_ARGS=(-S "${PKG_ROOT}/examples" -B "${EXAMPLE_BUILD}" -DIOTDB_SDK_ROOT="${PKG_ROOT}")
+ if [ -n "${CMAKE_GENERATOR:-}" ]; then
+ CMAKE_ARGS+=(-G "${CMAKE_GENERATOR}")
+ # windows-x86_64 SDK; VS2017/2019 default to Win32 without -A x64 (see client-cpp pom).
+ CMAKE_ARGS+=(-A x64)
+ fi
+ cmake "${CMAKE_ARGS[@]}"
+ cmake --build "${EXAMPLE_BUILD}" --config Release
+ ./mvnw -pl distribution -am -DskipTests -Dspotless.skip=true package
+ if [ "${RUNNER_OS}" = "Windows" ]; then
+ WORKSPACE_BASE="$(cygpath -u "${GITHUB_WORKSPACE}")"
+ else
+ WORKSPACE_BASE="${GITHUB_WORKSPACE}"
+ fi
+ SERVER_ROOT=$(find "${WORKSPACE_BASE}/distribution/target" -path '*/apache-iotdb-*-all-bin/sbin/windows/start-standalone.bat' -print -quit | sed 's#/sbin/windows/start-standalone.bat##')
+ test -n "${SERVER_ROOT}"
+ START_BAT="$(cygpath -w "${SERVER_ROOT}/sbin/windows/start-standalone.bat")"
+ STOP_BAT="$(cygpath -w "${SERVER_ROOT}/sbin/windows/stop-standalone.bat")"
+ # Git Bash maps cmd /c to a path; use //c. Avoid nested \" quotes — cmd then treats
+ # the quotes as part of the executable name and fails with "not recognized".
+ cmd.exe //c "${START_BAT}"
+ trap "cmd.exe //c \"${STOP_BAT}\" || true" EXIT
+ echo "Waiting for IoTDB RPC on 127.0.0.1:6667..."
+ ready=0
+ for _ in $(seq 1 60); do
+ if powershell.exe -NoProfile -Command \
+ '(Test-NetConnection -ComputerName 127.0.0.1 -Port 6667 -WarningAction SilentlyContinue).TcpTestSucceeded' \
+ | grep -qi True; then
+ ready=1
+ break
+ fi
+ sleep 2
+ done
+ if [ "${ready}" -ne 1 ]; then
+ echo "ERROR: IoTDB did not listen on 6667 within 120s"
+ ls -la "${SERVER_ROOT}/logs" 2>/dev/null || true
+ exit 1
+ fi
+ for exe in SessionExample.exe AlignedTimeseriesSessionExample.exe TableModelSessionExample.exe tree_example.exe table_example.exe; do
+ EXE=$(find "${EXAMPLE_BUILD}" -name "${exe}" -print -quit)
+ test -n "${EXE}"
+ "${EXE}"
+ done
diff --git a/.github/workflows/cluster-it-1c1d.yml b/.github/workflows/cluster-it-1c1d.yml
index caf1de91c68..30645593190 100644
--- a/.github/workflows/cluster-it-1c1d.yml
+++ b/.github/workflows/cluster-it-1c1d.yml
@@ -9,6 +9,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -17,6 +21,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/cluster-it-1c1d1a.yml b/.github/workflows/cluster-it-1c1d1a.yml
index 7ee6ca6ace6..74ebcbebaac 100644
--- a/.github/workflows/cluster-it-1c1d1a.yml
+++ b/.github/workflows/cluster-it-1c1d1a.yml
@@ -9,6 +9,10 @@ on:
paths-ignore:
- 'docs/**'
- 'site/**'
+ - 'iotdb-client/client-cpp/**'
+ - '.github/workflows/client-cpp-package.yml'
+ - '.github/scripts/package-client-cpp-*.sh'
+ - '.github/workflows/multi-language-client.yml'
pull_request:
branches:
- master
@@ -18,6 +22,10 @@ on:
paths-ignore:
- 'docs/**'
- 'site/**'
+ - 'iotdb-client/client-cpp/**'
+ - '.github/workflows/client-cpp-package.yml'
+ - '.github/scripts/package-client-cpp-*.sh'
+ - '.github/workflows/multi-language-client.yml'
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/cluster-it-1c3d.yml b/.github/workflows/cluster-it-1c3d.yml
index 035403e1695..14d808462f5 100644
--- a/.github/workflows/cluster-it-1c3d.yml
+++ b/.github/workflows/cluster-it-1c3d.yml
@@ -9,6 +9,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -18,6 +22,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/compile-check.yml b/.github/workflows/compile-check.yml
index 1cf45e07dc0..196b2169e92 100644
--- a/.github/workflows/compile-check.yml
+++ b/.github/workflows/compile-check.yml
@@ -11,6 +11,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -20,6 +24,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/dependency-check.yml b/.github/workflows/dependency-check.yml
index 4cf6cb202af..c0dcb39df88 100644
--- a/.github/workflows/dependency-check.yml
+++ b/.github/workflows/dependency-check.yml
@@ -11,6 +11,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -20,6 +24,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/multi-language-client.yml b/.github/workflows/multi-language-client.yml
index a699ce16429..d40168e556e 100644
--- a/.github/workflows/multi-language-client.yml
+++ b/.github/workflows/multi-language-client.yml
@@ -1,3 +1,4 @@
+# Shared client CI: run only affected language jobs via paths-filter.
name: Multi-Language Client
on:
push:
@@ -5,28 +6,28 @@ on:
- master
- "rc/*"
paths:
- - 'pom.xml'
- 'iotdb-client/pom.xml'
- 'iotdb-client/client-py/**'
- 'iotdb-client/client-cpp/**'
- - 'example/client-cpp-example/**'
- 'iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift'
- 'iotdb-protocol/thrift-commons/src/main/thrift/common.thrift'
- '.github/workflows/multi-language-client.yml'
+ - '.github/workflows/client-cpp-package.yml'
+ - '.github/scripts/package-client-cpp-*.sh'
pull_request:
branches:
- master
- "rc/*"
- 'force_ci/**'
paths:
- - 'pom.xml'
- 'iotdb-client/pom.xml'
- 'iotdb-client/client-py/**'
- 'iotdb-client/client-cpp/**'
- - 'example/client-cpp-example/**'
- 'iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift'
- 'iotdb-protocol/thrift-commons/src/main/thrift/common.thrift'
- '.github/workflows/multi-language-client.yml'
+ - '.github/workflows/client-cpp-package.yml'
+ - '.github/scripts/package-client-cpp-*.sh'
# allow manually run the action:
workflow_dispatch:
@@ -40,7 +41,50 @@ env:
MAVEN_ARGS: --batch-mode --no-transfer-progress
jobs:
+ # Per-language path filters: a client-cpp-only PR runs cpp, not go/python.
+ changes:
+ runs-on: ubuntu-latest
+ outputs:
+ cpp: ${{ steps.filter.outputs.cpp }}
+ python: ${{ steps.filter.outputs.python }}
+ go: ${{ steps.filter.outputs.go }}
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dorny/paths-filter@v3
+ id: filter
+ with:
+ filters: |
+ cpp:
+ - 'iotdb-client/pom.xml'
+ - 'iotdb-client/client-cpp/**'
+ - 'iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift'
+ - 'iotdb-protocol/thrift-commons/src/main/thrift/common.thrift'
+ - '.github/workflows/multi-language-client.yml'
+ - '.github/workflows/client-cpp-package.yml'
+ - '.github/scripts/package-client-cpp-*.sh'
+ python:
+ - 'pom.xml'
+ - 'iotdb-client/pom.xml'
+ - 'iotdb-client/client-py/**'
+ - 'docker/src/main/Dockerfile-1c1d'
+ - '.github/workflows/multi-language-client.yml'
+ go:
+ - 'pom.xml'
+ - 'iotdb-core/**'
+ - 'iotdb-api/**'
+ - 'iotdb-protocol/**'
+ - 'distribution/**'
+ - 'integration-test/**'
+ - 'iotdb-client/session/**'
+ - 'iotdb-client/jdbc/**'
+ - 'iotdb-client/cli/**'
+ - 'iotdb-client/service-rpc/**'
+ - '.github/workflows/multi-language-client.yml'
+
cpp:
+ needs: changes
+ # Full client validation (format + server build + verify) for C++ examples and SDK.
+ if: github.event_name == 'workflow_dispatch' || needs.changes.outputs.cpp == 'true'
strategy:
fail-fast: false
max-parallel: 15
@@ -76,11 +120,12 @@ jobs:
if: runner.os == 'macOS'
shell: bash
run: |
- brew install boost
- brew install openssl llvm@17
+ brew install boost openssl llvm@17 bison
ln -sf "$(brew --prefix llvm@17)/bin/clang-format" "$(brew --prefix)/bin/clang-format"
+ echo "$(brew --prefix bison)/bin" >> "$GITHUB_PATH"
echo "$(brew --prefix llvm@17)/bin" >> "$GITHUB_PATH"
clang-format --version
+ bison --version
sudo rm -rf /Applications/Xcode_14.3.1.app
sudo rm -rf /Applications/Xcode_15.0.1.app
sudo rm -rf /Applications/Xcode_15.1.app
@@ -110,7 +155,6 @@ jobs:
shell: bash
run: |
./mvnw -P with-cpp -pl iotdb-client/client-cpp spotless:check
- ./mvnw -P with-cpp -pl example/client-cpp-example spotless:check
- name: Build IoTDB server
shell: bash
run: ./mvnw clean install -pl distribution -am -DskipTests
@@ -121,9 +165,9 @@ jobs:
# (was causing problems on windows, but could cause problem on linux, when updating the thrift module)
run: |
if [[ "${{ matrix.os }}" == "windows-2025-vs2026" ]]; then
- ./mvnw clean verify -P with-cpp -pl iotdb-client/client-cpp,example/client-cpp-example -am -Dcmake.generator="Visual Studio 18 2026"
+ ./mvnw clean verify -P with-cpp -pl iotdb-client/client-cpp -am -Dcmake.generator="Visual Studio 18 2026"
else
- ./mvnw clean verify -P with-cpp -pl iotdb-client/client-cpp,example/client-cpp-example -am
+ ./mvnw clean verify -P with-cpp -pl iotdb-client/client-cpp -am
fi
- name: Upload Artifact
if: failure()
@@ -134,6 +178,8 @@ jobs:
retention-days: 1
go:
+ needs: changes
+ if: github.event_name == 'workflow_dispatch' || needs.changes.outputs.go == 'true'
runs-on: ubuntu-latest
steps:
@@ -158,6 +204,8 @@ jobs:
make e2e_test_for_parent_git_repo e2e_test_clean_for_parent_git_repo
python:
+ needs: changes
+ if: github.event_name == 'workflow_dispatch' || needs.changes.outputs.python == 'true'
strategy:
fail-fast: false
max-parallel: 15
diff --git a/.github/workflows/pipe-it.yml b/.github/workflows/pipe-it.yml
index fb2f732560d..0a4e5e54eda 100644
--- a/.github/workflows/pipe-it.yml
+++ b/.github/workflows/pipe-it.yml
@@ -9,6 +9,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
- "iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/**" #queryengine
pull_request:
branches:
@@ -19,6 +23,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
- "iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/**" #queryengine
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/sonar-codecov.yml b/.github/workflows/sonar-codecov.yml
index 4f62c8926fb..44e1901af7c 100644
--- a/.github/workflows/sonar-codecov.yml
+++ b/.github/workflows/sonar-codecov.yml
@@ -12,6 +12,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -22,6 +26,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/table-cluster-it-1c1d.yml b/.github/workflows/table-cluster-it-1c1d.yml
index a0058fe3219..8c5a838af33 100644
--- a/.github/workflows/table-cluster-it-1c1d.yml
+++ b/.github/workflows/table-cluster-it-1c1d.yml
@@ -9,6 +9,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -18,6 +22,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/table-cluster-it-1c3d.yml b/.github/workflows/table-cluster-it-1c3d.yml
index 99a7469500c..abca8062369 100644
--- a/.github/workflows/table-cluster-it-1c3d.yml
+++ b/.github/workflows/table-cluster-it-1c3d.yml
@@ -9,6 +9,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -18,6 +22,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml
index ccc0c2ca4b3..64a20a1f9a2 100644
--- a/.github/workflows/unit-test.yml
+++ b/.github/workflows/unit-test.yml
@@ -12,6 +12,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
pull_request:
branches:
- master
@@ -21,6 +25,10 @@ on:
paths-ignore:
- "docs/**"
- "site/**"
+ - "iotdb-client/client-cpp/**"
+ - ".github/workflows/client-cpp-package.yml"
+ - ".github/scripts/package-client-cpp-*.sh"
+ - ".github/workflows/multi-language-client.yml"
# allow manually run the action:
workflow_dispatch:
diff --git a/.gitignore b/.gitignore
index b6aa947b3e7..a66cf2b1aa9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,10 +40,10 @@ tsfile-jdbc/src/main/resources/output/queryRes.csv
*.txt
!iotdb-client/client-py/requirements.txt
!iotdb-client/client-py/requirements_dev.txt
-!iotdb-client/client-cpp/src/main/CMakeLists.txt
+!iotdb-client/client-cpp/CMakeLists.txt
!iotdb-client/client-cpp/src/test/CMakeLists.txt
!example/rest-client-c-example/CMakeLists.txt
-!example/client-cpp-example/src/CMakeLists.txt
+!iotdb-client/client-cpp/examples/CMakeLists.txt
*.jar
@@ -88,6 +88,11 @@ tsfile-jdbc/src/main/resources/output/queryRes.csv
*.tsfile
tsfile/src/test/resources/*.ts
+### clion project
+**/cmake-build-debug/
+**/cmake-build-release/
+iotdb-client/client-cpp/build-*/
+
### Apache release ###
local-snapshots-dir/
venv/
@@ -107,6 +112,7 @@ classes/
### Cmake files ###
*.cmake
+!iotdb-client/client-cpp/cmake/*.cmake
Makefile
**/CMakeFiles/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5b9c4d80d0e..f91968bdf3a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -117,15 +117,12 @@ Check only:
`./mvnw -P with-cpp -pl iotdb-client/client-cpp spotless:check`
-`./mvnw -P with-cpp -pl example/client-cpp-example spotless:check`
Auto-fix:
`./mvnw -P with-cpp -pl iotdb-client/client-cpp spotless:apply`
-`./mvnw -P with-cpp -pl example/client-cpp-example spotless:apply`
-On Windows PowerShell, a comma inside `-pl` can be parsed incorrectly; use the two commands above, or quote the full `-pl` value, for example `./mvnw -P with-cpp "-pl=iotdb-client/client-cpp,example/client-cpp-example" spotless:check`.
Temporarily skip Spotless (not recommended except emergency CI triage):
diff --git a/distribution/pom.xml b/distribution/pom.xml
index f4773f6afad..70c72ba9978 100644
--- a/distribution/pom.xml
+++ b/distribution/pom.xml
@@ -29,6 +29,9 @@
<artifactId>iotdb-distribution</artifactId>
<packaging>pom</packaging>
<name>IoTDB: Distribution</name>
+ <properties>
+ <client.cpp.package.classifier>${os.classifier}</client.cpp.package.classifier>
+ </properties>
<dependencies>
<dependency>
<groupId>org.apache.iotdb</groupId>
@@ -130,6 +133,67 @@
</plugins>
</build>
<profiles>
+ <profile>
+ <id>.os-unix</id>
+ <activation>
+ <os>
+ <name>Linux</name>
+ <family>unix</family>
+ <arch>!aarch64</arch>
+ </os>
+ </activation>
+ <properties>
+ <client.cpp.package.classifier>linux-x86_64-glibc2.28</client.cpp.package.classifier>
+ </properties>
+ </profile>
+ <profile>
+ <id>.os-unix-arm</id>
+ <activation>
+ <os>
+ <name>Linux</name>
+ <family>unix</family>
+ <arch>aarch64</arch>
+ </os>
+ </activation>
+ <properties>
+ <client.cpp.package.classifier>linux-aarch64-glibc2.28</client.cpp.package.classifier>
+ </properties>
+ </profile>
+ <profile>
+ <id>.os-mac</id>
+ <activation>
+ <os>
+ <family>mac</family>
+ <arch>!aarch64</arch>
+ </os>
+ </activation>
+ <properties>
+ <client.cpp.package.classifier>macos-x86_64</client.cpp.package.classifier>
+ </properties>
+ </profile>
+ <profile>
+ <id>.os-mac-arm</id>
+ <activation>
+ <os>
+ <family>mac</family>
+ <arch>aarch64</arch>
+ </os>
+ </activation>
+ <properties>
+ <client.cpp.package.classifier>macos-aarch64</client.cpp.package.classifier>
+ </properties>
+ </profile>
+ <profile>
+ <id>.os-windows</id>
+ <activation>
+ <os>
+ <family>windows</family>
+ </os>
+ </activation>
+ <properties>
+ <client.cpp.package.classifier>windows-x86_64-msvc14.3</client.cpp.package.classifier>
+ </properties>
+ </profile>
<profile>
<id>with-cpp</id>
<build>
@@ -170,7 +234,7 @@
<fileSets>
<fileSet>
<includes combine.children="append">
- <include>apache-iotdb-${project.version}-client-cpp-${os.classifier}-bin.zip</include>
+ <include>apache-iotdb-${project.version}-client-cpp-${client.cpp.package.classifier}-bin.zip</include>
</includes>
</fileSet>
</fileSets>
diff --git a/distribution/src/assembly/client-cpp.xml b/distribution/src/assembly/client-cpp.xml
index 0a4dfffbc06..579d6251c7b 100644
--- a/distribution/src/assembly/client-cpp.xml
+++ b/distribution/src/assembly/client-cpp.xml
@@ -20,15 +20,15 @@
-->
<assembly>
- <id>client-cpp-${os.classifier}-bin</id>
+ <id>client-cpp-${client.cpp.package.classifier}-bin</id>
<formats>
<format>dir</format>
<format>zip</format>
</formats>
- <baseDirectory>apache-iotdb-${project.version}-client-cpp-${os.classifier}-bin</baseDirectory>
+ <baseDirectory>apache-iotdb-${project.version}-client-cpp-${client.cpp.package.classifier}-bin</baseDirectory>
<fileSets>
<fileSet>
- <directory>${project.basedir}/../iotdb-client/client-cpp/target/client-cpp-${project.version}-cpp-${os.classifier}</directory>
+ <directory>${project.basedir}/../iotdb-client/client-cpp/target/iotdb-session-cpp-${project.version}-${client.cpp.package.classifier}</directory>
<outputDirectory>${file.separator}</outputDirectory>
</fileSet>
</fileSets>
diff --git a/example/client-c-example/README.md b/example/client-c-example/README.md
deleted file mode 100644
index 8920883ddbc..00000000000
--- a/example/client-c-example/README.md
+++ /dev/null
@@ -1,68 +0,0 @@
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-
-# How to get a complete C client demo project (SessionC)
-
-Pure **C** examples for the IoTDB Session **C API** (`SessionC.h`): **tree model** (`tree_example`) and **table model** (`table_example`). Default connection: `127.0.0.1:6667`, user `root` / password `root` (edit the macros at the top of each `.c` file).
-
-## Get a project
-
-Using Maven to build this example project (requires **Boost**, same as the C++ client; on Windows see [`iotdb-client/client-cpp/README.md`](../../iotdb-client/client-cpp/README.md)):
-
-* `cd` the root path of the whole project
-* run
- `mvn package -DskipTests -P with-cpp -pl example/client-c-example -am`
- (use `mvn clean package ...` when no other process holds files under `iotdb-client/client-cpp/target`; on Windows add Boost paths, e.g.
- `-D"boost.include.dir=C:\local\boost_1_87_0" -D"boost.library.dir=C:\local\boost_1_87_0\lib64-msvc-14.2"`)
-* `cd example/client-c-example/target`
-
-After a successful build you should have:
-
-* Unpacked C++ client headers and libraries under `client/` and Thrift under `thrift/` (same layout as [client-cpp-example](../client-cpp-example/README.md))
-* CMake-generated binaries, for example on Windows MSVC:
- `Release/tree_example.exe`, `Release/table_example.exe`
- (exact path depends on the CMake generator)
-
-## Run
-
-Start IoTDB first, then:
-
-```text
-# Windows (example)
-Release\tree_example.exe
-Release\table_example.exe
-```
-
-On failure, the programs print to `stderr` and you can inspect `ts_get_last_error()`.
-
-## Source layout
-
-```
-example/client-c-example/
-+-- README.md
-+-- pom.xml
-+-- src/
-| +-- CMakeLists.txt
-| +-- tree_example.c
-| +-- table_example.c
-```
-
-The Maven build copies `src/*.c` and `src/CMakeLists.txt` into `target/` next to the unpacked `client/` and `thrift/` trees, then runs CMake to compile the two executables.
diff --git a/example/client-c-example/pom.xml b/example/client-c-example/pom.xml
deleted file mode 100644
index 3116c0fd0b4..00000000000
--- a/example/client-c-example/pom.xml
+++ /dev/null
@@ -1,150 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.iotdb</groupId>
- <artifactId>iotdb-examples</artifactId>
- <version>2.0.7-SNAPSHOT</version>
- </parent>
- <artifactId>client-c-example</artifactId>
- <name>IoTDB: Example: C Client (SessionC)</name>
- <dependencies>
- <dependency>
- <groupId>org.apache.iotdb</groupId>
- <artifactId>client-cpp</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>com.coderplus.maven.plugins</groupId>
- <artifactId>copy-rename-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-c-sources-and-cmake</id>
- <goals>
- <goal>copy</goal>
- </goals>
- <configuration>
- <fileSets>
- <fileSet>
- <sourceFile>${project.basedir}/src/tree_example.c</sourceFile>
- <destinationFile>${project.build.directory}/tree_example.c</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>${project.basedir}/src/table_example.c</sourceFile>
- <destinationFile>${project.build.directory}/table_example.c</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>${project.basedir}/src/CMakeLists.txt</sourceFile>
- <destinationFile>${project.build.directory}/CMakeLists.txt</destinationFile>
- </fileSet>
- </fileSets>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>unpack-client</id>
- <goals>
- <goal>unpack</goal>
- </goals>
- <phase>generate-sources</phase>
- <configuration>
- <artifactItems>
- <artifactItem>
- <groupId>org.apache.iotdb</groupId>
- <artifactId>client-cpp</artifactId>
- <version>${project.version}</version>
- <type>zip</type>
- <classifier>cpp-${os.classifier}</classifier>
- <overWrite>true</overWrite>
- </artifactItem>
- </artifactItems>
- <outputDirectory>${project.build.directory}/client</outputDirectory>
- </configuration>
- </execution>
- <execution>
- <id>unpack-thrift</id>
- <goals>
- <goal>unpack</goal>
- </goals>
- <phase>generate-sources</phase>
- <configuration>
- <artifactItems>
- <artifactItem>
- <groupId>org.apache.iotdb.tools</groupId>
- <artifactId>iotdb-tools-thrift</artifactId>
- <version>${iotdb-tools-thrift.version}</version>
- <classifier>${os.classifier}</classifier>
- <type>zip</type>
- <overWrite>true</overWrite>
- <outputDirectory>${project.build.directory}/thrift</outputDirectory>
- </artifactItem>
- </artifactItems>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>io.github.cmake-maven-plugin</groupId>
- <artifactId>cmake-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>cmake-generate</id>
- <goals>
- <goal>generate</goal>
- </goals>
- <phase>compile</phase>
- <configuration>
- <generator>${cmake.generator}</generator>
- <sourcePath>${project.build.directory}</sourcePath>
- <projectDirectory>${project.build.directory}</projectDirectory>
- <options>
- <option>-DBOOST_INCLUDEDIR=${boost.include.dir}</option>
- </options>
- </configuration>
- </execution>
- <execution>
- <id>cmake-compile</id>
- <goals>
- <goal>compile</goal>
- </goals>
- <phase>compile</phase>
- <configuration>
- <config>${cmake.build.type}</config>
- <projectDirectory>${project.build.directory}</projectDirectory>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/example/client-c-example/src/table_example.c b/example/client-c-example/src/table_example.c
deleted file mode 100644
index 9ad844ec4c2..00000000000
--- a/example/client-c-example/src/table_example.c
+++ /dev/null
@@ -1,152 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/*
- * Table model: CREATE DATABASE/TABLE, insert rows via Tablet, SELECT, DROP DATABASE.
- * Requires IoTDB table-SQL support. Edit HOST / PORT / credentials below.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "SessionC.h"
-
-#define HOST "127.0.0.1"
-#define PORT 6667
-#define USER "root"
-#define PASS "root"
-
-#define DB_NAME "cdemo_db"
-#define TABLE_NAME "cdemo_t0"
-
-static void fail(const char* ctx, CTableSession* s) {
- fprintf(stderr, "[table_example] %s failed: %s\n", ctx, ts_get_last_error());
- if (s) {
- ts_table_session_close(s);
- ts_table_session_destroy(s);
- }
- exit(1);
-}
-
-int main(void) {
- /* Last arg: default database name; empty string leaves it unset (we USE "cdemo_db" via SQL below). */
- CTableSession* session = ts_table_session_new(HOST, PORT, USER, PASS, "");
- if (!session) {
- fprintf(stderr, "[table_example] ts_table_session_new returned NULL: %s\n", ts_get_last_error());
- return 1;
- }
- if (ts_table_session_open(session) != TS_OK) {
- fail("ts_table_session_open", session);
- }
-
- char sql[512];
- snprintf(sql, sizeof(sql), "DROP DATABASE IF EXISTS %s", DB_NAME);
- (void)ts_table_session_execute_non_query(session, sql);
-
- snprintf(sql, sizeof(sql), "CREATE DATABASE %s", DB_NAME);
- if (ts_table_session_execute_non_query(session, sql) != TS_OK) {
- fail("CREATE DATABASE", session);
- }
-
- snprintf(sql, sizeof(sql), "USE \"%s\"", DB_NAME);
- if (ts_table_session_execute_non_query(session, sql) != TS_OK) {
- fail("USE DATABASE", session);
- }
-
- const char* ddl =
- "CREATE TABLE " TABLE_NAME " ("
- "tag1 string tag,"
- "attr1 string attribute,"
- "m1 double field)";
- if (ts_table_session_execute_non_query(session, ddl) != TS_OK) {
- fail("CREATE TABLE", session);
- }
-
- const char* columnNames[] = {"tag1", "attr1", "m1"};
- TSDataType_C dataTypes[] = {TS_TYPE_STRING, TS_TYPE_STRING, TS_TYPE_DOUBLE};
- TSColumnCategory_C colCategories[] = {TS_COL_TAG, TS_COL_ATTRIBUTE, TS_COL_FIELD};
-
- CTablet* tablet = ts_tablet_new_with_category(TABLE_NAME, 3, columnNames, dataTypes, colCategories, 100);
- if (!tablet) {
- fail("ts_tablet_new_with_category", session);
- }
-
- int i;
- for (i = 0; i < 5; i++) {
- if (ts_tablet_add_timestamp(tablet, i, (int64_t)i) != TS_OK) {
- ts_tablet_destroy(tablet);
- fail("ts_tablet_add_timestamp", session);
- }
- if (ts_tablet_add_value_string(tablet, 0, i, "device_A") != TS_OK) {
- ts_tablet_destroy(tablet);
- fail("ts_tablet_add_value_string tag", session);
- }
- if (ts_tablet_add_value_string(tablet, 1, i, "attr_val") != TS_OK) {
- ts_tablet_destroy(tablet);
- fail("ts_tablet_add_value_string attr", session);
- }
- if (ts_tablet_add_value_double(tablet, 2, i, (double)i * 1.5) != TS_OK) {
- ts_tablet_destroy(tablet);
- fail("ts_tablet_add_value_double", session);
- }
- }
- if (ts_tablet_set_row_count(tablet, 5) != TS_OK) {
- ts_tablet_destroy(tablet);
- fail("ts_tablet_set_row_count", session);
- }
-
- if (ts_table_session_insert(session, tablet) != TS_OK) {
- ts_tablet_destroy(tablet);
- fail("ts_table_session_insert", session);
- }
- ts_tablet_destroy(tablet);
-
- CSessionDataSet* dataSet = NULL;
- if (ts_table_session_execute_query(session, "SELECT * FROM " TABLE_NAME, &dataSet) != TS_OK) {
- fail("ts_table_session_execute_query", session);
- }
- if (!dataSet) {
- fprintf(stderr, "[table_example] dataSet is NULL\n");
- ts_table_session_close(session);
- ts_table_session_destroy(session);
- return 1;
- }
- ts_dataset_set_fetch_size(dataSet, 1024);
-
- int count = 0;
- while (ts_dataset_has_next(dataSet)) {
- CRowRecord* record = ts_dataset_next(dataSet);
- if (!record) {
- break;
- }
- printf("[table_example] row %d: time=%lld\n", count, (long long)ts_row_record_get_timestamp(record));
- ts_row_record_destroy(record);
- count++;
- }
- ts_dataset_destroy(dataSet);
- printf("[table_example] SELECT returned %d row(s).\n", count);
-
- snprintf(sql, sizeof(sql), "DROP DATABASE IF EXISTS %s", DB_NAME);
- (void)ts_table_session_execute_non_query(session, sql);
-
- ts_table_session_close(session);
- ts_table_session_destroy(session);
- return 0;
-}
diff --git a/example/client-c-example/src/tree_example.c b/example/client-c-example/src/tree_example.c
deleted file mode 100644
index a98df2831b6..00000000000
--- a/example/client-c-example/src/tree_example.c
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/*
- * Tree model: create one timeseries, insert one row via string values, SELECT, cleanup.
- * Edit HOST / PORT / credentials below to match your IoTDB.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdbool.h>
-#include <string.h>
-
-#include "SessionC.h"
-
-#define HOST "127.0.0.1"
-#define PORT 6667
-#define USER "root"
-#define PASS "root"
-
-#define TS_PATH "root.cdemo.d0.s0"
-#define DEVICE "root.cdemo.d0"
-
-static void fail(const char* ctx, CSession* s) {
- fprintf(stderr, "[tree_example] %s failed: %s\n", ctx, ts_get_last_error());
- if (s) {
- ts_session_close(s);
- ts_session_destroy(s);
- }
- exit(1);
-}
-
-int main(void) {
- const char* path = TS_PATH;
- CSession* session = ts_session_new(HOST, PORT, USER, PASS);
- if (!session) {
- fprintf(stderr, "[tree_example] ts_session_new returned NULL: %s\n", ts_get_last_error());
- return 1;
- }
- if (ts_session_open(session) != TS_OK) {
- fail("ts_session_open", session);
- }
-
- bool exists = false;
- if (ts_session_check_timeseries_exists(session, path, &exists) != TS_OK) {
- fail("ts_session_check_timeseries_exists", session);
- }
- if (exists) {
- if (ts_session_delete_timeseries(session, path) != TS_OK) {
- fail("ts_session_delete_timeseries (cleanup old)", session);
- }
- }
- if (ts_session_create_timeseries(session, path, TS_TYPE_INT64, TS_ENCODING_RLE, TS_COMPRESSION_SNAPPY) !=
- TS_OK) {
- fail("ts_session_create_timeseries", session);
- }
-
- const char* measurements[] = {"s0"};
- const char* values[] = {"100"};
- if (ts_session_insert_record_str(session, DEVICE, 1LL, 1, measurements, values) != TS_OK) {
- fail("ts_session_insert_record_str", session);
- }
-
- CSessionDataSet* dataSet = NULL;
- if (ts_session_execute_query(session, "select s0 from root.cdemo.d0", &dataSet) != TS_OK) {
- fail("ts_session_execute_query", session);
- }
- if (!dataSet) {
- fprintf(stderr, "[tree_example] dataSet is NULL\n");
- ts_session_close(session);
- ts_session_destroy(session);
- return 1;
- }
- ts_dataset_set_fetch_size(dataSet, 1024);
-
- int rows = 0;
- while (ts_dataset_has_next(dataSet)) {
- CRowRecord* record = ts_dataset_next(dataSet);
- if (!record) {
- break;
- }
- int64_t v = ts_row_record_get_int64(record, 0);
- printf("[tree_example] row %d: s0 = %lld\n", rows, (long long)v);
- ts_row_record_destroy(record);
- rows++;
- }
- ts_dataset_destroy(dataSet);
-
- printf("[tree_example] done, read %d row(s).\n", rows);
-
- if (ts_session_delete_timeseries(session, path) != TS_OK) {
- fail("ts_session_delete_timeseries", session);
- }
-
- ts_session_close(session);
- ts_session_destroy(session);
- return 0;
-}
diff --git a/example/client-cpp-example/pom.xml b/example/client-cpp-example/pom.xml
deleted file mode 100644
index 9668aee28eb..00000000000
--- a/example/client-cpp-example/pom.xml
+++ /dev/null
@@ -1,200 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.iotdb</groupId>
- <artifactId>iotdb-examples</artifactId>
- <version>2.0.7-SNAPSHOT</version>
- </parent>
- <artifactId>client-cpp-example</artifactId>
- <name>IoTDB: Example: CPP Client</name>
- <dependencies>
- <dependency>
- <groupId>org.apache.iotdb</groupId>
- <artifactId>client-cpp</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <!-- We don't really want to include it, we just want to make sure it's built first -->
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <!-- TODO: Change the build so it doesn't copy the CMakeLists.txt into the target directory directly. -->
- <build>
- <plugins>
- <plugin>
- <groupId>com.coderplus.maven.plugins</groupId>
- <artifactId>copy-rename-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-thrift-source</id>
- <goals>
- <goal>copy</goal>
- </goals>
- <configuration>
- <fileSets>
- <fileSet>
- <sourceFile>${project.basedir}/src/SessionExample.cpp</sourceFile>
- <destinationFile>${project.build.directory}/SessionExample.cpp</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>${project.basedir}/src/AlignedTimeseriesSessionExample.cpp</sourceFile>
- <destinationFile>${project.build.directory}/AlignedTimeseriesSessionExample.cpp</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>${project.basedir}/src/TableModelSessionExample.cpp</sourceFile>
- <destinationFile>${project.build.directory}/TableModelSessionExample.cpp</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>${project.basedir}/src/MultiSvrNodeClient.cpp</sourceFile>
- <destinationFile>${project.build.directory}/MultiSvrNodeClient.cpp</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>${project.basedir}/src/CMakeLists.txt</sourceFile>
- <destinationFile>${project.build.directory}/CMakeLists.txt</destinationFile>
- </fileSet>
- </fileSets>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <!--
- Fetch the client-cpp module for this os and architecture and copy it to the
- target directory, so the build can find it.
- -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>unpack-client</id>
- <goals>
- <goal>unpack</goal>
- </goals>
- <phase>generate-sources</phase>
- <configuration>
- <artifactItems>
- <artifactItem>
- <groupId>org.apache.iotdb</groupId>
- <artifactId>client-cpp</artifactId>
- <version>${project.version}</version>
- <type>zip</type>
- <classifier>cpp-${os.classifier}</classifier>
- <overWrite>true</overWrite>
- </artifactItem>
- </artifactItems>
- <outputDirectory>${project.build.directory}/client</outputDirectory>
- </configuration>
- </execution>
- <execution>
- <id>unpack-thrift</id>
- <goals>
- <goal>unpack</goal>
- </goals>
- <phase>generate-sources</phase>
- <configuration>
- <artifactItems>
- <artifactItem>
- <groupId>org.apache.iotdb.tools</groupId>
- <artifactId>iotdb-tools-thrift</artifactId>
- <version>${iotdb-tools-thrift.version}</version>
- <classifier>${os.classifier}</classifier>
- <type>zip</type>
- <overWrite>true</overWrite>
- <outputDirectory>${project.build.directory}/thrift</outputDirectory>
- </artifactItem>
- </artifactItems>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>io.github.cmake-maven-plugin</groupId>
- <artifactId>cmake-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>cmake-generate</id>
- <goals>
- <goal>generate</goal>
- </goals>
- <phase>compile</phase>
- <configuration>
- <generator>${cmake.generator}</generator>
- <sourcePath>${project.build.directory}</sourcePath>
- <projectDirectory>${project.build.directory}</projectDirectory>
- <options>
- <option>-DBOOST_INCLUDEDIR=${boost.include.dir}</option>
- </options>
- </configuration>
- </execution>
- <execution>
- <id>cmake-compile</id>
- <goals>
- <goal>compile</goal>
- </goals>
- <phase>compile</phase>
- <configuration>
- <config>${cmake.build.type}</config>
- <!-- The directory where the "generate" step generated the build configuration -->
- <projectDirectory>${project.build.directory}</projectDirectory>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- <profiles>
- <profile>
- <id>spotless-cpp</id>
- <activation>
- <jdk>[11,)</jdk>
- </activation>
- <build>
- <plugins>
- <plugin>
- <groupId>com.diffplug.spotless</groupId>
- <artifactId>spotless-maven-plugin</artifactId>
- <version>2.44.5</version>
- <configuration>
- <cpp>
- <includes>
- <include>src/**/*.h</include>
- <include>src/**/*.hpp</include>
- <include>src/**/*.c</include>
- <include>src/**/*.cc</include>
- <include>src/**/*.cpp</include>
- </includes>
- <excludes>
- <exclude>src/test/catch2/**</exclude>
- </excludes>
- <clangFormat>
- <version>${clang.format.version}</version>
- <style>file</style>
- </clangFormat>
- </cpp>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
diff --git a/example/client-cpp-example/src/CMakeLists.txt b/example/client-cpp-example/src/CMakeLists.txt
deleted file mode 100644
index 1ee249bfb80..00000000000
--- a/example/client-cpp-example/src/CMakeLists.txt
+++ /dev/null
@@ -1,151 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-PROJECT(SessionExample)
-CMAKE_MINIMUM_REQUIRED(VERSION 3.7)
-
-SET(CMAKE_CXX_STANDARD 11)
-SET(CMAKE_CXX_STANDARD_REQUIRED ON)
-SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
-
-# Add Thrift include directory
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/thrift/include)
-# Add cpp-client include directory
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/client/include)
-
-# =========================
-# SSL option (default OFF)
-# =========================
-option(WITH_SSL "Build with SSL support" OFF)
-
-IF(WITH_SSL)
- FIND_PACKAGE(OpenSSL REQUIRED)
- IF(OpenSSL_FOUND)
- MESSAGE(STATUS "OpenSSL found: ${OPENSSL_VERSION}")
- INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
- ADD_DEFINITIONS(-DWITH_SSL=1)
- ELSE()
- MESSAGE(FATAL_ERROR "OpenSSL not found, but WITH_SSL is enabled")
- ENDIF()
-ELSE()
- MESSAGE(STATUS "Building without SSL support")
- ADD_DEFINITIONS(-DWITH_SSL=0)
-ENDIF()
-
-FIND_PACKAGE(Boost REQUIRED)
-IF (DEFINED BOOST_INCLUDEDIR)
- INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
-ENDIF()
-
-# Add the libs for the cpp-client
-LINK_DIRECTORIES(${CMAKE_SOURCE_DIR}/client/lib)
-
-ADD_EXECUTABLE(SessionExample SessionExample.cpp)
-ADD_EXECUTABLE(AlignedTimeseriesSessionExample AlignedTimeseriesSessionExample.cpp)
-ADD_EXECUTABLE(TableModelSessionExample TableModelSessionExample.cpp)
-ADD_EXECUTABLE(MultiSvrNodeClient MultiSvrNodeClient.cpp)
-
-IF(MSVC)
- IF(WITH_SSL)
- TARGET_LINK_LIBRARIES(SessionExample
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- TARGET_LINK_LIBRARIES(AlignedTimeseriesSessionExample
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- TARGET_LINK_LIBRARIES(TableModelSessionExample
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- TARGET_LINK_LIBRARIES(MultiSvrNodeClient
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- ELSE()
- TARGET_LINK_LIBRARIES(SessionExample
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- )
- TARGET_LINK_LIBRARIES(AlignedTimeseriesSessionExample
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- )
- TARGET_LINK_LIBRARIES(TableModelSessionExample
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- )
- TARGET_LINK_LIBRARIES(MultiSvrNodeClient
- iotdb_session
- "${CMAKE_SOURCE_DIR}/thrift/lib/Release/thriftmd.lib"
- )
- ENDIF()
-ELSE()
- IF(WITH_SSL)
- TARGET_LINK_LIBRARIES(SessionExample
- iotdb_session
- pthread
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- TARGET_LINK_LIBRARIES(AlignedTimeseriesSessionExample
- iotdb_session
- pthread
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- TARGET_LINK_LIBRARIES(TableModelSessionExample
- iotdb_session
- pthread
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- TARGET_LINK_LIBRARIES(MultiSvrNodeClient
- iotdb_session
- pthread
- OpenSSL::SSL
- OpenSSL::Crypto
- )
- ELSE()
- TARGET_LINK_LIBRARIES(SessionExample
- iotdb_session
- pthread
- )
- TARGET_LINK_LIBRARIES(AlignedTimeseriesSessionExample
- iotdb_session
- pthread
- )
- TARGET_LINK_LIBRARIES(TableModelSessionExample
- iotdb_session
- pthread
- )
- TARGET_LINK_LIBRARIES(MultiSvrNodeClient
- iotdb_session
- pthread
- )
- ENDIF()
-ENDIF()
diff --git a/example/pom.xml b/example/pom.xml
index a8415b04d07..7730f4e7cbe 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -80,13 +80,4 @@
</plugins>
</pluginManagement>
</build>
- <profiles>
- <profile>
- <id>with-cpp</id>
- <modules>
- <module>client-cpp-example</module>
- <module>client-c-example</module>
- </modules>
- </profile>
- </profiles>
</project>
diff --git a/iotdb-client/client-cpp/CMakeLists.txt b/iotdb-client/client-cpp/CMakeLists.txt
new file mode 100644
index 00000000000..749341dc88c
--- /dev/null
+++ b/iotdb-client/client-cpp/CMakeLists.txt
@@ -0,0 +1,305 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# Apache IoTDB - C++ Session Client (top-level CMake build)
+# =============================================================================
+
+cmake_minimum_required(VERSION 3.15)
+project(iotdb_session CXX C)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+set(CMAKE_POSITION_INDEPENDENT_CODE ON)
+set(CMAKE_POLICY_DEFAULT_CMP0091 NEW)
+
+if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
+endif()
+
+set(IOTDB_EXTRA_CXX_FLAGS ""
+ CACHE STRING "Extra flags appended to CMAKE_CXX_FLAGS")
+set(IOTDB_USE_CXX11_ABI ""
+ CACHE STRING "Set _GLIBCXX_USE_CXX11_ABI for GNU libstdc++ builds (empty keeps toolchain default)")
+
+if(NOT MSVC)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
+ if(IOTDB_EXTRA_CXX_FLAGS)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${IOTDB_EXTRA_CXX_FLAGS}")
+ endif()
+endif()
+
+if(MSVC)
+ # /MD: matches default Visual Studio projects; CRT lives in the VC redistributable.
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
+endif()
+
+if(NOT IOTDB_USE_CXX11_ABI STREQUAL "" AND NOT IOTDB_USE_CXX11_ABI MATCHES "^[01]$")
+ message(FATAL_ERROR "IOTDB_USE_CXX11_ABI must be empty, 0, or 1")
+endif()
+if(NOT MSVC)
+ if(NOT IOTDB_USE_CXX11_ABI STREQUAL "")
+ set(_iotdb_cxx11_abi_stamp_value "${IOTDB_USE_CXX11_ABI}")
+ add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=${IOTDB_USE_CXX11_ABI})
+ else()
+ set(_iotdb_cxx11_abi_stamp_value "default")
+ endif()
+ set(_iotdb_cxx11_abi_stamp "${CMAKE_BINARY_DIR}/.iotdb-cxx11-abi")
+ if(EXISTS "${_iotdb_cxx11_abi_stamp}")
+ file(READ "${_iotdb_cxx11_abi_stamp}" _iotdb_previous_cxx11_abi)
+ else()
+ set(_iotdb_previous_cxx11_abi "")
+ endif()
+ if(NOT _iotdb_previous_cxx11_abi STREQUAL _iotdb_cxx11_abi_stamp_value)
+ message(STATUS
+ "IOTDB_USE_CXX11_ABI changed from '${_iotdb_previous_cxx11_abi}' "
+ "to '${_iotdb_cxx11_abi_stamp_value}'; removing cached iotdb_session objects")
+ file(REMOVE_RECURSE "${CMAKE_BINARY_DIR}/CMakeFiles/iotdb_session.dir")
+ file(GLOB _iotdb_stale_session_libs "${CMAKE_BINARY_DIR}/libiotdb_session.so*")
+ if(_iotdb_stale_session_libs)
+ file(REMOVE ${_iotdb_stale_session_libs})
+ endif()
+ endif()
+ file(WRITE "${_iotdb_cxx11_abi_stamp}" "${_iotdb_cxx11_abi_stamp_value}")
+endif()
+
+option(WITH_SSL "Build with OpenSSL support" OFF)
+option(BUILD_TESTING "Build IT test executables" OFF)
+option(IOTDB_OFFLINE "Disable all network access during configure" OFF)
+set(IOTDB_SESSION_VERSION "0.0.0"
+ CACHE STRING "IoTDB C++ session package version")
+string(REGEX MATCH "^[0-9]+" IOTDB_SESSION_SOVERSION "${IOTDB_SESSION_VERSION}")
+if(NOT IOTDB_SESSION_SOVERSION)
+ set(IOTDB_SESSION_SOVERSION "0")
+endif()
+
+set(IOTDB_DEPS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third-party"
+ CACHE PATH "Local tarball cache for third-party dependencies (lives under client-cpp/)")
+if(APPLE)
+ set(_iotdb_default_boost_version "1.84.0")
+else()
+ set(_iotdb_default_boost_version "1.60.0")
+endif()
+set(BOOST_VERSION "${_iotdb_default_boost_version}"
+ CACHE STRING "Boost version used when downloading / unpacking (Thrift build only)")
+set(THRIFT_VERSION "0.21.0"
+ CACHE STRING "Apache Thrift version used when downloading / building")
+
+if(WIN32)
+ set(IOTDB_OS_DEPS_DIR "${IOTDB_DEPS_DIR}/windows")
+elseif(APPLE)
+ set(IOTDB_OS_DEPS_DIR "${IOTDB_DEPS_DIR}/mac")
+else()
+ set(IOTDB_OS_DEPS_DIR "${IOTDB_DEPS_DIR}/linux")
+endif()
+file(MAKE_DIRECTORY "${IOTDB_OS_DEPS_DIR}")
+
+if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+ set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install"
+ CACHE PATH "Install prefix" FORCE)
+endif()
+
+list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
+
+include(FetchBoost) # -> BOOST_INCLUDE_DIR (Thrift build only)
+include(FetchBuildTools)
+if(WITH_SSL)
+ include(FetchOpenSSL)
+endif()
+include(FetchThrift)
+include(GenerateThriftSources)
+
+file(GLOB SESSION_PUBLIC_SRCS CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/session/*.cpp")
+file(GLOB SESSION_RPC_SRCS CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/rpc/*.cpp")
+
+add_library(iotdb_session SHARED
+ ${SESSION_PUBLIC_SRCS}
+ ${SESSION_RPC_SRCS}
+ ${THRIFT_GENERATED_SRCS})
+
+if(WIN32)
+ set_target_properties(iotdb_session PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON)
+endif()
+
+if(UNIX AND NOT APPLE)
+ set_target_properties(iotdb_session PROPERTIES
+ VERSION "${IOTDB_SESSION_VERSION}"
+ SOVERSION "${IOTDB_SESSION_SOVERSION}")
+endif()
+
+add_dependencies(iotdb_session iotdb_thrift_external iotdb_thrift_codegen)
+
+target_compile_definitions(iotdb_session PRIVATE THRIFT_STATIC_DEFINE IOTDB_BUILDING_SHARED)
+if(NOT IOTDB_USE_CXX11_ABI STREQUAL "" AND NOT MSVC)
+ target_compile_definitions(iotdb_session PUBLIC
+ _GLIBCXX_USE_CXX11_ABI=${IOTDB_USE_CXX11_ABI})
+endif()
+
+target_include_directories(iotdb_session
+ PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/include>
+ $<INSTALL_INTERFACE:include>
+ PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/rpc
+ ${THRIFT_GEN_CPP_DIR}
+ ${THRIFT_INCLUDE_DIR}
+ $<$<BOOL:${BOOST_INCLUDE_DIR}>:${BOOST_INCLUDE_DIR}>)
+
+if(APPLE)
+ target_link_libraries(iotdb_session PRIVATE "-Wl,-force_load,${THRIFT_STATIC_LIB_PATH}")
+elseif(UNIX AND NOT MSVC)
+ # whole-archive pulls all Thrift objects into libiotdb_session.so; allow-multiple-definition
+ # avoids libgcc __morestack_* duplicate symbol errors on some GCC/toolchain combos.
+ target_link_libraries(iotdb_session PRIVATE
+ -Wl,--whole-archive
+ ${THRIFT_STATIC_LIB_PATH}
+ -Wl,--no-whole-archive
+ -Wl,--allow-multiple-definition)
+else()
+ target_link_libraries(iotdb_session PRIVATE iotdb_thrift_static)
+endif()
+
+if(WITH_SSL)
+ target_link_libraries(iotdb_session PUBLIC OpenSSL::SSL OpenSSL::Crypto)
+ target_compile_definitions(iotdb_session PUBLIC WITH_SSL=1)
+else()
+ target_compile_definitions(iotdb_session PUBLIC WITH_SSL=0)
+endif()
+
+if(UNIX)
+ target_link_libraries(iotdb_session PUBLIC pthread)
+endif()
+
+if(IOTDB_USE_CXX11_ABI STREQUAL "1" AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ add_custom_command(TARGET iotdb_session POST_BUILD
+ COMMAND ${CMAKE_COMMAND}
+ -DIOTDB_SESSION_LIBRARY=$<TARGET_FILE:iotdb_session>
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/CheckCxx11Abi.cmake"
+ COMMENT "Verifying _GLIBCXX_USE_CXX11_ABI=1 symbols in libiotdb_session")
+endif()
+
+include(GNUInstallDirs)
+
+set(IOTDB_PUBLIC_HEADERS
+ Export.h
+ SessionConfig.h
+ Session.h
+ Common.h
+ Optional.h
+ Date.h
+ Status.h
+ Endpoint.h
+ SessionBuilder.h
+ AbstractSessionBuilder.h
+ TableSession.h
+ TableSessionBuilder.h
+ SessionC.h
+ SessionDataSet.h
+ DeviceID.h
+ Column.h
+ ColumnDecoder.h
+ TsBlock.h)
+
+# Windows: RUNTIME = iotdb_session.dll, ARCHIVE = import .lib (both under lib/ in the zip).
+install(TARGETS iotdb_session
+ RUNTIME DESTINATION lib
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib)
+
+foreach(_hdr IN LISTS IOTDB_PUBLIC_HEADERS)
+ install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/include/${_hdr}"
+ DESTINATION include)
+endforeach()
+
+set(IOTDB_SESSION_PC_LIBS "-liotdb_session")
+set(IOTDB_SESSION_PC_CFLAGS "")
+set(IOTDB_SESSION_CXX11_ABI_COMPILE_DEFINITION "")
+if(UNIX)
+ set(IOTDB_SESSION_PC_LIBS "${IOTDB_SESSION_PC_LIBS} -pthread")
+endif()
+if(NOT IOTDB_USE_CXX11_ABI STREQUAL "" AND NOT MSVC)
+ set(IOTDB_SESSION_PC_CFLAGS "-D_GLIBCXX_USE_CXX11_ABI=${IOTDB_USE_CXX11_ABI}")
+ set(IOTDB_SESSION_CXX11_ABI_COMPILE_DEFINITION
+ "_GLIBCXX_USE_CXX11_ABI=${IOTDB_USE_CXX11_ABI}")
+endif()
+configure_file(
+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake/iotdb-session-config.cmake.in"
+ "${CMAKE_BINARY_DIR}/package-metadata/cmake/iotdb-session-config.cmake"
+ @ONLY)
+configure_file(
+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake/iotdb-session.pc.in"
+ "${CMAKE_BINARY_DIR}/package-metadata/pkgconfig/iotdb-session.pc"
+ @ONLY)
+execute_process(
+ COMMAND git rev-parse HEAD
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ OUTPUT_VARIABLE IOTDB_SESSION_GIT_COMMIT
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ ERROR_QUIET)
+if(NOT IOTDB_SESSION_GIT_COMMIT)
+ set(IOTDB_SESSION_GIT_COMMIT "unknown")
+endif()
+string(TIMESTAMP IOTDB_SESSION_BUILD_TIME "%Y-%m-%dT%H:%M:%SZ" UTC)
+set(IOTDB_SESSION_CI_BUILD_ID "$ENV{GITHUB_RUN_ID}")
+if(NOT IOTDB_SESSION_CI_BUILD_ID)
+ set(IOTDB_SESSION_CI_BUILD_ID "local")
+endif()
+file(WRITE "${CMAKE_BINARY_DIR}/package-metadata/VERSION"
+ "${IOTDB_SESSION_VERSION}\n")
+file(WRITE "${CMAKE_BINARY_DIR}/package-metadata/BUILD-INFO.txt"
+ "Apache IoTDB C++ session client build information\n\n"
+ "version=${IOTDB_SESSION_VERSION}\n"
+ "commit=${IOTDB_SESSION_GIT_COMMIT}\n"
+ "build.time=${IOTDB_SESSION_BUILD_TIME}\n"
+ "ci.build.id=${IOTDB_SESSION_CI_BUILD_ID}\n"
+ "compiler=${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}\n"
+ "cmake.generator=${CMAKE_GENERATOR}\n"
+ "cmake.build.type=${CMAKE_BUILD_TYPE}\n"
+ "with.ssl=${WITH_SSL}\n"
+ "iotdb.offline=${IOTDB_OFFLINE}\n"
+ "iotdb.use.cxx11.abi=${IOTDB_USE_CXX11_ABI}\n"
+ "iotdb.extra.cxx.flags=${IOTDB_EXTRA_CXX_FLAGS}\n")
+install(FILES "${CMAKE_BINARY_DIR}/package-metadata/cmake/iotdb-session-config.cmake"
+ DESTINATION cmake)
+install(FILES "${CMAKE_BINARY_DIR}/package-metadata/pkgconfig/iotdb-session.pc"
+ DESTINATION pkgconfig)
+install(FILES
+ "${CMAKE_BINARY_DIR}/package-metadata/VERSION"
+ "${CMAKE_BINARY_DIR}/package-metadata/BUILD-INFO.txt"
+ DESTINATION .)
+
+if(BUILD_TESTING)
+ enable_testing()
+ add_subdirectory(test)
+ set(IOTDB_EXAMPLES_REGISTER_TESTS ON)
+ add_subdirectory(examples)
+endif()
+
+message(STATUS "iotdb_session configuration summary:")
+message(STATUS " WITH_SSL = ${WITH_SSL}")
+message(STATUS " BUILD_TESTING = ${BUILD_TESTING}")
+message(STATUS " IOTDB_OFFLINE = ${IOTDB_OFFLINE}")
+message(STATUS " IOTDB_USE_CXX11_ABI = ${IOTDB_USE_CXX11_ABI}")
+message(STATUS " IOTDB_DEPS_DIR = ${IOTDB_DEPS_DIR}")
+message(STATUS " BOOST_INCLUDE_DIR = ${BOOST_INCLUDE_DIR} (Thrift build only)")
+message(STATUS " THRIFT_INCLUDE_DIR = ${THRIFT_INCLUDE_DIR}")
+message(STATUS " THRIFT_STATIC_LIB = ${THRIFT_STATIC_LIB_PATH}")
+message(STATUS " THRIFT_EXECUTABLE = ${THRIFT_EXECUTABLE}")
+message(STATUS " CMAKE_INSTALL_PREFIX = ${CMAKE_INSTALL_PREFIX}")
diff --git a/iotdb-client/client-cpp/README.md b/iotdb-client/client-cpp/README.md
index 21e251d92a5..b62d4c5c88a 100644
--- a/iotdb-client/client-cpp/README.md
+++ b/iotdb-client/client-cpp/README.md
@@ -18,182 +18,571 @@
under the License.
-->
-# Building C++ Client
+# Apache IoTDB C++ Client
-## Compile and Test:
+[中文说明](README_zh.md)
-### Compile
+This directory builds and packages the Apache IoTDB C++ Session SDK. If you
+already have an `iotdb-session-cpp-<version>-<classifier>.zip` package, you do
+not need Maven, Thrift, Boost, or this source tree to use it in your own
+application. Unpack the zip, point your build system at its `include/` and
+`lib/` directories, and deploy the IoTDB runtime library with your executable.
-#### Unix
-To compile the cpp client, use the following command:
-`mvn clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests`
+## Use a packaged SDK in your project
+
+### 1. Pick and unpack the right package
+
+Choose the zip whose classifier matches the machine where the application will
+run:
+
+| Target environment | Zip classifier (suffix) |
+|--------------------|-------------------------|
+| Linux x86_64, glibc >= 2.28 | `linux-x86_64-glibc2.28` |
+| Linux aarch64, glibc >= 2.28 | `linux-aarch64-glibc2.28` |
+| macOS x86_64 | `macos-x86_64` |
+| macOS arm64 | `macos-aarch64` |
+| Windows + Visual Studio 2017 | `windows-x86_64-msvc14.1` |
+| Windows + Visual Studio 2019 | `windows-x86_64-msvc14.2` |
+| Windows + Visual Studio 2022 | `windows-x86_64-msvc14.3` |
+| Windows + Visual Studio 2026 | `windows-x86_64-msvc14.4` |
+
+Example:
+
+```bash
+unzip iotdb-session-cpp-2.0.7-SNAPSHOT-linux-x86_64-glibc2.28.zip
+export IOTDB_SESSION_HOME=$PWD/iotdb-session-cpp-2.0.7-SNAPSHOT-linux-x86_64-glibc2.28
+```
+
+The unpacked SDK contains public headers, one runtime library, CMake and
+pkg-config metadata, and examples:
-#### Windows
-To compile on Windows, please install Boost first and add following Maven
-settings:
```
--Dboost.include.dir=${your boost header folder} -Dboost.library.dir=${your boost lib (stage) folder}`
+include/ public C and C++ API headers
+lib/ libiotdb_session.so/.dylib or iotdb_session.dll + .lib
+cmake/iotdb-session-config.cmake CMake package config
+pkgconfig/iotdb-session.pc pkg-config metadata
+examples/ sample source files and an example CMakeLists.txt
+third_party/DEPENDENCIES.md bundled third-party dependency notes
```
-The thrift dependency that the cpp client uses is incompatible with MinGW, please use Visual
-Studio. It is highly recommended to use Visual Studio 2022 or later.
+Thrift and Boost are embedded into `iotdb_session`; applications do not install
+separate Thrift or Boost headers/libraries for normal SDK use.
+
+### 2. Link with CMake
+
+```cmake
+cmake_minimum_required(VERSION 3.15)
+project(my_iotdb_app LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
-##### Visual Studio 2022
-If you are using Visual Studio 2022, you can compile the cpp client with the following command:
+find_package(iotdb-session REQUIRED CONFIG)
+add_executable(my_iotdb_app main.cpp)
+target_link_libraries(my_iotdb_app PRIVATE IoTDB::iotdb_session)
```
-mvn clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests
--D"boost.include.dir"="D:\boost_1_75_0" -D"boost.library.dir"="D:\boost_1_75_0\stage\lib"
+
+Configure with the SDK prefix:
+
+```bash
+cmake -S . -B build -DCMAKE_PREFIX_PATH="$IOTDB_SESSION_HOME"
+cmake --build build
```
-##### Visual Studio 2019
-If you are using Visual Studio 2019, you can compile the cpp client with the following command:
+On Windows, use the same Visual Studio generation as the SDK package. For
+example, link a `windows-x86_64-msvc14.3` package with Visual Studio 2022.
+
+Visual Studio users can either open the project folder and add the unpacked SDK
+directory to `CMAKE_PREFIX_PATH` in CMake cache settings, or configure from a
+Developer Command Prompt:
+```bat
+cmake -S . -B build -G "Visual Studio 17 2022" -A x64 ^
+ -DCMAKE_PREFIX_PATH="%IOTDB_SESSION_HOME%"
+cmake --build build --config Release
+copy "%IOTDB_SESSION_HOME%\lib\iotdb_session.dll" build\Release\
```
-mvn clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests
--D"boost.include.dir"="D:\boost_1_75_0" -D"boost.library.dir"="D:\boost_1_75_0\stage\lib"
--Diotdb-tools-thrift.version=0.14.1.1-msvc142-SNAPSHOT -Dcmake.generator="Visual Studio 16 2019"
+
+### 3. Link with pkg-config on Linux/macOS
+
+```bash
+export PKG_CONFIG_PATH="$IOTDB_SESSION_HOME/pkgconfig:$PKG_CONFIG_PATH"
+c++ -std=c++11 main.cpp $(pkg-config --cflags --libs iotdb-session) -o my_iotdb_app
```
-#### Visual Studio 2017 or older
-If you are using Visual Studio 2017 or older, the pre-built Thrift library is incompatible. You
-will have to compile the thrift library manually:
+When running from a directory that does not already know where the shared
+library is, either copy the runtime library next to the executable or set the
+library search path:
-1. Install the dependencies of Thrift:
-* flex http://gnuwin32.sourceforge.net/packages/flex.htm
-* bison http://gnuwin32.sourceforge.net/packages/bison.htm
-* openssl https://slproweb.com/products/Win32OpenSSL.html
+```bash
+cp -P "$IOTDB_SESSION_HOME"/lib/libiotdb_session.so* .
+./my_iotdb_app
-2. Clone the repository: https://github.com/apache/iotdb-bin-resources.
+# Or:
+LD_LIBRARY_PATH="$IOTDB_SESSION_HOME/lib:$LD_LIBRARY_PATH" ./my_iotdb_app
+```
-3. Enter the "iotdb-tools-thrift" folder in the cloned repository; use the following command to
- compile the thrift library:
+### 4. Link manually
-`mvn install`
+Linux:
-4. If you encounter a problem like "cannot find 'unistd.h'", please open the file
-"iotdb-bin-resources\iotdb-tools-thrift\target\build\compiler\cpp\thrift\thriftl.cc" and replace
-"#include <unistd.h>" with "#include <io.h>" and "#include <process.h>"; then, rerun the command
- in the third step;
+```bash
+c++ -std=c++11 main.cpp \
+ -I"$IOTDB_SESSION_HOME/include" \
+ -L"$IOTDB_SESSION_HOME/lib" \
+ -liotdb_session -pthread \
+ -Wl,-rpath,"$IOTDB_SESSION_HOME/lib" \
+ -o my_iotdb_app
+```
-5. Return to the cpp client repository and compile it with:
+macOS:
+```bash
+c++ -std=c++11 main.cpp \
+ -I"$IOTDB_SESSION_HOME/include" \
+ -L"$IOTDB_SESSION_HOME/lib" \
+ -liotdb_session \
+ -Wl,-rpath,"$IOTDB_SESSION_HOME/lib" \
+ -o my_iotdb_app
```
-mvn clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests
--D"boost.include.dir"="D:\boost_1_75_0" -D"boost.library.dir"="D:\boost_1_75_0\stage\lib"
+
+Windows with MSVC:
+
+```bat
+cl /std:c++14 /EHsc main.cpp /I "%IOTDB_SESSION_HOME%\include" ^
+ /link /LIBPATH:"%IOTDB_SESSION_HOME%\lib" iotdb_session.lib
+copy "%IOTDB_SESSION_HOME%\lib\iotdb_session.dll" .
```
+### 5. Build the bundled examples
+
+The package includes example sources under `examples/`. From the unpacked SDK
+root:
-### Test
-First build IoTDB server together with the cpp client.
+```bash
+cmake -S examples -B examples-build -DCMAKE_BUILD_TYPE=Release
+cmake --build examples-build
+```
-Explicitly using "install" instead of package in order to be sure we're using libs built on this
-machine.
+On Windows:
-`mvn clean install -P with-cpp -pl distribution,iotdb-client/client-cpp -am -DskipTests`
+```bat
+cmake -S examples -B examples-build -G "Visual Studio 17 2022" -A x64
+cmake --build examples-build --config Release
+```
-After run verify
+The example build copies the IoTDB runtime library next to each example
+executable. `cmake --build examples-build --target example-dist` also creates a
+`dist/` folder containing the examples and runtime library.
-`mvn clean verify -P with-cpp -pl iotdb-client/client-cpp -am`
+### 6. Minimal C++ program
-## Code Formatting
+```cpp
+#include "Session.h"
-We use `clang-format` as the only formatter for C++ code and trigger it through Maven Spotless.
+#include <iostream>
+#include <memory>
-### Required version
+int main() {
+ auto session = std::make_shared<Session>("127.0.0.1", 6667, "root", "root");
+ session->open(false);
-The version is pinned in the root `pom.xml` as property `clang.format.version` (same approach as Apache TsFile). Use **clang-format 17.0.6** locally so Spotless agrees with CI.
+ session->setStorageGroup("root.test");
+ if (!session->checkTimeseriesExists("root.test.d0.s0")) {
+ session->createTimeseries(
+ "root.test.d0.s0", TSDataType::INT64, TSEncoding::RLE, CompressionType::SNAPPY);
+ }
-**JDK for Maven:** the C++ `clangFormat` step is registered only when running Maven on **JDK 11 or newer** (see the `spotless-cpp` profile in this module and in `client-cpp-example`). The repository root still supports JDK 8 for Java builds, but `spotless:check` / `spotless:apply` for C++ will not apply the clang-format rules if you use JDK 8.
+ session->close();
+ std::cout << "IoTDB C++ session is ready." << std::endl;
+ return 0;
+}
+```
-### Install clang-format 17.0.6
+The examples in the package connect to `127.0.0.1:6667` with `root` / `root`
+by default. Start IoTDB before running them.
-- Linux (Ubuntu): On **24.04+**, `sudo apt-get install -y clang-format-17`. On **22.04**, that package is not in the default archive; add the LLVM 17 repo with [apt.llvm.org](https://apt.llvm.org/) (e.g. `sudo ./llvm.sh 17`, as CI does). The script installs `clang-17` and related tools but **not** the `clang-format-17` package, so also run `sudo apt-get install -y clang-format-17`. Then point the default `clang-format` at 17.x (Spotless invokes `clang-format` on `PATH`; some releases def [...]
+### Runtime deployment notes
- `sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-17 100`
+- Linux release packages are built in the `manylinux_2_28` container and require
+ glibc 2.28 or newer.
+- Windows packages use the dynamic MSVC runtime (`/MD`). Install the Microsoft
+ Visual C++ Redistributable matching your Visual Studio generation on target
+ machines that do not already have it.
+- Put `libiotdb_session.so`, `libiotdb_session.dylib`, or `iotdb_session.dll`
+ next to your executable, or configure the platform library search path. On
+ Linux, keep the `libiotdb_session.so*` symlink chain together when copying
+ files manually.
- `sudo update-alternatives --set clang-format /usr/bin/clang-format-17`
+## Build the SDK from source
-- macOS: `brew install llvm@17`, then e.g. `ln -sf "$(brew --prefix llvm@17)/bin/clang-format" "$(brew --prefix)/bin/clang-format"` and/or put `$(brew --prefix llvm@17)/bin` on your `PATH`.
+The C++ client is built by a single top-level `CMakeLists.txt` in this
+directory. The outer Maven POM is a thin wrapper that invokes CMake; you can
+also build the client standalone with just `cmake` if you don't have Maven
+available.
-- Windows: `choco install llvm --version=17.0.6 --force -y` (CI uses `--force` like TsFile so the expected LLVM is selected).
+### Build layout at a glance
-### Validate only (no changes)
+```
+iotdb-client/client-cpp/
+├── CMakeLists.txt # single entry point - manages everything
+├── cmake/ # helpers (FetchBoost / FetchThrift / ...)
+├── third-party/ # local tarball cache (one sub-dir per OS)
+│ ├── linux/ mac/ windows/
+├── src/include/ # public API headers (installed to include/)
+├── src/session/ # Session / Table / C API implementation (.cpp)
+├── src/rpc/ # Thrift RPC layer (private, not installed)
+├── test/ # Catch2-based integration tests
+└── pom.xml # Maven wrapper (cmake-maven-plugin)
+```
-`./mvnw -P with-cpp -pl iotdb-client/client-cpp spotless:check`
+During configure CMake will, in order:
+
+1. Resolve Boost headers (`find_package` → local `third-party/<os>/` tarball →
+ download from `archives.boost.io` when not in offline mode).
+2. On Linux/macOS, ensure `m4` / `flex` / `bison` are available; if not,
+ build them from local tarballs into `build/tools/bin` (no `sudo`
+ required).
+3. Build a static Apache Thrift from source (tarball cache → download fallback).
+4. Run the produced `thrift` compiler on
+ `iotdb-protocol/thrift-{commons,datanode}/src/main/thrift/*.thrift`.
+5. Compile `iotdb_session` (the C/C++ session library) and, optionally,
+ the Catch2 integration test binaries.
+6. `cmake --install` lays out the SDK under `target/install/{include,lib}`,
+ which Maven's assembly step packages into a zip.
+
+### Build matrix
+
+| Goal | Command |
+|-------------------------------|--------------------------------------------------------------------------------------------------------|
+| Library only (Linux/macOS) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests package` |
+| Debug library (Linux/macOS) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests -Dcmake.build.type=Debug package` |
+| Library only (Windows / MSVC) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests "-Dboost.include.dir=C:\boost_1_88_0" package` |
+| Debug library (Windows / MSVC) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests -Dcmake.build.type=Debug "-Dboost.include.dir=C:\boost_1_88_0" package` |
+| Library + ITs (Linux/macOS) | `mvn clean install -P with-cpp -pl distribution,iotdb-client/client-cpp -am` then `mvn -P with-cpp -pl iotdb-client/client-cpp -am verify` |
+| Direct CMake (no Maven) | `cmake -S iotdb-client/client-cpp -B build && cmake --build build --target install` |
+
+The Maven build sets `cmake.install.prefix` to `target/install/`. Output zips
+land at `iotdb-client/client-cpp/target/iotdb-session-cpp-<version>-<classifier>.zip`
+(with a package root directory and a `.sha512` checksum generated alongside).
+The classifier can be overridden with `-Dclient.cpp.package.classifier=...` when
+building multiple toolchains on the same platform.
+
+### Release packages (CI)
+
+The [C++ Client package](../../.github/workflows/client-cpp-package.yml) workflow
+builds one zip per platform/toolchain. Pick the artifact that matches your
+deployment environment:
+
+| Target environment | Zip classifier (suffix) |
+|--------------------|-------------------------|
+| Linux x86_64, glibc >= 2.28 | `linux-x86_64-glibc2.28` |
+| Linux aarch64, glibc >= 2.28 | `linux-aarch64-glibc2.28` |
+| macOS x86_64 | `macos-x86_64` |
+| macOS arm64 | `macos-aarch64` |
+| Windows + Visual Studio 2017 | `windows-x86_64-msvc14.1` |
+| Windows + Visual Studio 2019 | `windows-x86_64-msvc14.2` |
+| Windows + Visual Studio 2022 | `windows-x86_64-msvc14.3` |
+| Windows + Visual Studio 2026 | `windows-x86_64-msvc14.4` |
+
+Example file name:
+`iotdb-session-cpp-2.0.10.1-linux-x86_64-glibc2.28.zip`.
+
+Linux release packages are built in the `manylinux_2_28` containers with GCC 14,
+so they require glibc 2.28 or newer on the deployment host.
+
+| Architecture | manylinux_2_28 image |
+|--------------|----------------------|
+| x86_64 | `quay.io/pypa/manylinux_2_28_x86_64` |
+| i686 | `quay.io/pypa/manylinux_2_28_i686` |
+| aarch64 | `quay.io/pypa/manylinux_2_28_aarch64` |
+| ppc64le | `quay.io/pypa/manylinux_2_28_ppc64le` |
+| s390x | `quay.io/pypa/manylinux_2_28_s390x` |
+
+Thrift **0.21.0** is compiled from source during the CMake configure step (see
+`cmake/FetchThrift.cmake`). Older releases that used pre-built
+`iotdb-tools-thrift` Maven artifacts and `-Diotdb-tools-thrift.version=...`
+for glibc/MSVC compatibility apply only to the **legacy** client-cpp build;
+with the current CMake build, compatibility is determined by the **compiler
+and OS used to build** the SDK, not by that Maven property.
+
+### Local build for a specific classifier
+
+Linux x86_64 (glibc 2.28 baseline, matching the manylinux_2_28 release build):
+
+```bash
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Dclient.cpp.package.classifier=linux-x86_64-glibc2.28 package
+```
-`./mvnw -P with-cpp -pl example/client-cpp-example spotless:check`
+Debug build:
-### Auto-fix formatting
+```bash
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Dcmake.build.type=Debug package
+```
-`./mvnw -P with-cpp -pl iotdb-client/client-cpp spotless:apply`
+Direct CMake Debug builds use the same build type. On Linux/macOS, pass
+`-DCMAKE_BUILD_TYPE=Debug` during configure. On Windows with Visual Studio,
+also pass `-DCMAKE_BUILD_TYPE=Debug` during configure so the bundled Thrift
+static library is built with the Debug MSVC runtime, then build with
+`--config Debug`:
-`./mvnw -P with-cpp -pl example/client-cpp-example spotless:apply`
+```bash
+# Linux/macOS
+cmake -S iotdb-client/client-cpp -B build -DCMAKE_BUILD_TYPE=Debug
+cmake --build build --target install
-### Windows (PowerShell)
+# Windows / Visual Studio
+cmake -S iotdb-client/client-cpp -B build -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Debug
+cmake --build build --config Debug --target install
+```
-PowerShell may treat a comma in `-pl` as an argument separator. Prefer the two commands above. If you need a single invocation, quote the whole `-pl` value, for example:
+Windows (match the Visual Studio version you use to build your application):
-`./mvnw -P with-cpp "-pl=iotdb-client/client-cpp,example/client-cpp-example" spotless:check`
+```powershell
+# Visual Studio 2022 (default on recent Windows)
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests package
-## Package Hierarchy
+# Visual Studio 2019
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests `
+ -Dcmake.generator="Visual Studio 16 2019" `
+ -Dclient.cpp.package.classifier=windows-x86_64-msvc14.2 package
-If the compilation finishes successfully, the packaged zip file will be placed under
-"client-cpp/target/client-cpp-${project.version}-cpp-${os}.zip".
+# Visual Studio 2017 (CMake uses -A x64 on Windows automatically)
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests `
+ -Dcmake.generator="Visual Studio 15 2017" `
+ -Dclient.cpp.package.classifier=windows-x86_64-msvc14.1 package
+```
-On macOS, the hierarchy of the package should look like this:
+On Windows, the build passes `-DCMAKE_GENERATOR_PLATFORM=x64` so Visual Studio
+generators target **x64** (VS2017 otherwise defaults to Win32).
+
+## CMake options
+
+The table below lists CMake cache variables. When building through **Maven**,
+pass them as Maven properties (the POM maps them to `-D` options for CMake):
+
+| CMake variable | Maven property (`-D...`) |
+|----------------|--------------------------|
+| `WITH_SSL` | `with.ssl` (e.g. `-Dwith.ssl=ON`) |
+| `IOTDB_OFFLINE` | `iotdb.offline` |
+| `BUILD_TESTING` | `build.tests` |
+| `IOTDB_DEPS_DIR` | `iotdb.deps.dir` |
+| `BOOST_INCLUDEDIR` | `boost.include.dir` (legacy alias) |
+| `CMAKE_BUILD_TYPE` | `cmake.build.type` (e.g. `-Dcmake.build.type=Debug`) |
+
+For a **standalone** `cmake` configure, pass `-DWITH_SSL=ON`, `-DIOTDB_OFFLINE=ON`,
+etc. directly.
+
+| Option | Default | Purpose |
+|-----------------------|----------------------------------|----------------------------------------------------------------------------------------------------------|
+| `WITH_SSL` | `OFF` | Link against OpenSSL. See *SSL* below. |
+| `BUILD_TESTING` | `OFF` (Maven sets `ON` for verify) | Build Catch2 IT executables (Catch2 v2.13.7 header downloaded at configure time). |
+| `CATCH2_INCLUDE_DIR` | (unset) | Pre-downloaded Catch2 include dir (Maven sets this under `target/test/catch2`). |
+| `IOTDB_OFFLINE` | `OFF` | Disallow any network access during configure. |
+| `IOTDB_DEPS_DIR` | `<client-cpp>/third-party` | Override the local tarball cache directory. |
+| `BOOST_VERSION` | `1.60.0` (`1.84.0` on macOS) | Boost version that CMake will look for / download. |
+| `THRIFT_VERSION` | `0.21.0` | Apache Thrift version to build from source. |
+| `BOOST_ROOT` | (unset) | Existing Boost install to reuse, equivalent to `-Dboost.include.dir=...` from the legacy build. |
+| `OPENSSL_ROOT_DIR` | (unset) | Existing OpenSSL install when `WITH_SSL=ON`. |
+| `CMAKE_INSTALL_PREFIX`| `<build>/install` | Install location. |
+| `CMAKE_BUILD_TYPE` | `Release` | Single-config generator build type. Use `Debug` to produce a debug library. |
+
+For Visual Studio generators on Windows, still set `CMAKE_BUILD_TYPE=Debug`
+when configuring a Debug SDK build. The top-level project uses that value to
+build bundled third-party static libraries, while `cmake --build --config Debug`
+selects the final Visual Studio configuration.
+
+## Online build (default)
+
+CMake will download any missing tarball at configure time. The first run is
+slow (≈100 MB download + a Thrift build); subsequent runs reuse the
+extracted artifacts under `build/_deps/`.
+
+```bash
+# Linux / macOS
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests package
+
+# Windows (Developer Command Prompt for VS, PowerShell, or cmd)
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests "-Dboost.include.dir=C:\boost_1_88_0" package
```
-.
-+-- client
-| +-- include
-| +-- Session.h
-| +-- IClientRPCService.h
-| +-- client_types.h
-| +-- common_types.h
-| +-- thrift
-| +-- thrift_headers...
-| +-- lib
-| +-- Release
-| +-- libiotdb_session.dylib
-| +-- parser.dylib
-| +-- thriftmd.dylib
-| +-- tutorialgencpp.dylib
+
+Standalone CMake uses the same online dependency resolution:
+
+```bash
+# Linux / macOS
+cmake -S iotdb-client/client-cpp -B build -DCMAKE_BUILD_TYPE=Release
+cmake --build build --target install
+
+# Windows / Visual Studio
+cmake -S iotdb-client/client-cpp -B build -G "Visual Studio 17 2022" -A x64
+cmake --build build --config Release --target install
```
-## Using C++ Client:
+## Offline build
+
+1. Pre-populate the platform-specific sub-directory under `third-party/`:
+
+ | Platform | Required files |
+ |------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+ | `linux/` | `thrift-0.21.0.tar.gz`, `boost_1_60_0.tar.gz`, `m4-1.4.19.tar.gz`, `flex-2.6.4.tar.gz`, `bison-3.8.tar.gz` (and `openssl-3.5.0.tar.gz` when `WITH_SSL=ON`) |
+ | `mac/` | `thrift-0.21.0.tar.gz`, `boost_1_84_0.tar.gz` (newer Boost for Xcode/Clang; Apple ships m4/flex/bison; `openssl-3.5.0.tar.gz` optional) |
+ | `windows/` | `thrift-0.21.0.tar.gz`, `boost_1_60_0.tar.gz` (Boost headers only - no `b2` build required for `iotdb_session`) |
+
+ Reference URLs (the configure step uses the same):
+ - Apache Thrift 0.21.0: <https://archive.apache.org/dist/thrift/0.21.0/thrift-0.21.0.tar.gz>
+ - Boost 1.60.0: <https://archives.boost.io/release/1.60.0/source/boost_1_60_0.tar.gz>
+ - GNU m4 1.4.19: <https://ftp.gnu.org/gnu/m4/m4-1.4.19.tar.gz>
+ - GNU flex 2.6.4: <https://github.com/westes/flex/releases/download/v2.6.4/flex-2.6.4.tar.gz>
+ - GNU bison 3.8: <https://ftp.gnu.org/gnu/bison/bison-3.8.tar.gz>
+ - OpenSSL 3.5.0: <https://www.openssl.org/source/openssl-3.5.0.tar.gz>
+
+2. Run the build with offline mode enabled:
+
+ ```bash
+ mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Diotdb.offline=ON package
+ ```
+
+ or, going straight through CMake:
+
+ ```bash
+ cmake -S iotdb-client/client-cpp -B build -DIOTDB_OFFLINE=ON
+ cmake --build build --config Release --target install
+ ```
+
+CI environments can share a single cache by setting
+`-DIOTDB_DEPS_DIR=/path/to/cache` instead of copying tarballs around.
+
+## Platform-specific notes
+
+### Linux
+
+- Tested with GCC 7+ and Clang 9+. Anything that can compile Apache Thrift
+ 0.21.0 works.
+- Build deps that must already exist on the host (only required when
+ CMake auto-builds m4/flex/bison from tarball): `make`, `autoconf`,
+ `gcc`, plus the standard C/C++ toolchain. `sudo` is **not** required;
+ the helper tools install under `build/tools/`.
+- If you would rather use distro-provided tools (`apt install m4 flex
+ bison`), CMake will pick them up first.
+
+### macOS
+
+- Xcode Command Line Tools provide `m4`, `flex`, `bison`, and `make`,
+ so the auto-build path normally skips them.
+- Homebrew users can `brew install boost` to short-circuit `FetchBoost`.
+
+### Windows
+
+Visual Studio **2017, 2019, 2022, or 2026** is supported for building the SDK.
+Link your application against the zip built with the **same VS generation** you
+use for your project.
+
+Prerequisites:
+
+1. **Boost.** Download and extract
+ <https://archives.boost.io/release/1.88.0/source/boost_1_88_0.zip>
+ (any 1.60+ release will work). `iotdb_session` only needs Boost
+ headers, so running `bootstrap.bat` / `b2` is optional. Pass the
+ location with either `-Dboost.include.dir="C:\boost_1_88_0"` (Maven)
+ or `-DBOOST_ROOT="C:\boost_1_88_0"` (raw CMake).
+2. **flex / bison.** Install <https://sourceforge.net/projects/winflexbison/>
+ and rename `win_flex.exe`→`flex.exe`, `win_bison.exe`→`bison.exe` on
+ `PATH`.
+3. **OpenSSL** *(only when `WITH_SSL=ON`)*: run the Win64 OpenSSL
+ installer from <https://slproweb.com/products/Win32OpenSSL.html>, then
+ pass `-DOPENSSL_ROOT_DIR=...` to CMake.
+
+On Windows the SDK ships as **`iotdb_session.dll`** plus an import library
+**`iotdb_session.lib`**, built with **`/MD`** (dynamic CRT, same as a
+default Visual Studio application). Thrift is linked into the DLL; users
+do not install separate Thrift headers or libraries. Place
+`iotdb_session.dll` next to your `.exe` or on `PATH`.
+
+Auto-building m4/flex/bison from tarball is **not** supported on Windows;
+the GNU autotools tarballs assume a POSIX shell environment.
+
+## SSL
+
+Both Thrift and `iotdb_session` build without OpenSSL by default. Enable
+SSL with `-Dwith.ssl=ON` (Maven) or `-DWITH_SSL=ON` (standalone CMake).
+CMake first calls `find_package(OpenSSL)`;
+if nothing is found, it falls back to:
+
+- **Linux / macOS** – use a local `openssl-<ver>.tar.gz` (or download it
+ when not in offline mode), configure with `no-shared`, install into
+ `build/_deps/openssl/install`, and link statically.
+- **Windows** – fail with a friendly message that points at the Win64
+ OpenSSL installer. Building OpenSSL from source via MSVC is out of scope.
+
+## Tests
+
+Maven binds `cmake-maven-plugin`'s `test` goal to the `integration-test`
+phase and runs `ctest`. `pre-integration-test` spawns a local IoTDB server
+from `distribution/target/.../sbin/start-standalone.{sh,bat}`, so make sure
+the distribution module is built first:
+
+```bash
+mvn clean install -P with-cpp -pl distribution,iotdb-client/client-cpp -am -DskipTests
+mvn -P with-cpp -pl iotdb-client/client-cpp -am verify
```
-1. Put the zip file "client-cpp-${project.version}-cpp-${os}.zip" wherever you want;
-2. Unzip the archive using the following command, and then you can get the two directories
-mentioned above, the header file and the dynamic library:
- unzip client-cpp-${project.version}-cpp-${os}.zip
+Running ctest directly (after a `mvn ... package` build) is also supported:
+
+```bash
+cd iotdb-client/client-cpp/target/build
+ctest --output-on-failure
+```
-3. Write C++ code to call the operation interface of the cpp client to operate IoTDB,
- for detail interface information, please refer to the link: https://iotdb.apache.org/UserGuide/latest/API/Programming-Cpp-Native-API.html
+## Code formatting
- E.g:
- #include "include/Session.h"
- #include <memory>
- #include <iostream>
+We use `clang-format` (pinned by the root POM as `clang.format.version`)
+through Maven Spotless. **clang-format 17.0.6** is the version CI runs.
- int main() {
- std::cout << "open session" << std::endl;
- std::shared_ptr<Session> session(new Session("127.0.0.1", 6667, "root", "root"));
- session->open(false);
+```bash
+mvn -P with-cpp -pl iotdb-client/client-cpp spotless:check
+mvn -P with-cpp -pl iotdb-client/client-cpp spotless:apply
+```
- std::cout << "setStorageGroup: root.test01" << std::endl;
- session->setStorageGroup("root.test01");
+On JDK 8 the C++ Spotless profile is skipped automatically (Spotless's
+clang-format integration requires Spotless 2.44+, which itself requires
+JDK 11+).
- if (!session->checkTimeseriesExists("root.test01.d0.s0")) {
- session->createTimeseries("root.test01.d0.s0", TSDataType::INT64, TSEncoding::RLE, CompressionType::SNAPPY);
- std::cout << "create Timeseries: root.test01.d0.s0" << std::endl;
- }
+## Package layout
- std::cout << "session close" << std::endl;
- session->close();
- }
+A successful `mvn ... package` produces
+`target/iotdb-session-cpp-<version>-<classifier>.zip` with this layout:
-4. Compile and execute
- clang++ -O2 user-cpp-code.cpp -liotdb_session -L/user-unzip-absolute-path/lib -Wl,-rpath /user-unzip-absolute-path/lib -std=c++11
- ./a.out
```
+README.md
+README_zh.md
+LICENSE
+NOTICE
+VERSION
+BUILD-INFO.txt
+include/
+├── Session.h
+├── SessionC.h
+└── ... (public API headers only; no Thrift/Boost)
+lib/
+├── libiotdb_session.{so,dylib} (Linux / macOS)
+├── iotdb_session.dll (Windows – runtime)
+└── iotdb_session.lib (Windows – import library for linking)
+third_party/
+└── DEPENDENCIES.md
+cmake/
+└── iotdb-session-config.cmake
+pkgconfig/
+└── iotdb-session.pc
+examples/
+├── CMakeLists.txt
+└── ...
+```
+
+Thrift is embedded inside `iotdb_session` on all platforms; it is not shipped
+as a separate install artifact.
+
+For full API documentation see the [C++ Native API guide](https://iotdb.apache.org/UserGuide/latest/API/Programming-Cpp-Native-API.html).
diff --git a/iotdb-client/client-cpp/README_zh.md b/iotdb-client/client-cpp/README_zh.md
new file mode 100644
index 00000000000..ec198aa9d06
--- /dev/null
+++ b/iotdb-client/client-cpp/README_zh.md
@@ -0,0 +1,277 @@
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+# Apache IoTDB C++ Client
+
+[English](README.md)
+
+本目录用于构建和打包 Apache IoTDB C++ Session SDK。如果你已经拿到了
+`iotdb-session-cpp-<version>-<classifier>.zip`,在自己的 C/C++ 项目中使用
+时不需要 Maven、Thrift、Boost,也不需要本源码目录。解压 zip 后,让项目引用
+其中的 `include/` 和 `lib/`,并在运行时把 IoTDB 动态库随可执行文件一起部署
+即可。
+
+## 在项目中使用已打好的 SDK 包
+
+### 1. 选择并解压正确的包
+
+请按应用运行环境选择对应 classifier:
+
+| 目标环境 | Zip classifier 后缀 |
+|----------|---------------------|
+| Linux x86_64,glibc >= 2.28 | `linux-x86_64-glibc2.28` |
+| Linux aarch64,glibc >= 2.28 | `linux-aarch64-glibc2.28` |
+| macOS x86_64 | `macos-x86_64` |
+| macOS arm64 | `macos-aarch64` |
+| Windows + Visual Studio 2017 | `windows-x86_64-msvc14.1` |
+| Windows + Visual Studio 2019 | `windows-x86_64-msvc14.2` |
+| Windows + Visual Studio 2022 | `windows-x86_64-msvc14.3` |
+| Windows + Visual Studio 2026 | `windows-x86_64-msvc14.4` |
+
+示例:
+
+```bash
+unzip iotdb-session-cpp-2.0.7-SNAPSHOT-linux-x86_64-glibc2.28.zip
+export IOTDB_SESSION_HOME=$PWD/iotdb-session-cpp-2.0.7-SNAPSHOT-linux-x86_64-glibc2.28
+```
+
+解压后的 SDK 主要包含:
+
+```
+include/ C/C++ 公开 API 头文件
+lib/ libiotdb_session.so/.dylib 或 iotdb_session.dll + .lib
+cmake/iotdb-session-config.cmake CMake package config
+pkgconfig/iotdb-session.pc pkg-config 元数据
+examples/ 示例源码和示例 CMakeLists.txt
+third_party/DEPENDENCIES.md 内置第三方依赖说明
+```
+
+Thrift 和 Boost 已封装进 `iotdb_session`,普通应用接入时不需要额外安装
+Thrift 或 Boost 的头文件/库。
+
+### 2. 用 CMake 链接
+
+项目中的 `CMakeLists.txt` 可这样写:
+
+```cmake
+cmake_minimum_required(VERSION 3.15)
+project(my_iotdb_app LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+find_package(iotdb-session REQUIRED CONFIG)
+
+add_executable(my_iotdb_app main.cpp)
+target_link_libraries(my_iotdb_app PRIVATE IoTDB::iotdb_session)
+```
+
+配置时传入 SDK 解压目录:
+
+```bash
+cmake -S . -B build -DCMAKE_PREFIX_PATH="$IOTDB_SESSION_HOME"
+cmake --build build
+```
+
+Windows 上请使用与 SDK 包一致的 Visual Studio 代际。例如
+`windows-x86_64-msvc14.3` 对应 Visual Studio 2022。
+
+Visual Studio 用户可以直接打开项目目录,并在 CMake 缓存设置里把 SDK 解压目录
+加入 `CMAKE_PREFIX_PATH`;也可以在 Developer Command Prompt 中执行:
+
+```bat
+cmake -S . -B build -G "Visual Studio 17 2022" -A x64 ^
+ -DCMAKE_PREFIX_PATH="%IOTDB_SESSION_HOME%"
+cmake --build build --config Release
+copy "%IOTDB_SESSION_HOME%\lib\iotdb_session.dll" build\Release\
+```
+
+### 3. 在 Linux/macOS 上用 pkg-config 链接
+
+```bash
+export PKG_CONFIG_PATH="$IOTDB_SESSION_HOME/pkgconfig:$PKG_CONFIG_PATH"
+c++ -std=c++11 main.cpp $(pkg-config --cflags --libs iotdb-session) -o my_iotdb_app
+```
+
+运行时如果系统找不到动态库,可以把动态库复制到可执行文件同目录,或设置库搜索
+路径:
+
+```bash
+cp -P "$IOTDB_SESSION_HOME"/lib/libiotdb_session.so* .
+./my_iotdb_app
+
+# 或者:
+LD_LIBRARY_PATH="$IOTDB_SESSION_HOME/lib:$LD_LIBRARY_PATH" ./my_iotdb_app
+```
+
+### 4. 手动指定头文件和库路径
+
+Linux:
+
+```bash
+c++ -std=c++11 main.cpp \
+ -I"$IOTDB_SESSION_HOME/include" \
+ -L"$IOTDB_SESSION_HOME/lib" \
+ -liotdb_session -pthread \
+ -Wl,-rpath,"$IOTDB_SESSION_HOME/lib" \
+ -o my_iotdb_app
+```
+
+macOS:
+
+```bash
+c++ -std=c++11 main.cpp \
+ -I"$IOTDB_SESSION_HOME/include" \
+ -L"$IOTDB_SESSION_HOME/lib" \
+ -liotdb_session \
+ -Wl,-rpath,"$IOTDB_SESSION_HOME/lib" \
+ -o my_iotdb_app
+```
+
+Windows + MSVC:
+
+```bat
+cl /std:c++14 /EHsc main.cpp /I "%IOTDB_SESSION_HOME%\include" ^
+ /link /LIBPATH:"%IOTDB_SESSION_HOME%\lib" iotdb_session.lib
+copy "%IOTDB_SESSION_HOME%\lib\iotdb_session.dll" .
+```
+
+### 5. 编译包内 examples
+
+SDK 包内 `examples/` 目录包含示例源码。进入 SDK 解压根目录后执行:
+
+```bash
+cmake -S examples -B examples-build -DCMAKE_BUILD_TYPE=Release
+cmake --build examples-build
+```
+
+Windows:
+
+```bat
+cmake -S examples -B examples-build -G "Visual Studio 17 2022" -A x64
+cmake --build examples-build --config Release
+```
+
+examples 构建会把 IoTDB 运行时库复制到每个示例可执行文件旁边。也可以执行
+`cmake --build examples-build --target example-dist` 生成包含示例和运行时库的
+`dist/` 目录。
+
+### 6. 最小 C++ 示例
+
+```cpp
+#include "Session.h"
+
+#include <iostream>
+#include <memory>
+
+int main() {
+ auto session = std::make_shared<Session>("127.0.0.1", 6667, "root", "root");
+ session->open(false);
+
+ session->setStorageGroup("root.test");
+ if (!session->checkTimeseriesExists("root.test.d0.s0")) {
+ session->createTimeseries(
+ "root.test.d0.s0", TSDataType::INT64, TSEncoding::RLE, CompressionType::SNAPPY);
+ }
+
+ session->close();
+ std::cout << "IoTDB C++ session is ready." << std::endl;
+ return 0;
+}
+```
+
+包内 `examples/` 下的示例默认连接 `127.0.0.1:6667`,用户名和密码均为
+`root`。运行示例前请先启动 IoTDB 服务。
+
+### 运行时部署注意事项
+
+- Linux 发版包在 `manylinux_2_28` 容器中使用 GCC 14 构建,目标机器需要 glibc 2.28 或更新
+ 版本。
+- Windows 包使用 MSVC 动态运行时(`/MD`)。目标机器如果没有对应运行时,请安装
+ 与 Visual Studio 代际匹配的 Microsoft Visual C++ Redistributable。
+- 将 `libiotdb_session.so`、`libiotdb_session.dylib` 或 `iotdb_session.dll`
+ 放在可执行文件同目录,或配置平台对应的动态库搜索路径。Linux 手动复制时请保留
+ `libiotdb_session.so*` 的符号链接链。
+
+## 从源码构建 SDK
+
+C++ client 使用本目录下单一的 `CMakeLists.txt` 构建。外层 Maven POM 只是调用
+CMake 的包装;没有 Maven 时也可以直接使用 CMake。
+
+### 常用构建命令
+
+| 目标 | 命令 |
+|------|------|
+| 只构建库(Linux/macOS) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests package` |
+| 构建 Debug 库(Linux/macOS) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests -Dcmake.build.type=Debug package` |
+| 只构建库(Windows / MSVC) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests "-Dboost.include.dir=C:\boost_1_88_0" package` |
+| 构建 Debug 库(Windows / MSVC) | `mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests -Dcmake.build.type=Debug "-Dboost.include.dir=C:\boost_1_88_0" package` |
+| 直接使用 CMake | `cmake -S iotdb-client/client-cpp -B build && cmake --build build --target install` |
+
+Maven 构建会把 SDK 安装到 `target/install/`,并生成
+`target/iotdb-session-cpp-<version>-<classifier>.zip` 及对应 `.sha512`。
+可通过 `-Dclient.cpp.package.classifier=...` 指定 classifier。
+
+### CMake 选项
+
+通过 Maven 构建时,常用 CMake 选项对应的 Maven 属性如下:
+
+| CMake 变量 | Maven 属性 |
+|------------|------------|
+| `WITH_SSL` | `with.ssl`,例如 `-Dwith.ssl=ON` |
+| `IOTDB_OFFLINE` | `iotdb.offline` |
+| `BUILD_TESTING` | `build.tests` |
+| `IOTDB_DEPS_DIR` | `iotdb.deps.dir` |
+| `BOOST_INCLUDEDIR` | `boost.include.dir` |
+| `CMAKE_BUILD_TYPE` | `cmake.build.type`,例如 `-Dcmake.build.type=Debug` |
+
+直接使用 CMake 时传入 `-DWITH_SSL=ON`、`-DIOTDB_OFFLINE=ON` 等即可。
+Debug 构建请在配置阶段传入 `-DCMAKE_BUILD_TYPE=Debug`。Windows 使用 Visual
+Studio 生成器时也需要传入该选项,以便内置 Thrift 静态库使用 Debug MSVC 运行时;
+随后用 `cmake --build build --config Debug --target install` 构建安装。
+
+```bash
+# Linux/macOS
+cmake -S iotdb-client/client-cpp -B build -DCMAKE_BUILD_TYPE=Debug
+cmake --build build --target install
+
+# Windows / Visual Studio
+cmake -S iotdb-client/client-cpp -B build -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Debug
+cmake --build build --config Debug --target install
+```
+
+### 离线构建
+
+离线构建需要先把依赖源码包放入 `third-party/<platform>/`,然后执行:
+
+```bash
+mvn -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests \
+ -Diotdb.offline=ON package
+```
+
+或直接使用 CMake:
+
+```bash
+cmake -S iotdb-client/client-cpp -B build -DIOTDB_OFFLINE=ON
+cmake --build build --config Release --target install
+```
+
+完整依赖清单、SSL、测试和格式化说明请参考英文版 [README.md](README.md)。
diff --git a/iotdb-client/client-cpp/cmake/CheckCxx11Abi.cmake b/iotdb-client/client-cpp/cmake/CheckCxx11Abi.cmake
new file mode 100644
index 00000000000..579070b5987
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/CheckCxx11Abi.cmake
@@ -0,0 +1,59 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+if(NOT IOTDB_SESSION_LIBRARY)
+ message(FATAL_ERROR "IOTDB_SESSION_LIBRARY is required")
+endif()
+
+find_program(IOTDB_NM_EXECUTABLE nm)
+if(NOT IOTDB_NM_EXECUTABLE)
+ message(FATAL_ERROR "nm is required to verify _GLIBCXX_USE_CXX11_ABI=1")
+endif()
+
+execute_process(
+ COMMAND "${IOTDB_NM_EXECUTABLE}" -D --demangle "${IOTDB_SESSION_LIBRARY}"
+ OUTPUT_VARIABLE _iotdb_session_symbols
+ ERROR_VARIABLE _iotdb_nm_error
+ RESULT_VARIABLE _iotdb_nm_result)
+if(NOT _iotdb_nm_result EQUAL 0)
+ message(FATAL_ERROR
+ "Failed to inspect ${IOTDB_SESSION_LIBRARY}: ${_iotdb_nm_error}")
+endif()
+
+string(FIND
+ "${_iotdb_session_symbols}"
+ "Session::setStorageGroup(std::__cxx11::basic_string"
+ _iotdb_session_cxx11_symbol)
+string(FIND
+ "${_iotdb_session_symbols}"
+ "SessionDataSet::getColumnNames[abi:cxx11]() const"
+ _iotdb_dataset_cxx11_symbol)
+string(FIND
+ "${_iotdb_session_symbols}"
+ "RowRecord::toString[abi:cxx11]()"
+ _iotdb_row_record_cxx11_symbol)
+
+if(_iotdb_session_cxx11_symbol EQUAL -1
+ OR _iotdb_dataset_cxx11_symbol EQUAL -1
+ OR _iotdb_row_record_cxx11_symbol EQUAL -1)
+ message(FATAL_ERROR
+ "${IOTDB_SESSION_LIBRARY} is not built with "
+ "_GLIBCXX_USE_CXX11_ABI=1 for IoTDB C++ API symbols.")
+endif()
+
+message(STATUS
+ "${IOTDB_SESSION_LIBRARY} passed _GLIBCXX_USE_CXX11_ABI=1 symbol check")
diff --git a/iotdb-client/client-cpp/cmake/FetchBoost.cmake b/iotdb-client/client-cpp/cmake/FetchBoost.cmake
new file mode 100644
index 00000000000..d1ab9c18ae1
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/FetchBoost.cmake
@@ -0,0 +1,130 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# FetchBoost.cmake
+#
+# Resolves the location of Boost headers needed at thrift / iotdb_session
+# compile time, in three stages:
+#
+# 1. Use system / user-provided Boost (find_package, BOOST_ROOT, etc.).
+# 2. Fall back to a local tarball under ${IOTDB_OS_DEPS_DIR}/.
+# 3. Otherwise download the tarball from archives.boost.io (unless
+# IOTDB_OFFLINE is ON).
+#
+# Output (cache) variables:
+# BOOST_INCLUDE_DIR - directory containing <boost/...> headers.
+# =============================================================================
+
+if(DEFINED BOOST_INCLUDE_DIR AND EXISTS "${BOOST_INCLUDE_DIR}/boost/version.hpp")
+ message(STATUS "[Boost] reusing cached BOOST_INCLUDE_DIR=${BOOST_INCLUDE_DIR}")
+ return()
+endif()
+
+# ---------------------------------------------------------------------------
+# Stage 1: find_package(Boost) - respects BOOST_ROOT / Boost_INCLUDE_DIR
+# ---------------------------------------------------------------------------
+find_package(Boost QUIET)
+if(Boost_FOUND AND Boost_INCLUDE_DIRS)
+ set(BOOST_INCLUDE_DIR "${Boost_INCLUDE_DIRS}" CACHE PATH "Boost include directory" FORCE)
+ message(STATUS "[Boost] using system Boost at ${BOOST_INCLUDE_DIR}")
+ return()
+endif()
+
+# Allow plain -DBOOST_INCLUDEDIR= / -DBoost_INCLUDE_DIR= as a fast path.
+foreach(_hint Boost_INCLUDE_DIR BOOST_INCLUDEDIR BOOST_ROOT)
+ if(DEFINED ${_hint})
+ set(_candidate "${${_hint}}")
+ if(EXISTS "${_candidate}/boost/version.hpp")
+ set(BOOST_INCLUDE_DIR "${_candidate}" CACHE PATH "Boost include directory" FORCE)
+ message(STATUS "[Boost] using hinted path ${BOOST_INCLUDE_DIR}")
+ return()
+ elseif(EXISTS "${_candidate}/include/boost/version.hpp")
+ set(BOOST_INCLUDE_DIR "${_candidate}/include" CACHE PATH "Boost include directory" FORCE)
+ message(STATUS "[Boost] using hinted path ${BOOST_INCLUDE_DIR}")
+ return()
+ endif()
+ endif()
+endforeach()
+
+# ---------------------------------------------------------------------------
+# Stage 2: local tarball cache
+# ---------------------------------------------------------------------------
+string(REPLACE "." "_" _boost_us "${BOOST_VERSION}")
+set(_boost_dirname "boost_${_boost_us}")
+set(_boost_tarname_gz "${_boost_dirname}.tar.gz")
+set(_boost_tarname_zip "${_boost_dirname}.zip")
+
+set(_boost_tarball "")
+foreach(_name IN ITEMS ${_boost_tarname_gz} ${_boost_tarname_zip})
+ if(EXISTS "${IOTDB_OS_DEPS_DIR}/${_name}")
+ set(_boost_tarball "${IOTDB_OS_DEPS_DIR}/${_name}")
+ break()
+ endif()
+endforeach()
+
+# ---------------------------------------------------------------------------
+# Stage 3: download
+# ---------------------------------------------------------------------------
+if(NOT _boost_tarball)
+ if(IOTDB_OFFLINE)
+ message(FATAL_ERROR
+ "[Boost] IOTDB_OFFLINE=ON but no Boost tarball found in "
+ "${IOTDB_OS_DEPS_DIR}. Expected one of: ${_boost_tarname_gz}, ${_boost_tarname_zip}.")
+ endif()
+
+ set(_boost_url "https://archives.boost.io/release/${BOOST_VERSION}/source/${_boost_tarname_gz}")
+ set(_boost_tarball "${IOTDB_OS_DEPS_DIR}/${_boost_tarname_gz}")
+ message(STATUS "[Boost] downloading ${_boost_url}")
+ file(DOWNLOAD "${_boost_url}" "${_boost_tarball}"
+ SHOW_PROGRESS
+ STATUS _boost_dl_status
+ TLS_VERIFY ON)
+ list(GET _boost_dl_status 0 _boost_dl_code)
+ if(NOT _boost_dl_code EQUAL 0)
+ list(GET _boost_dl_status 1 _boost_dl_msg)
+ file(REMOVE "${_boost_tarball}")
+ message(FATAL_ERROR "[Boost] download failed: ${_boost_dl_msg}")
+ endif()
+endif()
+
+# ---------------------------------------------------------------------------
+# Extract headers-only into ${CMAKE_BINARY_DIR}/_deps/boost
+# ---------------------------------------------------------------------------
+set(_boost_extract_dir "${CMAKE_BINARY_DIR}/_deps/boost")
+set(_boost_marker "${_boost_extract_dir}/.extracted-${BOOST_VERSION}")
+
+if(NOT EXISTS "${_boost_marker}")
+ file(REMOVE_RECURSE "${_boost_extract_dir}")
+ file(MAKE_DIRECTORY "${_boost_extract_dir}")
+ message(STATUS "[Boost] extracting ${_boost_tarball}")
+ file(ARCHIVE_EXTRACT
+ INPUT "${_boost_tarball}"
+ DESTINATION "${_boost_extract_dir}")
+ file(TOUCH "${_boost_marker}")
+endif()
+
+set(BOOST_INCLUDE_DIR "${_boost_extract_dir}/${_boost_dirname}"
+ CACHE PATH "Boost include directory" FORCE)
+
+if(NOT EXISTS "${BOOST_INCLUDE_DIR}/boost/version.hpp")
+ message(FATAL_ERROR
+ "[Boost] Could not locate boost/version.hpp after extraction. "
+ "Looked in: ${BOOST_INCLUDE_DIR}")
+endif()
+
+message(STATUS "[Boost] BOOST_INCLUDE_DIR = ${BOOST_INCLUDE_DIR}")
diff --git a/iotdb-client/client-cpp/cmake/FetchBuildTools.cmake b/iotdb-client/client-cpp/cmake/FetchBuildTools.cmake
new file mode 100644
index 00000000000..c9d7482e906
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/FetchBuildTools.cmake
@@ -0,0 +1,266 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# FetchBuildTools.cmake
+#
+# Apache Thrift's source build needs a working flex / bison toolchain (m4 too
+# on Unix). When the host already provides them on PATH we use them as-is.
+# Otherwise we provision them locally:
+#
+# * Linux / macOS - configure-make-install each tool from a tarball into
+# ${CMAKE_BINARY_DIR}/tools (no sudo required).
+# * Windows - extract the winflexbison zip and copy
+# win_flex.exe -> flex.exe, win_bison.exe -> bison.exe.
+#
+# Tarballs / zips are resolved with the standard three-stage pattern:
+# 1. ${IOTDB_OS_DEPS_DIR}/<filename> (or any match for an optional GLOB)
+# 2. file(DOWNLOAD) when IOTDB_OFFLINE is OFF
+# 3. FATAL_ERROR otherwise
+# =============================================================================
+
+set(_tools_prefix "${CMAKE_BINARY_DIR}/tools")
+set(_tools_bin "${_tools_prefix}/bin")
+file(MAKE_DIRECTORY "${_tools_bin}")
+
+# Make sure any tool we install locally takes precedence over the system PATH
+# for the remainder of the configure step (and child ExternalProject calls).
+if(WIN32)
+ set(ENV{PATH} "${_tools_bin};$ENV{PATH}")
+else()
+ set(ENV{PATH} "${_tools_bin}:$ENV{PATH}")
+endif()
+
+set(M4_VERSION "1.4.19" CACHE STRING "GNU m4 version to build when missing")
+set(FLEX_VERSION "2.6.4" CACHE STRING "GNU flex version to build when missing")
+set(BISON_VERSION "3.8" CACHE STRING "GNU bison version to build when missing")
+set(WINFLEXBISON_VERSION "2.5.25"
+ CACHE STRING "winflexbison version to download when no local zip is present")
+
+set(_m4_url "https://ftp.gnu.org/gnu/m4/m4-${M4_VERSION}.tar.gz")
+set(_flex_url "https://github.com/westes/flex/releases/download/v${FLEX_VERSION}/flex-${FLEX_VERSION}.tar.gz")
+set(_bison_url "https://ftp.gnu.org/gnu/bison/bison-${BISON_VERSION}.tar.gz")
+set(_winflexbison_url
+ "https://github.com/lexxmark/winflexbison/releases/download/v${WINFLEXBISON_VERSION}/win_flex_bison-${WINFLEXBISON_VERSION}.zip")
+set(_winflexbison_filename "win_flex_bison-${WINFLEXBISON_VERSION}.zip")
+
+include(ProcessorCount)
+ProcessorCount(_jobs)
+if(_jobs LESS 1)
+ set(_jobs 1)
+endif()
+
+# Resolve tarball: prefer the exact filename in ${IOTDB_OS_DEPS_DIR}/, then
+# any path matching GLOB_PATTERN (caller-supplied wildcard for relaxed naming,
+# e.g. win_flex_bison*.zip), and finally fall back to a download.
+function(_iotdb_resolve_tarball OUT_VAR FILENAME URL)
+ cmake_parse_arguments(ARG "" "GLOB_PATTERN" "" ${ARGN})
+
+ set(_local "${IOTDB_OS_DEPS_DIR}/${FILENAME}")
+ if(EXISTS "${_local}")
+ set(${OUT_VAR} "${_local}" PARENT_SCOPE)
+ return()
+ endif()
+
+ if(ARG_GLOB_PATTERN)
+ file(GLOB _matches "${IOTDB_OS_DEPS_DIR}/${ARG_GLOB_PATTERN}")
+ if(_matches)
+ list(GET _matches 0 _hit)
+ message(STATUS "[BuildTools] reusing ${_hit}")
+ set(${OUT_VAR} "${_hit}" PARENT_SCOPE)
+ return()
+ endif()
+ endif()
+
+ if(IOTDB_OFFLINE)
+ set(_hint "${FILENAME}")
+ if(ARG_GLOB_PATTERN)
+ set(_hint "${FILENAME} (or any ${ARG_GLOB_PATTERN})")
+ endif()
+ message(FATAL_ERROR
+ "[BuildTools] IOTDB_OFFLINE=ON but ${_hint} is missing in "
+ "${IOTDB_OS_DEPS_DIR}.")
+ endif()
+
+ message(STATUS "[BuildTools] downloading ${URL}")
+ file(DOWNLOAD "${URL}" "${_local}" SHOW_PROGRESS STATUS _st TLS_VERIFY ON)
+ list(GET _st 0 _code)
+ if(NOT _code EQUAL 0)
+ list(GET _st 1 _msg)
+ file(REMOVE "${_local}")
+ message(FATAL_ERROR "[BuildTools] download failed for ${FILENAME}: ${_msg}")
+ endif()
+ set(${OUT_VAR} "${_local}" PARENT_SCOPE)
+endfunction()
+
+# Configure-make-install <name> from <tarball> into ${_tools_prefix}.
+function(_iotdb_build_autotools NAME TARBALL EXTRACTED_DIRNAME)
+ set(_src_root "${CMAKE_BINARY_DIR}/_deps/${NAME}")
+ set(_marker "${_tools_prefix}/.${NAME}-installed")
+ if(EXISTS "${_marker}")
+ return()
+ endif()
+ file(REMOVE_RECURSE "${_src_root}")
+ file(MAKE_DIRECTORY "${_src_root}")
+ message(STATUS "[BuildTools] extracting ${TARBALL}")
+ file(ARCHIVE_EXTRACT INPUT "${TARBALL}" DESTINATION "${_src_root}")
+ set(_src "${_src_root}/${EXTRACTED_DIRNAME}")
+ if(NOT EXISTS "${_src}/configure")
+ message(FATAL_ERROR
+ "[BuildTools] expected configure script at ${_src}/configure")
+ endif()
+ message(STATUS "[BuildTools] building ${NAME} -> ${_tools_prefix}")
+ # flex 2.6.4: reallocarray() needs _GNU_SOURCE on glibc 2.26+ (westes/flex#241).
+ set(_env_prefix "")
+ if(NAME STREQUAL "flex" AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ set(_env_prefix env CFLAGS=-D_GNU_SOURCE CXXFLAGS=-D_GNU_SOURCE)
+ endif()
+ if(_env_prefix)
+ execute_process(
+ COMMAND ${_env_prefix} ./configure --prefix=${_tools_prefix}
+ WORKING_DIRECTORY "${_src}"
+ RESULT_VARIABLE _rc)
+ else()
+ execute_process(
+ COMMAND ./configure --prefix=${_tools_prefix}
+ WORKING_DIRECTORY "${_src}"
+ RESULT_VARIABLE _rc)
+ endif()
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[BuildTools] configure failed for ${NAME}")
+ endif()
+ if(_env_prefix)
+ execute_process(
+ COMMAND ${_env_prefix} make -j${_jobs}
+ WORKING_DIRECTORY "${_src}"
+ RESULT_VARIABLE _rc)
+ else()
+ execute_process(
+ COMMAND make -j${_jobs}
+ WORKING_DIRECTORY "${_src}"
+ RESULT_VARIABLE _rc)
+ endif()
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[BuildTools] make failed for ${NAME}")
+ endif()
+ if(_env_prefix)
+ execute_process(
+ COMMAND ${_env_prefix} make install
+ WORKING_DIRECTORY "${_src}"
+ RESULT_VARIABLE _rc)
+ else()
+ execute_process(
+ COMMAND make install
+ WORKING_DIRECTORY "${_src}"
+ RESULT_VARIABLE _rc)
+ endif()
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[BuildTools] make install failed for ${NAME}")
+ endif()
+ file(TOUCH "${_marker}")
+endfunction()
+
+# =============================================================================
+# Windows branch - winflexbison
+# =============================================================================
+if(WIN32)
+ # Stage 1: pick up an existing flex/bison if the host already provides it.
+ find_program(FLEX_EXECUTABLE NAMES flex win_flex)
+ find_program(BISON_EXECUTABLE NAMES bison win_bison)
+
+ if(FLEX_EXECUTABLE AND BISON_EXECUTABLE)
+ message(STATUS "[BuildTools] using system flex = ${FLEX_EXECUTABLE}")
+ message(STATUS "[BuildTools] using system bison = ${BISON_EXECUTABLE}")
+ set(IOTDB_LOCAL_TOOLS_BIN "${_tools_bin}" CACHE INTERNAL "")
+ return()
+ endif()
+
+ # Stage 2/3: resolve and extract the winflexbison zip into _tools_bin.
+ _iotdb_resolve_tarball(_wfb_zip
+ "${_winflexbison_filename}"
+ "${_winflexbison_url}"
+ GLOB_PATTERN "win_flex_bison*.zip")
+
+ set(_wfb_marker "${_tools_bin}/.winflexbison-installed")
+ if(NOT EXISTS "${_wfb_marker}")
+ message(STATUS "[BuildTools] extracting ${_wfb_zip}")
+ file(ARCHIVE_EXTRACT INPUT "${_wfb_zip}" DESTINATION "${_tools_bin}")
+
+ if(NOT EXISTS "${_tools_bin}/win_flex.exe" OR NOT EXISTS "${_tools_bin}/win_bison.exe")
+ message(FATAL_ERROR
+ "[BuildTools] win_flex.exe / win_bison.exe not found after "
+ "extracting ${_wfb_zip} into ${_tools_bin}.")
+ endif()
+
+ # Copy with renamed targets so thrift's CMakeLists sees flex/bison.
+ execute_process(COMMAND ${CMAKE_COMMAND} -E copy
+ "${_tools_bin}/win_flex.exe" "${_tools_bin}/flex.exe"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[BuildTools] failed to copy win_flex.exe -> flex.exe")
+ endif()
+ execute_process(COMMAND ${CMAKE_COMMAND} -E copy
+ "${_tools_bin}/win_bison.exe" "${_tools_bin}/bison.exe"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[BuildTools] failed to copy win_bison.exe -> bison.exe")
+ endif()
+ file(TOUCH "${_wfb_marker}")
+ endif()
+
+ find_program(FLEX_EXECUTABLE flex PATHS "${_tools_bin}" NO_DEFAULT_PATH REQUIRED)
+ find_program(BISON_EXECUTABLE bison PATHS "${_tools_bin}" NO_DEFAULT_PATH REQUIRED)
+
+ message(STATUS "[BuildTools] flex = ${FLEX_EXECUTABLE}")
+ message(STATUS "[BuildTools] bison = ${BISON_EXECUTABLE}")
+ set(IOTDB_LOCAL_TOOLS_BIN "${_tools_bin}" CACHE INTERNAL "")
+ return()
+endif()
+
+# =============================================================================
+# Linux / macOS branch - m4 / flex / bison from autotools tarballs
+# =============================================================================
+
+# m4 (flex/bison both depend on this)
+find_program(M4_EXECUTABLE m4)
+if(NOT M4_EXECUTABLE)
+ _iotdb_resolve_tarball(_m4_tarball "m4-${M4_VERSION}.tar.gz" "${_m4_url}")
+ _iotdb_build_autotools(m4 "${_m4_tarball}" "m4-${M4_VERSION}")
+ find_program(M4_EXECUTABLE m4 PATHS "${_tools_bin}" NO_DEFAULT_PATH REQUIRED)
+endif()
+message(STATUS "[BuildTools] m4 = ${M4_EXECUTABLE}")
+
+# flex
+find_program(FLEX_EXECUTABLE flex)
+if(NOT FLEX_EXECUTABLE)
+ _iotdb_resolve_tarball(_flex_tarball "flex-${FLEX_VERSION}.tar.gz" "${_flex_url}")
+ _iotdb_build_autotools(flex "${_flex_tarball}" "flex-${FLEX_VERSION}")
+ find_program(FLEX_EXECUTABLE flex PATHS "${_tools_bin}" NO_DEFAULT_PATH REQUIRED)
+endif()
+message(STATUS "[BuildTools] flex = ${FLEX_EXECUTABLE}")
+
+# bison
+find_program(BISON_EXECUTABLE bison)
+if(NOT BISON_EXECUTABLE)
+ _iotdb_resolve_tarball(_bison_tarball "bison-${BISON_VERSION}.tar.gz" "${_bison_url}")
+ _iotdb_build_autotools(bison "${_bison_tarball}" "bison-${BISON_VERSION}")
+ find_program(BISON_EXECUTABLE bison PATHS "${_tools_bin}" NO_DEFAULT_PATH REQUIRED)
+endif()
+message(STATUS "[BuildTools] bison = ${BISON_EXECUTABLE}")
+
+# Expose the bin dir for downstream ExternalProject_Add calls.
+set(IOTDB_LOCAL_TOOLS_BIN "${_tools_bin}" CACHE INTERNAL "")
diff --git a/iotdb-client/client-cpp/cmake/FetchOpenSSL.cmake b/iotdb-client/client-cpp/cmake/FetchOpenSSL.cmake
new file mode 100644
index 00000000000..575e2803f2b
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/FetchOpenSSL.cmake
@@ -0,0 +1,121 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# FetchOpenSSL.cmake (only included when WITH_SSL=ON)
+#
+# Resolution order:
+# 1. find_package(OpenSSL) - any system / vendor install is taken as-is.
+# 2. On Linux/macOS:
+# use tarball ${IOTDB_OS_DEPS_DIR}/openssl-${OPENSSL_VERSION}.tar.gz
+# or download from openssl.org when not in offline mode, then
+# ./Configure && make && make install_sw into ${CMAKE_BINARY_DIR}/_deps/openssl.
+# 3. On Windows: emit a FATAL_ERROR with instructions to run the bundled
+# Win64OpenSSL installer (or any other prebuilt OpenSSL); building
+# OpenSSL from source on MSVC is out of scope.
+#
+# Side effects:
+# Defines imported targets OpenSSL::SSL / OpenSSL::Crypto via find_package
+# so callers can just link against them.
+# =============================================================================
+
+set(OPENSSL_VERSION "3.5.0" CACHE STRING "OpenSSL version to fetch when missing")
+
+find_package(OpenSSL QUIET)
+if(OpenSSL_FOUND)
+ message(STATUS "[OpenSSL] using system OpenSSL ${OPENSSL_VERSION_MAJOR}.${OPENSSL_VERSION_MINOR}")
+ return()
+endif()
+
+if(WIN32)
+ message(FATAL_ERROR
+ "[OpenSSL] WITH_SSL=ON but no OpenSSL was found on Windows. "
+ "Please run third-party/windows/Win64OpenSSL-3_5_0.exe (or any "
+ "OpenSSL installer), then re-run the configure step with "
+ "-DOPENSSL_ROOT_DIR=<install_path>.")
+endif()
+
+# --- Linux / macOS fallback: build from source ---------------------------
+set(_ossl_tarname "openssl-${OPENSSL_VERSION}.tar.gz")
+set(_ossl_tarball "${IOTDB_OS_DEPS_DIR}/${_ossl_tarname}")
+
+if(NOT EXISTS "${_ossl_tarball}")
+ if(IOTDB_OFFLINE)
+ message(FATAL_ERROR
+ "[OpenSSL] IOTDB_OFFLINE=ON but ${_ossl_tarname} is missing in ${IOTDB_OS_DEPS_DIR}.")
+ endif()
+ set(_ossl_url "https://www.openssl.org/source/${_ossl_tarname}")
+ message(STATUS "[OpenSSL] downloading ${_ossl_url}")
+ file(DOWNLOAD "${_ossl_url}" "${_ossl_tarball}"
+ SHOW_PROGRESS TLS_VERIFY ON STATUS _st)
+ list(GET _st 0 _code)
+ if(NOT _code EQUAL 0)
+ list(GET _st 1 _msg)
+ file(REMOVE "${_ossl_tarball}")
+ message(FATAL_ERROR "[OpenSSL] download failed: ${_msg}")
+ endif()
+endif()
+
+set(_ossl_root "${CMAKE_BINARY_DIR}/_deps/openssl")
+set(_ossl_src "${_ossl_root}/src/openssl-${OPENSSL_VERSION}")
+set(_ossl_inst "${_ossl_root}/install")
+set(_ossl_stamp "${_ossl_root}/.built-${OPENSSL_VERSION}")
+
+if(NOT EXISTS "${_ossl_stamp}")
+ file(REMOVE_RECURSE "${_ossl_root}/src")
+ file(MAKE_DIRECTORY "${_ossl_root}/src")
+ message(STATUS "[OpenSSL] extracting ${_ossl_tarball}")
+ file(ARCHIVE_EXTRACT INPUT "${_ossl_tarball}" DESTINATION "${_ossl_root}/src")
+
+ include(ProcessorCount)
+ ProcessorCount(_jobs)
+ if(_jobs LESS 1)
+ set(_jobs 1)
+ endif()
+
+ message(STATUS "[OpenSSL] configuring -> ${_ossl_inst}")
+ execute_process(
+ COMMAND ./Configure --prefix=${_ossl_inst} --openssldir=${_ossl_inst}/ssl no-shared
+ WORKING_DIRECTORY "${_ossl_src}"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[OpenSSL] Configure failed (rc=${_rc})")
+ endif()
+
+ message(STATUS "[OpenSSL] building (-j${_jobs})")
+ execute_process(
+ COMMAND make -j${_jobs}
+ WORKING_DIRECTORY "${_ossl_src}"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[OpenSSL] make failed (rc=${_rc})")
+ endif()
+
+ execute_process(
+ COMMAND make install_sw
+ WORKING_DIRECTORY "${_ossl_src}"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[OpenSSL] make install_sw failed (rc=${_rc})")
+ endif()
+ file(TOUCH "${_ossl_stamp}")
+endif()
+
+set(OPENSSL_ROOT_DIR "${_ossl_inst}" CACHE PATH "OpenSSL root" FORCE)
+set(OPENSSL_USE_STATIC_LIBS ON)
+find_package(OpenSSL REQUIRED)
+message(STATUS "[OpenSSL] built locally at ${OPENSSL_ROOT_DIR}")
diff --git a/iotdb-client/client-cpp/cmake/FetchThrift.cmake b/iotdb-client/client-cpp/cmake/FetchThrift.cmake
new file mode 100644
index 00000000000..f26ad643ff4
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/FetchThrift.cmake
@@ -0,0 +1,278 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# FetchThrift.cmake
+#
+# Downloads (or uses a local copy of) the Apache Thrift source tarball and
+# builds it from source as a static-only, runtime-and-compiler artifact. The
+# build runs at configure time so the thrift compiler is available for the
+# code generation step that follows.
+#
+# Exported variables:
+# THRIFT_EXECUTABLE - path to the thrift binary that just got built
+# THRIFT_INCLUDE_DIR - include directory containing <thrift/Thrift.h>
+# THRIFT_STATIC_LIB_PATH- path to libthrift.a / thriftmd.lib
+# THRIFT_RUNTIME_LIB_DIR- directory containing the static thrift library
+# (and any other build artifacts you may want to
+# bundle with the SDK)
+#
+# Imported targets:
+# iotdb_thrift_static - INTERFACE-compatible IMPORTED target that
+# propagates include dirs and the static lib.
+# iotdb_thrift_external - phony custom target representing the build
+# (use add_dependencies(<your-target> iotdb_thrift_external)
+# to ensure the thrift build runs first).
+# =============================================================================
+
+include(ExternalProject)
+
+set(_thrift_dirname "thrift-${THRIFT_VERSION}")
+set(_thrift_tarname "${_thrift_dirname}.tar.gz")
+
+# ---------------------------------------------------------------------------
+# Resolve tarball (local cache -> download)
+# ---------------------------------------------------------------------------
+set(_thrift_tarball "${IOTDB_OS_DEPS_DIR}/${_thrift_tarname}")
+if(NOT EXISTS "${_thrift_tarball}")
+ if(IOTDB_OFFLINE)
+ message(FATAL_ERROR
+ "[Thrift] IOTDB_OFFLINE=ON but ${_thrift_tarname} is missing in "
+ "${IOTDB_OS_DEPS_DIR}.")
+ endif()
+ set(_thrift_url "https://archive.apache.org/dist/thrift/${THRIFT_VERSION}/${_thrift_tarname}")
+ message(STATUS "[Thrift] downloading ${_thrift_url}")
+ file(DOWNLOAD "${_thrift_url}" "${_thrift_tarball}"
+ SHOW_PROGRESS TLS_VERIFY ON STATUS _thrift_dl)
+ list(GET _thrift_dl 0 _code)
+ if(NOT _code EQUAL 0)
+ list(GET _thrift_dl 1 _msg)
+ file(REMOVE "${_thrift_tarball}")
+ message(FATAL_ERROR "[Thrift] download failed: ${_msg}")
+ endif()
+endif()
+
+# ---------------------------------------------------------------------------
+# Extract once into ${CMAKE_BINARY_DIR}/_deps/thrift/src
+# ---------------------------------------------------------------------------
+set(_thrift_root "${CMAKE_BINARY_DIR}/_deps/thrift")
+set(_thrift_src "${_thrift_root}/src/${_thrift_dirname}")
+set(_thrift_build "${_thrift_root}/build")
+set(_thrift_install "${_thrift_root}/install")
+set(_thrift_marker "${_thrift_root}/.extracted-${THRIFT_VERSION}")
+
+set(_thrift_build_config "Release")
+if(MSVC AND CMAKE_BUILD_TYPE)
+ set(_thrift_build_config "${CMAKE_BUILD_TYPE}")
+endif()
+
+if(NOT EXISTS "${_thrift_marker}")
+ file(REMOVE_RECURSE "${_thrift_root}/src")
+ file(MAKE_DIRECTORY "${_thrift_root}/src")
+ message(STATUS "[Thrift] extracting ${_thrift_tarball}")
+ file(ARCHIVE_EXTRACT INPUT "${_thrift_tarball}"
+ DESTINATION "${_thrift_root}/src")
+ file(TOUCH "${_thrift_marker}")
+endif()
+
+if(NOT EXISTS "${_thrift_src}/CMakeLists.txt")
+ message(FATAL_ERROR
+ "[Thrift] could not find ${_thrift_src}/CMakeLists.txt after "
+ "extracting ${_thrift_tarball}.")
+endif()
+
+# ---------------------------------------------------------------------------
+# ExternalProject_Add: build thrift at *configure* time so the produced
+# binary / library can immediately drive code generation and linking.
+# ---------------------------------------------------------------------------
+set(_thrift_cmake_args
+ # CMake 4.x rejects Thrift 0.21's cmake_minimum_required(3.0); set policy first.
+ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5"
+ "-DCMAKE_INSTALL_PREFIX=${_thrift_install}"
+ "-DCMAKE_BUILD_TYPE=${_thrift_build_config}"
+ "-DBUILD_JAVA=OFF"
+ "-DBUILD_NODEJS=OFF"
+ "-DBUILD_JAVASCRIPT=OFF"
+ "-DBUILD_PYTHON=OFF"
+ "-DBUILD_TESTING=OFF"
+ "-DBUILD_TUTORIALS=OFF"
+ "-DBUILD_SHARED_LIBS=OFF"
+ "-DWITH_SHARED_LIB=OFF"
+ "-DWITH_STATIC_LIB=ON"
+ "-DCMAKE_POSITION_INDEPENDENT_CODE=ON"
+ "-DCMAKE_POLICY_DEFAULT_CMP0091=NEW"
+ "-DCMAKE_CXX_STANDARD=11")
+
+if(BOOST_INCLUDE_DIR)
+ list(APPEND _thrift_cmake_args
+ "-DBoost_INCLUDE_DIR=${BOOST_INCLUDE_DIR}"
+ "-DBOOST_INCLUDEDIR=${BOOST_INCLUDE_DIR}")
+endif()
+
+if(MSVC)
+ list(APPEND _thrift_cmake_args
+ "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
+else()
+ set(_thrift_cxxflags "-fPIC")
+ if(IOTDB_USE_CXX11_ABI)
+ set(_thrift_cxxflags "${_thrift_cxxflags} -D_GLIBCXX_USE_CXX11_ABI=${IOTDB_USE_CXX11_ABI}")
+ endif()
+ list(APPEND _thrift_cmake_args
+ "-DCMAKE_C_FLAGS=-fPIC"
+ "-DCMAKE_CXX_FLAGS=${_thrift_cxxflags}")
+endif()
+
+if(WITH_SSL)
+ list(APPEND _thrift_cmake_args "-DWITH_OPENSSL=ON")
+else()
+ list(APPEND _thrift_cmake_args "-DWITH_OPENSSL=OFF")
+endif()
+
+# Run the ExternalProject build immediately so the thrift compiler is
+# available for the subsequent code-generation step. We do this by
+# invoking cmake twice via execute_process and only register a phony
+# ExternalProject for dependency ordering.
+
+if(IOTDB_USE_CXX11_ABI)
+ set(_thrift_abi_stamp "-abi${IOTDB_USE_CXX11_ABI}")
+else()
+ set(_thrift_abi_stamp "-abidefault")
+endif()
+set(_thrift_stamp "${_thrift_build}/.built-${THRIFT_VERSION}-${_thrift_build_config}-mdll${_thrift_abi_stamp}")
+if(NOT EXISTS "${_thrift_stamp}")
+ file(MAKE_DIRECTORY "${_thrift_build}")
+ message(STATUS "[Thrift] configuring ${_thrift_dirname}")
+
+ # When we built m4/flex/bison locally, make sure CMake passes the
+ # updated PATH down to the nested cmake invocation.
+ if(IOTDB_LOCAL_TOOLS_BIN)
+ set(_thrift_env "PATH=${IOTDB_LOCAL_TOOLS_BIN}:$ENV{PATH}")
+ endif()
+
+ if(CMAKE_GENERATOR_PLATFORM)
+ set(_gen_platform_arg "-A" "${CMAKE_GENERATOR_PLATFORM}")
+ else()
+ set(_gen_platform_arg "")
+ endif()
+
+ execute_process(
+ COMMAND ${CMAKE_COMMAND}
+ -G "${CMAKE_GENERATOR}"
+ ${_gen_platform_arg}
+ ${_thrift_cmake_args}
+ "${_thrift_src}"
+ WORKING_DIRECTORY "${_thrift_build}"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[Thrift] configure step failed (rc=${_rc})")
+ endif()
+
+ message(STATUS "[Thrift] building (${_thrift_build_config})")
+ execute_process(
+ COMMAND ${CMAKE_COMMAND} --build . --config ${_thrift_build_config} --target install
+ WORKING_DIRECTORY "${_thrift_build}"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[Thrift] build/install step failed (rc=${_rc})")
+ endif()
+ file(TOUCH "${_thrift_stamp}")
+endif()
+
+# ---------------------------------------------------------------------------
+# Locate produced artifacts
+# ---------------------------------------------------------------------------
+set(THRIFT_INCLUDE_DIR "${_thrift_install}/include" CACHE PATH "" FORCE)
+
+# Thrift binary
+if(WIN32)
+ find_program(THRIFT_EXECUTABLE
+ NAMES thrift
+ HINTS "${_thrift_install}/bin" "${_thrift_build}/bin/Release"
+ "${_thrift_build}/compiler/cpp/Release"
+ "${_thrift_build}/compiler/cpp/bin/Release"
+ NO_DEFAULT_PATH)
+else()
+ find_program(THRIFT_EXECUTABLE
+ NAMES thrift
+ HINTS "${_thrift_install}/bin"
+ "${_thrift_build}/bin"
+ "${_thrift_build}/compiler/cpp/bin"
+ "${_thrift_build}/compiler/cpp"
+ NO_DEFAULT_PATH)
+endif()
+
+if(NOT THRIFT_EXECUTABLE)
+ message(FATAL_ERROR
+ "[Thrift] could not find the thrift binary under ${_thrift_install} or ${_thrift_build}")
+endif()
+message(STATUS "[Thrift] THRIFT_EXECUTABLE = ${THRIFT_EXECUTABLE}")
+
+# Thrift static library (search a few standard install/lib locations).
+set(_thrift_libname_candidates)
+if(MSVC)
+ if(_thrift_build_config STREQUAL "Debug")
+ list(APPEND _thrift_libname_candidates thriftmdd.lib thriftmd.lib thriftmtd.lib thriftmt.lib thrift.lib)
+ else()
+ list(APPEND _thrift_libname_candidates thriftmd.lib thriftmt.lib thrift.lib)
+ endif()
+else()
+ list(APPEND _thrift_libname_candidates libthrift.a)
+endif()
+
+set(THRIFT_STATIC_LIB_PATH "")
+foreach(_dir
+ "${_thrift_install}/lib"
+ "${_thrift_install}/lib64"
+ "${_thrift_build}/lib"
+ "${_thrift_build}/lib/Release"
+ "${_thrift_build}/lib/release")
+ if(THRIFT_STATIC_LIB_PATH)
+ break()
+ endif()
+ foreach(_n ${_thrift_libname_candidates})
+ if(EXISTS "${_dir}/${_n}")
+ set(THRIFT_STATIC_LIB_PATH "${_dir}/${_n}")
+ set(THRIFT_RUNTIME_LIB_DIR "${_dir}")
+ break()
+ endif()
+ endforeach()
+endforeach()
+
+if(NOT THRIFT_STATIC_LIB_PATH)
+ message(FATAL_ERROR
+ "[Thrift] could not locate the thrift static library under ${_thrift_install}/lib")
+endif()
+message(STATUS "[Thrift] THRIFT_STATIC_LIB_PATH = ${THRIFT_STATIC_LIB_PATH}")
+
+# Cache as well so subsequent reconfigures keep the same values.
+set(THRIFT_STATIC_LIB_PATH "${THRIFT_STATIC_LIB_PATH}" CACHE FILEPATH "" FORCE)
+set(THRIFT_RUNTIME_LIB_DIR "${THRIFT_RUNTIME_LIB_DIR}" CACHE PATH "" FORCE)
+
+# ---------------------------------------------------------------------------
+# Imported target wrapping the static library.
+# ---------------------------------------------------------------------------
+if(NOT TARGET iotdb_thrift_static)
+ add_library(iotdb_thrift_static STATIC IMPORTED GLOBAL)
+ set_target_properties(iotdb_thrift_static PROPERTIES
+ IMPORTED_LOCATION "${THRIFT_STATIC_LIB_PATH}"
+ INTERFACE_INCLUDE_DIRECTORIES "${THRIFT_INCLUDE_DIR}")
+endif()
+
+# Phony target so downstream code can express ordering deps.
+if(NOT TARGET iotdb_thrift_external)
+ add_custom_target(iotdb_thrift_external ALL)
+endif()
diff --git a/iotdb-client/client-cpp/cmake/GenerateThriftSources.cmake b/iotdb-client/client-cpp/cmake/GenerateThriftSources.cmake
new file mode 100644
index 00000000000..6a3685af458
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/GenerateThriftSources.cmake
@@ -0,0 +1,126 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# GenerateThriftSources.cmake
+#
+# Generates C++ stubs from the iotdb-protocol Thrift files using the thrift
+# compiler that FetchThrift just built.
+#
+# Inputs (resolved relative to the workspace root):
+# iotdb-protocol/thrift-commons/src/main/thrift/common.thrift
+# iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift
+#
+# Outputs:
+# ${THRIFT_GEN_CPP_DIR}/*.{h,cpp} - generated C++ sources
+# THRIFT_GENERATED_SRCS - list of *.cpp files for linking
+# THRIFT_GENERATED_HDRS - list of *.h files (informational)
+# =============================================================================
+
+if(NOT THRIFT_EXECUTABLE)
+ message(FATAL_ERROR "[GenThrift] THRIFT_EXECUTABLE not set - did FetchThrift run first?")
+endif()
+
+# Anchor the source-of-truth .thrift files via the workspace root. The CMake
+# project lives at <repo>/iotdb-client/client-cpp/, so the workspace root is
+# two levels up.
+get_filename_component(_workspace_root "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE)
+
+set(_common_thrift "${_workspace_root}/iotdb-protocol/thrift-commons/src/main/thrift/common.thrift")
+set(_client_thrift "${_workspace_root}/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift")
+
+foreach(_f IN ITEMS "${_common_thrift}" "${_client_thrift}")
+ if(NOT EXISTS "${_f}")
+ message(FATAL_ERROR "[GenThrift] missing thrift input: ${_f}")
+ endif()
+endforeach()
+
+# Mirror the bash reference script: stage both .thrift files into a flat
+# working directory so `include "common.thrift"` resolves without -I args.
+set(_thrift_proto_dir "${CMAKE_BINARY_DIR}/thrift-protocols")
+file(MAKE_DIRECTORY "${_thrift_proto_dir}")
+configure_file("${_common_thrift}" "${_thrift_proto_dir}/common.thrift" COPYONLY)
+configure_file("${_client_thrift}" "${_thrift_proto_dir}/client.thrift" COPYONLY)
+
+set(THRIFT_GEN_CPP_DIR "${CMAKE_BINARY_DIR}/gen-cpp" CACHE PATH "" FORCE)
+file(MAKE_DIRECTORY "${THRIFT_GEN_CPP_DIR}")
+
+# A stamp file lets us re-run thrift only when one of the inputs changes
+# (handled by add_custom_command at build time) while also making sure we
+# run once at configure time so the initial file(GLOB) finds something.
+set(_thrift_stamp "${THRIFT_GEN_CPP_DIR}/.generated-stamp")
+
+set(_thrift_inputs
+ "${_thrift_proto_dir}/common.thrift"
+ "${_thrift_proto_dir}/client.thrift")
+
+set(_run_thrift FALSE)
+if(NOT EXISTS "${_thrift_stamp}")
+ set(_run_thrift TRUE)
+else()
+ foreach(_in IN LISTS _thrift_inputs)
+ if("${_in}" IS_NEWER_THAN "${_thrift_stamp}")
+ set(_run_thrift TRUE)
+ break()
+ endif()
+ endforeach()
+endif()
+
+if(_run_thrift)
+ message(STATUS "[GenThrift] running ${THRIFT_EXECUTABLE} on common.thrift / client.thrift")
+ foreach(_in IN LISTS _thrift_inputs)
+ execute_process(
+ COMMAND "${THRIFT_EXECUTABLE}" -r --gen cpp:no_skeleton -out "${THRIFT_GEN_CPP_DIR}" "${_in}"
+ WORKING_DIRECTORY "${_thrift_proto_dir}"
+ RESULT_VARIABLE _rc)
+ if(NOT _rc EQUAL 0)
+ message(FATAL_ERROR "[GenThrift] thrift compile failed for ${_in} (rc=${_rc})")
+ endif()
+ endforeach()
+ # Defensive: remove any accidentally produced server skeleton.
+ file(GLOB _skeletons "${THRIFT_GEN_CPP_DIR}/*_server.skeleton.cpp")
+ if(_skeletons)
+ file(REMOVE ${_skeletons})
+ endif()
+ file(TOUCH "${_thrift_stamp}")
+endif()
+
+# Build-time regeneration: whenever the workspace .thrift files change, rerun
+# the thrift compiler. The OUTPUT is the stamp; downstream targets that
+# depend on iotdb_thrift_codegen will get the rebuild for free.
+add_custom_command(
+ OUTPUT "${_thrift_stamp}"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_common_thrift}" "${_thrift_proto_dir}/common.thrift"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_client_thrift}" "${_thrift_proto_dir}/client.thrift"
+ COMMAND "${THRIFT_EXECUTABLE}" -r --gen cpp:no_skeleton -out "${THRIFT_GEN_CPP_DIR}" "${_thrift_proto_dir}/common.thrift"
+ COMMAND "${THRIFT_EXECUTABLE}" -r --gen cpp:no_skeleton -out "${THRIFT_GEN_CPP_DIR}" "${_thrift_proto_dir}/client.thrift"
+ COMMAND ${CMAKE_COMMAND} -E touch "${_thrift_stamp}"
+ DEPENDS "${_common_thrift}" "${_client_thrift}" iotdb_thrift_external
+ WORKING_DIRECTORY "${_thrift_proto_dir}"
+ COMMENT "Regenerating thrift C++ stubs"
+ VERBATIM)
+
+add_custom_target(iotdb_thrift_codegen DEPENDS "${_thrift_stamp}")
+
+# Glob results with CONFIGURE_DEPENDS so re-cmake picks up newly produced files.
+file(GLOB THRIFT_GENERATED_SRCS CONFIGURE_DEPENDS "${THRIFT_GEN_CPP_DIR}/*.cpp")
+file(GLOB THRIFT_GENERATED_HDRS CONFIGURE_DEPENDS "${THRIFT_GEN_CPP_DIR}/*.h")
+
+list(FILTER THRIFT_GENERATED_SRCS EXCLUDE REGEX ".*_server\\.skeleton\\.cpp$")
+
+message(STATUS "[GenThrift] generated ${THRIFT_GEN_CPP_DIR} with "
+ "$<LIST_LENGTH:THRIFT_GENERATED_SRCS> cpp files")
diff --git a/iotdb-client/client-cpp/cmake/iotdb-session-config.cmake.in b/iotdb-client/client-cpp/cmake/iotdb-session-config.cmake.in
new file mode 100644
index 00000000000..57207aa2fa7
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/iotdb-session-config.cmake.in
@@ -0,0 +1,56 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+get_filename_component(_IOTDB_SESSION_PACKAGE_ROOT "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
+
+if(UNIX)
+ include(CMakeFindDependencyMacro)
+ find_dependency(Threads)
+endif()
+
+if(WIN32)
+ set(_IOTDB_SESSION_LIBRARY "${_IOTDB_SESSION_PACKAGE_ROOT}/lib/iotdb_session.lib")
+elseif(APPLE)
+ set(_IOTDB_SESSION_LIBRARY "${_IOTDB_SESSION_PACKAGE_ROOT}/lib/libiotdb_session.dylib")
+else()
+ set(_IOTDB_SESSION_LIBRARY "${_IOTDB_SESSION_PACKAGE_ROOT}/lib/libiotdb_session.so")
+endif()
+
+if(NOT TARGET IoTDB::iotdb_session)
+ add_library(IoTDB::iotdb_session SHARED IMPORTED)
+ set_target_properties(IoTDB::iotdb_session PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${_IOTDB_SESSION_PACKAGE_ROOT}/include")
+ set(_IOTDB_SESSION_CXX11_ABI_COMPILE_DEFINITION "@IOTDB_SESSION_CXX11_ABI_COMPILE_DEFINITION@")
+ if(_IOTDB_SESSION_CXX11_ABI_COMPILE_DEFINITION)
+ set_target_properties(IoTDB::iotdb_session PROPERTIES
+ INTERFACE_COMPILE_DEFINITIONS "${_IOTDB_SESSION_CXX11_ABI_COMPILE_DEFINITION}")
+ endif()
+ if(UNIX)
+ set_target_properties(IoTDB::iotdb_session PROPERTIES
+ INTERFACE_LINK_LIBRARIES Threads::Threads)
+ endif()
+ if(WIN32)
+ set_target_properties(IoTDB::iotdb_session PROPERTIES
+ IMPORTED_IMPLIB "${_IOTDB_SESSION_LIBRARY}"
+ IMPORTED_LOCATION "${_IOTDB_SESSION_PACKAGE_ROOT}/lib/iotdb_session.dll")
+ else()
+ set_target_properties(IoTDB::iotdb_session PROPERTIES
+ IMPORTED_LOCATION "${_IOTDB_SESSION_LIBRARY}")
+ endif()
+endif()
+
+set(iotdb-session_VERSION "@IOTDB_SESSION_VERSION@")
diff --git a/iotdb-client/client-cpp/cmake/iotdb-session.pc.in b/iotdb-client/client-cpp/cmake/iotdb-session.pc.in
new file mode 100644
index 00000000000..0cc6833e1ce
--- /dev/null
+++ b/iotdb-client/client-cpp/cmake/iotdb-session.pc.in
@@ -0,0 +1,26 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+prefix=${pcfiledir}/..
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: iotdb-session-cpp
+Description: Apache IoTDB C++ session client
+Version: @IOTDB_SESSION_VERSION@
+Libs: -L${libdir} @IOTDB_SESSION_PC_LIBS@
+Cflags: -I${includedir} @IOTDB_SESSION_PC_CFLAGS@
diff --git a/example/client-cpp-example/src/AlignedTimeseriesSessionExample.cpp b/iotdb-client/client-cpp/examples/AlignedTimeseriesSessionExample.cpp
similarity index 98%
rename from example/client-cpp-example/src/AlignedTimeseriesSessionExample.cpp
rename to iotdb-client/client-cpp/examples/AlignedTimeseriesSessionExample.cpp
index 3675525301a..80d1caadd35 100644
--- a/example/client-cpp-example/src/AlignedTimeseriesSessionExample.cpp
+++ b/iotdb-client/client-cpp/examples/AlignedTimeseriesSessionExample.cpp
@@ -23,7 +23,18 @@ using namespace std;
Session* session;
-#define DEFAULT_ROW_NUMBER 1000000
+#define DEFAULT_ROW_NUMBER 1000
+
+void setStorageGroupIfAbsent(const string& storageGroup) {
+ try {
+ session->setStorageGroup(storageGroup);
+ } catch (IoTDBException& e) {
+ string errorMessage(e.what());
+ if (errorMessage.find("StorageGroupAlreadySetException") == string::npos) {
+ cout << errorMessage << endl;
+ }
+ }
+}
void createAlignedTimeseries() {
string alignedDeviceId = "root.sg1.d1";
@@ -45,6 +56,8 @@ void createAlignedTimeseries() {
}
void createSchemaTemplate() {
+ setStorageGroupIfAbsent("root.sg3");
+
if (!session->checkTemplateExists("template1")) {
Template temp("template1", false);
@@ -349,15 +362,7 @@ int main() {
session->open(false);
cout << "setStorageGroup\n" << endl;
- try {
- session->setStorageGroup("root.sg1");
- } catch (IoTDBException& e) {
- string errorMessage(e.what());
- if (errorMessage.find("StorageGroupAlreadySetException") == string::npos) {
- cout << errorMessage << endl;
- //throw e;
- }
- }
+ setStorageGroupIfAbsent("root.sg1");
cout << "createAlignedTimeseries\n" << endl;
createAlignedTimeseries();
diff --git a/iotdb-client/client-cpp/examples/CMakeLists.txt b/iotdb-client/client-cpp/examples/CMakeLists.txt
new file mode 100644
index 00000000000..0b77bce5544
--- /dev/null
+++ b/iotdb-client/client-cpp/examples/CMakeLists.txt
@@ -0,0 +1,187 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+CMAKE_MINIMUM_REQUIRED(VERSION 3.15)
+CMAKE_POLICY(SET CMP0091 NEW)
+
+# Windows SDK zips are x86_64; Visual Studio generators (especially VS2017) default to Win32.
+IF(CMAKE_GENERATOR MATCHES "Visual Studio" AND NOT CMAKE_GENERATOR_PLATFORM)
+ SET(CMAKE_GENERATOR_PLATFORM "x64" CACHE STRING "IoTDB C++ SDK is x64-only" FORCE)
+ENDIF()
+
+PROJECT(iotdb_cpp_client_examples)
+
+SET(CMAKE_CXX_STANDARD 11)
+SET(CMAKE_CXX_STANDARD_REQUIRED ON)
+SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
+
+IF(MSVC)
+ # Match the IoTDB C++ SDK (/MD); same as a default Visual Studio application.
+ SET(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
+ENDIF()
+
+option(IOTDB_EXAMPLES_REGISTER_TESTS "Register runnable examples with ctest" OFF)
+
+if(TARGET iotdb_session)
+ set(_iotdb_examples_in_tree ON)
+ set(_iotdb_link_lib iotdb_session)
+else()
+ set(_iotdb_examples_in_tree OFF)
+ set(_iotdb_default_sdk_root "${CMAKE_CURRENT_LIST_DIR}/..")
+ if(NOT EXISTS "${_iotdb_default_sdk_root}/include" OR NOT EXISTS "${_iotdb_default_sdk_root}/lib")
+ set(_iotdb_default_sdk_root "${CMAKE_SOURCE_DIR}/client")
+ endif()
+ set(IOTDB_SDK_ROOT "${_iotdb_default_sdk_root}"
+ CACHE PATH "Unpacked IoTDB C++ SDK directory (contains include/ and lib/)")
+
+ if(NOT EXISTS "${IOTDB_SDK_ROOT}/include" OR NOT EXISTS "${IOTDB_SDK_ROOT}/lib")
+ file(GLOB _iotdb_sdk_children LIST_DIRECTORIES true "${IOTDB_SDK_ROOT}/iotdb-session-cpp-*")
+ list(LENGTH _iotdb_sdk_children _iotdb_sdk_child_count)
+ if(_iotdb_sdk_child_count EQUAL 1)
+ list(GET _iotdb_sdk_children 0 IOTDB_SDK_ROOT)
+ message(STATUS "Using IoTDB SDK package root: ${IOTDB_SDK_ROOT}")
+ endif()
+ endif()
+
+ INCLUDE_DIRECTORIES("${IOTDB_SDK_ROOT}/include")
+endif()
+
+option(WITH_SSL "Build with SSL support" OFF)
+
+IF(WITH_SSL)
+ FIND_PACKAGE(OpenSSL REQUIRED)
+ IF(OpenSSL_FOUND)
+ MESSAGE(STATUS "OpenSSL found: ${OPENSSL_VERSION}")
+ INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
+ ADD_DEFINITIONS(-DWITH_SSL=1)
+ ELSE()
+ MESSAGE(FATAL_ERROR "OpenSSL not found, but WITH_SSL is enabled")
+ ENDIF()
+ELSE()
+ MESSAGE(STATUS "Building without SSL support")
+ ADD_DEFINITIONS(-DWITH_SSL=0)
+ENDIF()
+
+if(NOT _iotdb_examples_in_tree)
+ find_package(iotdb-session CONFIG QUIET
+ PATHS "${IOTDB_SDK_ROOT}/cmake" "${IOTDB_SDK_ROOT}"
+ NO_DEFAULT_PATH)
+ if(WIN32)
+ set(_iotdb_link_lib "${IOTDB_SDK_ROOT}/lib/iotdb_session.lib")
+ set(_iotdb_runtime "${IOTDB_SDK_ROOT}/lib/iotdb_session.dll")
+ elseif(APPLE)
+ set(_iotdb_link_lib "${IOTDB_SDK_ROOT}/lib/libiotdb_session.dylib")
+ set(_iotdb_runtime "${_iotdb_link_lib}")
+ else()
+ set(_iotdb_link_lib "${IOTDB_SDK_ROOT}/lib/libiotdb_session.so")
+ set(_iotdb_runtime "${_iotdb_link_lib}")
+ endif()
+
+ if(NOT EXISTS "${_iotdb_link_lib}")
+ message(FATAL_ERROR
+ "IoTDB SDK not found at ${IOTDB_SDK_ROOT}. "
+ "Unpack iotdb-session-cpp-<version>-<classifier>.zip so that ${_iotdb_link_lib} exists.")
+ endif()
+
+ if(TARGET IoTDB::iotdb_session)
+ set(_iotdb_link_lib IoTDB::iotdb_session)
+ endif()
+endif()
+
+ADD_EXECUTABLE(SessionExample SessionExample.cpp)
+ADD_EXECUTABLE(AlignedTimeseriesSessionExample AlignedTimeseriesSessionExample.cpp)
+ADD_EXECUTABLE(TableModelSessionExample TableModelSessionExample.cpp)
+ADD_EXECUTABLE(MultiSvrNodeClient MultiSvrNodeClient.cpp)
+ADD_EXECUTABLE(tree_example tree_example.c)
+ADD_EXECUTABLE(table_example table_example.c)
+
+set(_example_targets
+ SessionExample
+ AlignedTimeseriesSessionExample
+ TableModelSessionExample
+ MultiSvrNodeClient
+ tree_example
+ table_example)
+
+foreach(_t IN LISTS _example_targets)
+ IF(WITH_SSL)
+ TARGET_LINK_LIBRARIES(${_t} PRIVATE "${_iotdb_link_lib}" OpenSSL::SSL OpenSSL::Crypto)
+ ELSE()
+ TARGET_LINK_LIBRARIES(${_t} PRIVATE "${_iotdb_link_lib}")
+ ENDIF()
+ IF(UNIX)
+ TARGET_LINK_LIBRARIES(${_t} PRIVATE pthread)
+ ENDIF()
+
+ # Run from the build output directory without setting LD_LIBRARY_PATH / PATH.
+ if(UNIX)
+ set_target_properties(${_t} PROPERTIES
+ BUILD_RPATH "\$ORIGIN"
+ INSTALL_RPATH "\$ORIGIN")
+ endif()
+
+ if(_iotdb_examples_in_tree)
+ add_custom_command(TARGET ${_t} POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ $<TARGET_FILE:iotdb_session> $<TARGET_FILE_DIR:${_t}>
+ COMMENT "Copy IoTDB runtime library next to ${_t}")
+ elseif(EXISTS "${_iotdb_runtime}")
+ add_custom_command(TARGET ${_t} POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${_iotdb_runtime}" $<TARGET_FILE_DIR:${_t}>
+ COMMENT "Copy IoTDB runtime library next to ${_t}")
+ elseif(WIN32)
+ message(WARNING "Missing ${_iotdb_runtime}; copy iotdb_session.dll manually before running ${_t}.")
+ endif()
+endforeach()
+
+# Optional: stage a self-contained folder for copying to another machine (see package README).
+set(_example_dist_dir "${CMAKE_BINARY_DIR}/dist")
+add_custom_target(example-dist DEPENDS ${_example_targets}
+ COMMENT "Collect example binaries and IoTDB runtime into ${_example_dist_dir}")
+foreach(_t IN LISTS _example_targets)
+ add_custom_command(TARGET example-dist POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E make_directory "${_example_dist_dir}"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ $<TARGET_FILE:${_t}> "${_example_dist_dir}/"
+ COMMENT "Stage ${_t}")
+endforeach()
+if(EXISTS "${_iotdb_runtime}")
+ add_custom_command(TARGET example-dist POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${_iotdb_runtime}" "${_example_dist_dir}/")
+endif()
+
+if(IOTDB_EXAMPLES_REGISTER_TESTS)
+ set(_runnable_example_targets
+ SessionExample
+ AlignedTimeseriesSessionExample
+ TableModelSessionExample
+ tree_example
+ table_example)
+ foreach(_t IN LISTS _runnable_example_targets)
+ add_test(NAME example_${_t} COMMAND ${_t})
+ endforeach()
+ set_tests_properties(
+ example_SessionExample
+ example_AlignedTimeseriesSessionExample
+ example_TableModelSessionExample
+ example_tree_example
+ example_table_example
+ PROPERTIES RUN_SERIAL TRUE)
+endif()
diff --git a/example/client-cpp-example/src/MultiSvrNodeClient.cpp b/iotdb-client/client-cpp/examples/MultiSvrNodeClient.cpp
similarity index 96%
rename from example/client-cpp-example/src/MultiSvrNodeClient.cpp
rename to iotdb-client/client-cpp/examples/MultiSvrNodeClient.cpp
index 06e96ecd31b..e7f94a2c778 100644
--- a/example/client-cpp-example/src/MultiSvrNodeClient.cpp
+++ b/iotdb-client/client-cpp/examples/MultiSvrNodeClient.cpp
@@ -17,9 +17,11 @@
* under the License.
*/
+#include <chrono>
#include <iostream>
#include <memory>
#include <string>
+#include <thread>
#include <vector>
#include "Session.h"
@@ -94,12 +96,10 @@ void RunResilienceExample() {
for (int i = 0; i < 60; ++i) { // run ~60 seconds
int64_t timestamp =
std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
- std::string value = to_string(i);
- const char* value_cstr = value.c_str();
+ std::string value = std::to_string(i);
try {
- session->insertRecord("root.resilience.d1", timestamp, {"s1"}, {TSDataType::INT64},
- {const_cast<char*>(value_cstr)});
+ session->insertRecord("root.resilience.d1", timestamp, {"s1"}, {value});
std::cout << "[Insert] ts=" << timestamp << ", value=" << value << std::endl;
auto dataset = session->executeQueryStatement("SELECT s1 FROM root.resilience.d1 LIMIT 1");
diff --git a/iotdb-client/client-cpp/examples/README.md b/iotdb-client/client-cpp/examples/README.md
new file mode 100644
index 00000000000..295aa29bdbe
--- /dev/null
+++ b/iotdb-client/client-cpp/examples/README.md
@@ -0,0 +1,260 @@
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+# IoTDB C++ client examples
+
+[中文说明](README_zh.md)
+
+Sample programs that link against the pre-built **IoTDB C++ Session SDK**
+(`iotdb_session`). Thrift and Boost are **not** required at application compile
+time; they are embedded inside the SDK shared library.
+
+All examples connect to a running IoTDB instance (default `127.0.0.1:6667`,
+user `root` / `root`).
+
+| Example | Description |
+|---------|-------------|
+| `SessionExample` | Tree model: DDL, insert, query, delete |
+| `AlignedTimeseriesSessionExample` | Aligned time series and templates |
+| `TableModelSessionExample` | Table (relational) model |
+| `MultiSvrNodeClient` | Multi-node insert/query loop |
+| `tree_example` | C Session API (tree model) |
+| `table_example` | C Session API (table model) |
+
+## Which SDK zip to use
+
+Release CI ([client-cpp-package.yml](../../.github/workflows/client-cpp-package.yml))
+publishes one zip per platform/toolchain:
+`iotdb-session-cpp-<version>-<classifier>.zip` (package root contains `include/` and `lib/`).
+
+| Deployment target | Classifier suffix |
+|-------------------|-------------------|
+| Linux x86_64, glibc >= 2.28 | `linux-x86_64-glibc2.28` |
+| Linux aarch64, glibc >= 2.28 | `linux-aarch64-glibc2.28` |
+| macOS x86_64 | `macos-x86_64` |
+| macOS arm64 | `macos-aarch64` |
+| Windows (match your Visual Studio version) | `windows-x86_64-msvc14.1` ... `msvc14.4` |
+
+The current build compiles Thrift 0.21 from source at CMake configure time.
+Legacy `-Diotdb-tools-thrift.version=...` flags applied to the **old**
+pre-built Thrift workflow only. Linux release packages are built in the
+`manylinux_2_28` container and require glibc 2.28 or newer. See
+[client-cpp README](../../iotdb-client/client-cpp/README.md).
+
+## SDK layout (after unpack)
+
+The SDK zip produced by `client-cpp` contains **public headers only** and one
+shared library:
+
+```
+client/
+├── include/
+│ ├── Session.h
+│ ├── Export.h
+│ └── ...
+└── lib/
+ ├── iotdb_session.dll + iotdb_session.lib (Windows)
+ ├── libiotdb_session.so (Linux)
+ └── libiotdb_session.dylib (macOS)
+```
+
+## Build the examples
+
+### Option A – Maven (recommended in this repo)
+
+From the repository root:
+
+```bash
+mvn clean verify -P with-cpp -pl iotdb-client/client-cpp -am
+```
+
+Maven builds the C++ client, starts a local IoTDB server for the verify phase,
+and runs the C++ tests plus runnable examples through CTest. Example binaries
+are under `iotdb-client/client-cpp/target/build/examples/` (or
+`target/build/examples/Release/` with Visual Studio).
+
+### Option B – CMake only (manual SDK)
+
+1. Build or download the SDK and unpack it so `client/include` and
+ `client/lib` exist (see layout above).
+2. Use this `examples/` directory as the source tree and place `client/` beside
+ it, or pass `-DIOTDB_SDK_ROOT=/path/to/iotdb-session-cpp-...`.
+3. Configure and build:
+
+```bash
+cmake -S iotdb-client/client-cpp/examples -B build \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DIOTDB_SDK_ROOT=/path/to/iotdb-session-cpp-...
+cmake --build build
+```
+
+Windows (Visual Studio generator):
+
+```powershell
+cmake -S . -B build -A x64
+cmake --build build --config Release
+```
+
+Each executable is built with the IoTDB runtime library copied **next to the
+`.exe` / binary** (POST_BUILD step). Linux/macOS binaries use `$ORIGIN` rpath
+so they resolve the `.so` / `.dylib` in the same directory.
+
+Optional staging folder for deployment:
+
+```bash
+cmake --build build --target example-dist
+# -> build/dist/ contains all example binaries + libiotdb_session.{so,dll,dylib}
+```
+
+## Run on a clean machine (no compiler, no IoTDB SDK headers)
+
+You only need:
+
+1. A running IoTDB server reachable from the machine.
+2. The **example executable(s)** and the **IoTDB runtime library** in the
+ **same directory** (or on the system library path).
+
+Copy either from `build/.../Release/` (Windows) / `build/` (Ninja/Make) or from
+`build/dist/` after `example-dist`.
+
+### Windows
+
+**Files to copy**
+
+```
+SessionExample.exe
+iotdb_session.dll
+```
+
+(Repeat for the other example names if needed.)
+
+**Prerequisites on the target PC**
+
+- **64-bit Windows** (examples are built x64).
+- **[Microsoft Visual C++ Redistributable for Visual Studio 2015–2022](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist)**
+ (x64). The SDK and examples are built with **`/MD`**; the redistributable
+ supplies `vcruntime140.dll`, `msvcp140.dll`, etc.
+ Installing this package is enough—you do **not** need Visual Studio or the
+ IoTDB SDK on the target machine.
+
+**Run**
+
+```powershell
+.\SessionExample.exe
+```
+
+If you see “The code execution cannot proceed because VCRUNRuntime140.dll was
+missing”, install the VC++ redistributable above.
+
+You do **not** need a separate Thrift or Boost runtime; they are inside
+`iotdb_session.dll`.
+
+### Linux
+
+**Files to copy**
+
+```
+SessionExample
+libiotdb_session.so
+chmod +x SessionExample
+```
+
+**Prerequisites on the target machine**
+
+- **glibc** on the target must be **≥ the glibc version on the machine that
+ built the SDK** (backward compatible only in that direction).
+
+Check **build machine** (record in release notes):
+
+```bash
+ldd --version | head -1
+# e.g. ldd (Ubuntu GLIBC 2.35-0ubuntu3) 2.35
+```
+
+Check **target machine**:
+
+```bash
+ldd --version | head -1
+# must be >= build glibc (same major.minor or newer)
+```
+
+See which `GLIBC_` symbols the binary needs:
+
+```bash
+objdump -T SessionExample | grep GLIBC_ | sed 's/.*GLIBC_/GLIBC_/' | sort -Vu | tail -5
+objdump -T libiotdb_session.so | grep GLIBC_ | sed 's/.*GLIBC_/GLIBC_/' | sort -Vu | tail -5
+```
+
+If the target glibc is too old, you'll get errors like
+`version 'GLIBC_2.34' not found` at runtime. Rebuild the SDK on an older distro
+(or in an older container) to widen compatibility.
+
+**Run** (with `.so` beside the binary):
+
+```bash
+./SessionExample
+```
+
+If the shared library is not found:
+
+```bash
+export LD_LIBRARY_PATH=.
+./SessionExample
+```
+
+No separate Thrift install is required.
+
+### macOS
+
+Copy the example binary and `libiotdb_session.dylib` together. The target macOS
+version should be **≥ the deployment target used to build the SDK**. Check with:
+
+```bash
+otool -L SessionExample
+```
+
+## Development notes
+
+- **Windows**: Application and SDK both use **`/MD`** (dynamic CRT). This
+ matches a default Visual Studio project; link `iotdb_session.lib`, ship
+ `iotdb_session.dll`.
+- **Linux**: SDK is `libiotdb_session.so`; link it directly. Prefer shipping
+ the `.so` next to your binary or setting `RPATH` to `$ORIGIN`.
+- Examples assume IoTDB is listening on `127.0.0.1:6667`; change host/port in
+ the source if needed.
+
+## Project layout in this module
+
+```
+client-cpp/examples/
+├── README.md
+├── README_zh.md
+├── CMakeLists.txt
+├── SessionExample.cpp
+├── AlignedTimeseriesSessionExample.cpp
+├── TableModelSessionExample.cpp
+├── MultiSvrNodeClient.cpp
+├── tree_example.c
+└── table_example.c
+```
+
+After `mvn package`, the runnable tree is under `target/` (sources, `client/`,
+and CMake build output).
diff --git a/iotdb-client/client-cpp/examples/README_zh.md b/iotdb-client/client-cpp/examples/README_zh.md
new file mode 100644
index 00000000000..435b58fe9e6
--- /dev/null
+++ b/iotdb-client/client-cpp/examples/README_zh.md
@@ -0,0 +1,253 @@
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+# IoTDB C++ 客户端示例
+
+[English](README.md)
+
+本目录提供链接 **IoTDB C++ Session SDK**(`iotdb_session`)的示例程序。
+应用侧编译 **不需要** 单独安装 Thrift 或 Boost 头文件/库,它们已封装在 SDK
+共享库内部。
+
+所有示例默认连接本机 IoTDB(`127.0.0.1:6667`,用户 `root` / 密码 `root`)。
+
+| 示例 | 说明 |
+|------|------|
+| `SessionExample` | 树模型:建库建序列、写入、查询、删除 |
+| `AlignedTimeseriesSessionExample` | 对齐时间序列与模板 |
+| `TableModelSessionExample` | 表模型(关系型) |
+| `MultiSvrNodeClient` | 多节点写入/查询循环 |
+| `tree_example` | C Session API(树模型) |
+| `table_example` | C Session API(表模型) |
+
+## 选择哪个 SDK 压缩包
+
+CI 发版([client-cpp-package.yml](../../.github/workflows/client-cpp-package.yml))
+会按平台/工具链打出多份 zip,文件名形如
+`iotdb-session-cpp-<version>-<classifier>.zip`(解压后根目录即为 `include/` 与 `lib/`)。请按目标环境选择:
+
+| 目标环境 | classifier 后缀 |
+|----------|-----------------|
+| Linux x86_64,glibc >= 2.28 | `linux-x86_64-glibc2.28` |
+| Linux aarch64,glibc >= 2.28 | `linux-aarch64-glibc2.28` |
+| macOS x86_64 | `macos-x86_64` |
+| macOS arm64 | `macos-aarch64` |
+| Windows + 与工程相同的 VS 版本 | `windows-x86_64-msvc14.1` ... `msvc14.4` |
+
+当前 CMake 构建在配置阶段从源码编译 Thrift 0.21,**不再**通过
+`-Diotdb-tools-thrift.version=0.14.1.1-gcc4-SNAPSHOT` 等旧参数控制 glibc;
+Linux 发版包在 `manylinux_2_28` 容器中构建,部署机需要 glibc 2.28 或更新版本。
+详见 [client-cpp README](../../iotdb-client/client-cpp/README.md)。
+
+## SDK 目录结构(解压后)
+
+`client-cpp` 打出的 SDK 压缩包只包含 **公开头文件** 和 **一个共享库**:
+
+```
+client/
+├── include/
+│ ├── Session.h
+│ ├── Export.h
+│ └── ... (17 个公开头;无 thrift/、boost/)
+└── lib/
+ ├── iotdb_session.dll + iotdb_session.lib (Windows)
+ ├── libiotdb_session.so (Linux)
+ └── libiotdb_session.dylib (macOS)
+```
+
+## 编译示例
+
+### 方式 A:Maven(本仓库推荐)
+
+在仓库根目录执行:
+
+```bash
+mvn clean verify -P with-cpp -pl iotdb-client/client-cpp -am
+```
+
+Maven 会构建 C++ client,在 verify 阶段启动本地 IoTDB,并通过 CTest 运行 C++
+测试和可自动运行的 examples。示例二进制在
+`iotdb-client/client-cpp/target/build/examples/` 下(Windows + Visual Studio
+通常在 `target/build/examples/Release/`)。
+
+### 方式 B:仅 CMake(手动准备 SDK)
+
+1. 自行编译或下载 SDK,解压后保证存在 `client/include` 与 `client/lib`(见
+ 上文目录结构)。
+2. 使用这个 `examples/` 目录作为源码目录,并把 `client/` 放在旁边;也可以传入
+ `-DIOTDB_SDK_ROOT=/path/to/iotdb-session-cpp-...`。
+3. 配置并编译:
+
+```bash
+cmake -S iotdb-client/client-cpp/examples -B build \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DIOTDB_SDK_ROOT=/path/to/iotdb-session-cpp-...
+cmake --build build
+```
+
+Windows(Visual Studio 生成器):
+
+```powershell
+cmake -S . -B build -A x64
+cmake --build build --config Release
+```
+
+编译完成后,IoTDB 运行时库会通过 POST_BUILD 自动复制到 **与可执行文件相同
+的目录**。Linux/macOS 可执行文件还设置了 `$ORIGIN` rpath,可在同目录加载
+`.so` / `.dylib`。
+
+可选:打部署包目录
+
+```bash
+cmake --build build --target example-dist
+# 生成 build/dist/,内含全部示例二进制 + libiotdb_session.{so,dll,dylib}
+```
+
+## 在「干净机器」上运行(无需编译器、无需 SDK 头文件)
+
+目标机器只需:
+
+1. 可访问的 **IoTDB 服务**(已启动)。
+2. **示例可执行文件** 与 **IoTDB 运行时库** 放在 **同一目录**(或位于系统
+ 库搜索路径中)。
+
+可从 `build/.../Release/`(Windows)或 `build/`(Ninja/Make)复制,也可在
+执行 `example-dist` 后直接使用 `build/dist/`。
+
+### Windows
+
+**需要拷贝的文件**
+
+```
+SessionExample.exe
+iotdb_session.dll
+```
+
+(其他示例同理,可执行文件与 `iotdb_session.dll` 成对拷贝。)
+
+**目标机器前置条件**
+
+- **64 位 Windows**(示例为 x64 构建)。
+- 安装 **[Microsoft Visual C++ 2015–2022 可再发行组件包(x64)](https://learn.microsoft.com/zh-cn/cpp/windows/latest-supported-vc-redist)**。
+ SDK 与示例均使用 **`/MD`**(动态 CRT),该安装包提供 `vcruntime140.dll`、
+ `msvcp140.dll` 等运行时。
+ **仅安装此 Redistributable 即可**,目标机 **不需要** Visual Studio,也
+ **不需要** IoTDB SDK 头文件或 Thrift/Boost。
+
+**运行**
+
+```powershell
+.\SessionExample.exe
+```
+
+若提示缺少 `VCRUNTIME140.dll`,请安装上述 VC++ 可再发行包。
+
+Thrift、Boost 已包含在 `iotdb_session.dll` 内,无需单独部署。
+
+### Linux
+
+**需要拷贝的文件**
+
+```
+SessionExample
+libiotdb_session.so
+chmod +x SessionExample
+```
+
+**目标机器前置条件**
+
+- 目标机的 **glibc 版本必须 ≥ 编译 SDK 时的 glibc 版本**(仅向后兼容:
+ 新系统可跑旧库要求,旧系统不能跑需要更高 glibc 的二进制)。
+
+在 **编译机** 上记录版本(建议写入发布说明):
+
+```bash
+ldd --version | head -1
+# 例如:ldd (Ubuntu GLIBC 2.35-0ubuntu3) 2.35
+```
+
+在 **目标机** 上检查:
+
+```bash
+ldd --version | head -1
+# 版本号应 >= 编译机(同主版本次版本或更新)
+```
+
+查看二进制依赖的最高 `GLIBC_` 符号:
+
+```bash
+objdump -T SessionExample | grep GLIBC_ | sed 's/.*GLIBC_/GLIBC_/' | sort -Vu | tail -5
+objdump -T libiotdb_session.so | grep GLIBC_ | sed 's/.*GLIBC_/GLIBC_/' | sort -Vu | tail -5
+```
+
+若目标 glibc 过旧,运行时会报错,例如
+`version 'GLIBC_2.34' not found`。可在更旧的发行版(或旧版容器)上重新编译
+SDK,以扩大兼容范围。
+
+**运行**(`.so` 与可执行文件同目录):
+
+```bash
+./SessionExample
+```
+
+若找不到共享库:
+
+```bash
+export LD_LIBRARY_PATH=.
+./SessionExample
+```
+
+无需单独安装 Thrift。
+
+### macOS
+
+将示例可执行文件与 `libiotdb_session.dylib` 放在同一目录。目标 macOS 版本
+应 **≥ 编译 SDK 时设置的 deployment target**。可用以下命令检查依赖:
+
+```bash
+otool -L SessionExample
+```
+
+## 开发说明
+
+- **Windows**:应用与 SDK 均使用 **`/MD`**,与 Visual Studio 默认工程一致;
+ 链接 `iotdb_session.lib`,部署时携带 `iotdb_session.dll`。
+- **Linux**:直接链接 `libiotdb_session.so`;建议与可执行文件同目录发布,或
+ 设置 `RPATH=$ORIGIN`。
+- 示例默认连接 `127.0.0.1:6667`;如需修改地址/端口,请编辑对应源码。
+
+## 本模块目录结构
+
+```
+client-cpp/examples/
+├── README.md # 英文说明
+├── README_zh.md # 中文说明(本文件)
+├── CMakeLists.txt
+├── SessionExample.cpp
+├── AlignedTimeseriesSessionExample.cpp
+├── TableModelSessionExample.cpp
+├── MultiSvrNodeClient.cpp
+├── tree_example.c
+└── table_example.c
+```
+
+执行 `mvn verify -P with-cpp -pl iotdb-client/client-cpp -am` 后,可在
+`iotdb-client/client-cpp/target/build/examples/` 下找到构建产物。
diff --git a/example/client-cpp-example/src/SessionExample.cpp b/iotdb-client/client-cpp/examples/SessionExample.cpp
similarity index 97%
rename from example/client-cpp-example/src/SessionExample.cpp
rename to iotdb-client/client-cpp/examples/SessionExample.cpp
index d589759e8ed..9b429b0189b 100644
--- a/example/client-cpp-example/src/SessionExample.cpp
+++ b/iotdb-client/client-cpp/examples/SessionExample.cpp
@@ -23,6 +23,17 @@ using namespace std;
Session* session;
+void setStorageGroupIfAbsent(const string& storageGroup) {
+ try {
+ session->setStorageGroup(storageGroup);
+ } catch (IoTDBException& e) {
+ string errorMessage(e.what());
+ if (errorMessage.find("StorageGroupAlreadySetException") == string::npos) {
+ cout << errorMessage << endl;
+ }
+ }
+}
+
void createTimeseries() {
if (!session->checkTimeseriesExists("root.sg1.d1.s1")) {
session->createTimeseries("root.sg1.d1.s1", TSDataType::BOOLEAN, TSEncoding::RLE,
@@ -87,6 +98,8 @@ void createMultiTimeseries() {
}
void createSchemaTemplate() {
+ setStorageGroupIfAbsent("root.sg3");
+
if (!session->checkTemplateExists("template1")) {
Template temp("template1", false);
@@ -382,26 +395,10 @@ int main() {
session->open(false);
cout << "setStorageGroup: root.sg1\n" << endl;
- try {
- session->setStorageGroup("root.sg1");
- } catch (IoTDBException& e) {
- string errorMessage(e.what());
- if (errorMessage.find("StorageGroupAlreadySetException") == string::npos) {
- cout << errorMessage << endl;
- }
- //throw e;
- }
+ setStorageGroupIfAbsent("root.sg1");
cout << "setStorageGroup: root.sg2\n" << endl;
- try {
- session->setStorageGroup("root.sg2");
- } catch (IoTDBException& e) {
- string errorMessage(e.what());
- if (errorMessage.find("StorageGroupAlreadySetException") == string::npos) {
- cout << errorMessage << endl;
- }
- //throw e;
- }
+ setStorageGroupIfAbsent("root.sg2");
cout << "createTimeseries\n" << endl;
createTimeseries();
diff --git a/example/client-cpp-example/src/TableModelSessionExample.cpp b/iotdb-client/client-cpp/examples/TableModelSessionExample.cpp
similarity index 100%
rename from example/client-cpp-example/src/TableModelSessionExample.cpp
rename to iotdb-client/client-cpp/examples/TableModelSessionExample.cpp
diff --git a/iotdb-client/client-cpp/examples/table_example.c b/iotdb-client/client-cpp/examples/table_example.c
new file mode 100644
index 00000000000..bc9df9aa823
--- /dev/null
+++ b/iotdb-client/client-cpp/examples/table_example.c
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Table model: CREATE DATABASE/TABLE, insert rows via Tablet, SELECT, DROP DATABASE.
+ * Requires IoTDB table-SQL support. Edit HOST / PORT / credentials below.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "SessionC.h"
+
+#define HOST "127.0.0.1"
+#define PORT 6667
+#define USER "root"
+#define PASS "root"
+
+#define DB_NAME "cdemo_db"
+#define TABLE_NAME "cdemo_t0"
+
+static void fail(const char* ctx, CTableSession* s) {
+ fprintf(stderr, "[table_example] %s failed: %s\n", ctx, ts_get_last_error());
+ if (s) {
+ ts_table_session_close(s);
+ ts_table_session_destroy(s);
+ }
+ exit(1);
+}
+
+int main(void) {
+ CTableSession* session = ts_table_session_new(HOST, PORT, USER, PASS, "");
+ if (!session) {
+ fprintf(stderr, "[table_example] ts_table_session_new returned NULL: %s\n",
+ ts_get_last_error());
+ return 1;
+ }
+ if (ts_table_session_open(session) != TS_OK) {
+ fail("ts_table_session_open", session);
+ }
+
+ char sql[512];
+ snprintf(sql, sizeof(sql), "DROP DATABASE IF EXISTS %s", DB_NAME);
+ (void)ts_table_session_execute_non_query(session, sql);
+
+ snprintf(sql, sizeof(sql), "CREATE DATABASE %s", DB_NAME);
+ if (ts_table_session_execute_non_query(session, sql) != TS_OK) {
+ fail("CREATE DATABASE", session);
+ }
+
+ snprintf(sql, sizeof(sql), "USE \"%s\"", DB_NAME);
+ if (ts_table_session_execute_non_query(session, sql) != TS_OK) {
+ fail("USE DATABASE", session);
+ }
+
+ const char* ddl = "CREATE TABLE " TABLE_NAME " ("
+ "tag1 string tag,"
+ "attr1 string attribute,"
+ "m1 double field)";
+ if (ts_table_session_execute_non_query(session, ddl) != TS_OK) {
+ fail("CREATE TABLE", session);
+ }
+
+ const char* columnNames[] = {"tag1", "attr1", "m1"};
+ TSDataType_C dataTypes[] = {TS_TYPE_STRING, TS_TYPE_STRING, TS_TYPE_DOUBLE};
+ TSColumnCategory_C colCategories[] = {TS_COL_TAG, TS_COL_ATTRIBUTE, TS_COL_FIELD};
+
+ CTablet* tablet =
+ ts_tablet_new_with_category(TABLE_NAME, 3, columnNames, dataTypes, colCategories, 100);
+ if (!tablet) {
+ fail("ts_tablet_new_with_category", session);
+ }
+
+ int i;
+ for (i = 0; i < 5; i++) {
+ if (ts_tablet_add_timestamp(tablet, i, (int64_t)i) != TS_OK) {
+ ts_tablet_destroy(tablet);
+ fail("ts_tablet_add_timestamp", session);
+ }
+ if (ts_tablet_add_value_string(tablet, 0, i, "device_A") != TS_OK) {
+ ts_tablet_destroy(tablet);
+ fail("ts_tablet_add_value_string tag", session);
+ }
+ if (ts_tablet_add_value_string(tablet, 1, i, "attr_val") != TS_OK) {
+ ts_tablet_destroy(tablet);
+ fail("ts_tablet_add_value_string attr", session);
+ }
+ if (ts_tablet_add_value_double(tablet, 2, i, (double)i * 1.5) != TS_OK) {
+ ts_tablet_destroy(tablet);
+ fail("ts_tablet_add_value_double", session);
+ }
+ }
+ if (ts_tablet_set_row_count(tablet, 5) != TS_OK) {
+ ts_tablet_destroy(tablet);
+ fail("ts_tablet_set_row_count", session);
+ }
+
+ if (ts_table_session_insert(session, tablet) != TS_OK) {
+ ts_tablet_destroy(tablet);
+ fail("ts_table_session_insert", session);
+ }
+ ts_tablet_destroy(tablet);
+
+ CSessionDataSet* dataSet = NULL;
+ if (ts_table_session_execute_query(session, "SELECT * FROM " TABLE_NAME, &dataSet) != TS_OK) {
+ fail("ts_table_session_execute_query", session);
+ }
+ if (!dataSet) {
+ fprintf(stderr, "[table_example] dataSet is NULL\n");
+ ts_table_session_close(session);
+ ts_table_session_destroy(session);
+ return 1;
+ }
+ ts_dataset_set_fetch_size(dataSet, 1024);
+
+ int count = 0;
+ while (ts_dataset_has_next(dataSet)) {
+ CRowRecord* record = ts_dataset_next(dataSet);
+ if (!record) {
+ break;
+ }
+ printf("[table_example] row %d: time=%lld\n", count,
+ (long long)ts_row_record_get_timestamp(record));
+ ts_row_record_destroy(record);
+ count++;
+ }
+ ts_dataset_destroy(dataSet);
+ printf("[table_example] SELECT returned %d row(s).\n", count);
+
+ snprintf(sql, sizeof(sql), "DROP DATABASE IF EXISTS %s", DB_NAME);
+ (void)ts_table_session_execute_non_query(session, sql);
+
+ ts_table_session_close(session);
+ ts_table_session_destroy(session);
+ return 0;
+}
diff --git a/iotdb-client/client-cpp/examples/tree_example.c b/iotdb-client/client-cpp/examples/tree_example.c
new file mode 100644
index 00000000000..b1eb53fafb8
--- /dev/null
+++ b/iotdb-client/client-cpp/examples/tree_example.c
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Tree model: create one timeseries, insert one row via string values, SELECT, cleanup.
+ * Edit HOST / PORT / credentials below to match your IoTDB.
+ */
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "SessionC.h"
+
+#define HOST "127.0.0.1"
+#define PORT 6667
+#define USER "root"
+#define PASS "root"
+
+#define TS_PATH "root.cdemo.d0.s0"
+#define DEVICE "root.cdemo.d0"
+
+static void fail(const char* ctx, CSession* s) {
+ fprintf(stderr, "[tree_example] %s failed: %s\n", ctx, ts_get_last_error());
+ if (s) {
+ ts_session_close(s);
+ ts_session_destroy(s);
+ }
+ exit(1);
+}
+
+int main(void) {
+ const char* path = TS_PATH;
+ CSession* session = ts_session_new(HOST, PORT, USER, PASS);
+ if (!session) {
+ fprintf(stderr, "[tree_example] ts_session_new returned NULL: %s\n", ts_get_last_error());
+ return 1;
+ }
+ if (ts_session_open(session) != TS_OK) {
+ fail("ts_session_open", session);
+ }
+
+ bool exists = false;
+ if (ts_session_check_timeseries_exists(session, path, &exists) != TS_OK) {
+ fail("ts_session_check_timeseries_exists", session);
+ }
+ if (exists) {
+ if (ts_session_delete_timeseries(session, path) != TS_OK) {
+ fail("ts_session_delete_timeseries (cleanup old)", session);
+ }
+ }
+ if (ts_session_create_timeseries(session, path, TS_TYPE_INT64, TS_ENCODING_RLE,
+ TS_COMPRESSION_SNAPPY) != TS_OK) {
+ fail("ts_session_create_timeseries", session);
+ }
+
+ const char* measurements[] = {"s0"};
+ const char* values[] = {"100"};
+ if (ts_session_insert_record_str(session, DEVICE, 1LL, 1, measurements, values) != TS_OK) {
+ fail("ts_session_insert_record_str", session);
+ }
+
+ CSessionDataSet* dataSet = NULL;
+ if (ts_session_execute_query(session, "select s0 from root.cdemo.d0", &dataSet) != TS_OK) {
+ fail("ts_session_execute_query", session);
+ }
+ if (!dataSet) {
+ fprintf(stderr, "[tree_example] dataSet is NULL\n");
+ ts_session_close(session);
+ ts_session_destroy(session);
+ return 1;
+ }
+ ts_dataset_set_fetch_size(dataSet, 1024);
+
+ int rows = 0;
+ while (ts_dataset_has_next(dataSet)) {
+ CRowRecord* record = ts_dataset_next(dataSet);
+ if (!record) {
+ break;
+ }
+ int64_t v = ts_row_record_get_int64(record, 0);
+ printf("[tree_example] row %d: s0 = %lld\n", rows, (long long)v);
+ ts_row_record_destroy(record);
+ rows++;
+ }
+ ts_dataset_destroy(dataSet);
+
+ printf("[tree_example] done, read %d row(s).\n", rows);
+
+ if (ts_session_delete_timeseries(session, path) != TS_OK) {
+ fail("ts_session_delete_timeseries", session);
+ }
+
+ ts_session_close(session);
+ ts_session_destroy(session);
+ return 0;
+}
diff --git a/iotdb-client/client-cpp/pom.xml b/iotdb-client/client-cpp/pom.xml
index c92fab10368..5ab79fd4e59 100644
--- a/iotdb-client/client-cpp/pom.xml
+++ b/iotdb-client/client-cpp/pom.xml
@@ -30,15 +30,38 @@
<packaging>pom</packaging>
<name>IoTDB: Client: Client for CPP</name>
<description>C++ client</description>
- <!-- TODO: The tests don't run, if distribution has not been built locally and fails without reasoning -->
+ <!--
+ The C++ client build is now driven entirely by the top-level
+ CMakeLists.txt in this directory. Maven only:
+ 1. Runs cmake configure + build (cmake-maven-plugin)
+ 2. Optionally starts/stops an IoTDB server (process-exec-maven-plugin)
+ 3. Packages the produced install tree (maven-assembly-plugin)
+
+ Everything else - thrift download, code generation, Boost/m4/flex/bison
+ bootstrap, OpenSSL discovery - lives in CMake modules under cmake/.
+ -->
<properties>
<catch2.url>https://github.com/catchorg/Catch2/releases/download/v2.13.7/catch.hpp</catch2.url>
<cmake.build.type>Release</cmake.build.type>
- <!-- Default value of cmake root -->
<cmake.root.dir>${project.build.directory}/dependency/cmake/</cmake.root.dir>
- <thrift.exec.absolute.path>${project.build.directory}/thrift/bin/${thrift.executable}</thrift.exec.absolute.path>
+ <cmake.source.dir>${project.basedir}</cmake.source.dir>
+ <cmake.project.dir>${project.build.directory}/build</cmake.project.dir>
+ <cmake.install.prefix>${project.build.directory}/install</cmake.install.prefix>
+ <iotdb.deps.dir>${project.basedir}/third-party</iotdb.deps.dir>
+ <iotdb.offline>OFF</iotdb.offline>
+ <with.ssl>OFF</with.ssl>
+ <iotdb.cxx11.abi/>
+ <!-- Switched to OFF by the .skipTests profile below. -->
+ <build.tests>ON</build.tests>
<maven.test.skip>${ctest.skip.tests}</maven.test.skip>
- <with.ssl>false</with.ssl>
+ <!-- Optional convenience: when a user still passes -Dboost.include.dir=...
+ (legacy CLI from the old build), feed it to CMake as BOOST_INCLUDEDIR. -->
+ <boost.include.dir/>
+ <iotdb.extra.cxx.flags/>
+ <!-- Override via -Dclient.cpp.package.classifier=... for per-toolchain release zips. -->
+ <client.cpp.package.classifier>${os.classifier}</client.cpp.package.classifier>
+ <client.cpp.package.name>iotdb-session-cpp-${project.version}-${client.cpp.package.classifier}</client.cpp.package.name>
+ <client.cpp.ci.build.id>${env.GITHUB_RUN_ID}</client.cpp.ci.build.id>
</properties>
<dependencies>
<dependency>
@@ -50,154 +73,22 @@
</dependencies>
<build>
<plugins>
- <!-- Build and do session integration test -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-cpp-files</id>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <phase>validate</phase>
- <configuration>
- <outputDirectory>${project.build.directory}/build/main/generated-sources-cpp</outputDirectory>
- <resources>
- <resource>
- <directory>${project.basedir}/src/main</directory>
- <includes>
- <include>**/*.h</include>
- <include>**/*.cpp</include>
- <include>**/*.cc</include>
- </includes>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>copy-test-resources</id>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <phase>validate</phase>
- <configuration>
- <outputDirectory>${project.build.directory}/build/test</outputDirectory>
- <resources>
- <resource>
- <directory>${project.basedir}/src/test</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>get-thrift</id>
- <goals>
- <goal>unpack</goal>
- </goals>
- <phase>generate-sources</phase>
- <configuration>
- <artifactItems>
- <artifactItem>
- <groupId>org.apache.iotdb.tools</groupId>
- <artifactId>iotdb-tools-thrift</artifactId>
- <version>${iotdb-tools-thrift.version}</version>
- <classifier>${os.classifier}</classifier>
- <type>zip</type>
- <overWrite>true</overWrite>
- <outputDirectory>${project.build.directory}/thrift</outputDirectory>
- </artifactItem>
- </artifactItems>
- </configuration>
- </execution>
- </executions>
- </plugin>
<plugin>
<groupId>com.googlecode.maven-download-plugin</groupId>
<artifactId>download-maven-plugin</artifactId>
<executions>
- <!-- Download the Catch2 header file. -->
- <!-- <execution>
+ <execution>
<id>get-catch2</id>
<goals>
<goal>wget</goal>
</goals>
- <phase>generate-test-resources</phase>
+ <phase>generate-resources</phase>
<configuration>
<url>${catch2.url}</url>
<unpack>false</unpack>
- <outputDirectory>${project.build.directory}/build/test/catch2</outputDirectory>
+ <outputDirectory>${project.build.directory}/test/catch2</outputDirectory>
<skip>${ctest.skip.tests}</skip>
</configuration>
- </execution> -->
- </executions>
- </plugin>
- <plugin>
- <groupId>com.coderplus.maven.plugins</groupId>
- <artifactId>copy-rename-maven-plugin</artifactId>
- <executions>
- <!-- TODO: Do this differently using the artifact downloader -->
- <execution>
- <id>copy-protocol-thrift-source</id>
- <goals>
- <goal>copy</goal>
- </goals>
- <configuration>
- <fileSets>
- <fileSet>
- <sourceFile>../../iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift</sourceFile>
- <destinationFile>${project.build.directory}/protocols/client.thrift</destinationFile>
- </fileSet>
- <fileSet>
- <sourceFile>../../iotdb-protocol/thrift-commons/src/main/thrift/common.thrift</sourceFile>
- <destinationFile>${project.build.directory}/protocols/common.thrift</destinationFile>
- </fileSet>
- </fileSets>
- </configuration>
- </execution>
- <!-- TODO: Do this differently using the maven-resources-plugin -->
- <execution>
- <!-- Copy source file and CmakeLists.txt into target directory -->
- <id>copy-cmakelist-file</id>
- <goals>
- <goal>copy</goal>
- </goals>
- <phase>compile</phase>
- <configuration>
- <fileSets>
- <fileSet>
- <sourceFile>${project.basedir}/src/main/CMakeLists.txt</sourceFile>
- <destinationFile>${project.build.directory}/build/main/CMakeLists.txt</destinationFile>
- </fileSet>
- </fileSets>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.thrift</groupId>
- <artifactId>thrift-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>generate-thrift-sources-cpp</id>
- <goals>
- <goal>compile</goal>
- </goals>
- <!-- Move from generate-sources to generate-resources to avoid double executions -->
- <phase>generate-resources</phase>
- <configuration>
- <generator>cpp:no_skeleton</generator>
- <thriftExecutable>${thrift.exec.absolute.path}</thriftExecutable>
- <thriftSourceRoot>${project.build.directory}/protocols</thriftSourceRoot>
- <outputDirectory>${project.build.directory}/build/main/generated-sources-cpp</outputDirectory>
- </configuration>
</execution>
</executions>
</plugin>
@@ -205,7 +96,7 @@
<groupId>io.github.cmake-maven-plugin</groupId>
<artifactId>cmake-maven-plugin</artifactId>
<executions>
- <!-- Uses a CMake generator to generate the build using the build tool of choice -->
+ <!-- Configure: top-level CMakeLists.txt of this module -->
<execution>
<id>cmake-generate</id>
<goals>
@@ -214,32 +105,25 @@
<phase>compile</phase>
<configuration>
<generator>${cmake.generator}</generator>
- <sourcePath>${project.build.directory}/build/main</sourcePath>
- <projectDirectory>${project.build.directory}/build/main</projectDirectory>
+ <sourcePath>${cmake.source.dir}</sourcePath>
+ <projectDirectory>${cmake.project.dir}</projectDirectory>
<options>
- <option>-DBOOST_INCLUDEDIR=${boost.include.dir}</option>
+ <option>-DCMAKE_BUILD_TYPE=${cmake.build.type}</option>
+ <option>-DCMAKE_INSTALL_PREFIX=${cmake.install.prefix}</option>
+ <option>-DBUILD_TESTING=${build.tests}</option>
<option>-DWITH_SSL=${with.ssl}</option>
- </options>
- </configuration>
- </execution>
- <!-- Generate Cmake build directory to compile testing program -->
- <execution>
- <id>cmake-generate-test</id>
- <goals>
- <goal>generate</goal>
- </goals>
- <phase>test-compile</phase>
- <configuration>
- <generator>${cmake.generator}</generator>
- <sourcePath>${project.build.directory}/build/test</sourcePath>
- <projectDirectory>${project.build.directory}/build/test</projectDirectory>
- <options>
+ <option>-DIOTDB_OFFLINE=${iotdb.offline}</option>
+ <option>-DIOTDB_DEPS_DIR=${iotdb.deps.dir}</option>
+ <option>-DIOTDB_USE_CXX11_ABI=${iotdb.cxx11.abi}</option>
<option>-DBOOST_INCLUDEDIR=${boost.include.dir}</option>
- <option>-DWITH_SSL=${with.ssl}</option>
+ <option>-DCMAKE_POLICY_DEFAULT_CMP0091=NEW</option>
+ <option>-DIOTDB_EXTRA_CXX_FLAGS=${iotdb.extra.cxx.flags}</option>
+ <option>-DIOTDB_SESSION_VERSION=${project.version}</option>
+ <option>-DCATCH2_INCLUDE_DIR=${project.build.directory}/test/catch2</option>
</options>
</configuration>
</execution>
- <!-- Actually executes the build -->
+ <!-- Build + install: drops headers/libs into target/install/{include,lib} -->
<execution>
<id>cmake-compile</id>
<goals>
@@ -248,24 +132,11 @@
<phase>compile</phase>
<configuration>
<config>${cmake.build.type}</config>
- <!-- The directory where the "generate" step generated the build configuration -->
- <projectDirectory>${project.build.directory}/build/main</projectDirectory>
+ <projectDirectory>${cmake.project.dir}</projectDirectory>
+ <target>install</target>
</configuration>
</execution>
- <!-- Actually executes the testing compilation -->
- <execution>
- <id>cmake-compile-test</id>
- <goals>
- <goal>compile</goal>
- </goals>
- <phase>test-compile</phase>
- <configuration>
- <config>${cmake.build.type}</config>
- <projectDirectory>${project.build.directory}/build/test</projectDirectory>
- </configuration>
- </execution>
- <!-- Run the integration test cases -->
- <!-- TODO: This execution doesn't seem to respect the "skipTests" config -->
+ <!-- Run ctest against the test binaries built in cmake-compile -->
<execution>
<id>cmake-run-test</id>
<goals>
@@ -274,37 +145,17 @@
<phase>integration-test</phase>
<configuration>
<config>${cmake.build.type}</config>
- <projectDirectory>${project.build.directory}/build/test</projectDirectory>
+ <projectDirectory>${cmake.project.dir}</projectDirectory>
<skipTests>${maven.test.skip}</skipTests>
</configuration>
</execution>
</executions>
</plugin>
- <!--Package all C++ header files and client library-->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>package-client-cpp</id>
- <goals>
- <goal>single</goal>
- </goals>
- <phase>package</phase>
- <configuration>
- <finalName>${project.artifactId}-${project.version}</finalName>
- <descriptors>
- <descriptor>src/assembly/client-cpp.xml</descriptor>
- </descriptors>
- </configuration>
- </execution>
- </executions>
- </plugin>
+ <!-- Start a local IoTDB server before integration-test, stop it after. -->
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<executions>
- <!-- Start a local IoTDB server to run integration test cases -->
<execution>
<id>start-iotdb</id>
<goals>
@@ -315,17 +166,13 @@
<skip>${ctest.skip.tests}</skip>
<name>iotdb-server</name>
<waitForInterrupt>false</waitForInterrupt>
- <!-- Maximum time in seconds to wait after launching IoTDB (JVM cold start on Windows can exceed 15s) -->
<waitAfterLaunch>45</waitAfterLaunch>
- <!-- Redirect IoTDB server log to /dev/null -->
- <processLogFile>${project.build.directory}/build/test/test.log</processLogFile>
+ <processLogFile>${cmake.project.dir}/test.log</processLogFile>
<arguments>
- <!-- TODO: This depends on distribution being build first and it being available in unpacked form ... unpacking the distribution locally will be the better option -->
<argument>${project.basedir}/../../distribution/target/apache-iotdb-${project.version}-all-bin/apache-iotdb-${project.version}-all-bin/sbin/${iotdb.start.script}</argument>
</arguments>
</configuration>
</execution>
- <!-- Stop the IoTDB server when integration test finishes -->
<execution>
<id>stop-iotdb</id>
<goals>
@@ -336,10 +183,8 @@
<skip>${ctest.skip.tests}</skip>
<name>iotdb-server</name>
<waitForInterrupt>false</waitForInterrupt>
- <!-- Maximum time in seconds to wait after launching IoTDB -->
<waitAfterLaunch>5</waitAfterLaunch>
- <!-- Redirect IoTDB server log to /dev/null -->
- <processLogFile>${project.build.directory}/build/test/test1.log</processLogFile>
+ <processLogFile>${cmake.project.dir}/stop.log</processLogFile>
<arguments>
<argument>${project.basedir}/../../distribution/target/apache-iotdb-${project.version}-all-bin/apache-iotdb-${project.version}-all-bin/sbin/${iotdb.stop.script}</argument>
</arguments>
@@ -347,6 +192,74 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>prepare-client-cpp-package-metadata</id>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <phase>prepare-package</phase>
+ <configuration>
+ <outputDirectory>${project.build.directory}/package-metadata</outputDirectory>
+ <resources>
+ <resource>
+ <directory>${project.basedir}/src/assembly/package-metadata</directory>
+ <filtering>true</filtering>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <!-- zip: iotdb-session-cpp-<version>-<classifier>.zip with a package root directory. -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>package-client-cpp</id>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <finalName>iotdb-session-cpp-${project.version}</finalName>
+ <descriptors>
+ <descriptor>src/assembly/client-cpp.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <!-- Create SHA512 checksum files for the release zip. -->
+ <plugin>
+ <groupId>net.nicoulaj.maven.plugins</groupId>
+ <artifactId>checksum-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>checksum-client-cpp-package</id>
+ <goals>
+ <goal>files</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <algorithms>
+ <algorithm>SHA-512</algorithm>
+ </algorithms>
+ <fileSets>
+ <fileSet>
+ <directory>${project.build.directory}</directory>
+ <includes>
+ <include>${client.cpp.package.name}.zip</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
<profiles>
@@ -363,6 +276,7 @@
<iotdb.start.script>start-standalone.sh</iotdb.start.script>
<iotdb.stop.script>stop-standalone.sh</iotdb.stop.script>
<os.suffix>linux</os.suffix>
+ <client.cpp.package.classifier>linux-x86_64-glibc2.28</client.cpp.package.classifier>
</properties>
</profile>
<profile>
@@ -378,6 +292,7 @@
<iotdb.start.script>start-standalone.sh</iotdb.start.script>
<iotdb.stop.script>stop-standalone.sh</iotdb.stop.script>
<os.suffix>linux</os.suffix>
+ <client.cpp.package.classifier>linux-aarch64-glibc2.28</client.cpp.package.classifier>
</properties>
</profile>
<profile>
@@ -392,6 +307,7 @@
<iotdb.start.script>start-standalone.sh</iotdb.start.script>
<iotdb.stop.script>stop-standalone.sh</iotdb.stop.script>
<os.suffix>mac</os.suffix>
+ <client.cpp.package.classifier>macos-x86_64</client.cpp.package.classifier>
</properties>
</profile>
<profile>
@@ -406,6 +322,7 @@
<iotdb.start.script>start-standalone.sh</iotdb.start.script>
<iotdb.stop.script>stop-standalone.sh</iotdb.stop.script>
<os.suffix>mac</os.suffix>
+ <client.cpp.package.classifier>macos-aarch64</client.cpp.package.classifier>
</properties>
</profile>
<profile>
@@ -419,14 +336,16 @@
<iotdb.start.script>windows/start-standalone.bat</iotdb.start.script>
<iotdb.stop.script>windows/stop-standalone.bat</iotdb.stop.script>
<os.suffix>win</os.suffix>
+ <client.cpp.package.classifier>windows-x86_64-msvc14.3</client.cpp.package.classifier>
</properties>
</profile>
+ <!-- Windows: default to x64 (VS2017 and older default to Win32 without -A x64). -->
<profile>
- <id>.skipTests</id>
+ <id>client-cpp-vs-x64</id>
<activation>
- <property>
- <name>skipTests</name>
- </property>
+ <os>
+ <family>windows</family>
+ </os>
</activation>
<build>
<plugins>
@@ -435,16 +354,34 @@
<artifactId>cmake-maven-plugin</artifactId>
<executions>
<execution>
- <id>cmake-compile-test</id>
- <phase>none</phase>
- <!-- This effectively skips the execution -->
+ <id>cmake-generate</id>
+ <configuration>
+ <options combine.children="append">
+ <option>-DCMAKE_GENERATOR_PLATFORM=x64</option>
+ </options>
+ </configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
- <!-- Spotless <clangFormat> needs Spotless 2.44+; root POM downgrades to 2.27.1 on JDK8 and cannot parse cpp config. Only register C++ rules when JDK 11+. -->
+ <profile>
+ <id>.skipTests</id>
+ <activation>
+ <property>
+ <name>skipTests</name>
+ </property>
+ </activation>
+ <properties>
+ <build.tests>OFF</build.tests>
+ </properties>
+ </profile>
+ <!--
+ Spotless <clangFormat> needs Spotless 2.44+; root POM downgrades to
+ 2.27.1 on JDK8 and cannot parse cpp config. Only register C++ rules
+ when JDK 11+.
+ -->
<profile>
<id>spotless-cpp</id>
<activation>
@@ -464,9 +401,12 @@
<include>src/**/*.c</include>
<include>src/**/*.cc</include>
<include>src/**/*.cpp</include>
+ <include>examples/**/*.c</include>
+ <include>examples/**/*.cc</include>
+ <include>examples/**/*.cpp</include>
</includes>
<excludes>
- <exclude>src/test/catch2/**</exclude>
+ <exclude>test/catch2/**</exclude>
</excludes>
<clangFormat>
<version>${clang.format.version}</version>
diff --git a/iotdb-client/client-cpp/src/assembly/client-cpp.xml b/iotdb-client/client-cpp/src/assembly/client-cpp.xml
index 729fdadde23..af7184f3fc4 100644
--- a/iotdb-client/client-cpp/src/assembly/client-cpp.xml
+++ b/iotdb-client/client-cpp/src/assembly/client-cpp.xml
@@ -17,51 +17,88 @@
specific language governing permissions and limitations
under the License.
-->
+<!--
+ The CMake build installs the SDK into ${cmake.install.prefix} = target/install.
+ Package layout:
+ iotdb-session-cpp-<version>-<classifier>.zip ->
+ iotdb-session-cpp-<version>-<classifier>/{include,lib,cmake,pkgconfig,examples,...}.
+-->
<assembly>
- <id>cpp-${os.classifier}</id>
+ <id>${client.cpp.package.classifier}</id>
<formats>
<format>zip</format>
<format>dir</format>
</formats>
- <includeBaseDirectory>false</includeBaseDirectory>
+ <includeBaseDirectory>true</includeBaseDirectory>
+ <baseDirectory>${client.cpp.package.name}</baseDirectory>
<fileSets>
<fileSet>
- <directory>${project.build.directory}/build/main/generated-sources-cpp</directory>
+ <directory>${project.basedir}/../..</directory>
<includes>
- <include>**/*.h</include>
+ <include>LICENSE</include>
+ <include>NOTICE</include>
</includes>
- <outputDirectory>include</outputDirectory>
+ <outputDirectory>${file.separator}</outputDirectory>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}</directory>
+ <includes>
+ <include>README.md</include>
+ <include>README_zh.md</include>
+ </includes>
+ <outputDirectory>${file.separator}</outputDirectory>
+ </fileSet>
+ <fileSet>
+ <directory>${project.build.directory}/package-metadata</directory>
+ <includes>
+ <include>third_party/DEPENDENCIES.md</include>
+ </includes>
+ <outputDirectory>${file.separator}</outputDirectory>
+ </fileSet>
+ <fileSet>
+ <directory>${project.build.directory}/install</directory>
+ <includes>
+ <include>VERSION</include>
+ <include>BUILD-INFO.txt</include>
+ </includes>
+ <outputDirectory>${file.separator}</outputDirectory>
</fileSet>
<fileSet>
- <directory>${project.build.directory}/thrift/include</directory>
+ <directory>${project.build.directory}/install/include</directory>
<includes>
<include>**</include>
</includes>
<outputDirectory>include</outputDirectory>
</fileSet>
<fileSet>
- <directory>${project.build.directory}/thrift/lib</directory>
+ <directory>${project.build.directory}/install/lib</directory>
<includes>
<include>**</include>
</includes>
<outputDirectory>lib</outputDirectory>
</fileSet>
<fileSet>
- <directory>${project.build.directory}/build/main</directory>
+ <directory>${project.build.directory}/install/cmake</directory>
<includes>
- <include>*.so</include>
- <include>*.dylib</include>
- <include>**/*.dll</include>
- <include>**/*.lib</include>
+ <include>**</include>
</includes>
- <outputDirectory>lib</outputDirectory>
+ <outputDirectory>cmake</outputDirectory>
</fileSet>
<fileSet>
- <directory>${project.basedir}/../compile-tools/thrift/target/build/lib/Release</directory>
+ <directory>${project.build.directory}/install/pkgconfig</directory>
<includes>
- <include>**/*.lib</include>
+ <include>**</include>
</includes>
- <outputDirectory>lib</outputDirectory>
+ <outputDirectory>pkgconfig</outputDirectory>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}/examples</directory>
+ <includes>
+ <include>CMakeLists.txt</include>
+ <include>*.c</include>
+ <include>*.cpp</include>
+ </includes>
+ <outputDirectory>examples</outputDirectory>
</fileSet>
</fileSets>
</assembly>
diff --git a/example/client-cpp-example/README.md b/iotdb-client/client-cpp/src/assembly/package-metadata/third_party/DEPENDENCIES.md
similarity index 55%
rename from example/client-cpp-example/README.md
rename to iotdb-client/client-cpp/src/assembly/package-metadata/third_party/DEPENDENCIES.md
index f36a084f888..e921c7eb948 100644
--- a/example/client-cpp-example/README.md
+++ b/iotdb-client/client-cpp/src/assembly/package-metadata/third_party/DEPENDENCIES.md
@@ -18,31 +18,17 @@
under the License.
-->
-
-# How to get a complete CPP client demo project
-
-## Get a project
-
-Using maven to build this example project:
-
-* cd the root path of the whole project
-* run `mvn clean package -DskipTests -P with-cpp -pl example/client-cpp-example -am`
-* cd example/client-cpp-example/target
-
-You can find some files to form a complete project:
-```
-+-- client
-| +-- include
-| +-- Session.h
-| +-- IClientRPCService.h
-| +-- rpc_types.h
-| +-- rpc_constants.h
-| +-- thrift
-| +-- thrift_headers...
-| +-- lib
-| +-- libiotdb_session.dylib
-+-- CMakeLists.txt
-+-- SessionExample.cpp
-```
-
-
+# Third-party Dependencies
+
+The release library is built with the following third-party components. Some
+components are linked into the produced IoTDB C++ session library; this file is
+included for provenance.
+
+| Component | Version | License |
+| --- | --- | --- |
+| Apache Thrift | 0.21.0 | Apache License 2.0 |
+| Boost | 1.60.0 on Linux/Windows, 1.84.0 on macOS by default | Boost Software License 1.0 |
+| OpenSSL | 3.5.0 when `WITH_SSL=ON` | Apache License 2.0 |
+| GNU m4 | 1.4.19 on Linux build bootstrap | GPL-3.0-or-later |
+| GNU flex | 2.6.4 on Linux build bootstrap | BSD-style flex license |
+| GNU bison | 3.8 on Linux build bootstrap | GPL-3.0-or-later |
diff --git a/iotdb-client/client-cpp/src/main/AbstractSessionBuilder.h b/iotdb-client/client-cpp/src/include/AbstractSessionBuilder.h
similarity index 83%
rename from iotdb-client/client-cpp/src/main/AbstractSessionBuilder.h
rename to iotdb-client/client-cpp/src/include/AbstractSessionBuilder.h
index 9f59504d388..3735dfa227d 100644
--- a/iotdb-client/client-cpp/src/main/AbstractSessionBuilder.h
+++ b/iotdb-client/client-cpp/src/include/AbstractSessionBuilder.h
@@ -22,16 +22,18 @@
#include <string>
+#include "SessionConfig.h"
+
class AbstractSessionBuilder {
public:
static constexpr const char* DEFAULT_HOST = "localhost";
static constexpr int DEFAULT_RPC_PORT = 6667;
static constexpr const char* DEFAULT_USERNAME = "root";
static constexpr const char* DEFAULT_PASSWORD = "root";
- static constexpr int DEFAULT_FETCH_SIZE = 10000;
- static constexpr int DEFAULT_CONNECT_TIMEOUT_MS = 3 * 1000;
- static constexpr int DEFAULT_MAX_RETRIES = 3;
- static constexpr int DEFAULT_RETRY_DELAY_MS = 500;
+ static constexpr int DEFAULT_FETCH_SIZE = iotdb::session::DEFAULT_FETCH_SIZE;
+ static constexpr int DEFAULT_CONNECT_TIMEOUT_MS = iotdb::session::DEFAULT_CONNECT_TIMEOUT_MS;
+ static constexpr int DEFAULT_MAX_RETRIES = iotdb::session::DEFAULT_MAX_RETRIES;
+ static constexpr int DEFAULT_RETRY_DELAY_MS = iotdb::session::DEFAULT_RETRY_DELAY_MS;
static constexpr const char* DEFAULT_SQL_DIALECT = "tree";
static constexpr bool DEFAULT_ENABLE_AUTO_FETCH = true;
static constexpr bool DEFAULT_ENABLE_REDIRECTIONS = true;
diff --git a/iotdb-client/client-cpp/src/main/Column.h b/iotdb-client/client-cpp/src/include/Column.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/Column.h
rename to iotdb-client/client-cpp/src/include/Column.h
diff --git a/iotdb-client/client-cpp/src/main/ColumnDecoder.h b/iotdb-client/client-cpp/src/include/ColumnDecoder.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/ColumnDecoder.h
rename to iotdb-client/client-cpp/src/include/ColumnDecoder.h
diff --git a/iotdb-client/client-cpp/src/main/Common.h b/iotdb-client/client-cpp/src/include/Common.h
similarity index 74%
rename from iotdb-client/client-cpp/src/main/Common.h
rename to iotdb-client/client-cpp/src/include/Common.h
index 74e3f622d10..49dca0bca4b 100644
--- a/iotdb-client/client-cpp/src/main/Common.h
+++ b/iotdb-client/client-cpp/src/include/Common.h
@@ -19,40 +19,21 @@
#ifndef IOTDB_COMMON_H
#define IOTDB_COMMON_H
+#include <cstdint>
+#include <ctime>
+#include <exception>
+#include <map>
#include <string>
#include <vector>
-#include <exception>
-
-#include <thrift/protocol/TBinaryProtocol.h>
-#include <thrift/protocol/TCompactProtocol.h>
-#include <thrift/transport/TSocket.h>
-#include <thrift/transport/TTransportException.h>
-#include <thrift/transport/TBufferTransports.h>
-#include <boost/date_time/gregorian/gregorian.hpp>
-#include <cstdint>
-#include <boost/optional/optional.hpp>
-#include "client_types.h"
-#include "common_types.h"
+#include "Date.h"
+#include "Endpoint.h"
+#include "Export.h"
+#include "Optional.h"
+#include "Status.h"
using namespace std;
-using ::apache::thrift::TException;
-using ::apache::thrift::protocol::TBinaryProtocol;
-using ::apache::thrift::protocol::TCompactProtocol;
-using ::apache::thrift::transport::TBufferedTransport;
-using ::apache::thrift::transport::TFramedTransport;
-using ::apache::thrift::transport::TSocket;
-using ::apache::thrift::transport::TTransport;
-using ::apache::thrift::transport::TTransportException;
-
-using namespace std;
-
-constexpr int32_t EMPTY_DATE_INT = 10000101;
-
-int32_t parseDateExpressionToInt(const boost::gregorian::date& date);
-boost::gregorian::date parseIntToDate(int32_t dateInt);
-
std::string getTimePrecision(int32_t timeFactor);
std::string formatDatetime(const std::string& format, const std::string& precision,
@@ -121,13 +102,11 @@ namespace TSStatusCode {
enum TSStatusCode {
SUCCESS_STATUS = 200,
- // System level
INCOMPATIBLE_VERSION = 201,
CONFIGURATION_ERROR = 202,
START_UP_ERROR = 203,
SHUT_DOWN_ERROR = 204,
- // General Error
UNSUPPORTED_OPERATION = 300,
EXECUTE_STATEMENT_ERROR = 301,
MULTIPLE_ERROR = 302,
@@ -135,10 +114,8 @@ enum TSStatusCode {
OVERLAP_WITH_EXISTING_TASK = 304,
INTERNAL_SERVER_ERROR = 305,
- // Client,
REDIRECTION_RECOMMEND = 400,
- // Schema Engine
DATABASE_NOT_EXIST = 500,
DATABASE_ALREADY_EXISTS = 501,
SERIES_OVERFLOW = 502,
@@ -165,12 +142,10 @@ enum TSStatusCode {
PBTREE_FILE_REDO_LOG_BROKEN = 523,
TEMPLATE_NOT_ACTIVATED = 524,
- // Storage Engine
SYSTEM_READ_ONLY = 600,
STORAGE_ENGINE_ERROR = 601,
STORAGE_ENGINE_NOT_READY = 602,
- // Query Engine
PLAN_FAILED_NETWORK_PARTITION = 721
};
}
@@ -178,13 +153,13 @@ enum TSStatusCode {
class Field {
public:
TSDataType::TSDataType dataType = TSDataType::UNKNOWN;
- boost::optional<bool> boolV;
- boost::optional<int> intV;
- boost::optional<boost::gregorian::date> dateV;
- boost::optional<int64_t> longV;
- boost::optional<float> floatV;
- boost::optional<double> doubleV;
- boost::optional<std::string> stringV;
+ Optional<bool> boolV;
+ Optional<int> intV;
+ Optional<IoTDBDate> dateV;
+ Optional<int64_t> longV;
+ Optional<float> floatV;
+ Optional<double> doubleV;
+ Optional<std::string> stringV;
explicit Field(TSDataType::TSDataType a) {
dataType = a;
@@ -192,7 +167,6 @@ public:
Field() = default;
- /** True if this field is SQL NULL (optional for the active dataType is unset). Unknown types are treated as null. */
bool isNull() const {
switch (dataType) {
case TSDataType::BOOLEAN:
@@ -229,7 +203,7 @@ public:
void clear();
bool hasRemaining();
int getInt();
- boost::gregorian::date getDate();
+ IoTDBDate getDate();
int64_t getInt64();
float getFloat();
double getDouble();
@@ -238,7 +212,7 @@ public:
std::string getString();
void putInt(int ins);
- void putDate(boost::gregorian::date date);
+ void putDate(IoTDBDate date);
void putInt64(int64_t ins);
void putFloat(float ins);
void putDouble(double ins);
@@ -258,7 +232,7 @@ private:
private:
bool isBigEndian{};
- char numericBuf[8]{}; //only be used by int, long, float, double etc.
+ char numericBuf[8]{};
};
class BitMap {
@@ -347,10 +321,10 @@ public:
explicit ExecutionException(const std::string& m) : IoTDBException(m) {}
- explicit ExecutionException(const std::string& m, const TSStatus& tsStatus)
+ explicit ExecutionException(const std::string& m, const Status& tsStatus)
: IoTDBException(m), status(tsStatus) {}
- TSStatus status;
+ Status status;
};
class BatchExecutionException : public IoTDBException {
@@ -361,13 +335,13 @@ public:
explicit BatchExecutionException(const std::string& m) : IoTDBException(m) {}
- explicit BatchExecutionException(const std::vector<TSStatus>& statusList)
+ explicit BatchExecutionException(const std::vector<Status>& statusList)
: statusList(statusList) {}
- BatchExecutionException(const std::string& m, const std::vector<TSStatus>& statusList)
+ BatchExecutionException(const std::string& m, const std::vector<Status>& statusList)
: IoTDBException(m), statusList(statusList) {}
- std::vector<TSStatus> statusList;
+ std::vector<Status> statusList;
};
class RedirectException : public IoTDBException {
@@ -378,18 +352,18 @@ public:
explicit RedirectException(const std::string& m) : IoTDBException(m) {}
- RedirectException(const std::string& m, const TEndPoint& endPoint)
+ RedirectException(const std::string& m, const Endpoint& endPoint)
: IoTDBException(m), endPoint(endPoint) {}
- RedirectException(const std::string& m, const map<string, TEndPoint>& deviceEndPointMap)
+ RedirectException(const std::string& m, const map<string, Endpoint>& deviceEndPointMap)
: IoTDBException(m), deviceEndPointMap(deviceEndPointMap) {}
- RedirectException(const std::string& m, const vector<TEndPoint>& endPointList)
+ RedirectException(const std::string& m, const vector<Endpoint>& endPointList)
: IoTDBException(m), endPointList(endPointList) {}
- TEndPoint endPoint;
- map<string, TEndPoint> deviceEndPointMap;
- vector<TEndPoint> endPointList;
+ Endpoint endPoint;
+ map<string, Endpoint> deviceEndPointMap;
+ vector<Endpoint> endPointList;
};
class UnSupportedDataTypeException : public IoTDBException {
@@ -422,7 +396,7 @@ public:
enum LogLevelType { LEVEL_DEBUG = 0, LEVEL_INFO, LEVEL_WARN, LEVEL_ERROR };
-extern LogLevelType LOG_LEVEL;
+extern IOTDB_SESSION_API LogLevelType LOG_LEVEL;
#define log_debug(fmt, ...) \
do { \
@@ -453,62 +427,4 @@ extern LogLevelType LOG_LEVEL;
} \
} while (0)
-class RpcUtils {
-public:
- std::shared_ptr<TSStatus> SUCCESS_STATUS;
-
- RpcUtils() {
- SUCCESS_STATUS = std::make_shared<TSStatus>();
- SUCCESS_STATUS->__set_code(TSStatusCode::SUCCESS_STATUS);
- }
-
- static void verifySuccess(const TSStatus& status);
-
- static void verifySuccessWithRedirection(const TSStatus& status);
-
- static void verifySuccessWithRedirectionForMultiDevices(const TSStatus& status,
- vector<string> devices);
-
- static void verifySuccess(const std::vector<TSStatus>& statuses);
-
- static TSStatus getStatus(TSStatusCode::TSStatusCode tsStatusCode);
-
- static TSStatus getStatus(int code, const std::string& message);
-
- static std::shared_ptr<TSExecuteStatementResp>
- getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode);
-
- static std::shared_ptr<TSExecuteStatementResp>
- getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode, const std::string& message);
-
- static std::shared_ptr<TSExecuteStatementResp> getTSExecuteStatementResp(const TSStatus& status);
-
- static std::shared_ptr<TSFetchResultsResp>
- getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode);
-
- static std::shared_ptr<TSFetchResultsResp>
- getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode, const std::string& appendMessage);
-
- static std::shared_ptr<TSFetchResultsResp> getTSFetchResultsResp(const TSStatus& status);
-};
-
-class UrlUtils {
-private:
- static const std::string PORT_SEPARATOR;
- static const std::string ABB_COLON;
-
- UrlUtils() = delete;
- ~UrlUtils() = delete;
-
-public:
- /**
- * Parse TEndPoint from a given TEndPointUrl
- * example:[D80:0000:0000:0000:ABAA:0000:00C2:0002]:22227
- *
- * @param endPointUrl ip:port
- * @return TEndPoint with default values if parse error
- */
- static TEndPoint parseTEndPointIpv4AndIpv6Url(const std::string& endPointUrl);
-};
-
#endif
diff --git a/iotdb-client/client-cpp/src/include/Date.h b/iotdb-client/client-cpp/src/include/Date.h
new file mode 100644
index 00000000000..e2fa114b890
--- /dev/null
+++ b/iotdb-client/client-cpp/src/include/Date.h
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef IOTDB_DATE_H
+#define IOTDB_DATE_H
+
+#include <cstdint>
+#include <string>
+
+constexpr int32_t EMPTY_DATE_INT = 10000101;
+
+class IoTDBDate {
+public:
+ IoTDBDate() : valid_(false), year_(0), month_(0), day_(0) {}
+
+ IoTDBDate(int year, int month, int day) : valid_(true), year_(year), month_(month), day_(day) {}
+
+ static IoTDBDate notADate() {
+ return IoTDBDate();
+ }
+
+ bool is_not_a_date() const {
+ return !valid_;
+ }
+
+ int year() const {
+ return year_;
+ }
+
+ int month() const {
+ return month_;
+ }
+
+ int day() const {
+ return day_;
+ }
+
+ std::string toIsoExtendedString() const;
+
+ friend bool operator==(const IoTDBDate& lhs, const IoTDBDate& rhs) {
+ return lhs.valid_ == rhs.valid_ && lhs.year_ == rhs.year_ && lhs.month_ == rhs.month_ &&
+ lhs.day_ == rhs.day_;
+ }
+
+ friend bool operator!=(const IoTDBDate& lhs, const IoTDBDate& rhs) {
+ return !(lhs == rhs);
+ }
+
+private:
+ bool valid_;
+ int year_;
+ int month_;
+ int day_;
+};
+
+int32_t parseDateExpressionToInt(const IoTDBDate& date);
+IoTDBDate parseIntToDate(int32_t dateInt);
+
+#endif
diff --git a/iotdb-client/client-cpp/src/main/DeviceID.h b/iotdb-client/client-cpp/src/include/DeviceID.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/DeviceID.h
rename to iotdb-client/client-cpp/src/include/DeviceID.h
diff --git a/iotdb-client/client-cpp/src/main/TableSession.h b/iotdb-client/client-cpp/src/include/Endpoint.h
similarity index 51%
copy from iotdb-client/client-cpp/src/main/TableSession.h
copy to iotdb-client/client-cpp/src/include/Endpoint.h
index d1eecfeeaba..187e939c0d3 100644
--- a/iotdb-client/client-cpp/src/main/TableSession.h
+++ b/iotdb-client/client-cpp/src/include/Endpoint.h
@@ -1,4 +1,4 @@
-/*
+/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -16,31 +16,28 @@
* specific language governing permissions and limitations
* under the License.
*/
+#ifndef IOTDB_ENDPOINT_H
+#define IOTDB_ENDPOINT_H
-// This file is a translation of the Java file iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java
+#include <cstdint>
+#include <functional>
+#include <string>
-#ifndef IOTDB_TABLESESSION_H
-#define IOTDB_TABLESESSION_H
-
-#include "Session.h"
-
-class TableSession {
-private:
- std::shared_ptr<Session> session_;
- string getDatabase();
+struct Endpoint {
+ std::string host;
+ int32_t port = 0;
+};
-public:
- TableSession(std::shared_ptr<Session> session) {
- this->session_ = session;
+struct EndpointHash {
+ size_t operator()(const Endpoint& endpoint) const {
+ return std::hash<std::string>()(endpoint.host) ^ std::hash<int>()(endpoint.port);
}
- ~TableSession() {}
+};
- void insert(Tablet& tablet, bool sorted = false);
- void executeNonQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql, int64_t timeoutInMs);
- void open(bool enableRPCCompression = false);
- void close();
+struct EndpointEqual {
+ bool operator()(const Endpoint& lhs, const Endpoint& rhs) const {
+ return lhs.host == rhs.host && lhs.port == rhs.port;
+ }
};
-#endif // IOTDB_TABLESESSION_H
\ No newline at end of file
+#endif
diff --git a/iotdb-client/client-cpp/src/main/TableSession.h b/iotdb-client/client-cpp/src/include/Export.h
similarity index 50%
copy from iotdb-client/client-cpp/src/main/TableSession.h
copy to iotdb-client/client-cpp/src/include/Export.h
index d1eecfeeaba..71262d0cffb 100644
--- a/iotdb-client/client-cpp/src/main/TableSession.h
+++ b/iotdb-client/client-cpp/src/include/Export.h
@@ -1,4 +1,4 @@
-/*
+/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -16,31 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
+#ifndef IOTDB_EXPORT_H
+#define IOTDB_EXPORT_H
-// This file is a translation of the Java file iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java
+#if defined(_WIN32) && defined(IOTDB_BUILDING_SHARED)
+#define IOTDB_SESSION_API __declspec(dllexport)
+#elif defined(_WIN32)
+#define IOTDB_SESSION_API __declspec(dllimport)
+#else
+#define IOTDB_SESSION_API
+#endif
-#ifndef IOTDB_TABLESESSION_H
-#define IOTDB_TABLESESSION_H
-
-#include "Session.h"
-
-class TableSession {
-private:
- std::shared_ptr<Session> session_;
- string getDatabase();
-
-public:
- TableSession(std::shared_ptr<Session> session) {
- this->session_ = session;
- }
- ~TableSession() {}
-
- void insert(Tablet& tablet, bool sorted = false);
- void executeNonQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql, int64_t timeoutInMs);
- void open(bool enableRPCCompression = false);
- void close();
-};
-
-#endif // IOTDB_TABLESESSION_H
\ No newline at end of file
+#endif // IOTDB_EXPORT_H
diff --git a/iotdb-client/client-cpp/src/include/Optional.h b/iotdb-client/client-cpp/src/include/Optional.h
new file mode 100644
index 00000000000..07092859c22
--- /dev/null
+++ b/iotdb-client/client-cpp/src/include/Optional.h
@@ -0,0 +1,77 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef IOTDB_OPTIONAL_H
+#define IOTDB_OPTIONAL_H
+
+#include <utility>
+
+template <typename T> class Optional {
+public:
+ Optional() : hasValue_(false) {}
+
+ Optional(const T& value) : hasValue_(true), value_(value) {}
+
+ Optional(T&& value) : hasValue_(true), value_(std::move(value)) {}
+
+ static Optional<T> of(const T& value) {
+ return Optional<T>(value);
+ }
+
+ static Optional<T> of(T&& value) {
+ return Optional<T>(std::move(value));
+ }
+
+ static Optional<T> none() {
+ return Optional<T>();
+ }
+
+ bool is_initialized() const {
+ return hasValue_;
+ }
+
+ bool has_value() const {
+ return hasValue_;
+ }
+
+ const T& value() const {
+ return value_;
+ }
+
+ T& value() {
+ return value_;
+ }
+
+ const T& get() const {
+ return value_;
+ }
+
+ T& get() {
+ return value_;
+ }
+
+ explicit operator bool() const {
+ return hasValue_;
+ }
+
+private:
+ bool hasValue_;
+ T value_{};
+};
+
+#endif
diff --git a/iotdb-client/client-cpp/src/main/Session.h b/iotdb-client/client-cpp/src/include/Session.h
similarity index 74%
rename from iotdb-client/client-cpp/src/main/Session.h
rename to iotdb-client/client-cpp/src/include/Session.h
index 58bb0a7d300..bd9d77f3bba 100644
--- a/iotdb-client/client-cpp/src/main/Session.h
+++ b/iotdb-client/client-cpp/src/include/Session.h
@@ -33,19 +33,11 @@
#include <cstdlib>
#include <cstdio>
#include <future>
-#include <boost/date_time/gregorian/gregorian.hpp>
-#include <thrift/protocol/TBinaryProtocol.h>
-#include <thrift/protocol/TCompactProtocol.h>
-#include <thrift/transport/TSocket.h>
-#include <thrift/transport/TTransportException.h>
-#include <thrift/transport/TBufferTransports.h>
-#include "IClientRPCService.h"
-#include "NodesSupplier.h"
#include "AbstractSessionBuilder.h"
-#include "SessionConnection.h"
-#include "SessionDataSet.h"
-#include "DeviceID.h"
#include "Common.h"
+#include "Date.h"
+#include "DeviceID.h"
+#include "SessionDataSet.h"
//== For compatible with Windows OS ==
#ifndef LONG_LONG_MIN
@@ -54,15 +46,6 @@
using namespace std;
-using ::apache::thrift::TException;
-using ::apache::thrift::protocol::TBinaryProtocol;
-using ::apache::thrift::protocol::TCompactProtocol;
-using ::apache::thrift::transport::TBufferedTransport;
-using ::apache::thrift::transport::TFramedTransport;
-using ::apache::thrift::transport::TSocket;
-using ::apache::thrift::transport::TTransport;
-using ::apache::thrift::transport::TTransportException;
-
template <typename T, typename Target> void safe_cast(const T& value, Target& target) {
/*
Target Allowed Source Types
@@ -284,8 +267,7 @@ public:
break;
}
case TSDataType::DATE: {
- safe_cast<T, boost::gregorian::date>(value,
- ((boost::gregorian::date*)values[schemaId])[rowIndex]);
+ safe_cast<T, IoTDBDate>(value, ((IoTDBDate*)values[schemaId])[rowIndex]);
break;
}
case TSDataType::TIMESTAMP:
@@ -393,7 +375,7 @@ public:
case TSDataType::INT32:
return &(reinterpret_cast<int32_t*>(values[schemaId])[rowIndex]);
case TSDataType::DATE:
- return &(reinterpret_cast<boost::gregorian::date*>(values[schemaId])[rowIndex]);
+ return &(reinterpret_cast<IoTDBDate*>(values[schemaId])[rowIndex]);
case TSDataType::TIMESTAMP:
case TSDataType::INT64:
return &(reinterpret_cast<int64_t*>(values[schemaId])[rowIndex]);
@@ -576,214 +558,35 @@ private:
bool is_aligned_;
};
+class SessionConnection;
+class TableSession;
+
class Session {
-private:
- std::string host_;
- int rpcPort_;
- bool useSSL_ = false;
- std::string trustCertFilePath_;
- std::vector<string> nodeUrls_;
- std::string username_;
- std::string password_;
- const TSProtocolVersion::type protocolVersion_ = TSProtocolVersion::IOTDB_SERVICE_PROTOCOL_V3;
- bool isClosed_ = true;
- std::string zoneId_;
- int fetchSize_;
- const static int DEFAULT_FETCH_SIZE = 10000;
- const static int DEFAULT_TIMEOUT_MS = 0;
- int connectTimeoutMs_;
- Version::Version version;
- std::string sqlDialect_ = "tree"; // default sql dialect
- std::string database_;
- bool enableAutoFetch_ = true;
- bool enableRedirection_ = true;
- std::shared_ptr<INodesSupplier> nodesSupplier_;
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
friend class SessionConnection;
friend class TableSession;
- std::shared_ptr<SessionConnection> defaultSessionConnection_;
-
- TEndPoint defaultEndPoint_;
-
- struct TEndPointHash {
- size_t operator()(const TEndPoint& endpoint) const {
- return std::hash<std::string>()(endpoint.ip) ^ std::hash<int>()(endpoint.port);
- }
- };
-
- struct TEndPointEqual {
- bool operator()(const TEndPoint& lhs, const TEndPoint& rhs) const {
- return lhs.ip == rhs.ip && lhs.port == rhs.port;
- }
- };
-
- using EndPointSessionMap =
- std::unordered_map<TEndPoint, shared_ptr<SessionConnection>, TEndPointHash, TEndPointEqual>;
- EndPointSessionMap endPointToSessionConnection;
- std::unordered_map<std::string, TEndPoint> deviceIdToEndpoint;
- std::unordered_map<std::shared_ptr<storage::IDeviceID>, TEndPoint> tableModelDeviceIdToEndpoint;
-
-private:
- void removeBrokenSessionConnection(shared_ptr<SessionConnection> sessionConnection);
-
- static bool checkSorted(const Tablet& tablet);
-
- static bool checkSorted(const std::vector<int64_t>& times);
-
- static void sortTablet(Tablet& tablet);
-
- static void sortIndexByTimestamp(int* index, std::vector<int64_t>& timestamps, int length);
-
- void appendValues(std::string& buffer, const char* value, int size);
-
- void putValuesIntoBuffer(const std::vector<TSDataType::TSDataType>& types,
- const std::vector<char*>& values, std::string& buf);
-
- int8_t getDataTypeNumber(TSDataType::TSDataType type);
-
- struct TsCompare {
- std::vector<int64_t>& timestamps;
-
- explicit TsCompare(std::vector<int64_t>& inTimestamps) : timestamps(inTimestamps){};
-
- bool operator()(int i, int j) {
- return (timestamps[i] < timestamps[j]);
- };
- };
-
- std::string getVersionString(Version::Version version);
-
- void initZoneId();
-
- void initNodesSupplier(const std::vector<std::string>& nodeUrls = std::vector<std::string>());
-
- void initDefaultSessionConnection();
-
- template <typename T, typename InsertConsumer>
- void insertByGroup(std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
- InsertConsumer insertConsumer);
-
- template <typename T, typename InsertConsumer>
- void insertOnce(std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
- InsertConsumer insertConsumer);
-
- void insertStringRecordsWithLeaderCache(vector<string> deviceIds, vector<int64_t> times,
- vector<vector<string>> measurementsList,
- vector<vector<string>> valuesList, bool isAligned);
-
- void insertRecordsWithLeaderCache(vector<string> deviceIds, vector<int64_t> times,
- vector<vector<string>> measurementsList,
- const vector<vector<TSDataType::TSDataType>>& typesList,
- vector<vector<char*>> valuesList, bool isAligned);
-
- void insertTabletsWithLeaderCache(unordered_map<string, Tablet*> tablets, bool sorted,
- bool isAligned);
-
- shared_ptr<SessionConnection> getQuerySessionConnection();
-
- shared_ptr<SessionConnection> getSessionConnection(std::string deviceId);
-
- shared_ptr<SessionConnection> getSessionConnection(std::shared_ptr<storage::IDeviceID> deviceId);
-
- void handleQueryRedirection(TEndPoint endPoint);
-
- void handleRedirection(const std::string& deviceId, TEndPoint endPoint);
-
- void handleRedirection(const std::shared_ptr<storage::IDeviceID>& deviceId, TEndPoint endPoint);
-
- void setSqlDialect(const std::string& dialect) {
- this->sqlDialect_ = dialect;
- }
-
- void setDatabase(const std::string& database) {
- this->database_ = database;
- }
-
- string getDatabase() {
- return database_;
- }
-
- void changeDatabase(string database) {
- this->database_ = database;
- }
public:
- Session(const std::string& host, int rpcPort)
- : username_("root"), password_("root"), version(Version::V_1_0) {
- this->host_ = host;
- this->rpcPort_ = rpcPort;
- initZoneId();
- initNodesSupplier();
- }
-
- Session(const std::vector<string>& nodeUrls, const std::string& username,
- const std::string& password)
- : nodeUrls_(nodeUrls), username_(username), password_(password), version(Version::V_1_0) {
- initZoneId();
- initNodesSupplier(this->nodeUrls_);
- }
-
+ Session(const std::string& host, int rpcPort);
+ Session(const std::vector<std::string>& nodeUrls, const std::string& username,
+ const std::string& password);
Session(const std::string& host, int rpcPort, const std::string& username,
- const std::string& password)
- : fetchSize_(DEFAULT_FETCH_SIZE) {
- this->host_ = host;
- this->rpcPort_ = rpcPort;
- this->username_ = username;
- this->password_ = password;
- this->version = Version::V_1_0;
- initZoneId();
- initNodesSupplier();
- }
-
+ const std::string& password);
Session(const std::string& host, int rpcPort, const std::string& username,
const std::string& password, const std::string& zoneId,
- int fetchSize = DEFAULT_FETCH_SIZE) {
- this->host_ = host;
- this->rpcPort_ = rpcPort;
- this->username_ = username;
- this->password_ = password;
- this->zoneId_ = zoneId;
- this->fetchSize_ = fetchSize;
- this->version = Version::V_1_0;
- initZoneId();
- initNodesSupplier();
- }
-
+ int fetchSize = AbstractSessionBuilder::DEFAULT_FETCH_SIZE);
Session(const std::string& host, const std::string& rpcPort, const std::string& username = "user",
const std::string& password = "password", const std::string& zoneId = "",
- int fetchSize = DEFAULT_FETCH_SIZE) {
- this->host_ = host;
- this->rpcPort_ = stoi(rpcPort);
- this->username_ = username;
- this->password_ = password;
- this->zoneId_ = zoneId;
- this->fetchSize_ = fetchSize;
- this->version = Version::V_1_0;
- initZoneId();
- initNodesSupplier();
- }
-
- Session(AbstractSessionBuilder* builder) {
- this->host_ = builder->host;
- this->rpcPort_ = builder->rpcPort;
- this->username_ = builder->username;
- this->password_ = builder->password;
- this->zoneId_ = builder->zoneId;
- this->fetchSize_ = builder->fetchSize;
- this->version = Version::V_1_0;
- this->sqlDialect_ = builder->sqlDialect;
- this->database_ = builder->database;
- this->enableAutoFetch_ = builder->enableAutoFetch;
- this->enableRedirection_ = builder->enableRedirections;
- this->connectTimeoutMs_ = builder->connectTimeoutMs;
- this->nodeUrls_ = builder->nodeUrls;
- this->useSSL_ = builder->useSSL;
- this->trustCertFilePath_ = builder->trustCertFilePath;
- initZoneId();
- initNodesSupplier(this->nodeUrls_);
- }
-
+ int fetchSize = AbstractSessionBuilder::DEFAULT_FETCH_SIZE);
+ Session(AbstractSessionBuilder* builder);
~Session();
+ void setSqlDialect(const std::string& dialect);
+ void setDatabase(const std::string& database);
+ std::string getDatabase();
+ void changeDatabase(const std::string& database);
+
void open();
void open(bool enableRPCCompression);
@@ -860,20 +663,8 @@ public:
void insertRelationalTablet(Tablet& tablet);
- void insertRelationalTabletOnce(
- const std::unordered_map<std::shared_ptr<SessionConnection>, Tablet>& relationalTabletGroup,
- bool sorted);
-
- void insertRelationalTabletByGroup(
- const std::unordered_map<std::shared_ptr<SessionConnection>, Tablet>& relationalTabletGroup,
- bool sorted);
-
void insertRelationalTablet(Tablet& tablet, bool sorted);
- static void buildInsertTabletReq(TSInsertTabletReq& request, Tablet& tablet, bool sorted);
-
- void insertTablet(TSInsertTabletReq request);
-
void insertAlignedTablet(Tablet& tablet);
void insertAlignedTablet(Tablet& tablet, bool sorted);
@@ -1010,79 +801,4 @@ public:
bool checkTemplateExists(const std::string& template_name);
};
-template <typename T, typename InsertConsumer>
-void Session::insertByGroup(std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
- InsertConsumer insertConsumer) {
- std::vector<std::future<void>> futures;
-
- for (auto& entry : insertGroup) {
- auto connection = entry.first;
- auto& req = entry.second;
- futures.emplace_back(std::async(std::launch::async, [=, &req]() mutable {
- try {
- insertConsumer(connection, req);
- } catch (const RedirectException& e) {
- for (const auto& deviceEndPoint : e.deviceEndPointMap) {
- handleRedirection(deviceEndPoint.first, deviceEndPoint.second);
- }
- } catch (const IoTDBConnectionException& e) {
- if (endPointToSessionConnection.size() > 1) {
- removeBrokenSessionConnection(connection);
- try {
- insertConsumer(defaultSessionConnection_, req);
- } catch (const RedirectException&) {
- }
- } else {
- throw;
- }
- } catch (const std::exception& e) {
- log_debug(e.what());
- throw IoTDBException(e.what());
- }
- }));
- }
-
- std::string errorMessages;
- for (auto& f : futures) {
- try {
- f.get();
- } catch (const IoTDBConnectionException& e) {
- throw;
- } catch (const std::exception& e) {
- if (!errorMessages.empty()) {
- errorMessages += ";";
- }
- errorMessages += e.what();
- }
- }
-
- if (!errorMessages.empty()) {
- throw StatementExecutionException(errorMessages);
- }
-}
-
-template <typename T, typename InsertConsumer>
-void Session::insertOnce(std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
- InsertConsumer insertConsumer) {
- auto connection = insertGroup.begin()->first;
- auto req = insertGroup.begin()->second;
- try {
- insertConsumer(connection, req);
- } catch (const RedirectException& e) {
- for (const auto& deviceEndPoint : e.deviceEndPointMap) {
- handleRedirection(deviceEndPoint.first, deviceEndPoint.second);
- }
- } catch (const IoTDBConnectionException& e) {
- if (endPointToSessionConnection.size() > 1) {
- removeBrokenSessionConnection(connection);
- try {
- insertConsumer(defaultSessionConnection_, req);
- } catch (const RedirectException& e) {
- }
- } else {
- throw;
- }
- }
-}
-
#endif // IOTDB_SESSION_H
diff --git a/iotdb-client/client-cpp/src/main/SessionBuilder.h b/iotdb-client/client-cpp/src/include/SessionBuilder.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/SessionBuilder.h
rename to iotdb-client/client-cpp/src/include/SessionBuilder.h
diff --git a/iotdb-client/client-cpp/src/main/SessionC.h b/iotdb-client/client-cpp/src/include/SessionC.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/SessionC.h
rename to iotdb-client/client-cpp/src/include/SessionC.h
diff --git a/iotdb-client/client-cpp/src/main/TableSession.h b/iotdb-client/client-cpp/src/include/SessionConfig.h
similarity index 50%
copy from iotdb-client/client-cpp/src/main/TableSession.h
copy to iotdb-client/client-cpp/src/include/SessionConfig.h
index d1eecfeeaba..2106a1b6c7b 100644
--- a/iotdb-client/client-cpp/src/main/TableSession.h
+++ b/iotdb-client/client-cpp/src/include/SessionConfig.h
@@ -1,4 +1,4 @@
-/*
+/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -16,31 +16,19 @@
* specific language governing permissions and limitations
* under the License.
*/
+#ifndef IOTDB_SESSION_CONFIG_H
+#define IOTDB_SESSION_CONFIG_H
-// This file is a translation of the Java file iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java
+namespace iotdb {
+namespace session {
-#ifndef IOTDB_TABLESESSION_H
-#define IOTDB_TABLESESSION_H
+// Defaults aligned with org.apache.iotdb.isession.SessionConfig (Java client).
+constexpr int DEFAULT_FETCH_SIZE = 5000;
+constexpr int DEFAULT_CONNECT_TIMEOUT_MS = 3 * 1000;
+constexpr int DEFAULT_MAX_RETRIES = 3;
+constexpr int DEFAULT_RETRY_DELAY_MS = 500;
-#include "Session.h"
+} // namespace session
+} // namespace iotdb
-class TableSession {
-private:
- std::shared_ptr<Session> session_;
- string getDatabase();
-
-public:
- TableSession(std::shared_ptr<Session> session) {
- this->session_ = session;
- }
- ~TableSession() {}
-
- void insert(Tablet& tablet, bool sorted = false);
- void executeNonQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql, int64_t timeoutInMs);
- void open(bool enableRPCCompression = false);
- void close();
-};
-
-#endif // IOTDB_TABLESESSION_H
\ No newline at end of file
+#endif // IOTDB_SESSION_CONFIG_H
diff --git a/iotdb-client/client-cpp/src/include/SessionDataSet.h b/iotdb-client/client-cpp/src/include/SessionDataSet.h
new file mode 100644
index 00000000000..9eea926d343
--- /dev/null
+++ b/iotdb-client/client-cpp/src/include/SessionDataSet.h
@@ -0,0 +1,124 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#ifndef IOTDB_SESSION_DATA_SET_H
+#define IOTDB_SESSION_DATA_SET_H
+
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "Column.h"
+#include "Date.h"
+#include "Optional.h"
+
+class RowRecord {
+public:
+ int64_t timestamp;
+ std::vector<Field> fields;
+
+ explicit RowRecord(int64_t timestamp);
+ RowRecord(int64_t timestamp, const std::vector<Field>& fields);
+ explicit RowRecord(const std::vector<Field>& fields);
+ RowRecord();
+
+ void addField(const Field& f);
+ std::string toString();
+};
+
+class Session;
+
+class SessionDataSet {
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+ SessionDataSet() = default;
+ friend class Session;
+ friend std::unique_ptr<SessionDataSet>
+ createSessionDataSet(const std::string& sql, const std::vector<std::string>& columnNameList,
+ const std::vector<std::string>& columnTypeList,
+ const std::map<std::string, int32_t>& columnNameIndex, int64_t queryId,
+ int64_t statementId, std::shared_ptr<class IClientRPCServiceClient> client,
+ int64_t sessionId, const std::vector<std::string>& queryResult,
+ bool ignoreTimestamp, int64_t timeout, bool moreData, int32_t fetchSize,
+ const std::string& zoneId, int32_t timeFactor,
+ std::vector<int32_t>& columnIndex2TsBlockColumnIndexList);
+
+private:
+ std::shared_ptr<RowRecord> constructRowRecordFromValueArray();
+
+public:
+ ~SessionDataSet();
+
+ bool hasNext();
+ std::shared_ptr<RowRecord> next();
+
+ int getFetchSize();
+ void setFetchSize(int fetchSize);
+
+ const std::vector<std::string>& getColumnNames() const;
+ const std::vector<std::string>& getColumnTypeList() const;
+ void closeOperationHandle(bool forceClose = false);
+
+ class DataIterator {
+ std::shared_ptr<Impl> impl_;
+
+ public:
+ explicit DataIterator(std::shared_ptr<Impl> impl);
+
+ bool next();
+
+ bool isNull(const std::string& columnName);
+ bool isNullByIndex(int32_t columnIndex);
+
+ Optional<bool> getBooleanByIndex(int32_t columnIndex);
+ Optional<bool> getBoolean(const std::string& columnName);
+
+ Optional<double> getDoubleByIndex(int32_t columnIndex);
+ Optional<double> getDouble(const std::string& columnName);
+
+ Optional<float> getFloatByIndex(int32_t columnIndex);
+ Optional<float> getFloat(const std::string& columnName);
+
+ Optional<int32_t> getIntByIndex(int32_t columnIndex);
+ Optional<int32_t> getInt(const std::string& columnName);
+
+ Optional<int64_t> getLongByIndex(int32_t columnIndex);
+ Optional<int64_t> getLong(const std::string& columnName);
+
+ Optional<std::string> getStringByIndex(int32_t columnIndex);
+ Optional<std::string> getString(const std::string& columnName);
+
+ Optional<int64_t> getTimestampByIndex(int32_t columnIndex);
+ Optional<int64_t> getTimestamp(const std::string& columnName);
+
+ Optional<IoTDBDate> getDateByIndex(int32_t columnIndex);
+ Optional<IoTDBDate> getDate(const std::string& columnName);
+
+ int32_t findColumn(const std::string& columnName);
+ const std::vector<std::string>& getColumnNames() const;
+ const std::vector<std::string>& getColumnTypeList() const;
+ };
+
+ // The returned iterator must not outlive this SessionDataSet.
+ DataIterator getIterator();
+};
+
+#endif
diff --git a/iotdb-client/client-cpp/src/main/SessionPool.h b/iotdb-client/client-cpp/src/include/SessionPool.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/SessionPool.h
rename to iotdb-client/client-cpp/src/include/SessionPool.h
diff --git a/iotdb-client/client-cpp/src/main/TableSession.h b/iotdb-client/client-cpp/src/include/Status.h
similarity index 50%
copy from iotdb-client/client-cpp/src/main/TableSession.h
copy to iotdb-client/client-cpp/src/include/Status.h
index d1eecfeeaba..147c20cffd2 100644
--- a/iotdb-client/client-cpp/src/main/TableSession.h
+++ b/iotdb-client/client-cpp/src/include/Status.h
@@ -1,4 +1,4 @@
-/*
+/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -16,31 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
+#ifndef IOTDB_STATUS_H
+#define IOTDB_STATUS_H
-// This file is a translation of the Java file iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java
+#include <cstdint>
+#include <string>
-#ifndef IOTDB_TABLESESSION_H
-#define IOTDB_TABLESESSION_H
-
-#include "Session.h"
-
-class TableSession {
-private:
- std::shared_ptr<Session> session_;
- string getDatabase();
-
-public:
- TableSession(std::shared_ptr<Session> session) {
- this->session_ = session;
- }
- ~TableSession() {}
-
- void insert(Tablet& tablet, bool sorted = false);
- void executeNonQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql, int64_t timeoutInMs);
- void open(bool enableRPCCompression = false);
- void close();
+struct Status {
+ int32_t code = 0;
+ std::string message;
};
-#endif // IOTDB_TABLESESSION_H
\ No newline at end of file
+#endif
diff --git a/iotdb-client/client-cpp/src/main/TableSession.h b/iotdb-client/client-cpp/src/include/TableSession.h
similarity index 100%
copy from iotdb-client/client-cpp/src/main/TableSession.h
copy to iotdb-client/client-cpp/src/include/TableSession.h
diff --git a/iotdb-client/client-cpp/src/main/TableSessionBuilder.h b/iotdb-client/client-cpp/src/include/TableSessionBuilder.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/TableSessionBuilder.h
rename to iotdb-client/client-cpp/src/include/TableSessionBuilder.h
diff --git a/iotdb-client/client-cpp/src/main/TsBlock.h b/iotdb-client/client-cpp/src/include/TsBlock.h
similarity index 100%
rename from iotdb-client/client-cpp/src/main/TsBlock.h
rename to iotdb-client/client-cpp/src/include/TsBlock.h
diff --git a/iotdb-client/client-cpp/src/main/CMakeLists.txt b/iotdb-client/client-cpp/src/main/CMakeLists.txt
deleted file mode 100644
index 8cfed4e7db9..00000000000
--- a/iotdb-client/client-cpp/src/main/CMakeLists.txt
+++ /dev/null
@@ -1,90 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-CMAKE_MINIMUM_REQUIRED(VERSION 3.7)
-PROJECT(iotdb_session CXX)
-SET(CMAKE_CXX_STANDARD 11)
-SET(CMAKE_CXX_STANDARD_REQUIRED ON)
-SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
-IF(NOT MSVC)
- # Keep GCC/Clang style flags off on MSVC to avoid invalid-option build errors.
- SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -g -O2")
-ENDIF()
-
-# Add Thrift include directory
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/../../thrift/include)
-
-# =========================
-# SSL option (default OFF)
-# =========================
-option(WITH_SSL "Build with SSL support" OFF)
-
-IF(WITH_SSL)
- FIND_PACKAGE(OpenSSL REQUIRED)
- IF(OpenSSL_FOUND)
- MESSAGE(STATUS "OpenSSL found: ${OPENSSL_VERSION}")
- INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
- ADD_DEFINITIONS(-DWITH_SSL=1)
- ELSE()
- MESSAGE(FATAL_ERROR "OpenSSL not found, but WITH_SSL is enabled")
- ENDIF()
-ELSE()
- MESSAGE(STATUS "Building without SSL support")
- ADD_DEFINITIONS(-DWITH_SSL=0)
-ENDIF()
-
-# Add Boost include path for MacOS
-INCLUDE_DIRECTORIES(/usr/local/include)
-
-# Add Boost library headers for MaxOS
-FIND_PACKAGE(Boost REQUIRED)
-IF (DEFINED BOOST_INCLUDEDIR)
- INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
-ENDIF()
-
-IF(MSVC)
- SET(THRIFT_STATIC_LIB "${CMAKE_SOURCE_DIR}/../../thrift/lib/Release/thriftmd.lib")
-ELSE()
- SET(THRIFT_STATIC_LIB "${CMAKE_SOURCE_DIR}/../../thrift/lib/libthrift.a")
-ENDIF()
-
-# Add the generated source files to the sources for the library.
-AUX_SOURCE_DIRECTORY(./generated-sources-cpp SESSION_SRCS)
-IF(MSVC)
- ADD_LIBRARY(iotdb_session ${SESSION_SRCS})
-ELSE()
- ADD_LIBRARY(iotdb_session SHARED ${SESSION_SRCS})
-ENDIF()
-
-# =========================
-# Link libraries (SSL optional)
-# =========================
-IF(WITH_SSL)
- target_link_libraries(iotdb_session
- PUBLIC
- OpenSSL::SSL
- OpenSSL::Crypto
- ${THRIFT_STATIC_LIB}
- )
-ELSE()
- target_link_libraries(iotdb_session
- PUBLIC
- ${THRIFT_STATIC_LIB}
- )
-ENDIF()
-
diff --git a/iotdb-client/client-cpp/src/main/SessionDataSet.h b/iotdb-client/client-cpp/src/main/SessionDataSet.h
deleted file mode 100644
index 0f2c018d256..00000000000
--- a/iotdb-client/client-cpp/src/main/SessionDataSet.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
-* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#ifndef IOTDB_SESSION_DATA_SET_H
-#define IOTDB_SESSION_DATA_SET_H
-
-#include <memory>
-#include <string>
-#include <vector>
-#include <map>
-#include <boost/date_time/gregorian/gregorian.hpp>
-#include "IoTDBRpcDataSet.h"
-#include "Column.h"
-
-class RowRecord {
-public:
- int64_t timestamp;
- std::vector<Field> fields;
-
- explicit RowRecord(int64_t timestamp);
- RowRecord(int64_t timestamp, const std::vector<Field>& fields);
- explicit RowRecord(const std::vector<Field>& fields);
- RowRecord();
-
- void addField(const Field& f);
- std::string toString();
-};
-
-class SessionDataSet {
-public:
- SessionDataSet(const std::string& sql, const std::vector<std::string>& columnNameList,
- const std::vector<std::string>& columnTypeList,
- const std::map<std::string, int32_t>& columnNameIndex, int64_t queryId,
- int64_t statementId, std::shared_ptr<IClientRPCServiceClient> client,
- int64_t sessionId, const std::vector<std::string>& queryResult,
- bool ignoreTimestamp, int64_t timeout, bool moreData, int32_t fetchSize,
- const std::string& zoneId, int32_t timeFactor,
- std::vector<int32_t>& columnIndex2TsBlockColumnIndexList) {
- iotdbRpcDataSet_ = std::make_shared<IoTDBRpcDataSet>(
- sql, columnNameList, columnTypeList, columnNameIndex, ignoreTimestamp, moreData, queryId,
- statementId, client, sessionId, queryResult, fetchSize, timeout, zoneId,
- IoTDBRpcDataSet::DEFAULT_TIME_FORMAT, timeFactor, columnIndex2TsBlockColumnIndexList);
- }
-
- ~SessionDataSet() = default;
-
- bool hasNext();
- shared_ptr<RowRecord> next();
-
- int getFetchSize();
- void setFetchSize(int fetchSize);
-
- const std::vector<std::string>& getColumnNames() const;
- const std::vector<std::string>& getColumnTypeList() const;
- void closeOperationHandle(bool forceClose = false);
-
- class DataIterator {
- std::shared_ptr<IoTDBRpcDataSet> iotdbRpcDataSet_;
-
- public:
- DataIterator(std::shared_ptr<IoTDBRpcDataSet> iotdbRpcDataSet)
- : iotdbRpcDataSet_(iotdbRpcDataSet) {}
-
- bool next();
-
- bool isNull(const std::string& columnName);
- bool isNullByIndex(int32_t columnIndex);
-
- boost::optional<bool> getBooleanByIndex(int32_t columnIndex);
- boost::optional<bool> getBoolean(const std::string& columnName);
-
- boost::optional<double> getDoubleByIndex(int32_t columnIndex);
- boost::optional<double> getDouble(const std::string& columnName);
-
- boost::optional<float> getFloatByIndex(int32_t columnIndex);
- boost::optional<float> getFloat(const std::string& columnName);
-
- boost::optional<int32_t> getIntByIndex(int32_t columnIndex);
- boost::optional<int32_t> getInt(const std::string& columnName);
-
- boost::optional<int64_t> getLongByIndex(int32_t columnIndex);
- boost::optional<int64_t> getLong(const std::string& columnName);
-
- boost::optional<std::string> getStringByIndex(int32_t columnIndex);
- boost::optional<std::string> getString(const std::string& columnName);
-
- boost::optional<int64_t> getTimestampByIndex(int32_t columnIndex);
- boost::optional<int64_t> getTimestamp(const std::string& columnName);
-
- boost::optional<boost::gregorian::date> getDateByIndex(int32_t columnIndex);
- boost::optional<boost::gregorian::date> getDate(const std::string& columnName);
-
- int32_t findColumn(const std::string& columnName);
- const std::vector<std::string>& getColumnNames() const;
- const std::vector<std::string>& getColumnTypeList() const;
- };
-
- DataIterator getIterator() {
- return {iotdbRpcDataSet_};
- };
-
-private:
- std::shared_ptr<RowRecord> constructRowRecordFromValueArray();
-
- std::shared_ptr<IoTDBRpcDataSet> iotdbRpcDataSet_;
-};
-
-#endif
diff --git a/iotdb-client/client-cpp/src/main/IoTDBRpcDataSet.cpp b/iotdb-client/client-cpp/src/rpc/IoTDBRpcDataSet.cpp
similarity index 88%
rename from iotdb-client/client-cpp/src/main/IoTDBRpcDataSet.cpp
rename to iotdb-client/client-cpp/src/rpc/IoTDBRpcDataSet.cpp
index 8b02a356079..cf8454af1a1 100644
--- a/iotdb-client/client-cpp/src/main/IoTDBRpcDataSet.cpp
+++ b/iotdb-client/client-cpp/src/rpc/IoTDBRpcDataSet.cpp
@@ -23,10 +23,15 @@
#include "IoTDBRpcDataSet.h"
-#include <boost/optional/optional.hpp>
+#include <thrift/transport/TTransportException.h>
+#include "RpcCommon.h"
+#include "Optional.h"
+#include "Date.h"
#include "Column.h"
+using apache::thrift::transport::TTransportException;
+
const int32_t IoTDBRpcDataSet::startIndex = 2;
const std::string IoTDBRpcDataSet::TimestampColumnName = "Time";
const std::string IoTDBRpcDataSet::DEFAULT_TIME_FORMAT = "default";
@@ -235,12 +240,12 @@ bool IoTDBRpcDataSet::isNull(int32_t index, int32_t rowNum) {
return index >= 0 && curTsBlock_->getColumn(index)->isNull(rowNum);
}
-boost::optional<bool> IoTDBRpcDataSet::getBooleanByIndex(int32_t columnIndex) {
+Optional<bool> IoTDBRpcDataSet::getBooleanByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getBooleanByTsBlockColumnIndex(index);
}
-boost::optional<bool> IoTDBRpcDataSet::getBoolean(const std::string& columnName) {
+Optional<bool> IoTDBRpcDataSet::getBoolean(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getBooleanByTsBlockColumnIndex(index);
}
@@ -249,7 +254,7 @@ boost::optional<bool> IoTDBRpcDataSet::getBoolean(const std::string& columnName)
// Only getLong and getString support reading the time column directly.
// All other typed getters throw IoTDBException to prevent undefined behavior
// from accessing valueColumns_ with a negative index.
-boost::optional<bool> IoTDBRpcDataSet::getBooleanByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<bool> IoTDBRpcDataSet::getBooleanByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
checkRecord();
if (tsBlockColumnIndex < 0) {
throw IoTDBException("Cannot read boolean from time column");
@@ -259,21 +264,21 @@ boost::optional<bool> IoTDBRpcDataSet::getBooleanByTsBlockColumnIndex(int32_t ts
return curTsBlock_->getColumn(tsBlockColumnIndex)->getBoolean(tsBlockIndex_);
} else {
lastReadWasNull_ = true;
- return boost::none;
+ return Optional<bool>::none();
}
}
-boost::optional<double> IoTDBRpcDataSet::getDoubleByIndex(int32_t columnIndex) {
+Optional<double> IoTDBRpcDataSet::getDoubleByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getDoubleByTsBlockColumnIndex(index);
}
-boost::optional<double> IoTDBRpcDataSet::getDouble(const std::string& columnName) {
+Optional<double> IoTDBRpcDataSet::getDouble(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getDoubleByTsBlockColumnIndex(index);
}
-boost::optional<double> IoTDBRpcDataSet::getDoubleByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<double> IoTDBRpcDataSet::getDoubleByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
checkRecord();
if (tsBlockColumnIndex < 0) {
throw IoTDBException("Cannot read double from time column");
@@ -283,21 +288,21 @@ boost::optional<double> IoTDBRpcDataSet::getDoubleByTsBlockColumnIndex(int32_t t
return curTsBlock_->getColumn(tsBlockColumnIndex)->getDouble(tsBlockIndex_);
} else {
lastReadWasNull_ = true;
- return boost::none;
+ return Optional<double>::none();
}
}
-boost::optional<float> IoTDBRpcDataSet::getFloatByIndex(int32_t columnIndex) {
+Optional<float> IoTDBRpcDataSet::getFloatByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getFloatByTsBlockColumnIndex(index);
}
-boost::optional<float> IoTDBRpcDataSet::getFloat(const std::string& columnName) {
+Optional<float> IoTDBRpcDataSet::getFloat(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getFloatByTsBlockColumnIndex(index);
}
-boost::optional<float> IoTDBRpcDataSet::getFloatByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<float> IoTDBRpcDataSet::getFloatByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
checkRecord();
if (tsBlockColumnIndex < 0) {
throw IoTDBException("Cannot read float from time column");
@@ -307,21 +312,21 @@ boost::optional<float> IoTDBRpcDataSet::getFloatByTsBlockColumnIndex(int32_t tsB
return curTsBlock_->getColumn(tsBlockColumnIndex)->getFloat(tsBlockIndex_);
} else {
lastReadWasNull_ = true;
- return boost::none;
+ return Optional<float>::none();
}
}
-boost::optional<int32_t> IoTDBRpcDataSet::getIntByIndex(int32_t columnIndex) {
+Optional<int32_t> IoTDBRpcDataSet::getIntByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getIntByTsBlockColumnIndex(index);
}
-boost::optional<int32_t> IoTDBRpcDataSet::getInt(const std::string& columnName) {
+Optional<int32_t> IoTDBRpcDataSet::getInt(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getIntByTsBlockColumnIndex(index);
}
-boost::optional<int32_t> IoTDBRpcDataSet::getIntByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<int32_t> IoTDBRpcDataSet::getIntByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
checkRecord();
if (tsBlockColumnIndex < 0) {
throw IoTDBException("Cannot read int32 from time column");
@@ -336,21 +341,21 @@ boost::optional<int32_t> IoTDBRpcDataSet::getIntByTsBlockColumnIndex(int32_t tsB
return curTsBlock_->getColumn(tsBlockColumnIndex)->getInt(tsBlockIndex_);
} else {
lastReadWasNull_ = true;
- return boost::none;
+ return Optional<int32_t>::none();
}
}
-boost::optional<int64_t> IoTDBRpcDataSet::getLongByIndex(int32_t columnIndex) {
+Optional<int64_t> IoTDBRpcDataSet::getLongByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getLongByTsBlockColumnIndex(index);
}
-boost::optional<int64_t> IoTDBRpcDataSet::getLong(const std::string& columnName) {
+Optional<int64_t> IoTDBRpcDataSet::getLong(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getLongByTsBlockColumnIndex(index);
}
-boost::optional<int64_t> IoTDBRpcDataSet::getLongByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<int64_t> IoTDBRpcDataSet::getLongByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
checkRecord();
if (tsBlockColumnIndex < 0) {
lastReadWasNull_ = false;
@@ -366,7 +371,7 @@ boost::optional<int64_t> IoTDBRpcDataSet::getLongByTsBlockColumnIndex(int32_t ts
return curTsBlock_->getColumn(tsBlockColumnIndex)->getLong(tsBlockIndex_);
} else {
lastReadWasNull_ = true;
- return boost::none;
+ return Optional<int64_t>::none();
}
}
@@ -394,18 +399,17 @@ std::shared_ptr<Binary> IoTDBRpcDataSet::getBinaryByTsBlockColumnIndex(int32_t t
}
}
-boost::optional<std::string> IoTDBRpcDataSet::getStringByIndex(int32_t columnIndex) {
+Optional<std::string> IoTDBRpcDataSet::getStringByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getStringByTsBlockColumnIndex(index);
}
-boost::optional<std::string> IoTDBRpcDataSet::getString(const std::string& columnName) {
+Optional<std::string> IoTDBRpcDataSet::getString(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getStringByTsBlockColumnIndex(index);
}
-boost::optional<std::string>
-IoTDBRpcDataSet::getStringByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<std::string> IoTDBRpcDataSet::getStringByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
checkRecord();
if (tsBlockColumnIndex < 0) {
int64_t timestamp = curTsBlock_->getTimeByIndex(tsBlockIndex_);
@@ -413,7 +417,7 @@ IoTDBRpcDataSet::getStringByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
}
if (isNull(tsBlockColumnIndex, tsBlockIndex_)) {
lastReadWasNull_ = true;
- return boost::none;
+ return Optional<std::string>::none();
}
lastReadWasNull_ = false;
return getStringByTsBlockColumnIndexAndDataType(
@@ -448,43 +452,41 @@ IoTDBRpcDataSet::getStringByTsBlockColumnIndexAndDataType(int32_t index,
case TSDataType::DATE: {
int32_t value = curTsBlock_->getColumn(index)->getInt(tsBlockIndex_);
auto date = parseIntToDate(value);
- return boost::gregorian::to_iso_extended_string(date);
+ return date.toIsoExtendedString();
}
default:
return "";
}
}
-boost::optional<int64_t> IoTDBRpcDataSet::getTimestampByIndex(int32_t columnIndex) {
+Optional<int64_t> IoTDBRpcDataSet::getTimestampByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getTimestampByTsBlockColumnIndex(index);
}
-boost::optional<int64_t> IoTDBRpcDataSet::getTimestamp(const std::string& columnName) {
+Optional<int64_t> IoTDBRpcDataSet::getTimestamp(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getTimestampByTsBlockColumnIndex(index);
}
-boost::optional<int64_t>
-IoTDBRpcDataSet::getTimestampByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<int64_t> IoTDBRpcDataSet::getTimestampByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
return getLongByTsBlockColumnIndex(tsBlockColumnIndex);
}
-boost::optional<boost::gregorian::date> IoTDBRpcDataSet::getDateByIndex(int32_t columnIndex) {
+Optional<IoTDBDate> IoTDBRpcDataSet::getDateByIndex(int32_t columnIndex) {
int32_t index = getTsBlockColumnIndexForColumnIndex(columnIndex);
return getDateByTsBlockColumnIndex(index);
}
-boost::optional<boost::gregorian::date> IoTDBRpcDataSet::getDate(const std::string& columnName) {
+Optional<IoTDBDate> IoTDBRpcDataSet::getDate(const std::string& columnName) {
int32_t index = getTsBlockColumnIndexForColumnName(columnName);
return getDateByTsBlockColumnIndex(index);
}
-boost::optional<boost::gregorian::date>
-IoTDBRpcDataSet::getDateByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
+Optional<IoTDBDate> IoTDBRpcDataSet::getDateByTsBlockColumnIndex(int32_t tsBlockColumnIndex) {
auto value = getIntByTsBlockColumnIndex(tsBlockColumnIndex);
if (!value.is_initialized()) {
- return boost::none;
+ return Optional<IoTDBDate>::none();
}
return parseIntToDate(value.value());
}
diff --git a/iotdb-client/client-cpp/src/main/IoTDBRpcDataSet.h b/iotdb-client/client-cpp/src/rpc/IoTDBRpcDataSet.h
similarity index 72%
rename from iotdb-client/client-cpp/src/main/IoTDBRpcDataSet.h
rename to iotdb-client/client-cpp/src/rpc/IoTDBRpcDataSet.h
index 0e6855f4049..054dd84a2e3 100644
--- a/iotdb-client/client-cpp/src/main/IoTDBRpcDataSet.h
+++ b/iotdb-client/client-cpp/src/rpc/IoTDBRpcDataSet.h
@@ -26,7 +26,8 @@
#include <memory>
#include <cstdint>
#include "IClientRPCService.h"
-#include <boost/date_time/gregorian/gregorian.hpp>
+#include "Date.h"
+#include "Optional.h"
#include "TsBlock.h"
class IoTDBRpcDataSet {
@@ -60,24 +61,24 @@ public:
bool isNull(int32_t index, int32_t rowNum);
bool isNullByIndex(int32_t columnIndex);
bool isNullByColumnName(const std::string& columnName);
- boost::optional<bool> getBooleanByIndex(int32_t columnIndex);
- boost::optional<bool> getBoolean(const std::string& columnName);
- boost::optional<double> getDoubleByIndex(int32_t columnIndex);
- boost::optional<double> getDouble(const std::string& columnName);
- boost::optional<float> getFloatByIndex(int32_t columnIndex);
- boost::optional<float> getFloat(const std::string& columnName);
- boost::optional<int32_t> getIntByIndex(int32_t columnIndex);
- boost::optional<int32_t> getInt(const std::string& columnName);
- boost::optional<int64_t> getLongByIndex(int32_t columnIndex);
- boost::optional<int64_t> getLong(const std::string& columnName);
+ Optional<bool> getBooleanByIndex(int32_t columnIndex);
+ Optional<bool> getBoolean(const std::string& columnName);
+ Optional<double> getDoubleByIndex(int32_t columnIndex);
+ Optional<double> getDouble(const std::string& columnName);
+ Optional<float> getFloatByIndex(int32_t columnIndex);
+ Optional<float> getFloat(const std::string& columnName);
+ Optional<int32_t> getIntByIndex(int32_t columnIndex);
+ Optional<int32_t> getInt(const std::string& columnName);
+ Optional<int64_t> getLongByIndex(int32_t columnIndex);
+ Optional<int64_t> getLong(const std::string& columnName);
std::shared_ptr<Binary> getBinaryByIndex(int32_t columnIndex);
std::shared_ptr<Binary> getBinary(const std::string& columnName);
- boost::optional<std::string> getStringByIndex(int32_t columnIndex);
- boost::optional<std::string> getString(const std::string& columnName);
- boost::optional<int64_t> getTimestampByIndex(int32_t columnIndex);
- boost::optional<int64_t> getTimestamp(const std::string& columnName);
- boost::optional<boost::gregorian::date> getDateByIndex(int32_t columnIndex);
- boost::optional<boost::gregorian::date> getDate(const std::string& columnName);
+ Optional<std::string> getStringByIndex(int32_t columnIndex);
+ Optional<std::string> getString(const std::string& columnName);
+ Optional<int64_t> getTimestampByIndex(int32_t columnIndex);
+ Optional<int64_t> getTimestamp(const std::string& columnName);
+ Optional<IoTDBDate> getDateByIndex(int32_t columnIndex);
+ Optional<IoTDBDate> getDate(const std::string& columnName);
TSDataType::TSDataType getDataTypeByIndex(int32_t columnIndex);
TSDataType::TSDataType getDataType(const std::string& columnName);
@@ -104,17 +105,17 @@ private:
int32_t getTsBlockColumnIndexForColumnIndex(int32_t columnIndex);
void checkRecord();
TSDataType::TSDataType getDataTypeByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<bool> getBooleanByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<bool> getBooleanByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
std::string getStringByTsBlockColumnIndexAndDataType(int32_t index,
TSDataType::TSDataType tsDataType);
- boost::optional<double> getDoubleByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<float> getFloatByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<int32_t> getIntByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<int64_t> getLongByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<double> getDoubleByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<float> getFloatByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<int32_t> getIntByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<int64_t> getLongByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
std::shared_ptr<Binary> getBinaryByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<std::string> getStringByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<boost::gregorian::date> getDateByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
- boost::optional<int64_t> getTimestampByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<std::string> getStringByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<IoTDBDate> getDateByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
+ Optional<int64_t> getTimestampByTsBlockColumnIndex(int32_t tsBlockColumnIndex);
std::string sql_;
bool isClosed_;
diff --git a/iotdb-client/client-cpp/src/main/NodesSupplier.cpp b/iotdb-client/client-cpp/src/rpc/NodesSupplier.cpp
similarity index 97%
rename from iotdb-client/client-cpp/src/main/NodesSupplier.cpp
rename to iotdb-client/client-cpp/src/rpc/NodesSupplier.cpp
index 3f3a807dae8..604099a82d1 100644
--- a/iotdb-client/client-cpp/src/main/NodesSupplier.cpp
+++ b/iotdb-client/client-cpp/src/rpc/NodesSupplier.cpp
@@ -31,7 +31,6 @@ const std::string NodesSupplier::PORT_COLUMN_NAME = "RpcPort";
const std::string NodesSupplier::REMOVING_STATUS = "Removing";
const int64_t NodesSupplier::TIMEOUT_IN_MS = 60000;
-const int NodesSupplier::FETCH_SIZE = 10000;
const int NodesSupplier::THRIFT_DEFAULT_BUFFER_SIZE = 4096;
const int NodesSupplier::THRIFT_MAX_FRAME_SIZE = 1048576;
const int NodesSupplier::CONNECTION_TIMEOUT_IN_MS = 1000;
@@ -50,14 +49,14 @@ StaticNodesSupplier::StaticNodesSupplier(const std::vector<TEndPoint>& nodes,
NodeSelectionPolicy policy)
: availableNodes_(nodes), policy_(std::move(policy)) {}
-boost::optional<TEndPoint> StaticNodesSupplier::getQueryEndPoint() {
+Optional<TEndPoint> StaticNodesSupplier::getQueryEndPoint() {
try {
if (availableNodes_.empty()) {
- return boost::none;
+ return Optional<TEndPoint>::none();
}
return policy_(availableNodes_);
} catch (const IoTDBException& e) {
- return boost::none;
+ return Optional<TEndPoint>::none();
}
}
@@ -112,11 +111,11 @@ TEndPoint NodesSupplier::selectQueryEndpoint() {
}
}
-boost::optional<TEndPoint> NodesSupplier::getQueryEndPoint() {
+Optional<TEndPoint> NodesSupplier::getQueryEndPoint() {
try {
return selectQueryEndpoint();
} catch (const IoTDBException& e) {
- return boost::none;
+ return Optional<TEndPoint>::none();
}
}
diff --git a/iotdb-client/client-cpp/src/main/NodesSupplier.h b/iotdb-client/client-cpp/src/rpc/NodesSupplier.h
similarity index 94%
rename from iotdb-client/client-cpp/src/main/NodesSupplier.h
rename to iotdb-client/client-cpp/src/rpc/NodesSupplier.h
index 7c56f8e75ba..c067bbb6d72 100644
--- a/iotdb-client/client-cpp/src/main/NodesSupplier.h
+++ b/iotdb-client/client-cpp/src/rpc/NodesSupplier.h
@@ -21,7 +21,7 @@
#include <vector>
#include <atomic>
-#include <boost/optional.hpp>
+#include "Optional.h"
#include <mutex>
#include <chrono>
#include <thread>
@@ -41,7 +41,7 @@ public:
class INodesSupplier {
public:
virtual ~INodesSupplier() = default;
- virtual boost::optional<TEndPoint> getQueryEndPoint() = 0;
+ virtual Optional<TEndPoint> getQueryEndPoint() = 0;
virtual std::vector<TEndPoint> getEndPointList() = 0;
using NodeSelectionPolicy = std::function<TEndPoint(const std::vector<TEndPoint>&)>;
};
@@ -51,7 +51,7 @@ public:
explicit StaticNodesSupplier(const std::vector<TEndPoint>& nodes,
NodeSelectionPolicy policy = RoundRobinPolicy::select);
- boost::optional<TEndPoint> getQueryEndPoint() override;
+ Optional<TEndPoint> getQueryEndPoint() override;
std::vector<TEndPoint> getEndPointList() override;
@@ -72,7 +72,6 @@ public:
static const std::string REMOVING_STATUS;
static const int64_t TIMEOUT_IN_MS;
- static const int FETCH_SIZE;
static const int THRIFT_DEFAULT_BUFFER_SIZE;
static const int THRIFT_MAX_FRAME_SIZE;
static const int CONNECTION_TIMEOUT_IN_MS;
@@ -97,7 +96,7 @@ public:
std::vector<TEndPoint> getEndPointList() override;
- boost::optional<TEndPoint> getQueryEndPoint() override;
+ Optional<TEndPoint> getQueryEndPoint() override;
~NodesSupplier() override;
diff --git a/iotdb-client/client-cpp/src/rpc/RpcCommon.cpp b/iotdb-client/client-cpp/src/rpc/RpcCommon.cpp
new file mode 100644
index 00000000000..c83b39a5fb5
--- /dev/null
+++ b/iotdb-client/client-cpp/src/rpc/RpcCommon.cpp
@@ -0,0 +1,214 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "RpcCommon.h"
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "ThriftConvert.h"
+#include "client_types.h"
+#include "common_types.h"
+
+using namespace std;
+
+RpcUtils::RpcUtils() {
+ SUCCESS_STATUS = std::make_shared<TSStatus>();
+ SUCCESS_STATUS->__set_code(TSStatusCode::SUCCESS_STATUS);
+}
+
+void RpcUtils::verifySuccess(const TSStatus& status) {
+ if (status.code == TSStatusCode::MULTIPLE_ERROR) {
+ verifySuccess(status.subStatus);
+ return;
+ }
+ if (status.code != TSStatusCode::SUCCESS_STATUS &&
+ status.code != TSStatusCode::REDIRECTION_RECOMMEND) {
+ throw ExecutionException(to_string(status.code) + ": " + status.message,
+ statusFromThrift(status));
+ }
+}
+
+void RpcUtils::verifySuccessWithRedirection(const TSStatus& status) {
+ verifySuccess(status);
+ if (status.__isset.redirectNode) {
+ throw RedirectException(to_string(status.code) + ": " + status.message,
+ endpointFromThrift(status.redirectNode));
+ }
+ if (status.__isset.subStatus) {
+ auto statusSubStatus = status.subStatus;
+ vector<TEndPoint> endPointList(statusSubStatus.size());
+ int count = 0;
+ for (const TSStatus& subStatus : statusSubStatus) {
+ if (subStatus.__isset.redirectNode) {
+ endPointList[count++] = subStatus.redirectNode;
+ } else {
+ TEndPoint endPoint;
+ endPointList[count++] = endPoint;
+ }
+ }
+ if (!endPointList.empty()) {
+ throw RedirectException(to_string(status.code) + ": " + status.message,
+ endpointListFromThrift(endPointList));
+ }
+ }
+}
+
+void RpcUtils::verifySuccessWithRedirectionForMultiDevices(const TSStatus& status,
+ vector<string> devices) {
+ verifySuccess(status);
+
+ if (status.code == TSStatusCode::MULTIPLE_ERROR ||
+ status.code == TSStatusCode::REDIRECTION_RECOMMEND) {
+ map<string, TEndPoint> deviceEndPointMap;
+ const vector<TSStatus>& statusSubStatus = status.subStatus;
+ for (size_t i = 0; i < statusSubStatus.size() && i < devices.size(); i++) {
+ const TSStatus& subStatus = statusSubStatus[i];
+ if (subStatus.__isset.redirectNode) {
+ deviceEndPointMap.insert(make_pair(devices[i], subStatus.redirectNode));
+ }
+ }
+ throw RedirectException(to_string(status.code) + ": " + status.message,
+ endpointMapFromThrift(deviceEndPointMap));
+ }
+
+ if (status.__isset.redirectNode) {
+ throw RedirectException(to_string(status.code) + ": " + status.message,
+ endpointFromThrift(status.redirectNode));
+ }
+ if (status.__isset.subStatus) {
+ auto statusSubStatus = status.subStatus;
+ vector<TEndPoint> endPointList(statusSubStatus.size());
+ int count = 0;
+ for (const TSStatus& subStatus : statusSubStatus) {
+ if (subStatus.__isset.redirectNode) {
+ endPointList[count++] = subStatus.redirectNode;
+ } else {
+ TEndPoint endPoint;
+ endPointList[count++] = endPoint;
+ }
+ }
+ if (!endPointList.empty()) {
+ throw RedirectException(to_string(status.code) + ": " + status.message,
+ endpointListFromThrift(endPointList));
+ }
+ }
+}
+
+void RpcUtils::verifySuccess(const vector<TSStatus>& statuses) {
+ for (const TSStatus& status : statuses) {
+ if (status.code != TSStatusCode::SUCCESS_STATUS) {
+ vector<Status> publicStatuses;
+ publicStatuses.reserve(statuses.size());
+ for (const TSStatus& s : statuses) {
+ publicStatuses.push_back(statusFromThrift(s));
+ }
+ throw BatchExecutionException(status.message, publicStatuses);
+ }
+ }
+}
+
+TSStatus RpcUtils::getStatus(TSStatusCode::TSStatusCode tsStatusCode) {
+ TSStatus status;
+ status.__set_code(tsStatusCode);
+ return status;
+}
+
+TSStatus RpcUtils::getStatus(int code, const string& message) {
+ TSStatus status;
+ status.__set_code(code);
+ status.__set_message(message);
+ return status;
+}
+
+shared_ptr<TSExecuteStatementResp>
+RpcUtils::getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode) {
+ TSStatus status = getStatus(tsStatusCode);
+ return getTSExecuteStatementResp(status);
+}
+
+shared_ptr<TSExecuteStatementResp>
+RpcUtils::getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode,
+ const string& message) {
+ TSStatus status = getStatus(tsStatusCode, message);
+ return getTSExecuteStatementResp(status);
+}
+
+shared_ptr<TSExecuteStatementResp> RpcUtils::getTSExecuteStatementResp(const TSStatus& status) {
+ shared_ptr<TSExecuteStatementResp> resp(new TSExecuteStatementResp());
+ resp->__set_status(status);
+ return resp;
+}
+
+shared_ptr<TSFetchResultsResp>
+RpcUtils::getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode) {
+ TSStatus status = getStatus(tsStatusCode);
+ return getTSFetchResultsResp(status);
+}
+
+shared_ptr<TSFetchResultsResp>
+RpcUtils::getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode,
+ const string& appendMessage) {
+ TSStatus status = getStatus(tsStatusCode, appendMessage);
+ return getTSFetchResultsResp(status);
+}
+
+shared_ptr<TSFetchResultsResp> RpcUtils::getTSFetchResultsResp(const TSStatus& status) {
+ shared_ptr<TSFetchResultsResp> resp(new TSFetchResultsResp());
+ resp->__set_status(status);
+ return resp;
+}
+
+const string UrlUtils::PORT_SEPARATOR = ":";
+const string UrlUtils::ABB_COLON = "[";
+
+TEndPoint UrlUtils::parseTEndPointIpv4AndIpv6Url(const string& endPointUrl) {
+ TEndPoint endPoint;
+
+ if (endPointUrl.empty()) {
+ return endPoint;
+ }
+
+ size_t portSeparatorPos = endPointUrl.find_last_of(PORT_SEPARATOR);
+
+ if (portSeparatorPos == string::npos) {
+ endPoint.__set_ip(endPointUrl);
+ return endPoint;
+ }
+
+ string portStr = endPointUrl.substr(portSeparatorPos + 1);
+ string ip = endPointUrl.substr(0, portSeparatorPos);
+
+ if (ip.find(ABB_COLON) != string::npos) {
+ if (ip.size() >= 2 && ip.front() == '[' && ip.back() == ']') {
+ ip = ip.substr(1, ip.size() - 2);
+ }
+ }
+
+ try {
+ int port = stoi(portStr);
+ endPoint.__set_ip(ip);
+ endPoint.__set_port(port);
+ } catch (const exception&) {
+ endPoint.__set_ip(endPointUrl);
+ }
+
+ return endPoint;
+}
diff --git a/iotdb-client/client-cpp/src/rpc/RpcCommon.h b/iotdb-client/client-cpp/src/rpc/RpcCommon.h
new file mode 100644
index 00000000000..721150bd6ca
--- /dev/null
+++ b/iotdb-client/client-cpp/src/rpc/RpcCommon.h
@@ -0,0 +1,81 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef IOTDB_RPC_COMMON_H
+#define IOTDB_RPC_COMMON_H
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "Common.h"
+
+class TSStatus;
+class TSExecuteStatementResp;
+class TSFetchResultsResp;
+class TEndPoint;
+
+class RpcUtils {
+public:
+ std::shared_ptr<TSStatus> SUCCESS_STATUS;
+
+ RpcUtils();
+
+ static void verifySuccess(const TSStatus& status);
+
+ static void verifySuccessWithRedirection(const TSStatus& status);
+
+ static void verifySuccessWithRedirectionForMultiDevices(const TSStatus& status,
+ std::vector<std::string> devices);
+
+ static void verifySuccess(const std::vector<TSStatus>& statuses);
+
+ static TSStatus getStatus(TSStatusCode::TSStatusCode tsStatusCode);
+
+ static TSStatus getStatus(int code, const std::string& message);
+
+ static std::shared_ptr<TSExecuteStatementResp>
+ getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode);
+
+ static std::shared_ptr<TSExecuteStatementResp>
+ getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode, const std::string& message);
+
+ static std::shared_ptr<TSExecuteStatementResp> getTSExecuteStatementResp(const TSStatus& status);
+
+ static std::shared_ptr<TSFetchResultsResp>
+ getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode);
+
+ static std::shared_ptr<TSFetchResultsResp>
+ getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode, const std::string& appendMessage);
+
+ static std::shared_ptr<TSFetchResultsResp> getTSFetchResultsResp(const TSStatus& status);
+};
+
+class UrlUtils {
+private:
+ static const std::string PORT_SEPARATOR;
+ static const std::string ABB_COLON;
+
+ UrlUtils() = delete;
+ ~UrlUtils() = delete;
+
+public:
+ static TEndPoint parseTEndPointIpv4AndIpv6Url(const std::string& endPointUrl);
+};
+
+#endif
diff --git a/iotdb-client/client-cpp/src/main/SessionConnection.cpp b/iotdb-client/client-cpp/src/rpc/SessionConnection.cpp
similarity index 93%
rename from iotdb-client/client-cpp/src/main/SessionConnection.cpp
rename to iotdb-client/client-cpp/src/rpc/SessionConnection.cpp
index a7fa3beb6ff..dfdb0198e38 100644
--- a/iotdb-client/client-cpp/src/main/SessionConnection.cpp
+++ b/iotdb-client/client-cpp/src/rpc/SessionConnection.cpp
@@ -17,19 +17,25 @@
* under the License.
*/
#include "SessionConnection.h"
-#include "Session.h"
+#include "SessionImpl.h"
+#include "RpcCommon.h"
#include "common_types.h"
+#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TCompactProtocol.h>
+#include <thrift/transport/TBufferTransports.h>
+#include <thrift/transport/TSocket.h>
+#include <thrift/transport/TTransportException.h>
#include <utility>
#include "SessionDataSet.h"
+#include "SessionDataSetFactory.h"
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
-SessionConnection::SessionConnection(Session* session_ptr, const TEndPoint& endpoint,
+SessionConnection::SessionConnection(Session::Impl* session_ptr, const TEndPoint& endpoint,
const std::string& zoneId,
std::shared_ptr<INodesSupplier> nodeSupplier, int fetchSize,
int maxRetries, int64_t retryInterval,
@@ -189,10 +195,10 @@ std::unique_ptr<SessionDataSet> SessionConnection::executeQueryStatement(const s
RpcUtils::verifySuccess(resp.status);
}
- return std::unique_ptr<SessionDataSet>(new SessionDataSet(
- sql, resp.columns, resp.dataTypeList, resp.columnNameIndexMap, resp.queryId, statementId,
- client, sessionId, resp.queryResult, resp.ignoreTimeStamp, timeoutInMs, resp.moreData,
- fetchSize, zoneId, timeFactor, resp.columnIndex2TsBlockColumnIndexList));
+ return createSessionDataSet(sql, resp.columns, resp.dataTypeList, resp.columnNameIndexMap,
+ resp.queryId, statementId, client, sessionId, resp.queryResult,
+ resp.ignoreTimeStamp, timeoutInMs, resp.moreData, fetchSize, zoneId,
+ timeFactor, resp.columnIndex2TsBlockColumnIndexList);
}
std::unique_ptr<SessionDataSet>
@@ -218,10 +224,10 @@ SessionConnection::executeRawDataQuery(const std::vector<std::string>& paths, in
} else {
RpcUtils::verifySuccess(resp.status);
}
- return std::unique_ptr<SessionDataSet>(new SessionDataSet(
- "", resp.columns, resp.dataTypeList, resp.columnNameIndexMap, resp.queryId, statementId,
- client, sessionId, resp.queryResult, resp.ignoreTimeStamp, connectionTimeoutInMs,
- resp.moreData, fetchSize, zoneId, timeFactor, resp.columnIndex2TsBlockColumnIndexList));
+ return createSessionDataSet("", resp.columns, resp.dataTypeList, resp.columnNameIndexMap,
+ resp.queryId, statementId, client, sessionId, resp.queryResult,
+ resp.ignoreTimeStamp, connectionTimeoutInMs, resp.moreData, fetchSize,
+ zoneId, timeFactor, resp.columnIndex2TsBlockColumnIndexList);
}
std::unique_ptr<SessionDataSet>
@@ -246,10 +252,10 @@ SessionConnection::executeLastDataQuery(const std::vector<std::string>& paths, i
} else {
RpcUtils::verifySuccess(resp.status);
}
- return std::unique_ptr<SessionDataSet>(new SessionDataSet(
- "", resp.columns, resp.dataTypeList, resp.columnNameIndexMap, resp.queryId, statementId,
- client, sessionId, resp.queryResult, resp.ignoreTimeStamp, connectionTimeoutInMs,
- resp.moreData, fetchSize, zoneId, timeFactor, resp.columnIndex2TsBlockColumnIndexList));
+ return createSessionDataSet("", resp.columns, resp.dataTypeList, resp.columnNameIndexMap,
+ resp.queryId, statementId, client, sessionId, resp.queryResult,
+ resp.ignoreTimeStamp, connectionTimeoutInMs, resp.moreData, fetchSize,
+ zoneId, timeFactor, resp.columnIndex2TsBlockColumnIndexList);
}
void SessionConnection::executeNonQueryStatement(const string& sql) {
diff --git a/iotdb-client/client-cpp/src/main/SessionConnection.h b/iotdb-client/client-cpp/src/rpc/SessionConnection.h
similarity index 93%
rename from iotdb-client/client-cpp/src/main/SessionConnection.h
rename to iotdb-client/client-cpp/src/rpc/SessionConnection.h
index 45d1b55cc56..472e29fd665 100644
--- a/iotdb-client/client-cpp/src/main/SessionConnection.h
+++ b/iotdb-client/client-cpp/src/rpc/SessionConnection.h
@@ -31,17 +31,21 @@
#include "common_types.h"
#include "NodesSupplier.h"
#include "Common.h"
+#include "RpcCommon.h"
+#include "Session.h"
+#include "SessionConfig.h"
class SessionDataSet;
-class Session;
class SessionConnection : public std::enable_shared_from_this<SessionConnection> {
public:
- SessionConnection(Session* session_ptr, const TEndPoint& endpoint, const std::string& zoneId,
- std::shared_ptr<INodesSupplier> nodeSupplier, int fetchSize = 10000,
- int maxRetries = 3, int64_t retryInterval = 500,
- int64_t connectionTimeoutMs = 3 * 1000, std::string dialect = "tree",
- std::string db = "");
+ SessionConnection(Session::Impl* session_ptr, const TEndPoint& endpoint,
+ const std::string& zoneId, std::shared_ptr<INodesSupplier> nodeSupplier,
+ int fetchSize = iotdb::session::DEFAULT_FETCH_SIZE,
+ int maxRetries = iotdb::session::DEFAULT_MAX_RETRIES,
+ int64_t retryInterval = iotdb::session::DEFAULT_RETRY_DELAY_MS,
+ int64_t connectionTimeoutMs = iotdb::session::DEFAULT_CONNECT_TIMEOUT_MS,
+ std::string dialect = "tree", std::string db = "");
~SessionConnection();
@@ -183,9 +187,9 @@ private:
std::shared_ptr<apache::thrift::transport::TSSLSocketFactory> socketFactory_ =
std::make_shared<apache::thrift::transport::TSSLSocketFactory>();
#endif
- std::shared_ptr<TTransport> transport;
+ std::shared_ptr<apache::thrift::transport::TTransport> transport;
std::shared_ptr<IClientRPCServiceClient> client;
- Session* session;
+ Session::Impl* session;
int64_t sessionId;
int64_t statementId;
int64_t connectionTimeoutInMs;
diff --git a/iotdb-client/client-cpp/src/rpc/SessionDataSetFactory.h b/iotdb-client/client-cpp/src/rpc/SessionDataSetFactory.h
new file mode 100644
index 00000000000..520aaf0f520
--- /dev/null
+++ b/iotdb-client/client-cpp/src/rpc/SessionDataSetFactory.h
@@ -0,0 +1,42 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef IOTDB_SESSION_DATA_SET_FACTORY_H
+#define IOTDB_SESSION_DATA_SET_FACTORY_H
+
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "IClientRPCService.h"
+
+class SessionDataSet;
+
+std::unique_ptr<SessionDataSet>
+createSessionDataSet(const std::string& sql, const std::vector<std::string>& columnNameList,
+ const std::vector<std::string>& columnTypeList,
+ const std::map<std::string, int32_t>& columnNameIndex, int64_t queryId,
+ int64_t statementId, std::shared_ptr<IClientRPCServiceClient> client,
+ int64_t sessionId, const std::vector<std::string>& queryResult,
+ bool ignoreTimestamp, int64_t timeout, bool moreData, int32_t fetchSize,
+ const std::string& zoneId, int32_t timeFactor,
+ std::vector<int32_t>& columnIndex2TsBlockColumnIndexList);
+
+#endif
diff --git a/iotdb-client/client-cpp/src/rpc/SessionImpl.h b/iotdb-client/client-cpp/src/rpc/SessionImpl.h
new file mode 100644
index 00000000000..4d14c99f381
--- /dev/null
+++ b/iotdb-client/client-cpp/src/rpc/SessionImpl.h
@@ -0,0 +1,231 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef IOTDB_SESSION_IMPL_H
+#define IOTDB_SESSION_IMPL_H
+
+#include <functional>
+#include <future>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "AbstractSessionBuilder.h"
+#include "Common.h"
+#include "DeviceID.h"
+#include "Endpoint.h"
+#include "NodesSupplier.h"
+#include "Session.h"
+#include "SessionConnection.h"
+#include "ThriftConvert.h"
+#include "client_types.h"
+#include "common_types.h"
+
+class Session::Impl {
+public:
+ std::string host_;
+ int rpcPort_ = 6667;
+ bool useSSL_ = false;
+ std::string trustCertFilePath_;
+ std::vector<std::string> nodeUrls_;
+ std::string username_ = "root";
+ std::string password_ = "root";
+ const TSProtocolVersion::type protocolVersion_ = TSProtocolVersion::IOTDB_SERVICE_PROTOCOL_V3;
+ bool isClosed_ = true;
+ std::string zoneId_;
+ int fetchSize_ = iotdb::session::DEFAULT_FETCH_SIZE;
+ static const int DEFAULT_TIMEOUT_MS = 0;
+ int connectTimeoutMs_ = iotdb::session::DEFAULT_CONNECT_TIMEOUT_MS;
+ Version::Version version = Version::V_1_0;
+ std::string sqlDialect_ = "tree";
+ std::string database_;
+ bool enableAutoFetch_ = true;
+ bool enableRedirection_ = true;
+ std::shared_ptr<INodesSupplier> nodesSupplier_;
+ std::shared_ptr<SessionConnection> defaultSessionConnection_;
+
+ TEndPoint defaultEndPoint_;
+
+ struct TEndPointHash {
+ size_t operator()(const TEndPoint& endpoint) const {
+ return std::hash<std::string>()(endpoint.ip) ^ std::hash<int>()(endpoint.port);
+ }
+ };
+
+ struct TEndPointEqual {
+ bool operator()(const TEndPoint& lhs, const TEndPoint& rhs) const {
+ return lhs.ip == rhs.ip && lhs.port == rhs.port;
+ }
+ };
+
+ using EndPointSessionMap = std::unordered_map<TEndPoint, std::shared_ptr<SessionConnection>,
+ TEndPointHash, TEndPointEqual>;
+ EndPointSessionMap endPointToSessionConnection;
+ std::unordered_map<std::string, TEndPoint> deviceIdToEndpoint;
+ std::unordered_map<std::shared_ptr<storage::IDeviceID>, TEndPoint> tableModelDeviceIdToEndpoint;
+
+ void removeBrokenSessionConnection(std::shared_ptr<SessionConnection> sessionConnection);
+
+ static bool checkSorted(const Tablet& tablet);
+ static bool checkSorted(const std::vector<int64_t>& times);
+ static void sortTablet(Tablet& tablet);
+ static void sortIndexByTimestamp(int* index, std::vector<int64_t>& timestamps, int length);
+
+ void appendValues(std::string& buffer, const char* value, int size);
+ void putValuesIntoBuffer(const std::vector<TSDataType::TSDataType>& types,
+ const std::vector<char*>& values, std::string& buf);
+ int8_t getDataTypeNumber(TSDataType::TSDataType type);
+
+ struct TsCompare {
+ std::vector<int64_t>& timestamps;
+ explicit TsCompare(std::vector<int64_t>& inTimestamps) : timestamps(inTimestamps) {}
+ bool operator()(int i, int j) {
+ return timestamps[i] < timestamps[j];
+ }
+ };
+
+ std::string getVersionString(Version::Version version);
+
+ void initZoneId();
+ void initNodesSupplier(const std::vector<std::string>& nodeUrls = std::vector<std::string>());
+ void initDefaultSessionConnection();
+
+ template <typename T, typename InsertConsumer>
+ void insertByGroup(std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
+ InsertConsumer insertConsumer);
+
+ template <typename T, typename InsertConsumer>
+ void insertOnce(std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
+ InsertConsumer insertConsumer);
+
+ void insertStringRecordsWithLeaderCache(std::vector<std::string> deviceIds,
+ std::vector<int64_t> times,
+ std::vector<std::vector<std::string>> measurementsList,
+ std::vector<std::vector<std::string>> valuesList,
+ bool isAligned);
+
+ void
+ insertRecordsWithLeaderCache(std::vector<std::string> deviceIds, std::vector<int64_t> times,
+ std::vector<std::vector<std::string>> measurementsList,
+ const std::vector<std::vector<TSDataType::TSDataType>>& typesList,
+ std::vector<std::vector<char*>> valuesList, bool isAligned);
+
+ void insertTabletsWithLeaderCache(std::unordered_map<std::string, Tablet*>& tablets, bool sorted,
+ bool isAligned);
+
+ std::shared_ptr<SessionConnection> getQuerySessionConnection();
+ std::shared_ptr<SessionConnection> getSessionConnection(std::string deviceId);
+ std::shared_ptr<SessionConnection>
+ getSessionConnection(std::shared_ptr<storage::IDeviceID> deviceId);
+
+ void handleQueryRedirection(TEndPoint endPoint);
+ void handleRedirection(const std::string& deviceId, TEndPoint endPoint);
+ void handleRedirection(const std::shared_ptr<storage::IDeviceID>& deviceId, TEndPoint endPoint);
+
+ static void buildInsertTabletReq(TSInsertTabletReq& request, Tablet& tablet, bool sorted);
+ void insertTablet(TSInsertTabletReq request);
+ void insertRelationalTabletOnce(
+ const std::unordered_map<std::shared_ptr<SessionConnection>, Tablet>& relationalTabletGroup,
+ bool sorted);
+ void insertRelationalTabletByGroup(
+ const std::unordered_map<std::shared_ptr<SessionConnection>, Tablet>& relationalTabletGroup,
+ bool sorted);
+};
+
+template <typename T, typename InsertConsumer>
+void Session::Impl::insertByGroup(
+ std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
+ InsertConsumer insertConsumer) {
+ std::vector<std::future<void>> futures;
+
+ for (auto& entry : insertGroup) {
+ auto connection = entry.first;
+ auto& req = entry.second;
+ futures.emplace_back(std::async(std::launch::async, [=, &req]() mutable {
+ try {
+ insertConsumer(connection, req);
+ } catch (const RedirectException& e) {
+ for (const auto& deviceEndPoint : e.deviceEndPointMap) {
+ handleRedirection(deviceEndPoint.first, endpointToThrift(deviceEndPoint.second));
+ }
+ } catch (const IoTDBConnectionException&) {
+ if (endPointToSessionConnection.size() > 1) {
+ removeBrokenSessionConnection(connection);
+ try {
+ insertConsumer(defaultSessionConnection_, req);
+ } catch (const RedirectException&) {
+ }
+ } else {
+ throw;
+ }
+ } catch (const std::exception& e) {
+ log_debug(e.what());
+ throw IoTDBException(e.what());
+ }
+ }));
+ }
+
+ std::string errorMessages;
+ for (auto& f : futures) {
+ try {
+ f.get();
+ } catch (const IoTDBConnectionException&) {
+ throw;
+ } catch (const std::exception& e) {
+ if (!errorMessages.empty()) {
+ errorMessages += ";";
+ }
+ errorMessages += e.what();
+ }
+ }
+
+ if (!errorMessages.empty()) {
+ throw StatementExecutionException(errorMessages);
+ }
+}
+
+template <typename T, typename InsertConsumer>
+void Session::Impl::insertOnce(
+ std::unordered_map<std::shared_ptr<SessionConnection>, T>& insertGroup,
+ InsertConsumer insertConsumer) {
+ auto connection = insertGroup.begin()->first;
+ auto req = insertGroup.begin()->second;
+ try {
+ insertConsumer(connection, req);
+ } catch (const RedirectException& e) {
+ for (const auto& deviceEndPoint : e.deviceEndPointMap) {
+ handleRedirection(deviceEndPoint.first, endpointToThrift(deviceEndPoint.second));
+ }
+ } catch (const IoTDBConnectionException&) {
+ if (endPointToSessionConnection.size() > 1) {
+ removeBrokenSessionConnection(connection);
+ try {
+ insertConsumer(defaultSessionConnection_, req);
+ } catch (const RedirectException&) {
+ }
+ } else {
+ throw;
+ }
+ } catch (const std::exception& e) {
+ log_debug(e.what());
+ throw IoTDBException(e.what());
+ }
+}
+
+#endif
diff --git a/iotdb-client/client-cpp/src/main/ThriftConnection.cpp b/iotdb-client/client-cpp/src/rpc/ThriftConnection.cpp
similarity index 93%
rename from iotdb-client/client-cpp/src/main/ThriftConnection.cpp
rename to iotdb-client/client-cpp/src/rpc/ThriftConnection.cpp
index b02cb03c454..1cc6c5417b2 100644
--- a/iotdb-client/client-cpp/src/main/ThriftConnection.cpp
+++ b/iotdb-client/client-cpp/src/rpc/ThriftConnection.cpp
@@ -19,15 +19,23 @@
#include "ThriftConnection.h"
#include <ctime>
#include <iostream>
+#include <thrift/protocol/TBinaryProtocol.h>
+#include <thrift/protocol/TCompactProtocol.h>
+#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TSocket.h>
+#include <thrift/transport/TTransportException.h>
-#include "Session.h"
+#include "RpcCommon.h"
#include "SessionDataSet.h"
+#include "SessionDataSetFactory.h"
+
+using namespace apache::thrift;
+using namespace apache::thrift::protocol;
+using namespace apache::thrift::transport;
const int ThriftConnection::THRIFT_DEFAULT_BUFFER_SIZE = 4096;
const int ThriftConnection::THRIFT_MAX_FRAME_SIZE = 1048576;
const int ThriftConnection::CONNECTION_TIMEOUT_IN_MS = 1000;
-const int ThriftConnection::DEFAULT_FETCH_SIZE = 10000;
ThriftConnection::ThriftConnection(const TEndPoint& endPoint, int thriftDefaultBufferSize,
int thriftMaxFrameSize, int connectionTimeoutInMs, int fetchSize)
@@ -141,10 +149,10 @@ std::unique_ptr<SessionDataSet> ThriftConnection::executeQueryStatement(const st
throw IoTDBException(e.what());
}
std::shared_ptr<TSQueryDataSet> queryDataSet(new TSQueryDataSet(resp.queryDataSet));
- return std::unique_ptr<SessionDataSet>(new SessionDataSet(
+ return createSessionDataSet(
"", resp.columns, resp.dataTypeList, resp.columnNameIndexMap, resp.queryId, statementId_,
client_, sessionId_, resp.queryResult, resp.ignoreTimeStamp, connectionTimeoutInMs_,
- resp.moreData, fetchSize_, zoneId_, timeFactor_, resp.columnIndex2TsBlockColumnIndexList));
+ resp.moreData, fetchSize_, zoneId_, timeFactor_, resp.columnIndex2TsBlockColumnIndexList);
}
void ThriftConnection::close() {
diff --git a/iotdb-client/client-cpp/src/main/ThriftConnection.h b/iotdb-client/client-cpp/src/rpc/ThriftConnection.h
similarity index 95%
rename from iotdb-client/client-cpp/src/main/ThriftConnection.h
rename to iotdb-client/client-cpp/src/rpc/ThriftConnection.h
index ab094c6608c..28691174031 100644
--- a/iotdb-client/client-cpp/src/main/ThriftConnection.h
+++ b/iotdb-client/client-cpp/src/rpc/ThriftConnection.h
@@ -24,6 +24,7 @@
#include <thrift/transport/TSSLSocket.h>
#endif
#include "IClientRPCService.h"
+#include "SessionConfig.h"
class SessionDataSet;
@@ -32,13 +33,12 @@ public:
static const int THRIFT_DEFAULT_BUFFER_SIZE;
static const int THRIFT_MAX_FRAME_SIZE;
static const int CONNECTION_TIMEOUT_IN_MS;
- static const int DEFAULT_FETCH_SIZE;
explicit ThriftConnection(const TEndPoint& endPoint,
int thriftDefaultBufferSize = THRIFT_DEFAULT_BUFFER_SIZE,
int thriftMaxFrameSize = THRIFT_MAX_FRAME_SIZE,
int connectionTimeoutInMs = CONNECTION_TIMEOUT_IN_MS,
- int fetchSize = DEFAULT_FETCH_SIZE);
+ int fetchSize = iotdb::session::DEFAULT_FETCH_SIZE);
~ThriftConnection();
diff --git a/iotdb-client/client-cpp/src/rpc/ThriftConvert.cpp b/iotdb-client/client-cpp/src/rpc/ThriftConvert.cpp
new file mode 100644
index 00000000000..3dd01e68157
--- /dev/null
+++ b/iotdb-client/client-cpp/src/rpc/ThriftConvert.cpp
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "ThriftConvert.h"
+
+#include "common_types.h"
+
+Status statusFromThrift(const TSStatus& tsStatus) {
+ Status status;
+ status.code = tsStatus.code;
+ status.message = tsStatus.message;
+ return status;
+}
+
+Endpoint endpointFromThrift(const TEndPoint& endPoint) {
+ Endpoint endpoint;
+ endpoint.host = endPoint.ip;
+ endpoint.port = endPoint.port;
+ return endpoint;
+}
+
+TEndPoint endpointToThrift(const Endpoint& endpoint) {
+ TEndPoint endPoint;
+ endPoint.__set_ip(endpoint.host);
+ endPoint.__set_port(endpoint.port);
+ return endPoint;
+}
+
+std::map<std::string, Endpoint>
+endpointMapFromThrift(const std::map<std::string, TEndPoint>& deviceEndPointMap) {
+ std::map<std::string, Endpoint> result;
+ for (const auto& entry : deviceEndPointMap) {
+ result.emplace(entry.first, endpointFromThrift(entry.second));
+ }
+ return result;
+}
+
+std::vector<Endpoint> endpointListFromThrift(const std::vector<TEndPoint>& endPointList) {
+ std::vector<Endpoint> result;
+ result.reserve(endPointList.size());
+ for (const auto& endPoint : endPointList) {
+ result.push_back(endpointFromThrift(endPoint));
+ }
+ return result;
+}
diff --git a/iotdb-client/client-cpp/src/main/TableSession.h b/iotdb-client/client-cpp/src/rpc/ThriftConvert.h
similarity index 50%
rename from iotdb-client/client-cpp/src/main/TableSession.h
rename to iotdb-client/client-cpp/src/rpc/ThriftConvert.h
index d1eecfeeaba..66ce7903634 100644
--- a/iotdb-client/client-cpp/src/main/TableSession.h
+++ b/iotdb-client/client-cpp/src/rpc/ThriftConvert.h
@@ -1,4 +1,4 @@
-/*
+/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -16,31 +16,25 @@
* specific language governing permissions and limitations
* under the License.
*/
+#ifndef IOTDB_THRIFT_CONVERT_H
+#define IOTDB_THRIFT_CONVERT_H
-// This file is a translation of the Java file iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java
+#include <map>
+#include <string>
+#include <vector>
-#ifndef IOTDB_TABLESESSION_H
-#define IOTDB_TABLESESSION_H
+#include "Endpoint.h"
+#include "Status.h"
-#include "Session.h"
+class TEndPoint;
+class TSStatus;
-class TableSession {
-private:
- std::shared_ptr<Session> session_;
- string getDatabase();
+Status statusFromThrift(const TSStatus& tsStatus);
+Endpoint endpointFromThrift(const TEndPoint& endPoint);
+TEndPoint endpointToThrift(const Endpoint& endpoint);
-public:
- TableSession(std::shared_ptr<Session> session) {
- this->session_ = session;
- }
- ~TableSession() {}
+std::map<std::string, Endpoint>
+endpointMapFromThrift(const std::map<std::string, TEndPoint>& deviceEndPointMap);
+std::vector<Endpoint> endpointListFromThrift(const std::vector<TEndPoint>& endPointList);
- void insert(Tablet& tablet, bool sorted = false);
- void executeNonQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql);
- unique_ptr<SessionDataSet> executeQueryStatement(const std::string& sql, int64_t timeoutInMs);
- void open(bool enableRPCCompression = false);
- void close();
-};
-
-#endif // IOTDB_TABLESESSION_H
\ No newline at end of file
+#endif
diff --git a/iotdb-client/client-cpp/src/main/Column.cpp b/iotdb-client/client-cpp/src/session/Column.cpp
similarity index 100%
rename from iotdb-client/client-cpp/src/main/Column.cpp
rename to iotdb-client/client-cpp/src/session/Column.cpp
diff --git a/iotdb-client/client-cpp/src/main/ColumnDecoder.cpp b/iotdb-client/client-cpp/src/session/ColumnDecoder.cpp
similarity index 100%
rename from iotdb-client/client-cpp/src/main/ColumnDecoder.cpp
rename to iotdb-client/client-cpp/src/session/ColumnDecoder.cpp
diff --git a/iotdb-client/client-cpp/src/main/Common.cpp b/iotdb-client/client-cpp/src/session/Common.cpp
similarity index 52%
rename from iotdb-client/client-cpp/src/main/Common.cpp
rename to iotdb-client/client-cpp/src/session/Common.cpp
index 842150241da..859a8209a11 100644
--- a/iotdb-client/client-cpp/src/main/Common.cpp
+++ b/iotdb-client/client-cpp/src/session/Common.cpp
@@ -18,9 +18,13 @@
*/
#include "Common.h"
-#include <boost/date_time/gregorian/gregorian.hpp>
+
+#include <cstring>
+#include <ctime>
#include <typeinfo>
+LogLevelType LOG_LEVEL = LEVEL_WARN;
+
std::string extractExceptionMessage(const std::exception& exception) {
const char* what = exception.what();
if (what != nullptr) {
@@ -45,35 +49,6 @@ std::string extractExceptionMessage(const std::exception_ptr& exceptionPtr) {
}
}
-int32_t parseDateExpressionToInt(const boost::gregorian::date& date) {
- if (date.is_not_a_date()) {
- throw IoTDBException("Date expression is null or empty.");
- }
-
- const int year = date.year();
- if (year < 1000 || year > 9999) {
- throw DateTimeParseException("Year must be between 1000 and 9999.",
- boost::gregorian::to_iso_extended_string(date), 0);
- }
-
- const int64_t result = static_cast<int64_t>(year) * 10000 + date.month() * 100 + date.day();
- if (result > INT32_MAX || result < INT32_MIN) {
- throw DateTimeParseException("Date value overflow. ",
- boost::gregorian::to_iso_extended_string(date), 0);
- }
- return static_cast<int32_t>(result);
-}
-
-boost::gregorian::date parseIntToDate(int32_t dateInt) {
- if (dateInt == EMPTY_DATE_INT) {
- return boost::gregorian::date(boost::date_time::not_a_date_time);
- }
- int year = dateInt / 10000;
- int month = (dateInt % 10000) / 100;
- int day = dateInt % 100;
- return boost::gregorian::date(year, month, day);
-}
-
std::string getTimePrecision(int32_t timeFactor) {
if (timeFactor >= 1000000)
return "us";
@@ -84,7 +59,6 @@ std::string getTimePrecision(int32_t timeFactor) {
std::string formatDatetime(const std::string& format, const std::string& precision,
int64_t timestamp, const std::string& zoneId) {
- // Simplified implementation - in real code you'd use proper timezone handling
std::time_t time = static_cast<std::time_t>(timestamp);
std::tm* tm = std::localtime(&time);
char buffer[80];
@@ -124,144 +98,10 @@ TSDataType::TSDataType getDataTypeByStr(const std::string& typeStr) {
}
std::tm int32ToDate(int32_t value) {
- // Convert days since epoch (1970-01-01) to tm struct
- std::time_t time = static_cast<std::time_t>(value) * 86400; // seconds per day
+ std::time_t time = static_cast<std::time_t>(value) * 86400;
return *std::localtime(&time);
}
-void RpcUtils::verifySuccess(const TSStatus& status) {
- if (status.code == TSStatusCode::MULTIPLE_ERROR) {
- verifySuccess(status.subStatus);
- return;
- }
- if (status.code != TSStatusCode::SUCCESS_STATUS &&
- status.code != TSStatusCode::REDIRECTION_RECOMMEND) {
- throw ExecutionException(to_string(status.code) + ": " + status.message, status);
- }
-}
-
-void RpcUtils::verifySuccessWithRedirection(const TSStatus& status) {
- verifySuccess(status);
- if (status.__isset.redirectNode) {
- throw RedirectException(to_string(status.code) + ": " + status.message, status.redirectNode);
- }
- if (status.__isset.subStatus) {
- auto statusSubStatus = status.subStatus;
- vector<TEndPoint> endPointList(statusSubStatus.size());
- int count = 0;
- for (TSStatus subStatus : statusSubStatus) {
- if (subStatus.__isset.redirectNode) {
- endPointList[count++] = subStatus.redirectNode;
- } else {
- TEndPoint endPoint;
- endPointList[count++] = endPoint;
- }
- }
- if (!endPointList.empty()) {
- throw RedirectException(to_string(status.code) + ": " + status.message, endPointList);
- }
- }
-}
-
-void RpcUtils::verifySuccessWithRedirectionForMultiDevices(const TSStatus& status,
- vector<string> devices) {
- verifySuccess(status);
-
- if (status.code == TSStatusCode::MULTIPLE_ERROR ||
- status.code == TSStatusCode::REDIRECTION_RECOMMEND) {
- map<string, TEndPoint> deviceEndPointMap;
- vector<TSStatus> statusSubStatus;
- for (int i = 0; i < statusSubStatus.size(); i++) {
- TSStatus subStatus = statusSubStatus[i];
- if (subStatus.__isset.redirectNode) {
- deviceEndPointMap.insert(make_pair(devices[i], subStatus.redirectNode));
- }
- }
- throw RedirectException(to_string(status.code) + ": " + status.message, deviceEndPointMap);
- }
-
- if (status.__isset.redirectNode) {
- throw RedirectException(to_string(status.code) + ": " + status.message, status.redirectNode);
- }
- if (status.__isset.subStatus) {
- auto statusSubStatus = status.subStatus;
- vector<TEndPoint> endPointList(statusSubStatus.size());
- int count = 0;
- for (TSStatus subStatus : statusSubStatus) {
- if (subStatus.__isset.redirectNode) {
- endPointList[count++] = subStatus.redirectNode;
- } else {
- TEndPoint endPoint;
- endPointList[count++] = endPoint;
- }
- }
- if (!endPointList.empty()) {
- throw RedirectException(to_string(status.code) + ": " + status.message, endPointList);
- }
- }
-}
-
-void RpcUtils::verifySuccess(const vector<TSStatus>& statuses) {
- for (const TSStatus& status : statuses) {
- if (status.code != TSStatusCode::SUCCESS_STATUS) {
- throw BatchExecutionException(status.message, statuses);
- }
- }
-}
-
-TSStatus RpcUtils::getStatus(TSStatusCode::TSStatusCode tsStatusCode) {
- TSStatus status;
- status.__set_code(tsStatusCode);
- return status;
-}
-
-TSStatus RpcUtils::getStatus(int code, const string& message) {
- TSStatus status;
- status.__set_code(code);
- status.__set_message(message);
- return status;
-}
-
-shared_ptr<TSExecuteStatementResp>
-RpcUtils::getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode) {
- TSStatus status = getStatus(tsStatusCode);
- return getTSExecuteStatementResp(status);
-}
-
-shared_ptr<TSExecuteStatementResp>
-RpcUtils::getTSExecuteStatementResp(TSStatusCode::TSStatusCode tsStatusCode,
- const string& message) {
- TSStatus status = getStatus(tsStatusCode, message);
- return getTSExecuteStatementResp(status);
-}
-
-shared_ptr<TSExecuteStatementResp> RpcUtils::getTSExecuteStatementResp(const TSStatus& status) {
- shared_ptr<TSExecuteStatementResp> resp(new TSExecuteStatementResp());
- TSStatus tsStatus(status);
- resp->__set_status(status);
- return resp;
-}
-
-shared_ptr<TSFetchResultsResp>
-RpcUtils::getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode) {
- TSStatus status = getStatus(tsStatusCode);
- return getTSFetchResultsResp(status);
-}
-
-shared_ptr<TSFetchResultsResp>
-RpcUtils::getTSFetchResultsResp(TSStatusCode::TSStatusCode tsStatusCode,
- const string& appendMessage) {
- TSStatus status = getStatus(tsStatusCode, appendMessage);
- return getTSFetchResultsResp(status);
-}
-
-shared_ptr<TSFetchResultsResp> RpcUtils::getTSFetchResultsResp(const TSStatus& status) {
- shared_ptr<TSFetchResultsResp> resp(new TSFetchResultsResp());
- TSStatus tsStatus(status);
- resp->__set_status(tsStatus);
- return resp;
-}
-
MyStringBuffer::MyStringBuffer() : pos(0) {
checkBigEndian();
}
@@ -287,7 +127,7 @@ int MyStringBuffer::getInt() {
return *(int*)getOrderedByte(4);
}
-boost::gregorian::date MyStringBuffer::getDate() {
+IoTDBDate MyStringBuffer::getDate() {
return parseIntToDate(getInt());
}
@@ -357,7 +197,7 @@ void MyStringBuffer::putInt(int ins) {
putOrderedByte((char*)&ins, 4);
}
-void MyStringBuffer::putDate(boost::gregorian::date date) {
+void MyStringBuffer::putDate(IoTDBDate date) {
putInt(parseDateExpressionToInt(date));
}
@@ -392,7 +232,7 @@ void MyStringBuffer::concat(const std::string& ins) {
}
void MyStringBuffer::checkBigEndian() {
- static int chk = 0x0201; //used to distinguish CPU's type (BigEndian or LittleEndian)
+ static int chk = 0x0201;
isBigEndian = (0x01 != *(char*)(&chk));
}
@@ -432,7 +272,7 @@ BitMap::BitMap(size_t size) {
void BitMap::resize(size_t size) {
this->size = size;
- this->bits.resize((size >> 3) + 1); // equal to "size/8 + 1"
+ this->bits.resize((size >> 3) + 1);
reset();
}
@@ -504,47 +344,3 @@ const std::vector<char>& BitMap::getByteArray() const {
size_t BitMap::getSize() const {
return this->size;
}
-
-const std::string UrlUtils::PORT_SEPARATOR = ":";
-const std::string UrlUtils::ABB_COLON = "[";
-
-TEndPoint UrlUtils::parseTEndPointIpv4AndIpv6Url(const std::string& endPointUrl) {
- TEndPoint endPoint;
-
- // Return default TEndPoint if input is empty
- if (endPointUrl.empty()) {
- return endPoint;
- }
-
- size_t portSeparatorPos = endPointUrl.find_last_of(PORT_SEPARATOR);
-
- // If no port separator found, treat entire string as IP
- if (portSeparatorPos == std::string::npos) {
- endPoint.__set_ip(endPointUrl);
- return endPoint;
- }
-
- // Extract port part
- std::string portStr = endPointUrl.substr(portSeparatorPos + 1);
-
- // Extract IP part
- std::string ip = endPointUrl.substr(0, portSeparatorPos);
-
- // Handle IPv6 addresses with brackets
- if (ip.find(ABB_COLON) != std::string::npos) {
- // Remove surrounding square brackets for IPv6
- if (ip.size() >= 2 && ip.front() == '[' && ip.back() == ']') {
- ip = ip.substr(1, ip.size() - 2);
- }
- }
-
- try {
- int port = std::stoi(portStr);
- endPoint.__set_ip(ip);
- endPoint.__set_port(port);
- } catch (const std::exception& e) {
- endPoint.__set_ip(endPointUrl);
- }
-
- return endPoint;
-}
diff --git a/iotdb-client/client-cpp/src/session/Date.cpp b/iotdb-client/client-cpp/src/session/Date.cpp
new file mode 100644
index 00000000000..91095c250da
--- /dev/null
+++ b/iotdb-client/client-cpp/src/session/Date.cpp
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "Date.h"
+
+#include <climits>
+#include <cstdio>
+#include <string>
+
+#include "Common.h"
+
+std::string IoTDBDate::toIsoExtendedString() const {
+ if (!valid_) {
+ return "";
+ }
+ char buf[16];
+ std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d", year_, month_, day_);
+ return std::string(buf);
+}
+
+int32_t parseDateExpressionToInt(const IoTDBDate& date) {
+ if (date.is_not_a_date()) {
+ throw IoTDBException("Date expression is null or empty.");
+ }
+
+ const int year = date.year();
+ if (year < 1000 || year > 9999) {
+ throw DateTimeParseException("Year must be between 1000 and 9999.", date.toIsoExtendedString(),
+ 0);
+ }
+
+ const int64_t result = static_cast<int64_t>(year) * 10000 + date.month() * 100 + date.day();
+ if (result > INT32_MAX || result < INT32_MIN) {
+ throw DateTimeParseException("Date value overflow. ", date.toIsoExtendedString(), 0);
+ }
... 20062 lines suppressed ...