You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@arrow.apache.org by li...@apache.org on 2024/03/25 21:26:21 UTC
(arrow-adbc) branch main updated: refactor(c/driver/sqlite): port to driver base (#1603)
This is an automated email from the ASF dual-hosted git repository.
lidavidm pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-adbc.git
The following commit(s) were added to refs/heads/main by this push:
new 6ca22c2f6 refactor(c/driver/sqlite): port to driver base (#1603)
6ca22c2f6 is described below
commit 6ca22c2f6a824a872e2f630a35ecac82755a8e6f
Author: David Li <li...@gmail.com>
AuthorDate: Mon Mar 25 17:26:16 2024 -0400
refactor(c/driver/sqlite): port to driver base (#1603)
Fixes #1141.
Fixes #1355.
Fixes #1602.
---
CONTRIBUTING.md | 2 +
LICENSE.txt | 26 +
c/CMakeLists.txt | 3 +
c/cmake_modules/AdbcDefines.cmake | 5 +
c/driver/common/utils.h | 19 -
c/driver/framework/CMakeLists.txt | 44 +
c/driver/framework/base.cc | 160 +
c/driver/framework/base.h | 648 +++
c/driver/framework/base_connection.h | 370 ++
c/driver/framework/base_database.h | 78 +
c/driver/framework/base_statement.h | 413 ++
c/driver/framework/catalog.cc | 263 +
c/driver/framework/catalog.h | 154 +
c/driver/framework/objects.cc | 364 ++
c/driver/framework/objects.h | 40 +
c/driver/framework/status.h | 292 ++
.../src/init.c => c/driver/framework/type_fwd.h | 26 +-
c/driver/postgresql/CMakeLists.txt | 2 +
c/driver/postgresql/connection.cc | 37 +-
c/driver/postgresql/copy/copy_common.h | 2 +
c/driver/postgresql/database.cc | 2 +-
c/driver/postgresql/error.cc | 2 +-
c/driver/postgresql/postgresql.cc | 2 +-
c/driver/postgresql/result_helper.cc | 2 +-
c/driver/postgresql/statement.cc | 4 +-
c/driver/postgresql/statement.h | 2 +-
c/driver/sqlite/CMakeLists.txt | 4 +-
c/driver/sqlite/sqlite.c | 2064 --------
c/driver/sqlite/sqlite.cc | 1482 ++++++
c/driver/sqlite/sqlite_test.cc | 9 +-
c/driver/sqlite/statement_reader.c | 2 +-
c/driver/sqlite/types.h | 64 -
c/driver_manager/adbc_driver_manager_test.cc | 6 +-
c/validation/adbc_validation_connection.cc | 24 +-
c/vendor/fmt/.clang-format | 8 +
c/vendor/fmt/CMakeLists.txt | 453 ++
c/vendor/fmt/CONTRIBUTING.md | 20 +
c/vendor/fmt/ChangeLog.md | 5533 ++++++++++++++++++++
c/vendor/fmt/LICENSE | 27 +
c/vendor/fmt/README.md | 490 ++
c/vendor/fmt/include/fmt/args.h | 235 +
c/vendor/fmt/include/fmt/chrono.h | 2240 ++++++++
c/vendor/fmt/include/fmt/color.h | 643 +++
c/vendor/fmt/include/fmt/compile.h | 535 ++
c/vendor/fmt/include/fmt/core.h | 2969 +++++++++++
c/vendor/fmt/include/fmt/format-inl.h | 1678 ++++++
c/vendor/fmt/include/fmt/format.h | 4535 ++++++++++++++++
c/vendor/fmt/include/fmt/os.h | 455 ++
c/vendor/fmt/include/fmt/ostream.h | 245 +
c/vendor/fmt/include/fmt/printf.h | 675 +++
c/vendor/fmt/include/fmt/ranges.h | 738 +++
c/vendor/fmt/include/fmt/std.h | 537 ++
c/vendor/fmt/include/fmt/xchar.h | 259 +
c/vendor/fmt/src/fmt.cc | 108 +
c/vendor/fmt/src/format.cc | 43 +
c/vendor/fmt/src/os.cc | 402 ++
c/vendor/fmt/support/cmake/FindSetEnv.cmake | 7 +
c/vendor/fmt/support/cmake/JoinPaths.cmake | 26 +
c/vendor/fmt/support/cmake/fmt-config.cmake.in | 7 +
c/vendor/fmt/support/cmake/fmt.pc.in | 11 +
.../src/Makevars.ucrt => c/vendor/vendor_fmt.sh | 25 +-
ci/linux-packages/debian/rules | 6 +-
ci/scripts/cpp_clang_tidy.sh | 1 +
ci/scripts/cpp_test.sh | 8 +-
dev/release/rat_exclude_files.txt | 1 +
glib/test/test-connection.rb | 26 +-
go/adbc/drivermgr/wrapper_sqlite_test.go | 9 +-
license.tpl | 26 +
python/adbc_driver_manager/tests/test_dbapi.py | 2 +-
python/adbc_driver_manager/tests/test_lowlevel.py | 6 +-
r/adbcpostgresql/bootstrap.R | 90 +-
r/adbcpostgresql/src/Makevars.in | 20 +-
r/adbcpostgresql/src/Makevars.ucrt | 19 +-
r/adbcpostgresql/src/Makevars.win | 20 +-
.../src/{ => c/driver}/common/.gitignore | 6 +-
.../driver/framework}/.gitignore | 8 +-
.../src/{common => c/driver/postgresql}/.gitignore | 20 +-
.../driver/postgresql/copy}/.gitignore | 8 +-
.../vendor/fmt/include/fmt}/.gitignore | 20 +-
.../src/{ => c/vendor}/nanoarrow/.gitignore | 4 +-
r/adbcpostgresql/src/{init.c => init.cc} | 2 +
r/adbcsqlite/bootstrap.R | 60 +-
r/adbcsqlite/src/Makevars.in | 15 +-
.../src/c/driver}/common/.gitignore | 3 +-
.../src/c/driver/framework}/.gitignore | 13 +-
.../src/c/driver/sqlite}/.gitignore | 5 +-
.../src/c/vendor/fmt}/.gitignore | 8 +-
.../src/c/vendor/fmt/include/fmt}/.gitignore | 15 +-
.../src/c/vendor/fmt/src}/.gitignore | 5 +-
.../src/c/vendor/fmt/support/cmake}/.gitignore | 6 +-
.../src/c/vendor}/nanoarrow/.gitignore | 3 +-
.../src/c/vendor/sqlite3}/.gitignore | 4 +-
r/adbcsqlite/src/{init.c => init.cc} | 2 +
r/adbcsqlite/src/nanoarrow/.gitignore | 1 +
94 files changed, 27578 insertions(+), 2385 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 986f26a88..7acb111a9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -415,7 +415,9 @@ $ cd go/adbc && go-licenses report ./... \
--ignore github.com/apache/arrow/go/v11 \
--ignore github.com/apache/arrow/go/v12 \
--ignore github.com/apache/arrow/go/v13 \
+ --ignore github.com/apache/arrow/go/v14 \
--ignore github.com/apache/arrow/go/v15 \
+ --ignore github.com/apache/arrow/go/v16 \
--template ../../license.tpl > ../../LICENSE.txt 2> /dev/null
```
diff --git a/LICENSE.txt b/LICENSE.txt
index 49f8560e3..6b1a9f794 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -246,6 +246,32 @@ All rights reserved.
--------------------------------------------------------------------------------
+3rdparty dependency {fmt} is statically linked in certain binary
+distributions, like the Python wheels. {fmt} is under the MIT license:
+
+Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+--------------------------------------------------------------------------------
+
3rdparty dependency Go is statically linked in certain binary distributions,
like the Python wheels. The Go project is under the BSD 3-clause license +
PATENTS weak patent termination clause
diff --git a/c/CMakeLists.txt b/c/CMakeLists.txt
index 21d399eee..06be81426 100644
--- a/c/CMakeLists.txt
+++ b/c/CMakeLists.txt
@@ -28,8 +28,11 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(CTest)
+add_subdirectory(vendor/fmt EXCLUDE_FROM_ALL)
+set_target_properties(fmt PROPERTIES POSITION_INDEPENDENT_CODE ON)
add_subdirectory(vendor/nanoarrow)
add_subdirectory(driver/common)
+add_subdirectory(driver/framework)
if(ADBC_BUILD_TESTS)
add_subdirectory(validation)
diff --git a/c/cmake_modules/AdbcDefines.cmake b/c/cmake_modules/AdbcDefines.cmake
index 8c9c37ee6..4155cd4df 100644
--- a/c/cmake_modules/AdbcDefines.cmake
+++ b/c/cmake_modules/AdbcDefines.cmake
@@ -85,6 +85,7 @@ if(MSVC)
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang"
OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang"
OR CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ # maybe-uninitialized is flaky
set(ADBC_C_CXX_FLAGS_CHECKIN
-Wall
-Wextra
@@ -93,6 +94,10 @@ elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang"
-Wno-unused-parameter)
set(ADBC_C_CXX_FLAGS_PRODUCTION -Wall)
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ list(APPEND ADBC_C_CXX_FLAGS_CHECKIN -Wno-maybe-uninitialized)
+ endif()
+
if(NOT CMAKE_C_FLAGS_DEBUG MATCHES "-O")
string(APPEND CMAKE_C_FLAGS_DEBUG " -Og")
endif()
diff --git a/c/driver/common/utils.h b/c/driver/common/utils.h
index ff75fa720..cab5ddbe2 100644
--- a/c/driver/common/utils.h
+++ b/c/driver/common/utils.h
@@ -119,25 +119,6 @@ AdbcStatusCode BatchToArrayStream(struct ArrowArray* values, struct ArrowSchema*
if (adbc_status_code != ADBC_STATUS_OK) return adbc_status_code; \
} while (0)
-/// \defgroup adbc-connection-utils Connection Utilities
-/// Utilities for implementing connection-related functions for drivers
-///
-/// @{
-AdbcStatusCode AdbcInitConnectionGetInfoSchema(struct ArrowSchema* schema,
- struct ArrowArray* array,
- struct AdbcError* error);
-AdbcStatusCode AdbcConnectionGetInfoAppendString(struct ArrowArray* array,
- uint32_t info_code,
- const char* info_value,
- struct AdbcError* error);
-AdbcStatusCode AdbcConnectionGetInfoAppendInt(struct ArrowArray* array,
- uint32_t info_code, int64_t info_value,
- struct AdbcError* error);
-
-AdbcStatusCode AdbcInitConnectionObjectsSchema(struct ArrowSchema* schema,
- struct AdbcError* error);
-/// @}
-
struct AdbcGetObjectsUsage {
struct ArrowStringView fk_catalog;
struct ArrowStringView fk_db_schema;
diff --git a/c/driver/framework/CMakeLists.txt b/c/driver/framework/CMakeLists.txt
new file mode 100644
index 000000000..50f1dafdd
--- /dev/null
+++ b/c/driver/framework/CMakeLists.txt
@@ -0,0 +1,44 @@
+# 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(FetchContent)
+
+add_library(adbc_driver_framework STATIC base.cc catalog.cc objects.cc)
+adbc_configure_target(adbc_driver_framework)
+set_target_properties(adbc_driver_framework PROPERTIES POSITION_INDEPENDENT_CODE ON)
+target_include_directories(adbc_driver_framework
+ PRIVATE "${REPOSITORY_ROOT}" "${REPOSITORY_ROOT}/c/"
+ "${REPOSITORY_ROOT}/c/vendor")
+target_link_libraries(adbc_driver_framework PUBLIC adbc_driver_common fmt::fmt)
+
+# if(ADBC_BUILD_TESTS)
+# add_test_case(driver_framework_test
+# PREFIX
+# adbc
+# EXTRA_LABELS
+# driver-framework
+# SOURCES
+# utils_test.cc
+# driver_test.cc
+# EXTRA_LINK_LIBS
+# adbc_driver_framework
+# nanoarrow)
+# target_compile_features(adbc-driver-framework-test PRIVATE cxx_std_17)
+# target_include_directories(adbc-driver-framework-test
+# PRIVATE "${REPOSITORY_ROOT}" "${REPOSITORY_ROOT}/c/vendor")
+# adbc_configure_target(adbc-driver-framework-test)
+# endif()
diff --git a/c/driver/framework/base.cc b/c/driver/framework/base.cc
new file mode 100644
index 000000000..ab94caf37
--- /dev/null
+++ b/c/driver/framework/base.cc
@@ -0,0 +1,160 @@
+// 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 "driver/framework/base.h"
+
+namespace adbc::driver {
+Result<bool> Option::AsBool() const {
+ return std::visit(
+ [&](auto&& value) -> Result<bool> {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, std::string>) {
+ if (value == ADBC_OPTION_VALUE_ENABLED) {
+ return true;
+ } else if (value == ADBC_OPTION_VALUE_DISABLED) {
+ return false;
+ }
+ }
+ return status::InvalidArgument("Invalid boolean value {}", *this);
+ },
+ value_);
+}
+
+Result<int64_t> Option::AsInt() const {
+ return std::visit(
+ [&](auto&& value) -> Result<int64_t> {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, int64_t>) {
+ return value;
+ } else if constexpr (std::is_same_v<T, std::string>) {
+ int64_t parsed = 0;
+ auto begin = value.data();
+ auto end = value.data() + value.size();
+ auto result = std::from_chars(begin, end, parsed);
+ if (result.ec != std::errc()) {
+ return status::InvalidArgument("Invalid integer value '{}': not an integer",
+ value);
+ } else if (result.ptr != end) {
+ return status::InvalidArgument("Invalid integer value '{}': trailing data",
+ value);
+ }
+ return parsed;
+ }
+ return status::InvalidArgument("Invalid integer value {}", *this);
+ },
+ value_);
+}
+
+Result<std::string_view> Option::AsString() const {
+ return std::visit(
+ [&](auto&& value) -> Result<std::string_view> {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, std::string>) {
+ return value;
+ }
+ return status::InvalidArgument("Invalid string value {}", *this);
+ },
+ value_);
+}
+
+AdbcStatusCode Option::CGet(char* out, size_t* length, AdbcError* error) const {
+ if (!out || !length) {
+ return status::InvalidArgument("Must provide both out and length to GetOption")
+ .ToAdbc(error);
+ }
+ return std::visit(
+ [&](auto&& value) -> AdbcStatusCode {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, std::string>) {
+ size_t value_size_with_terminator = value.size() + 1;
+ if (*length >= value_size_with_terminator) {
+ std::memcpy(out, value.data(), value.size());
+ out[value.size()] = 0;
+ }
+ *length = value_size_with_terminator;
+ return ADBC_STATUS_OK;
+ } else if constexpr (std::is_same_v<T, Unset>) {
+ return status::NotFound("Unknown option").ToAdbc(error);
+ } else {
+ return status::NotFound("Option value is not a string").ToAdbc(error);
+ }
+ },
+ value_);
+}
+
+AdbcStatusCode Option::CGet(uint8_t* out, size_t* length, AdbcError* error) const {
+ if (!out || !length) {
+ return status::InvalidArgument("Must provide both out and length to GetOption")
+ .ToAdbc(error);
+ }
+ return std::visit(
+ [&](auto&& value) -> AdbcStatusCode {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, std::string> ||
+ std::is_same_v<T, std::vector<uint8_t>>) {
+ if (*length >= value.size()) {
+ std::memcpy(out, value.data(), value.size());
+ }
+ *length = value.size();
+ return ADBC_STATUS_OK;
+ } else if constexpr (std::is_same_v<T, Unset>) {
+ return status::NotFound("Unknown option").ToAdbc(error);
+ } else {
+ return status::NotFound("Option value is not a bytestring").ToAdbc(error);
+ }
+ },
+ value_);
+}
+
+AdbcStatusCode Option::CGet(int64_t* out, AdbcError* error) const {
+ if (!out) {
+ return status::InvalidArgument("Must provide out to GetOption").ToAdbc(error);
+ }
+ return std::visit(
+ [&](auto&& value) -> AdbcStatusCode {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, int64_t>) {
+ *out = value;
+ return ADBC_STATUS_OK;
+ } else if constexpr (std::is_same_v<T, Unset>) {
+ return status::NotFound("Unknown option").ToAdbc(error);
+ } else {
+ return status::NotFound("Option value is not an integer").ToAdbc(error);
+ }
+ },
+ value_);
+}
+
+AdbcStatusCode Option::CGet(double* out, AdbcError* error) const {
+ if (!out) {
+ return status::InvalidArgument("Must provide out to GetOption").ToAdbc(error);
+ }
+ return std::visit(
+ [&](auto&& value) -> AdbcStatusCode {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, double> || std::is_same_v<T, int64_t>) {
+ *out = value;
+ return ADBC_STATUS_OK;
+ } else if constexpr (std::is_same_v<T, Unset>) {
+ return status::NotFound("Unknown option").ToAdbc(error);
+ } else {
+ return status::NotFound("Option value is not a double").ToAdbc(error);
+ }
+ },
+ value_);
+}
+} // namespace adbc::driver
diff --git a/c/driver/framework/base.h b/c/driver/framework/base.h
new file mode 100644
index 000000000..e416f89d0
--- /dev/null
+++ b/c/driver/framework/base.h
@@ -0,0 +1,648 @@
+// 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.
+
+#pragma once
+
+#include <charconv>
+#include <cstring>
+#include <memory>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <type_traits>
+#include <utility>
+#include <variant>
+#include <vector>
+
+#include <adbc.h>
+#include <fmt/core.h>
+#include <fmt/format.h>
+
+#include "driver/common/utils.h"
+#include "driver/framework/status.h"
+
+/// \file base.h ADBC Driver Framework
+///
+/// A base implementation of an ADBC driver that allows easier driver
+/// development by overriding functions. Databases, connections, and
+/// statements can be defined by subclassing the [CRTP][crtp] base classes.
+///
+/// Generally, base classes provide a set of functions that correspond to the
+/// ADBC functions. These should not be directly overridden, as they provide
+/// the core logic and argument checking/error handling. Instead, override
+/// the -Impl functions that are also exposed by base classes.
+///
+/// [crtp]: https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
+namespace adbc::driver {
+
+/// \brief The state of a database/connection/statement.
+enum class LifecycleState {
+ /// \brief New has been called but not Init.
+ kUninitialized,
+ /// \brief Init has been called.
+ kInitialized,
+};
+
+/// \brief A typed option value wrapper. It currently does not attempt
+/// conversion (i.e., getting a double option as a string).
+class Option {
+ public:
+ /// \brief The option is unset.
+ struct Unset {};
+ /// \brief The possible values of an option.
+ using Value = std::variant<Unset, std::string, std::vector<uint8_t>, int64_t, double>;
+
+ Option() : value_(Unset{}) {}
+ /// \brief Construct an option from a C string.
+ /// NULL strings are treated as unset.
+ explicit Option(const char* value)
+ : value_(value ? Value(std::string(value)) : Value{Unset{}}) {}
+ explicit Option(std::string value) : value_(std::move(value)) {}
+ explicit Option(std::vector<uint8_t> value) : value_(std::move(value)) {}
+ explicit Option(double value) : value_(value) {}
+ explicit Option(int64_t value) : value_(value) {}
+
+ const Value& value() const& { return value_; }
+ Value& value() && { return value_; }
+
+ /// \brief Check whether this option is set.
+ bool has_value() const { return !std::holds_alternative<Unset>(value_); }
+
+ /// \brief Try to parse a string value as a boolean.
+ Result<bool> AsBool() const;
+
+ /// \brief Try to parse a string or integer value as an integer.
+ Result<int64_t> AsInt() const;
+
+ /// \brief Get the value if it is a string.
+ Result<std::string_view> AsString() const;
+
+ private:
+ Value value_;
+
+ // Methods used by trampolines to export option values in C below
+ friend class ObjectBase;
+ AdbcStatusCode CGet(char* out, size_t* length, AdbcError* error) const;
+ AdbcStatusCode CGet(uint8_t* out, size_t* length, AdbcError* error) const;
+ AdbcStatusCode CGet(int64_t* out, AdbcError* error) const;
+ AdbcStatusCode CGet(double* out, AdbcError* error) const;
+};
+
+/// \brief Base class for private_data of AdbcDatabase, AdbcConnection, and
+/// AdbcStatement.
+///
+/// This class handles option setting and getting.
+class ObjectBase {
+ public:
+ ObjectBase() = default;
+ virtual ~ObjectBase() = default;
+
+ // Called After zero or more SetOption() calls. The parent is the
+ // private_data of the AdbcDatabase, or AdbcConnection when initializing a
+ // subclass of ConnectionObjectBase, and StatementObjectBase (respectively),
+ // or otherwise nullptr. For example, if you have defined
+ // Driver<MyDatabase, MyConnection, MyStatement>, you can
+ // reinterpret_cast<MyDatabase>(parent) in MyConnection::Init().
+
+ /// \brief Initialize the object.
+ ///
+ /// Called after 0 or more SetOption calls. Generally, you won't need to
+ /// override this directly. Instead, use the typed InitImpl provided by
+ /// DatabaseBase/ConnectionBase/StatementBase.
+ ///
+ /// \param[in] parent A pointer to the AdbcDatabase or AdbcConnection
+ /// implementation as appropriate, or nullptr.
+ virtual AdbcStatusCode Init(void* parent, AdbcError* error) {
+ lifecycle_state_ = LifecycleState::kInitialized;
+ return ADBC_STATUS_OK;
+ }
+
+ /// \brief Finalize the object.
+ ///
+ /// This can be used to return an error if the object is not in a valid
+ /// state (e.g. prevent closing a connection with open statements) or to
+ /// clean up resources when resource cleanup could fail. Infallible
+ /// resource cleanup (e.g. releasing memory) should generally be handled in
+ /// the destructor.
+ ///
+ /// Generally, you won't need to override this directly. Instead, use the
+ /// typed ReleaseImpl provided by DatabaseBase/ConnectionBase/StatementBase.
+ virtual AdbcStatusCode Release(AdbcError* error) { return ADBC_STATUS_OK; }
+
+ /// \brief Get an option value.
+ virtual Result<Option> GetOption(std::string_view key) {
+ Option option(nullptr);
+ return option;
+ }
+
+ /// \brief Set an option value.
+ virtual AdbcStatusCode SetOption(std::string_view key, Option value, AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ protected:
+ LifecycleState lifecycle_state_;
+
+ private:
+ // Let the Driver use these to expose C callables wrapping option setters/getters
+ template <typename DatabaseT, typename ConnectionT, typename StatementT>
+ friend class Driver;
+
+ template <typename T>
+ AdbcStatusCode CSetOption(const char* key, T value, AdbcError* error) {
+ Option option(value);
+ return SetOption(key, std::move(option), error);
+ }
+
+ AdbcStatusCode CSetOptionBytes(const char* key, const uint8_t* value, size_t length,
+ AdbcError* error) {
+ std::vector<uint8_t> cppvalue(value, value + length);
+ Option option(std::move(cppvalue));
+ return SetOption(key, std::move(option), error);
+ }
+
+ template <typename T>
+ AdbcStatusCode CGetOptionStringLike(const char* key, T* value, size_t* length,
+ AdbcError* error) {
+ RAISE_RESULT(error, auto option, GetOption(key));
+ return option.CGet(value, length, error);
+ }
+
+ template <typename T>
+ AdbcStatusCode CGetOptionNumeric(const char* key, T* value, AdbcError* error) {
+ RAISE_RESULT(error, auto option, GetOption(key));
+ return option.CGet(value, error);
+ }
+};
+
+/// Helper for below: given the ADBC type, pick the right driver type.
+template <typename DatabaseT, typename ConnectionT, typename StatementT, typename T>
+struct ResolveObjectTImpl {};
+
+template <typename DatabaseT, typename ConnectionT, typename StatementT>
+struct ResolveObjectTImpl<DatabaseT, ConnectionT, StatementT, struct AdbcDatabase> {
+ using type = DatabaseT;
+};
+template <typename DatabaseT, typename ConnectionT, typename StatementT>
+struct ResolveObjectTImpl<DatabaseT, ConnectionT, StatementT, struct AdbcConnection> {
+ using type = ConnectionT;
+};
+template <typename DatabaseT, typename ConnectionT, typename StatementT>
+struct ResolveObjectTImpl<DatabaseT, ConnectionT, StatementT, struct AdbcStatement> {
+ using type = StatementT;
+};
+
+/// Helper for below: given the ADBC type, pick the right driver type.
+template <typename DatabaseT, typename ConnectionT, typename StatementT, typename T>
+using ResolveObjectT =
+ typename ResolveObjectTImpl<DatabaseT, ConnectionT, StatementT, T>::type;
+
+// Driver authors can declare a template specialization of the Driver class
+// and use it to provide their driver init function. It is possible, but
+// rarely useful, to subclass a driver.
+template <typename DatabaseT, typename ConnectionT, typename StatementT>
+class Driver {
+ public:
+ static AdbcStatusCode Init(int version, void* raw_driver, AdbcError* error) {
+ if (version != ADBC_VERSION_1_0_0 && version != ADBC_VERSION_1_1_0) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ auto* driver = reinterpret_cast<AdbcDriver*>(raw_driver);
+ if (version >= ADBC_VERSION_1_1_0) {
+ std::memset(driver, 0, ADBC_DRIVER_1_1_0_SIZE);
+
+ driver->ErrorGetDetailCount = &CErrorGetDetailCount;
+ driver->ErrorGetDetail = &CErrorGetDetail;
+
+ driver->DatabaseGetOption = &CGetOption<AdbcDatabase>;
+ driver->DatabaseGetOptionBytes = &CGetOptionBytes<AdbcDatabase>;
+ driver->DatabaseGetOptionInt = &CGetOptionInt<AdbcDatabase>;
+ driver->DatabaseGetOptionDouble = &CGetOptionDouble<AdbcDatabase>;
+ driver->DatabaseSetOptionBytes = &CSetOptionBytes<AdbcDatabase>;
+ driver->DatabaseSetOptionInt = &CSetOptionInt<AdbcDatabase>;
+ driver->DatabaseSetOptionDouble = &CSetOptionDouble<AdbcDatabase>;
+
+ driver->ConnectionCancel = &CConnectionCancel;
+ driver->ConnectionGetOption = &CGetOption<AdbcConnection>;
+ driver->ConnectionGetOptionBytes = &CGetOptionBytes<AdbcConnection>;
+ driver->ConnectionGetOptionInt = &CGetOptionInt<AdbcConnection>;
+ driver->ConnectionGetOptionDouble = &CGetOptionDouble<AdbcConnection>;
+ driver->ConnectionGetStatistics = &CConnectionGetStatistics;
+ driver->ConnectionGetStatisticNames = &CConnectionGetStatisticNames;
+ driver->ConnectionSetOptionBytes = &CSetOptionBytes<AdbcConnection>;
+ driver->ConnectionSetOptionInt = &CSetOptionInt<AdbcConnection>;
+ driver->ConnectionSetOptionDouble = &CSetOptionDouble<AdbcConnection>;
+
+ driver->StatementCancel = &CStatementCancel;
+ driver->StatementExecuteSchema = &CStatementExecuteSchema;
+ driver->StatementGetOption = &CGetOption<AdbcStatement>;
+ driver->StatementGetOptionBytes = &CGetOptionBytes<AdbcStatement>;
+ driver->StatementGetOptionInt = &CGetOptionInt<AdbcStatement>;
+ driver->StatementGetOptionDouble = &CGetOptionDouble<AdbcStatement>;
+ driver->StatementSetOptionBytes = &CSetOptionBytes<AdbcStatement>;
+ driver->StatementSetOptionInt = &CSetOptionInt<AdbcStatement>;
+ driver->StatementSetOptionDouble = &CSetOptionDouble<AdbcStatement>;
+ } else {
+ std::memset(driver, 0, ADBC_DRIVER_1_0_0_SIZE);
+ }
+
+ driver->private_data = new Driver();
+ driver->release = &CDriverRelease;
+
+ driver->DatabaseInit = &CDatabaseInit;
+ driver->DatabaseNew = &CNew<AdbcDatabase>;
+ driver->DatabaseRelease = &CRelease<AdbcDatabase>;
+ driver->DatabaseSetOption = &CSetOption<AdbcDatabase>;
+
+ driver->ConnectionCommit = &CConnectionCommit;
+ driver->ConnectionGetInfo = &CConnectionGetInfo;
+ driver->ConnectionGetObjects = &CConnectionGetObjects;
+ driver->ConnectionGetTableSchema = &CConnectionGetTableSchema;
+ driver->ConnectionGetTableTypes = &CConnectionGetTableTypes;
+ driver->ConnectionInit = &CConnectionInit;
+ driver->ConnectionNew = &CNew<AdbcConnection>;
+ driver->ConnectionRelease = &CRelease<AdbcConnection>;
+ driver->ConnectionReadPartition = &CConnectionReadPartition;
+ driver->ConnectionRollback = &CConnectionRollback;
+ driver->ConnectionSetOption = &CSetOption<AdbcConnection>;
+
+ driver->StatementBind = &CStatementBind;
+ driver->StatementBindStream = &CStatementBindStream;
+ driver->StatementExecutePartitions = &CStatementExecutePartitions;
+ driver->StatementExecuteQuery = &CStatementExecuteQuery;
+ driver->StatementGetParameterSchema = &CStatementGetParameterSchema;
+ driver->StatementNew = &CStatementNew;
+ driver->StatementPrepare = &CStatementPrepare;
+ driver->StatementRelease = &CRelease<AdbcStatement>;
+ driver->StatementSetOption = &CSetOption<AdbcStatement>;
+ driver->StatementSetSqlQuery = &CStatementSetSqlQuery;
+ driver->StatementSetSubstraitPlan = &CStatementSetSubstraitPlan;
+
+ return ADBC_STATUS_OK;
+ }
+
+ // Driver trampolines
+ static AdbcStatusCode CDriverRelease(AdbcDriver* driver, AdbcError* error) {
+ auto driver_private = reinterpret_cast<Driver*>(driver->private_data);
+ delete driver_private;
+ driver->private_data = nullptr;
+ return ADBC_STATUS_OK;
+ }
+
+ static int CErrorGetDetailCount(const AdbcError* error) {
+ if (error->vendor_code != ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA) {
+ return 0;
+ }
+
+ auto error_obj = reinterpret_cast<Status*>(error->private_data);
+ return error_obj->CDetailCount();
+ }
+
+ static AdbcErrorDetail CErrorGetDetail(const AdbcError* error, int index) {
+ auto error_obj = reinterpret_cast<Status*>(error->private_data);
+ return error_obj->CDetail(index);
+ }
+
+ // Templatable trampolines
+
+ template <typename T>
+ static AdbcStatusCode CNew(T* obj, AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = new ObjectT();
+ obj->private_data = private_data;
+ return ADBC_STATUS_OK;
+ }
+
+ template <typename T>
+ static AdbcStatusCode CRelease(T* obj, AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ if (obj == nullptr) return ADBC_STATUS_INVALID_STATE;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ if (private_data == nullptr) return ADBC_STATUS_INVALID_STATE;
+ AdbcStatusCode result = private_data->Release(error);
+ if (result != ADBC_STATUS_OK) {
+ return result;
+ }
+
+ delete private_data;
+ obj->private_data = nullptr;
+ return ADBC_STATUS_OK;
+ }
+
+ template <typename T>
+ static AdbcStatusCode CSetOption(T* obj, const char* key, const char* value,
+ AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CSetOption<>(key, value, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CSetOptionBytes(T* obj, const char* key, const uint8_t* value,
+ size_t length, AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->CSetOptionBytes(key, value, length, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CSetOptionInt(T* obj, const char* key, int64_t value,
+ AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CSetOption<>(key, value, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CSetOptionDouble(T* obj, const char* key, double value,
+ AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CSetOption<>(key, value, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CGetOption(T* obj, const char* key, char* value, size_t* length,
+ AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CGetOptionStringLike<>(key, value, length, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CGetOptionBytes(T* obj, const char* key, uint8_t* value,
+ size_t* length, AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CGetOptionStringLike<>(key, value, length, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CGetOptionInt(T* obj, const char* key, int64_t* value,
+ AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CGetOptionNumeric<>(key, value, error);
+ }
+
+ template <typename T>
+ static AdbcStatusCode CGetOptionDouble(T* obj, const char* key, double* value,
+ AdbcError* error) {
+ using ObjectT = ResolveObjectT<DatabaseT, ConnectionT, StatementT, T>;
+ auto private_data = reinterpret_cast<ObjectT*>(obj->private_data);
+ return private_data->template CGetOptionNumeric<>(key, value, error);
+ }
+
+#define CHECK_INIT(DATABASE, ERROR) \
+ if (!(DATABASE) || !(DATABASE)->private_data) { \
+ return status::InvalidState("Database is uninitialized").ToAdbc(ERROR); \
+ }
+
+ // Database trampolines
+ static AdbcStatusCode CDatabaseInit(AdbcDatabase* database, AdbcError* error) {
+ CHECK_INIT(database, error);
+ auto private_data = reinterpret_cast<DatabaseT*>(database->private_data);
+ return private_data->Init(nullptr, error);
+ }
+
+#undef CHECK_INIT
+#define CHECK_INIT(CONNECTION, ERROR) \
+ if (!(CONNECTION) || !(CONNECTION)->private_data) { \
+ return status::InvalidState("Connection is uninitialized").ToAdbc(ERROR); \
+ }
+
+ // Connection trampolines
+ static AdbcStatusCode CConnectionInit(AdbcConnection* connection,
+ AdbcDatabase* database, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ if (!database || !database->private_data) {
+ return status::InvalidState("Database is uninitialized").ToAdbc(error);
+ }
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->Init(database->private_data, error);
+ }
+
+ static AdbcStatusCode CConnectionCancel(AdbcConnection* connection, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->Cancel(error);
+ }
+
+ static AdbcStatusCode CConnectionGetInfo(AdbcConnection* connection,
+ const uint32_t* info_codes,
+ size_t info_codes_length,
+ ArrowArrayStream* out, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->GetInfo(info_codes, info_codes_length, out, error);
+ }
+
+ static AdbcStatusCode CConnectionGetObjects(AdbcConnection* connection, int depth,
+ const char* catalog, const char* db_schema,
+ const char* table_name,
+ const char** table_type,
+ const char* column_name,
+ ArrowArrayStream* out, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->GetObjects(depth, catalog, db_schema, table_name, table_type,
+ column_name, out, error);
+ }
+
+ static AdbcStatusCode CConnectionGetStatistics(
+ AdbcConnection* connection, const char* catalog, const char* db_schema,
+ const char* table_name, char approximate, ArrowArrayStream* out, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->GetStatistics(catalog, db_schema, table_name, approximate, out,
+ error);
+ }
+
+ static AdbcStatusCode CConnectionGetStatisticNames(AdbcConnection* connection,
+ ArrowArrayStream* out,
+ AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->GetStatisticNames(out, error);
+ }
+
+ static AdbcStatusCode CConnectionGetTableSchema(AdbcConnection* connection,
+ const char* catalog,
+ const char* db_schema,
+ const char* table_name,
+ ArrowSchema* schema, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->GetTableSchema(catalog, db_schema, table_name, schema, error);
+ }
+
+ static AdbcStatusCode CConnectionGetTableTypes(AdbcConnection* connection,
+ ArrowArrayStream* out,
+ AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->GetTableTypes(out, error);
+ }
+
+ static AdbcStatusCode CConnectionReadPartition(AdbcConnection* connection,
+ const uint8_t* serialized_partition,
+ size_t serialized_length,
+ ArrowArrayStream* out,
+ AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->ReadPartition(serialized_partition, serialized_length, out,
+ error);
+ }
+
+ static AdbcStatusCode CConnectionCommit(AdbcConnection* connection, AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->Commit(error);
+ }
+
+ static AdbcStatusCode CConnectionRollback(AdbcConnection* connection,
+ AdbcError* error) {
+ CHECK_INIT(connection, error);
+ auto private_data = reinterpret_cast<ConnectionT*>(connection->private_data);
+ return private_data->Rollback(error);
+ }
+
+#undef CHECK_INIT
+#define CHECK_INIT(STATEMENT, ERROR) \
+ if (!(STATEMENT) || !(STATEMENT)->private_data) { \
+ return status::InvalidState("Statement is uninitialized").ToAdbc(ERROR); \
+ }
+
+ // Statement trampolines
+ static AdbcStatusCode CStatementNew(AdbcConnection* connection,
+ AdbcStatement* statement, AdbcError* error) {
+ if (!connection || !connection->private_data) {
+ return status::InvalidState("Connection is uninitialized").ToAdbc(error);
+ }
+ auto private_data = new StatementT();
+ AdbcStatusCode status = private_data->Init(connection->private_data, error);
+ if (status != ADBC_STATUS_OK) {
+ delete private_data;
+ }
+
+ statement->private_data = private_data;
+ return ADBC_STATUS_OK;
+ }
+
+ static AdbcStatusCode CStatementBind(AdbcStatement* statement, ArrowArray* values,
+ ArrowSchema* schema, AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->Bind(values, schema, error);
+ }
+
+ static AdbcStatusCode CStatementBindStream(AdbcStatement* statement,
+ ArrowArrayStream* stream, AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->BindStream(stream, error);
+ }
+
+ static AdbcStatusCode CStatementCancel(AdbcStatement* statement, AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->Cancel(error);
+ }
+
+ static AdbcStatusCode CStatementExecutePartitions(AdbcStatement* statement,
+ struct ArrowSchema* schema,
+ struct AdbcPartitions* partitions,
+ int64_t* rows_affected,
+ AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->ExecutePartitions(schema, partitions, rows_affected, error);
+ }
+
+ static AdbcStatusCode CStatementExecuteQuery(AdbcStatement* statement,
+ ArrowArrayStream* stream,
+ int64_t* rows_affected, AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->ExecuteQuery(stream, rows_affected, error);
+ }
+
+ static AdbcStatusCode CStatementExecuteSchema(AdbcStatement* statement,
+ ArrowSchema* schema, AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->ExecuteSchema(schema, error);
+ }
+
+ static AdbcStatusCode CStatementGetParameterSchema(AdbcStatement* statement,
+ ArrowSchema* schema,
+ AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->GetParameterSchema(schema, error);
+ }
+
+ static AdbcStatusCode CStatementPrepare(AdbcStatement* statement, AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->Prepare(error);
+ }
+
+ static AdbcStatusCode CStatementSetSqlQuery(AdbcStatement* statement, const char* query,
+ AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->SetSqlQuery(query, error);
+ }
+
+ static AdbcStatusCode CStatementSetSubstraitPlan(AdbcStatement* statement,
+ const uint8_t* plan, size_t length,
+ AdbcError* error) {
+ CHECK_INIT(statement, error);
+ auto private_data = reinterpret_cast<StatementT*>(statement->private_data);
+ return private_data->SetSubstraitPlan(plan, length, error);
+ }
+
+#undef CHECK_INIT
+};
+
+} // namespace adbc::driver
+
+/// \brief Formatter for Option values.
+template <>
+struct fmt::formatter<adbc::driver::Option> : fmt::nested_formatter<std::string_view> {
+ auto format(const adbc::driver::Option& option, fmt::format_context& ctx) {
+ return write_padded(ctx, [=](auto out) {
+ return std::visit(
+ [&](auto&& value) {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, adbc::driver::Option::Unset>) {
+ return fmt::format_to(out, "(NULL)");
+ } else if constexpr (std::is_same_v<T, std::string>) {
+ return fmt::format_to(out, "'{}'", value);
+ } else if constexpr (std::is_same_v<T, std::vector<uint8_t>>) {
+ return fmt::format_to(out, "({} bytes)", value.size());
+ } else {
+ return fmt::format_to(out, "{}", value);
+ }
+ },
+ option.value());
+ });
+ }
+};
diff --git a/c/driver/framework/base_connection.h b/c/driver/framework/base_connection.h
new file mode 100644
index 000000000..33d30b3ec
--- /dev/null
+++ b/c/driver/framework/base_connection.h
@@ -0,0 +1,370 @@
+// 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.
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include <adbc.h>
+#include <nanoarrow/nanoarrow.h>
+#include <nanoarrow/nanoarrow.hpp>
+
+#include "driver/common/options.h"
+#include "driver/common/utils.h"
+#include "driver/framework/base.h"
+#include "driver/framework/catalog.h"
+#include "driver/framework/objects.h"
+
+namespace adbc::driver {
+/// \brief The CRTP base implementation of an AdbcConnection.
+///
+/// Derived should override and implement the Impl methods, but not others.
+/// Overridden methods should defer to the superclass version at the end.
+/// (The Base typedef is provided to make this easier.) Derived should also
+/// define a constexpr static symbol called kErrorPrefix that is used to
+/// construct error messages.
+template <typename Derived>
+class ConnectionBase : public ObjectBase {
+ public:
+ using Base = ConnectionBase<Derived>;
+
+ /// \brief Whether autocommit is enabled or not (by default: enabled).
+ enum class AutocommitState {
+ kAutocommit,
+ kTransaction,
+ };
+
+ ConnectionBase() : ObjectBase() {}
+ ~ConnectionBase() = default;
+
+ /// \internal
+ AdbcStatusCode Init(void* parent, AdbcError* error) override {
+ if (auto status = impl().InitImpl(parent); !status.ok()) {
+ return status.ToAdbc(error);
+ }
+ return ObjectBase::Init(parent, error);
+ }
+
+ /// \internal
+ AdbcStatusCode Cancel(AdbcError* error) { return ADBC_STATUS_NOT_IMPLEMENTED; }
+
+ /// \internal
+ AdbcStatusCode Commit(AdbcError* error) {
+ switch (autocommit_) {
+ case AutocommitState::kAutocommit:
+ return status::InvalidState("{} No active transaction, cannot commit",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ case AutocommitState::kTransaction:
+ return impl().CommitImpl().ToAdbc(error);
+ }
+ assert(false);
+ return ADBC_STATUS_INTERNAL;
+ }
+
+ /// \internal
+ AdbcStatusCode GetInfo(const uint32_t* info_codes, size_t info_codes_length,
+ ArrowArrayStream* out, AdbcError* error) {
+ std::vector<uint32_t> codes(info_codes, info_codes + info_codes_length);
+ RAISE_RESULT(error, auto infos, impl().InfoImpl(codes));
+
+ nanoarrow::UniqueSchema schema;
+ nanoarrow::UniqueArray array;
+ RAISE_STATUS(error, AdbcInitConnectionGetInfoSchema(schema.get(), array.get()));
+
+ for (const auto& info : infos) {
+ RAISE_STATUS(
+ error,
+ std::visit(
+ [&](auto&& value) -> Status {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<T, std::string>) {
+ return AdbcConnectionGetInfoAppendString(array.get(), info.code, value);
+ } else if constexpr (std::is_same_v<T, int64_t>) {
+ return AdbcConnectionGetInfoAppendInt(array.get(), info.code, value);
+ } else {
+ static_assert(!sizeof(T), "info value type not implemented");
+ }
+ return status::Ok();
+ },
+ info.value));
+ CHECK_NA(INTERNAL, ArrowArrayFinishElement(array.get()), error);
+ }
+
+ struct ArrowError na_error = {0};
+ CHECK_NA_DETAIL(INTERNAL, ArrowArrayFinishBuildingDefault(array.get(), &na_error),
+ &na_error, error);
+ return BatchToArrayStream(array.get(), schema.get(), out, error);
+ }
+
+ /// \internal
+ AdbcStatusCode GetObjects(int c_depth, const char* catalog, const char* db_schema,
+ const char* table_name, const char** table_type,
+ const char* column_name, ArrowArrayStream* out,
+ AdbcError* error) {
+ const auto catalog_filter =
+ catalog ? std::make_optional(std::string_view(catalog)) : std::nullopt;
+ const auto schema_filter =
+ db_schema ? std::make_optional(std::string_view(db_schema)) : std::nullopt;
+ const auto table_filter =
+ table_name ? std::make_optional(std::string_view(table_name)) : std::nullopt;
+ const auto column_filter =
+ column_name ? std::make_optional(std::string_view(column_name)) : std::nullopt;
+ std::vector<std::string_view> table_type_filter;
+ while (table_type && *table_type) {
+ if (*table_type) {
+ table_type_filter.push_back(std::string_view(*table_type));
+ }
+ table_type++;
+ }
+
+ GetObjectsDepth depth = GetObjectsDepth::kColumns;
+ switch (c_depth) {
+ case ADBC_OBJECT_DEPTH_CATALOGS:
+ depth = GetObjectsDepth::kCatalogs;
+ break;
+ case ADBC_OBJECT_DEPTH_COLUMNS:
+ depth = GetObjectsDepth::kColumns;
+ break;
+ case ADBC_OBJECT_DEPTH_DB_SCHEMAS:
+ depth = GetObjectsDepth::kSchemas;
+ break;
+ case ADBC_OBJECT_DEPTH_TABLES:
+ depth = GetObjectsDepth::kTables;
+ break;
+ default:
+ return status::InvalidArgument("{} GetObjects: invalid depth {}",
+ Derived::kErrorPrefix, c_depth)
+ .ToAdbc(error);
+ }
+
+ RAISE_RESULT(error, auto helper, impl().GetObjectsImpl());
+ nanoarrow::UniqueSchema schema;
+ nanoarrow::UniqueArray array;
+ auto status =
+ BuildGetObjects(helper.get(), depth, catalog_filter, schema_filter, table_filter,
+ column_filter, table_type_filter, schema.get(), array.get());
+ RAISE_STATUS(error, helper->Close());
+ RAISE_STATUS(error, status);
+ return BatchToArrayStream(array.get(), schema.get(), out, error);
+ }
+
+ /// \internal
+ Result<Option> GetOption(std::string_view key) override {
+ if (key == ADBC_CONNECTION_OPTION_AUTOCOMMIT) {
+ switch (autocommit_) {
+ case AutocommitState::kAutocommit:
+ return driver::Option(ADBC_OPTION_VALUE_ENABLED);
+ case AutocommitState::kTransaction:
+ return driver::Option(ADBC_OPTION_VALUE_DISABLED);
+ }
+ } else if (key == ADBC_CONNECTION_OPTION_CURRENT_CATALOG) {
+ UNWRAP_RESULT(auto catalog, impl().GetCurrentCatalogImpl());
+ if (catalog) {
+ return driver::Option(std::move(*catalog));
+ }
+ return driver::Option();
+ } else if (key == ADBC_CONNECTION_OPTION_CURRENT_DB_SCHEMA) {
+ UNWRAP_RESULT(auto schema, impl().GetCurrentSchemaImpl());
+ if (schema) {
+ return driver::Option(std::move(*schema));
+ }
+ return driver::Option();
+ }
+ return Base::GetOption(key);
+ }
+
+ /// \internal
+ AdbcStatusCode GetStatistics(const char* catalog, const char* db_schema,
+ const char* table_name, char approximate,
+ ArrowArrayStream* out, AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ /// \internal
+ AdbcStatusCode GetStatisticNames(ArrowArrayStream* out, AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ /// \internal
+ AdbcStatusCode GetTableSchema(const char* catalog, const char* db_schema,
+ const char* table_name, ArrowSchema* schema,
+ AdbcError* error) {
+ if (!table_name) {
+ return status::InvalidArgument("{} GetTableSchema: must provide table_name",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ }
+ std::memset(schema, 0, sizeof(*schema));
+ std::optional<std::string_view> catalog_param =
+ catalog ? std::make_optional(std::string_view(catalog)) : std::nullopt;
+ std::optional<std::string_view> db_schema_param =
+ db_schema ? std::make_optional(std::string_view(db_schema)) : std::nullopt;
+ std::string_view table_name_param = table_name;
+
+ return impl()
+ .GetTableSchemaImpl(catalog_param, db_schema_param, table_name_param, schema)
+ .ToAdbc(error);
+ }
+
+ /// \internal
+ AdbcStatusCode GetTableTypes(ArrowArrayStream* out, AdbcError* error) {
+ RAISE_RESULT(error, std::vector<std::string> table_types, impl().GetTableTypesImpl());
+
+ nanoarrow::UniqueArray array;
+ nanoarrow::UniqueSchema schema;
+ ArrowSchemaInit(schema.get());
+
+ CHECK_NA(INTERNAL, ArrowSchemaSetType(schema.get(), NANOARROW_TYPE_STRUCT), error);
+ CHECK_NA(INTERNAL, ArrowSchemaAllocateChildren(schema.get(), /*num_columns=*/1),
+ error);
+ ArrowSchemaInit(schema.get()->children[0]);
+ CHECK_NA(INTERNAL,
+ ArrowSchemaSetType(schema.get()->children[0], NANOARROW_TYPE_STRING), error);
+ CHECK_NA(INTERNAL, ArrowSchemaSetName(schema.get()->children[0], "table_type"),
+ error);
+ schema.get()->children[0]->flags &= ~ARROW_FLAG_NULLABLE;
+
+ CHECK_NA(INTERNAL, ArrowArrayInitFromSchema(array.get(), schema.get(), NULL), error);
+ CHECK_NA(INTERNAL, ArrowArrayStartAppending(array.get()), error);
+
+ for (std::string const& table_type : table_types) {
+ CHECK_NA(
+ INTERNAL,
+ ArrowArrayAppendString(array->children[0], ArrowCharView(table_type.c_str())),
+ error);
+ CHECK_NA(INTERNAL, ArrowArrayFinishElement(array.get()), error);
+ }
+
+ CHECK_NA(INTERNAL, ArrowArrayFinishBuildingDefault(array.get(), NULL), error);
+
+ return BatchToArrayStream(array.get(), schema.get(), out, error);
+ }
+
+ /// \internal
+ AdbcStatusCode ReadPartition(const uint8_t* serialized_partition,
+ size_t serialized_length, ArrowArrayStream* out,
+ AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ /// \internal
+ AdbcStatusCode Release(AdbcError* error) override {
+ return impl().ReleaseImpl().ToAdbc(error);
+ }
+
+ /// \internal
+ AdbcStatusCode Rollback(AdbcError* error) {
+ switch (autocommit_) {
+ case AutocommitState::kAutocommit:
+ return status::InvalidState("{} No active transaction, cannot rollback",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ case AutocommitState::kTransaction:
+ return impl().RollbackImpl().ToAdbc(error);
+ }
+ assert(false);
+ return ADBC_STATUS_INTERNAL;
+ }
+
+ /// \internal
+ AdbcStatusCode SetOption(std::string_view key, Option value,
+ AdbcError* error) override {
+ return impl().SetOptionImpl(key, value).ToAdbc(error);
+ }
+
+ /// \brief Commit the current transaction and begin a new transaction.
+ ///
+ /// Only called when autocommit is disabled.
+ Status CommitImpl() { return status::NotImplemented("Commit"); }
+
+ Result<std::optional<std::string>> GetCurrentCatalogImpl() { return std::nullopt; }
+
+ Result<std::optional<std::string>> GetCurrentSchemaImpl() { return std::nullopt; }
+
+ /// \brief Query the database catalog.
+ ///
+ /// The default implementation assumes the underlying database allows
+ /// querying the catalog in a certain manner, embodied in the helper class
+ /// returned here. If the database can directly implement GetObjects, then
+ /// directly override GetObjects instead of using this helper.
+ Result<std::unique_ptr<GetObjectsHelper>> GetObjectsImpl() {
+ return std::make_unique<GetObjectsHelper>();
+ }
+
+ Status GetTableSchemaImpl(std::optional<std::string_view> catalog,
+ std::optional<std::string_view> db_schema,
+ std::string_view table_name, ArrowSchema* schema) {
+ return status::NotImplemented("GetTableSchema");
+ }
+
+ Result<std::vector<std::string>> GetTableTypesImpl() {
+ return std::vector<std::string>();
+ }
+
+ Result<std::vector<InfoValue>> InfoImpl(const std::vector<uint32_t>& codes) {
+ return std::vector<InfoValue>{};
+ }
+
+ Status InitImpl(void* parent) { return status::Ok(); }
+
+ Status ReleaseImpl() { return status::Ok(); }
+
+ Status RollbackImpl() { return status::NotImplemented("Rollback"); }
+
+ Status SetOptionImpl(std::string_view key, Option value) {
+ if (key == ADBC_CONNECTION_OPTION_AUTOCOMMIT) {
+ UNWRAP_RESULT(auto enabled, value.AsBool());
+ switch (autocommit_) {
+ case AutocommitState::kAutocommit: {
+ if (!enabled) {
+ UNWRAP_STATUS(impl().ToggleAutocommitImpl(false));
+ autocommit_ = AutocommitState::kTransaction;
+ }
+ break;
+ }
+ case AutocommitState::kTransaction: {
+ if (enabled) {
+ UNWRAP_STATUS(impl().ToggleAutocommitImpl(true));
+ autocommit_ = AutocommitState::kAutocommit;
+ }
+ break;
+ }
+ }
+ return status::Ok();
+ }
+ return status::NotImplemented("{} Unknown connection option {}={}",
+ Derived::kErrorPrefix, key, value);
+ }
+
+ Status ToggleAutocommitImpl(bool enable_autocommit) {
+ return status::NotImplemented("{} Cannot change autocommit", Derived::kErrorPrefix);
+ }
+
+ protected:
+ AutocommitState autocommit_ = AutocommitState::kAutocommit;
+
+ private:
+ Derived& impl() { return static_cast<Derived&>(*this); }
+};
+
+} // namespace adbc::driver
diff --git a/c/driver/framework/base_database.h b/c/driver/framework/base_database.h
new file mode 100644
index 000000000..c840fa876
--- /dev/null
+++ b/c/driver/framework/base_database.h
@@ -0,0 +1,78 @@
+// 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.
+
+#pragma once
+
+#include <string_view>
+#include <utility>
+
+#include <adbc.h>
+
+#include "driver/framework/base.h"
+#include "driver/framework/status.h"
+
+namespace adbc::driver {
+/// \brief The CRTP base implementation of an AdbcDatabase.
+///
+/// Derived should override and implement the Impl methods, but not others.
+/// Overridden methods should defer to the superclass version at the end.
+/// (The Base typedef is provided to make this easier.) Derived should also
+/// define a constexpr static symbol called kErrorPrefix that is used to
+/// construct error messages.
+template <typename Derived>
+class DatabaseBase : public ObjectBase {
+ public:
+ using Base = DatabaseBase<Derived>;
+
+ DatabaseBase() : ObjectBase() {}
+ ~DatabaseBase() = default;
+
+ /// \internal
+ AdbcStatusCode Init(void* parent, AdbcError* error) override {
+ if (auto status = impl().InitImpl(); !status.ok()) {
+ return status.ToAdbc(error);
+ }
+ return ObjectBase::Init(parent, error);
+ }
+
+ /// \internal
+ AdbcStatusCode Release(AdbcError* error) override {
+ return impl().ReleaseImpl().ToAdbc(error);
+ }
+
+ /// \internal
+ AdbcStatusCode SetOption(std::string_view key, Option value,
+ AdbcError* error) override {
+ return impl().SetOptionImpl(key, std::move(value)).ToAdbc(error);
+ }
+
+ /// \brief Initialize the database.
+ virtual Status InitImpl() { return status::Ok(); }
+
+ /// \brief Release the database.
+ virtual Status ReleaseImpl() { return status::Ok(); }
+
+ /// \brief Set an option. May be called prior to InitImpl.
+ virtual Status SetOptionImpl(std::string_view key, Option value) {
+ return status::NotImplemented("{} Unknown database option {}={}",
+ Derived::kErrorPrefix, key, value);
+ }
+
+ private:
+ Derived& impl() { return static_cast<Derived&>(*this); }
+};
+} // namespace adbc::driver
diff --git a/c/driver/framework/base_statement.h b/c/driver/framework/base_statement.h
new file mode 100644
index 000000000..3ea7bc5e7
--- /dev/null
+++ b/c/driver/framework/base_statement.h
@@ -0,0 +1,413 @@
+// 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.
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <variant>
+#include <vector>
+
+#include "driver/common/options.h"
+#include "driver/framework/base.h"
+#include "driver/framework/status.h"
+
+namespace adbc::driver {
+
+/// One-value ArrowArrayStream used to unify the implementations of Bind
+struct OneValueStream {
+ struct ArrowSchema schema;
+ struct ArrowArray array;
+
+ static int GetSchema(struct ArrowArrayStream* self, struct ArrowSchema* out) {
+ OneValueStream* stream = static_cast<OneValueStream*>(self->private_data);
+ return ArrowSchemaDeepCopy(&stream->schema, out);
+ }
+ static int GetNext(struct ArrowArrayStream* self, struct ArrowArray* out) {
+ OneValueStream* stream = static_cast<OneValueStream*>(self->private_data);
+ *out = stream->array;
+ stream->array.release = nullptr;
+ return 0;
+ }
+ static const char* GetLastError(struct ArrowArrayStream* self) { return NULL; }
+ static void Release(struct ArrowArrayStream* self) {
+ OneValueStream* stream = static_cast<OneValueStream*>(self->private_data);
+ if (stream->schema.release) {
+ stream->schema.release(&stream->schema);
+ stream->schema.release = nullptr;
+ }
+ if (stream->array.release) {
+ stream->array.release(&stream->array);
+ stream->array.release = nullptr;
+ }
+ delete stream;
+ self->release = nullptr;
+ }
+};
+
+/// \brief A base implementation of a statement.
+template <typename Derived>
+class StatementBase : public ObjectBase {
+ public:
+ using Base = StatementBase<Derived>;
+
+ /// \brief What to do in ingestion when the table does not exist.
+ enum class TableDoesNotExist {
+ kCreate,
+ kFail,
+ };
+
+ /// \brief What to do in ingestion when the table already exists.
+ enum class TableExists {
+ kAppend,
+ kFail,
+ kReplace,
+ };
+
+ /// \brief Statement state: initialized with no set query.
+ struct EmptyState {};
+ /// \brief Statement state: bulk ingestion.
+ struct IngestState {
+ std::optional<std::string> target_catalog;
+ std::optional<std::string> target_schema;
+ std::optional<std::string> target_table;
+ bool temporary = false;
+ TableDoesNotExist table_does_not_exist_ = TableDoesNotExist::kCreate;
+ TableExists table_exists_ = TableExists::kFail;
+ };
+ /// \brief Statement state: prepared statement.
+ struct PreparedState {
+ std::string query;
+ };
+ /// \brief Statement state: ad-hoc query.
+ struct QueryState {
+ std::string query;
+ };
+ /// \brief Statement state: one of the above.
+ using State = std::variant<EmptyState, IngestState, PreparedState, QueryState>;
+
+ StatementBase() : ObjectBase() {
+ std::memset(&bind_parameters_, 0, sizeof(bind_parameters_));
+ }
+ ~StatementBase() = default;
+
+ AdbcStatusCode Bind(ArrowArray* values, ArrowSchema* schema, AdbcError* error) {
+ if (!values || !values->release) {
+ return status::InvalidArgument("{} Bind: must provide non-NULL array",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ } else if (!schema || !schema->release) {
+ return status::InvalidArgument("{} Bind: must provide non-NULL stream",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ }
+ if (bind_parameters_.release) bind_parameters_.release(&bind_parameters_);
+ // Make a one-value stream
+ bind_parameters_.private_data = new OneValueStream{*schema, *values};
+ bind_parameters_.get_schema = &OneValueStream::GetSchema;
+ bind_parameters_.get_next = &OneValueStream::GetNext;
+ bind_parameters_.get_last_error = &OneValueStream::GetLastError;
+ bind_parameters_.release = &OneValueStream::Release;
+ std::memset(values, 0, sizeof(*values));
+ std::memset(schema, 0, sizeof(*schema));
+ return ADBC_STATUS_OK;
+ }
+
+ AdbcStatusCode BindStream(ArrowArrayStream* stream, AdbcError* error) {
+ if (!stream || !stream->release) {
+ return status::InvalidArgument("{} BindStream: must provide non-NULL stream",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ }
+ if (bind_parameters_.release) bind_parameters_.release(&bind_parameters_);
+ // Move stream
+ bind_parameters_ = *stream;
+ std::memset(stream, 0, sizeof(*stream));
+ return ADBC_STATUS_OK;
+ }
+
+ AdbcStatusCode Cancel(AdbcError* error) { return ADBC_STATUS_NOT_IMPLEMENTED; }
+
+ AdbcStatusCode ExecutePartitions(struct ArrowSchema* schema,
+ struct AdbcPartitions* partitions,
+ int64_t* rows_affected, AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ AdbcStatusCode ExecuteQuery(ArrowArrayStream* stream, int64_t* rows_affected,
+ AdbcError* error) {
+ return std::visit(
+ [&](auto&& state) -> AdbcStatusCode {
+ using T = std::decay_t<decltype(state)>;
+ if constexpr (std::is_same_v<T, EmptyState>) {
+ return status::InvalidState(
+ "{} Cannot ExecuteQuery without setting the query",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ } else if constexpr (std::is_same_v<T, IngestState>) {
+ if (stream) {
+ return status::InvalidState("{} Cannot ingest with result set",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ }
+ RAISE_RESULT(error, int64_t rows, impl().ExecuteIngestImpl(state));
+ if (rows_affected) {
+ *rows_affected = rows;
+ }
+ return ADBC_STATUS_OK;
+ } else if constexpr (std::is_same_v<T, PreparedState> ||
+ std::is_same_v<T, QueryState>) {
+ int64_t rows = 0;
+ if (stream) {
+ RAISE_RESULT(error, rows, impl().ExecuteQueryImpl(state, stream));
+ } else {
+ RAISE_RESULT(error, rows, impl().ExecuteUpdateImpl(state));
+ }
+ if (rows_affected) {
+ *rows_affected = rows;
+ }
+ return ADBC_STATUS_OK;
+ } else {
+ static_assert(!sizeof(T), "case not implemented");
+ }
+ },
+ state_);
+ }
+
+ AdbcStatusCode ExecuteSchema(ArrowSchema* schema, AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ AdbcStatusCode GetParameterSchema(struct ArrowSchema* schema, struct AdbcError* error) {
+ return std::visit(
+ [&](auto&& state) -> AdbcStatusCode {
+ using T = std::decay_t<decltype(state)>;
+ if constexpr (std::is_same_v<T, EmptyState>) {
+ return status::InvalidState(
+ "{} Cannot GetParameterSchema without setting the query",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ } else if constexpr (std::is_same_v<T, IngestState>) {
+ return status::InvalidState("{} Cannot GetParameterSchema in bulk ingestion",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ } else if constexpr (std::is_same_v<T, PreparedState>) {
+ return impl().GetParameterSchemaImpl(state, schema).ToAdbc(error);
+ } else if constexpr (std::is_same_v<T, QueryState>) {
+ return status::InvalidState(
+ "{} Cannot GetParameterSchema without calling Prepare",
+ Derived::kErrorPrefix)
+ .ToAdbc(error);
+ } else {
+ static_assert(!sizeof(T), "case not implemented");
+ }
+ },
+ state_);
+ }
+
+ AdbcStatusCode Init(void* parent, AdbcError* error) {
+ lifecycle_state_ = LifecycleState::kInitialized;
+ if (auto status = impl().InitImpl(parent); !status.ok()) {
+ return status.ToAdbc(error);
+ }
+ return ObjectBase::Init(parent, error);
+ }
+
+ AdbcStatusCode Prepare(AdbcError* error) {
+ RAISE_STATUS(error, std::visit(
+ [&](auto&& state) -> Status {
+ using T = std::decay_t<decltype(state)>;
+ if constexpr (std::is_same_v<T, EmptyState>) {
+ return status::InvalidState(
+ "{} Cannot Prepare without setting the query",
+ Derived::kErrorPrefix);
+ } else if constexpr (std::is_same_v<T, IngestState>) {
+ return status::InvalidState(
+ "{} Cannot Prepare without setting the query",
+ Derived::kErrorPrefix);
+ } else if constexpr (std::is_same_v<T, PreparedState>) {
+ // No-op
+ return status::Ok();
+ } else if constexpr (std::is_same_v<T, QueryState>) {
+ UNWRAP_STATUS(impl().PrepareImpl(state));
+ state_ = PreparedState{std::move(state.query)};
+ return status::Ok();
+ } else {
+ static_assert(!sizeof(T), "case not implemented");
+ }
+ },
+ state_));
+ return ADBC_STATUS_OK;
+ }
+
+ AdbcStatusCode Release(AdbcError* error) {
+ if (bind_parameters_.release) {
+ bind_parameters_.release(&bind_parameters_);
+ bind_parameters_.release = nullptr;
+ }
+ return impl().ReleaseImpl().ToAdbc(error);
+ }
+
+ AdbcStatusCode SetOption(std::string_view key, Option value, AdbcError* error) {
+ auto ensure_ingest = [&]() -> IngestState& {
+ if (!std::holds_alternative<IngestState>(state_)) {
+ state_ = IngestState{};
+ }
+ return std::get<IngestState>(state_);
+ };
+ if (key == ADBC_INGEST_OPTION_MODE) {
+ RAISE_RESULT(error, auto mode, value.AsString());
+ if (mode == ADBC_INGEST_OPTION_MODE_APPEND) {
+ auto& state = ensure_ingest();
+ state.table_does_not_exist_ = TableDoesNotExist::kFail;
+ state.table_exists_ = TableExists::kAppend;
+ } else if (mode == ADBC_INGEST_OPTION_MODE_CREATE) {
+ auto& state = ensure_ingest();
+ state.table_does_not_exist_ = TableDoesNotExist::kCreate;
+ state.table_exists_ = TableExists::kFail;
+ } else if (mode == ADBC_INGEST_OPTION_MODE_CREATE_APPEND) {
+ auto& state = ensure_ingest();
+ state.table_does_not_exist_ = TableDoesNotExist::kCreate;
+ state.table_exists_ = TableExists::kAppend;
+ } else if (mode == ADBC_INGEST_OPTION_MODE_REPLACE) {
+ auto& state = ensure_ingest();
+ state.table_does_not_exist_ = TableDoesNotExist::kCreate;
+ state.table_exists_ = TableExists::kReplace;
+ } else {
+ return status::InvalidArgument("{} Invalid ingest mode '{}'",
+ Derived::kErrorPrefix, key, value)
+ .ToAdbc(error);
+ }
+ return ADBC_STATUS_OK;
+ } else if (key == ADBC_INGEST_OPTION_TARGET_CATALOG) {
+ if (value.has_value()) {
+ RAISE_RESULT(error, auto catalog, value.AsString());
+ ensure_ingest().target_catalog = catalog;
+ } else {
+ ensure_ingest().target_catalog = std::nullopt;
+ }
+ return ADBC_STATUS_OK;
+ } else if (key == ADBC_INGEST_OPTION_TARGET_DB_SCHEMA) {
+ if (value.has_value()) {
+ RAISE_RESULT(error, auto schema, value.AsString());
+ ensure_ingest().target_schema = schema;
+ } else {
+ ensure_ingest().target_schema = std::nullopt;
+ }
+ return ADBC_STATUS_OK;
+ } else if (key == ADBC_INGEST_OPTION_TARGET_TABLE) {
+ RAISE_RESULT(error, auto table, value.AsString());
+ ensure_ingest().target_table = table;
+ return ADBC_STATUS_OK;
+ } else if (key == ADBC_INGEST_OPTION_TEMPORARY) {
+ RAISE_RESULT(error, auto temporary, value.AsBool());
+ ensure_ingest().temporary = temporary;
+ return ADBC_STATUS_OK;
+ }
+ return impl().SetOptionImpl(key, value).ToAdbc(error);
+ }
+
+ AdbcStatusCode SetSqlQuery(const char* query, AdbcError* error) {
+ RAISE_STATUS(error, std::visit(
+ [&](auto&& state) -> Status {
+ using T = std::decay_t<decltype(state)>;
+ if constexpr (std::is_same_v<T, EmptyState>) {
+ state_ = QueryState{
+ std::string(query),
+ };
+ return status::Ok();
+ } else if constexpr (std::is_same_v<T, IngestState>) {
+ state_ = QueryState{
+ std::string(query),
+ };
+ return status::Ok();
+ } else if constexpr (std::is_same_v<T, PreparedState>) {
+ state_ = QueryState{
+ std::string(query),
+ };
+ return status::Ok();
+ } else if constexpr (std::is_same_v<T, QueryState>) {
+ state.query = std::string(query);
+ return status::Ok();
+ } else {
+ static_assert(!sizeof(T),
+ "info value type not implemented");
+ }
+ },
+ state_));
+ return ADBC_STATUS_OK;
+ }
+
+ AdbcStatusCode SetSubstraitPlan(const uint8_t* plan, size_t length, AdbcError* error) {
+ return ADBC_STATUS_NOT_IMPLEMENTED;
+ }
+
+ Result<int64_t> ExecuteIngestImpl(IngestState& state) {
+ return status::NotImplemented("{} Bulk ingest is not implemented",
+ Derived::kErrorPrefix);
+ }
+
+ Result<int64_t> ExecuteQueryImpl(PreparedState& state, ArrowArrayStream* stream) {
+ return status::NotImplemented("{} ExecuteQuery is not implemented",
+ Derived::kErrorPrefix);
+ }
+
+ Result<int64_t> ExecuteQueryImpl(QueryState& state, ArrowArrayStream* stream) {
+ return status::NotImplemented("{} ExecuteQuery is not implemented",
+ Derived::kErrorPrefix);
+ }
+
+ Result<int64_t> ExecuteUpdateImpl(PreparedState& state) {
+ return status::NotImplemented("{} ExecuteQuery (update) is not implemented",
+ Derived::kErrorPrefix);
+ }
+
+ Result<int64_t> ExecuteUpdateImpl(QueryState& state) {
+ return status::NotImplemented("{} ExecuteQuery (update) is not implemented",
+ Derived::kErrorPrefix);
+ }
+
+ Status GetParameterSchemaImpl(PreparedState& state, ArrowSchema* schema) {
+ return status::NotImplemented("{} GetParameterSchema is not implemented",
+ Derived::kErrorPrefix);
+ }
+
+ Status InitImpl(void* parent) { return status::Ok(); }
+
+ Status PrepareImpl(QueryState& state) {
+ return status::NotImplemented("{} Prepare is not implemented", Derived::kErrorPrefix);
+ }
+
+ Status ReleaseImpl() { return status::Ok(); }
+
+ Status SetOptionImpl(std::string_view key, Option value) {
+ return status::NotImplemented("{} Unknown statement option {}={}",
+ Derived::kErrorPrefix, key, value);
+ }
+
+ protected:
+ ArrowArrayStream bind_parameters_;
+
+ private:
+ State state_ = State(EmptyState{});
+ Derived& impl() { return static_cast<Derived&>(*this); }
+};
+
+} // namespace adbc::driver
diff --git a/c/driver/framework/catalog.cc b/c/driver/framework/catalog.cc
new file mode 100644
index 000000000..3860ebb9e
--- /dev/null
+++ b/c/driver/framework/catalog.cc
@@ -0,0 +1,263 @@
+// 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 "driver/framework/catalog.h"
+
+#include <nanoarrow/nanoarrow.h>
+
+namespace adbc::driver {
+Status AdbcInitConnectionGetInfoSchema(struct ArrowSchema* schema,
+ struct ArrowArray* array) {
+ ArrowSchemaInit(schema);
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetTypeStruct(schema, /*num_columns=*/2));
+
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(schema->children[0], NANOARROW_TYPE_UINT32));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(schema->children[0], "info_name"));
+ schema->children[0]->flags &= ~ARROW_FLAG_NULLABLE;
+
+ struct ArrowSchema* info_value = schema->children[1];
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetTypeUnion(info_value, NANOARROW_TYPE_DENSE_UNION, 6));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(info_value, "info_value"));
+
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(info_value->children[0], "string_value"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[1], NANOARROW_TYPE_BOOL));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(info_value->children[1], "bool_value"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[2], NANOARROW_TYPE_INT64));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(info_value->children[2], "int64_value"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[3], NANOARROW_TYPE_INT32));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(info_value->children[3], "int32_bitmask"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[4], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(info_value->children[4], "string_list"));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(info_value->children[5], NANOARROW_TYPE_MAP));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(info_value->children[5], "int32_to_int32_list_map"));
+
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(info_value->children[4]->children[0],
+ NANOARROW_TYPE_STRING));
+
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[5]->children[0]->children[0],
+ NANOARROW_TYPE_INT32));
+ info_value->children[5]->children[0]->children[0]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(info_value->children[5]->children[0]->children[1],
+ NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(
+ Internal,
+ ArrowSchemaSetType(info_value->children[5]->children[0]->children[1]->children[0],
+ NANOARROW_TYPE_INT32));
+
+ struct ArrowError na_error = {0};
+ UNWRAP_NANOARROW(na_error, Internal,
+ ArrowArrayInitFromSchema(array, schema, &na_error));
+ UNWRAP_ERRNO(Internal, ArrowArrayStartAppending(array));
+
+ return status::Ok();
+}
+
+Status AdbcConnectionGetInfoAppendString(struct ArrowArray* array, uint32_t info_code,
+ std::string_view info_value) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendUInt(array->children[0], info_code));
+ // Append to type variant
+ struct ArrowStringView value;
+ value.data = info_value.data();
+ value.size_bytes = static_cast<int64_t>(info_value.size());
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(array->children[1]->children[0], value));
+ // Append type code/offset
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishUnionElement(array->children[1], /*type_id=*/0));
+ return status::Ok();
+}
+
+Status AdbcConnectionGetInfoAppendInt(struct ArrowArray* array, uint32_t info_code,
+ int64_t info_value) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendUInt(array->children[0], info_code));
+ // Append to type variant
+ UNWRAP_ERRNO(Internal,
+ ArrowArrayAppendInt(array->children[1]->children[2], info_value));
+ // Append type code/offset
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishUnionElement(array->children[1], /*type_id=*/2));
+ return status::Ok();
+}
+
+Status AdbcInitConnectionObjectsSchema(struct ArrowSchema* schema) {
+ ArrowSchemaInit(schema);
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetTypeStruct(schema, /*num_columns=*/2));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(schema->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(schema->children[0], "catalog_name"));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(schema->children[1], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(schema->children[1], "catalog_db_schemas"));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetTypeStruct(schema->children[1]->children[0], 2));
+
+ struct ArrowSchema* db_schema_schema = schema->children[1]->children[0];
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(db_schema_schema->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(db_schema_schema->children[0], "db_schema_name"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(db_schema_schema->children[1], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(db_schema_schema->children[1], "db_schema_tables"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetTypeStruct(db_schema_schema->children[1]->children[0], 4));
+
+ struct ArrowSchema* table_schema = db_schema_schema->children[1]->children[0];
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(table_schema->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(table_schema->children[0], "table_name"));
+ table_schema->children[0]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(table_schema->children[1], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(table_schema->children[1], "table_type"));
+ table_schema->children[1]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(table_schema->children[2], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(table_schema->children[2], "table_columns"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetTypeStruct(table_schema->children[2]->children[0], 19));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(table_schema->children[3], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(table_schema->children[3], "table_constraints"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetTypeStruct(table_schema->children[3]->children[0], 4));
+
+ struct ArrowSchema* column_schema = table_schema->children[2]->children[0];
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(column_schema->children[0], "column_name"));
+ column_schema->children[0]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[1], NANOARROW_TYPE_INT32));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[1], "ordinal_position"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[2], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(column_schema->children[2], "remarks"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[3], NANOARROW_TYPE_INT16));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[3], "xdbc_data_type"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[4], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[4], "xdbc_type_name"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[5], NANOARROW_TYPE_INT32));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[5], "xdbc_column_size"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[6], NANOARROW_TYPE_INT16));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[6], "xdbc_decimal_digits"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[7], NANOARROW_TYPE_INT16));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[7], "xdbc_num_prec_radix"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[8], NANOARROW_TYPE_INT16));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(column_schema->children[8], "xdbc_nullable"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[9], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[9], "xdbc_column_def"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[10], NANOARROW_TYPE_INT16));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[10], "xdbc_sql_data_type"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[11], NANOARROW_TYPE_INT16));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[11], "xdbc_datetime_sub"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[12], NANOARROW_TYPE_INT32));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[12], "xdbc_char_octet_length"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[13], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[13], "xdbc_is_nullable"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[14], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[14], "xdbc_scope_catalog"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[15], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[15], "xdbc_scope_schema"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[16], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[16], "xdbc_scope_table"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[17], NANOARROW_TYPE_BOOL));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(column_schema->children[17], "xdbc_is_autoincrement"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(column_schema->children[18], NANOARROW_TYPE_BOOL));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(column_schema->children[18],
+ "xdbc_is_generatedcolumn"));
+
+ struct ArrowSchema* constraint_schema = table_schema->children[3]->children[0];
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(constraint_schema->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(constraint_schema->children[0], "constraint_name"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(constraint_schema->children[1], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetName(constraint_schema->children[1], "constraint_type"));
+ constraint_schema->children[1]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(constraint_schema->children[2], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(constraint_schema->children[2],
+ "constraint_column_names"));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(constraint_schema->children[2]->children[0],
+ NANOARROW_TYPE_STRING));
+ constraint_schema->children[2]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(constraint_schema->children[3], NANOARROW_TYPE_LIST));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(constraint_schema->children[3],
+ "constraint_column_usage"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetTypeStruct(constraint_schema->children[3]->children[0], 4));
+
+ struct ArrowSchema* usage_schema = constraint_schema->children[3]->children[0];
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(usage_schema->children[0], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(usage_schema->children[0], "fk_catalog"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(usage_schema->children[1], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(usage_schema->children[1], "fk_db_schema"));
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(usage_schema->children[2], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(usage_schema->children[2], "fk_table"));
+ usage_schema->children[2]->flags &= ~ARROW_FLAG_NULLABLE;
+ UNWRAP_ERRNO(Internal,
+ ArrowSchemaSetType(usage_schema->children[3], NANOARROW_TYPE_STRING));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(usage_schema->children[3], "fk_column_name"));
+ usage_schema->children[3]->flags &= ~ARROW_FLAG_NULLABLE;
+
+ return status::Ok();
+}
+} // namespace adbc::driver
diff --git a/c/driver/framework/catalog.h b/c/driver/framework/catalog.h
new file mode 100644
index 000000000..a415765ca
--- /dev/null
+++ b/c/driver/framework/catalog.h
@@ -0,0 +1,154 @@
+// 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.
+
+#pragma once
+
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <variant>
+#include <vector>
+
+#include <adbc.h>
+
+#include "driver/framework/status.h"
+
+namespace adbc::driver {
+
+/// \defgroup adbc-framework-catalog Catalog Utilities
+/// Utilities for implementing catalog/metadata-related functions.
+///
+/// @{
+
+/// \brief The GetObjects level.
+enum class GetObjectsDepth {
+ kCatalogs,
+ kSchemas,
+ kTables,
+ kColumns,
+};
+
+/// \brief Helper to implement GetObjects.
+struct GetObjectsHelper {
+ virtual ~GetObjectsHelper() = default;
+
+ struct Table {
+ std::string_view name;
+ std::string_view type;
+ };
+
+ struct ColumnXdbc {
+ std::optional<int16_t> xdbc_data_type;
+ std::optional<std::string_view> xdbc_type_name;
+ std::optional<int32_t> xdbc_column_size;
+ std::optional<int16_t> xdbc_decimal_digits;
+ std::optional<int16_t> xdbc_num_prec_radix;
+ std::optional<int16_t> xdbc_nullable;
+ std::optional<std::string_view> xdbc_column_def;
+ std::optional<int16_t> xdbc_sql_data_type;
+ std::optional<int16_t> xdbc_datetime_sub;
+ std::optional<int32_t> xdbc_char_octet_length;
+ std::optional<std::string_view> xdbc_is_nullable;
+ std::optional<std::string_view> xdbc_scope_catalog;
+ std::optional<std::string_view> xdbc_scope_schema;
+ std::optional<std::string_view> xdbc_scope_table;
+ std::optional<bool> xdbc_is_autoincrement;
+ std::optional<bool> xdbc_is_generatedcolumn;
+ };
+
+ struct Column {
+ std::string_view column_name;
+ int32_t ordinal_position;
+ std::optional<std::string_view> remarks;
+ std::optional<ColumnXdbc> xdbc;
+ };
+
+ struct ConstraintUsage {
+ std::optional<std::string_view> catalog;
+ std::optional<std::string_view> schema;
+ std::string_view table;
+ std::string_view column;
+ };
+
+ struct Constraint {
+ std::optional<std::string_view> name;
+ std::string_view type;
+ std::vector<std::string_view> column_names;
+ std::optional<std::vector<ConstraintUsage>> usage;
+ };
+
+ Status Close() { return status::Ok(); }
+
+ /// \brief Fetch all metadata needed. The driver is free to delay loading
+ /// but this gives it a chance to load data up front.
+ virtual Status Load(GetObjectsDepth depth,
+ std::optional<std::string_view> catalog_filter,
+ std::optional<std::string_view> schema_filter,
+ std::optional<std::string_view> table_filter,
+ std::optional<std::string_view> column_filter,
+ const std::vector<std::string_view>& table_types) {
+ return status::NotImplemented("GetObjects");
+ }
+
+ virtual Status LoadCatalogs() {
+ return status::NotImplemented("GetObjects at depth = catalog");
+ };
+
+ virtual Result<std::optional<std::string_view>> NextCatalog() { return std::nullopt; }
+
+ virtual Status LoadSchemas(std::string_view catalog) {
+ return status::NotImplemented("GetObjects at depth = schema");
+ };
+
+ virtual Result<std::optional<std::string_view>> NextSchema() { return std::nullopt; }
+
+ virtual Status LoadTables(std::string_view catalog, std::string_view schema) {
+ return status::NotImplemented("GetObjects at depth = table");
+ };
+
+ virtual Result<std::optional<Table>> NextTable() { return std::nullopt; }
+
+ virtual Status LoadColumns(std::string_view catalog, std::string_view schema,
+ std::string_view table) {
+ return status::NotImplemented("GetObjects at depth = column");
+ };
+
+ virtual Result<std::optional<Column>> NextColumn() { return std::nullopt; }
+
+ virtual Result<std::optional<Constraint>> NextConstraint() { return std::nullopt; }
+};
+
+struct InfoValue {
+ uint32_t code;
+ std::variant<std::string, int64_t> value;
+
+ explicit InfoValue(uint32_t code, std::variant<std::string, int64_t> value)
+ : code(code), value(std::move(value)) {}
+};
+
+Status AdbcInitConnectionGetInfoSchema(struct ArrowSchema* schema,
+ struct ArrowArray* array);
+Status AdbcConnectionGetInfoAppendString(struct ArrowArray* array, uint32_t info_code,
+ std::string_view info_value);
+Status AdbcConnectionGetInfoAppendInt(struct ArrowArray* array, uint32_t info_code,
+ int64_t info_value);
+Status AdbcInitConnectionObjectsSchema(struct ArrowSchema* schema);
+/// @}
+
+} // namespace adbc::driver
diff --git a/c/driver/framework/objects.cc b/c/driver/framework/objects.cc
new file mode 100644
index 000000000..28e33c0c1
--- /dev/null
+++ b/c/driver/framework/objects.cc
@@ -0,0 +1,364 @@
+// 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 "driver/framework/objects.h"
+
+#include <string_view>
+
+#include "driver/framework/catalog.h"
+#include "driver/framework/status.h"
+
+namespace adbc::driver {
+
+namespace {
+/// \brief A helper to convert std::string_view to Nanoarrow's ArrowStringView.
+ArrowStringView ToStringView(std::string_view s) {
+ return {
+ s.data(),
+ static_cast<int64_t>(s.size()),
+ };
+}
+
+/// \brief A helper to append an optional value to an ArrowArray.
+template <typename T>
+Status AppendOptional(ArrowArray* array, std::optional<T> value) {
+ if (!value) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(array, 1));
+ } else if constexpr (std::is_same_v<T, bool>) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendInt(array, *value));
+ } else if constexpr (std::is_same_v<T, int16_t>) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendInt(array, *value));
+ } else if constexpr (std::is_same_v<T, int32_t>) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendInt(array, *value));
+ } else if constexpr (std::is_same_v<T, std::string_view>) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(array, ToStringView(*value)));
+ } else {
+ static_assert(!sizeof(T), "unimplemented type");
+ }
+ return status::Ok();
+}
+
+struct GetObjectsBuilder {
+ GetObjectsBuilder(GetObjectsHelper* helper, GetObjectsDepth depth,
+ std::optional<std::string_view> catalog_filter,
+ std::optional<std::string_view> schema_filter,
+ std::optional<std::string_view> table_filter,
+ std::optional<std::string_view> column_filter,
+ const std::vector<std::string_view>& table_types,
+ struct ArrowSchema* schema, struct ArrowArray* array)
+ : helper(helper),
+ depth(depth),
+ catalog_filter(catalog_filter),
+ schema_filter(schema_filter),
+ table_filter(table_filter),
+ column_filter(column_filter),
+ table_types(table_types),
+ schema(schema),
+ array(array) {
+ na_error = {0};
+ }
+
+ Status Build() {
+ UNWRAP_STATUS(InitArrowArray());
+ UNWRAP_STATUS(helper->Load(depth, catalog_filter, schema_filter, table_filter,
+ column_filter, table_types));
+
+ catalog_name_col = array->children[0];
+ catalog_db_schemas_col = array->children[1];
+ catalog_db_schemas_items = catalog_db_schemas_col->children[0];
+ db_schema_name_col = catalog_db_schemas_items->children[0];
+ db_schema_tables_col = catalog_db_schemas_items->children[1];
+ schema_table_items = db_schema_tables_col->children[0];
+ table_name_col = schema_table_items->children[0];
+ table_type_col = schema_table_items->children[1];
+
+ table_columns_col = schema_table_items->children[2];
+ table_columns_items = table_columns_col->children[0];
+ column_name_col = table_columns_items->children[0];
+ column_position_col = table_columns_items->children[1];
+ column_remarks_col = table_columns_items->children[2];
+
+ table_constraints_col = schema_table_items->children[3];
+ table_constraints_items = table_constraints_col->children[0];
+ constraint_name_col = table_constraints_items->children[0];
+ constraint_type_col = table_constraints_items->children[1];
+
+ constraint_column_names_col = table_constraints_items->children[2];
+ constraint_column_name_col = constraint_column_names_col->children[0];
+
+ constraint_column_usages_col = table_constraints_items->children[3];
+ constraint_column_usage_items = constraint_column_usages_col->children[0];
+ fk_catalog_col = constraint_column_usage_items->children[0];
+ fk_db_schema_col = constraint_column_usage_items->children[1];
+ fk_table_col = constraint_column_usage_items->children[2];
+ fk_column_name_col = constraint_column_usage_items->children[3];
+
+ UNWRAP_STATUS(AppendCatalogs());
+ return FinishArrowArray();
+ }
+
+ private:
+ Status InitArrowArray() {
+ UNWRAP_STATUS(AdbcInitConnectionObjectsSchema(schema));
+ UNWRAP_NANOARROW(na_error, Internal,
+ ArrowArrayInitFromSchema(array, schema, &na_error));
+ UNWRAP_ERRNO(Internal, ArrowArrayStartAppending(array));
+ return status::Ok();
+ }
+
+ Status AppendCatalogs() {
+ UNWRAP_STATUS(helper->LoadCatalogs());
+ while (true) {
+ UNWRAP_RESULT(auto maybe_catalog, helper->NextCatalog());
+ if (!maybe_catalog.has_value()) break;
+
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(catalog_name_col,
+ ToStringView(*maybe_catalog)));
+ if (depth == GetObjectsDepth::kCatalogs) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(catalog_db_schemas_col, 1));
+ } else {
+ UNWRAP_STATUS(AppendSchemas(*maybe_catalog));
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(array));
+ }
+ return status::Ok();
+ }
+
+ Status AppendSchemas(std::string_view catalog) {
+ UNWRAP_STATUS(helper->LoadSchemas(catalog));
+ while (true) {
+ UNWRAP_RESULT(auto maybe_schema, helper->NextSchema());
+ if (!maybe_schema.has_value()) break;
+
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(db_schema_name_col,
+ ToStringView(*maybe_schema)));
+
+ if (depth == GetObjectsDepth::kSchemas) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(db_schema_tables_col, 1));
+ } else {
+ UNWRAP_STATUS(AppendTables(catalog, *maybe_schema));
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(catalog_db_schemas_items));
+ }
+
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(catalog_db_schemas_col));
+ return status::Ok();
+ }
+
+ Status AppendTables(std::string_view catalog, std::string_view schema) {
+ UNWRAP_STATUS(helper->LoadTables(catalog, schema));
+ while (true) {
+ UNWRAP_RESULT(auto maybe_table, helper->NextTable());
+ if (!maybe_table.has_value()) break;
+
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(table_name_col,
+ ToStringView(maybe_table->name)));
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(table_type_col,
+ ToStringView(maybe_table->type)));
+ if (depth == GetObjectsDepth::kTables) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(table_columns_col, 1));
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(table_constraints_col, 1));
+ } else {
+ UNWRAP_STATUS(AppendColumns(catalog, schema, maybe_table->name));
+ UNWRAP_STATUS(AppendConstraints(catalog, schema, maybe_table->name));
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(schema_table_items));
+ }
+
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(db_schema_tables_col));
+ return status::Ok();
+ }
+
+ Status AppendColumns(std::string_view catalog, std::string_view schema,
+ std::string_view table) {
+ UNWRAP_STATUS(helper->LoadColumns(catalog, schema, table));
+ while (true) {
+ UNWRAP_RESULT(auto maybe_column, helper->NextColumn());
+ if (!maybe_column.has_value()) break;
+ const auto& column = *maybe_column;
+
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(column_name_col,
+ ToStringView(column.column_name)));
+ UNWRAP_ERRNO(Internal,
+ ArrowArrayAppendInt(column_position_col, column.ordinal_position));
+ if (column.remarks) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(column_remarks_col,
+ ToStringView(*column.remarks)));
+ } else {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(column_remarks_col, 1));
+ }
+
+ if (column.xdbc) {
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[3],
+ column.xdbc->xdbc_data_type));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[4],
+ column.xdbc->xdbc_type_name));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[5],
+ column.xdbc->xdbc_column_size));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[6],
+ column.xdbc->xdbc_decimal_digits));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[7],
+ column.xdbc->xdbc_num_prec_radix));
+ UNWRAP_STATUS(
+ AppendOptional(table_columns_items->children[8], column.xdbc->xdbc_nullable));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[9],
+ column.xdbc->xdbc_column_def));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[10],
+ column.xdbc->xdbc_sql_data_type));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[11],
+ column.xdbc->xdbc_datetime_sub));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[12],
+ column.xdbc->xdbc_char_octet_length));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[13],
+ column.xdbc->xdbc_is_nullable));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[14],
+ column.xdbc->xdbc_scope_catalog));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[15],
+ column.xdbc->xdbc_scope_schema));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[16],
+ column.xdbc->xdbc_scope_table));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[17],
+ column.xdbc->xdbc_is_autoincrement));
+ UNWRAP_STATUS(AppendOptional(table_columns_items->children[18],
+ column.xdbc->xdbc_is_generatedcolumn));
+ } else {
+ for (auto i = 3; i < 19; i++) {
+ UNWRAP_ERRNO(Internal,
+ ArrowArrayAppendNull(table_columns_items->children[i], 1));
+ }
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(table_columns_items));
+ }
+
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(table_columns_col));
+ return status::Ok();
+ }
+
+ Status AppendConstraints(std::string_view catalog, std::string_view schema,
+ std::string_view table) {
+ while (true) {
+ UNWRAP_RESULT(auto maybe_constraint, helper->NextConstraint());
+ if (!maybe_constraint.has_value()) break;
+ // XXX: copy to make gcc 12.2's -Wmaybe-uninitialized happy (only
+ // happens with optimizations enabled)
+ const auto constraint = *maybe_constraint;
+
+ if (constraint.name) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(constraint_name_col,
+ ToStringView(*constraint.name)));
+ } else {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(constraint_name_col, 1));
+ }
+
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(constraint_type_col,
+ ToStringView(constraint.type)));
+
+ for (const auto& constraint_column_name : constraint.column_names) {
+ UNWRAP_ERRNO(Internal,
+ ArrowArrayAppendString(constraint_column_name_col,
+ ToStringView(constraint_column_name)));
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(constraint_column_names_col));
+
+ if (constraint.usage) {
+ for (const auto& usage : constraint.usage.value()) {
+ if (usage.catalog) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(fk_catalog_col,
+ ToStringView(*usage.catalog)));
+ } else {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(fk_catalog_col, 1));
+ }
+ if (usage.schema) {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(fk_db_schema_col,
+ ToStringView(*usage.schema)));
+ } else {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(fk_db_schema_col, 1));
+ }
+ UNWRAP_ERRNO(Internal,
+ ArrowArrayAppendString(fk_table_col, ToStringView(usage.table)));
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendString(fk_column_name_col,
+ ToStringView(usage.column)));
+
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(constraint_column_usage_items));
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(constraint_column_usages_col));
+ } else {
+ UNWRAP_ERRNO(Internal, ArrowArrayAppendNull(constraint_column_usages_col, 1));
+ }
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(table_constraints_items));
+ }
+
+ UNWRAP_ERRNO(Internal, ArrowArrayFinishElement(table_constraints_col));
+ return status::Ok();
+ }
+
+ Status FinishArrowArray() {
+ UNWRAP_NANOARROW(na_error, Internal,
+ ArrowArrayFinishBuildingDefault(array, &na_error));
+ return status::Ok();
+ }
+
+ GetObjectsHelper* helper;
+ GetObjectsDepth depth;
+ std::optional<std::string_view> catalog_filter;
+ std::optional<std::string_view> schema_filter;
+ std::optional<std::string_view> table_filter;
+ std::optional<std::string_view> column_filter;
+ const std::vector<std::string_view>& table_types;
+ struct ArrowSchema* schema;
+ struct ArrowArray* array;
+ struct ArrowError na_error;
+ struct ArrowArray* catalog_name_col;
+ struct ArrowArray* catalog_db_schemas_col;
+ struct ArrowArray* catalog_db_schemas_items;
+ struct ArrowArray* db_schema_name_col;
+ struct ArrowArray* db_schema_tables_col;
+ struct ArrowArray* schema_table_items;
+ struct ArrowArray* table_name_col;
+ struct ArrowArray* table_type_col;
+ struct ArrowArray* table_columns_col;
+ struct ArrowArray* table_columns_items;
+ struct ArrowArray* column_name_col;
+ struct ArrowArray* column_position_col;
+ struct ArrowArray* column_remarks_col;
+ struct ArrowArray* table_constraints_col;
+ struct ArrowArray* table_constraints_items;
+ struct ArrowArray* constraint_name_col;
+ struct ArrowArray* constraint_type_col;
+ struct ArrowArray* constraint_column_names_col;
+ struct ArrowArray* constraint_column_name_col;
+ struct ArrowArray* constraint_column_usages_col;
+ struct ArrowArray* constraint_column_usage_items;
+ struct ArrowArray* fk_catalog_col;
+ struct ArrowArray* fk_db_schema_col;
+ struct ArrowArray* fk_table_col;
+ struct ArrowArray* fk_column_name_col;
+};
+} // namespace
+
+Status BuildGetObjects(GetObjectsHelper* helper, GetObjectsDepth depth,
+ std::optional<std::string_view> catalog_filter,
+ std::optional<std::string_view> schema_filter,
+ std::optional<std::string_view> table_filter,
+ std::optional<std::string_view> column_filter,
+ const std::vector<std::string_view>& table_types,
+ struct ArrowSchema* schema, struct ArrowArray* array) {
+ return GetObjectsBuilder(helper, depth, catalog_filter, schema_filter, table_filter,
+ column_filter, table_types, schema, array)
+ .Build();
+}
+} // namespace adbc::driver
diff --git a/c/driver/framework/objects.h b/c/driver/framework/objects.h
new file mode 100644
index 000000000..0d14c5c6b
--- /dev/null
+++ b/c/driver/framework/objects.h
@@ -0,0 +1,40 @@
+// 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.
+
+#pragma once
+
+#include <optional>
+#include <string_view>
+#include <vector>
+
+#include <nanoarrow/nanoarrow.h>
+
+#include "driver/framework/catalog.h"
+#include "driver/framework/status.h"
+#include "driver/framework/type_fwd.h"
+
+namespace adbc::driver {
+/// \brief A helper that implements GetObjects.
+/// The schema/array/helper lifetime are caller-managed.
+Status BuildGetObjects(GetObjectsHelper* helper, GetObjectsDepth depth,
+ std::optional<std::string_view> catalog_filter,
+ std::optional<std::string_view> schema_filter,
+ std::optional<std::string_view> table_filter,
+ std::optional<std::string_view> column_filter,
+ const std::vector<std::string_view>& table_types,
+ struct ArrowSchema* schema, struct ArrowArray* array);
+} // namespace adbc::driver
diff --git a/c/driver/framework/status.h b/c/driver/framework/status.h
new file mode 100644
index 000000000..482a9cea3
--- /dev/null
+++ b/c/driver/framework/status.h
@@ -0,0 +1,292 @@
+// 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.
+
+#pragma once
+
+#include <cassert>
+#include <cstring>
+#include <memory>
+#include <string>
+#include <utility>
+#include <variant>
+#include <vector>
+
+#include <adbc.h>
+#include <fmt/core.h>
+
+/// \file status.h
+
+namespace adbc::driver {
+
+/// \brief A wrapper around AdbcStatusCode + AdbcError.
+///
+/// Drivers should prefer to use Status, and convert at the boundaries with
+/// ToAdbc.
+class Status {
+ public:
+ /// \brief Construct an OK status.
+ Status() : impl_(nullptr) {}
+
+ /// \brief Construct a non-OK status with a message.
+ explicit Status(AdbcStatusCode code, std::string message)
+ : Status(code, std::move(message), {}) {}
+
+ /// \brief Construct a non-OK status with a message.
+ explicit Status(AdbcStatusCode code, const char* message)
+ : Status(code, std::string(message), {}) {}
+
+ /// \brief Construct a non-OK status with a message and details.
+ explicit Status(AdbcStatusCode code, std::string message,
+ std::vector<std::pair<std::string, std::string>> details)
+ : impl_(std::make_unique<Impl>(code, std::move(message), std::move(details))) {
+ assert(code != ADBC_STATUS_OK);
+ }
+
+ /// \brief Check if this is an error or not.
+ bool ok() const { return impl_ == nullptr; }
+
+ /// \brief Add another error detail.
+ void AddDetail(std::string key, std::string value) {
+ assert(impl_ != nullptr);
+ impl_->details.push_back({std::move(key), std::move(value)});
+ }
+
+ /// \brief Export this status to an AdbcError.
+ AdbcStatusCode ToAdbc(AdbcError* adbc_error) const {
+ if (impl_ == nullptr) return ADBC_STATUS_OK;
+ if (adbc_error == nullptr) return impl_->code;
+
+ if (adbc_error->release) {
+ adbc_error->release(adbc_error);
+ }
+
+ if (adbc_error->vendor_code == ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA) {
+ auto error_owned_by_adbc_error =
+ new Status(impl_->code, std::move(impl_->message), std::move(impl_->details));
+ adbc_error->message =
+ const_cast<char*>(error_owned_by_adbc_error->impl_->message.c_str());
+ adbc_error->private_data = error_owned_by_adbc_error;
+ } else {
+ adbc_error->message = new char[impl_->message.size() + 1];
+ if (adbc_error->message != nullptr) {
+ std::memcpy(adbc_error->message, impl_->message.c_str(),
+ impl_->message.size() + 1);
+ }
+ }
+
+ std::memcpy(adbc_error->sqlstate, impl_->sql_state, sizeof(impl_->sql_state));
+ adbc_error->release = &CRelease;
+ return impl_->code;
+ }
+
+ static Status FromAdbc(AdbcStatusCode code, AdbcError& error) {
+ // not really meant to be used, just something we have for now while porting
+ if (code == ADBC_STATUS_OK) {
+ if (error.release) {
+ error.release(&error);
+ }
+ return Status();
+ }
+ auto status = Status(code, error.message ? error.message : "(unknown error)");
+ if (error.release) {
+ error.release(&error);
+ }
+ return status;
+ }
+
+ private:
+ struct Impl {
+ // invariant: code is never OK
+ AdbcStatusCode code;
+ std::string message;
+ std::vector<std::pair<std::string, std::string>> details;
+ char sql_state[5];
+
+ explicit Impl(AdbcStatusCode code, std::string message,
+ std::vector<std::pair<std::string, std::string>> details)
+ : code(code), message(std::move(message)), details(std::move(details)) {
+ std::memset(sql_state, 0, sizeof(sql_state));
+ }
+ };
+ // invariant: code is OK iff impl_ is nullptr
+ std::unique_ptr<Impl> impl_;
+
+ // Let the Driver use these to expose C callables wrapping option setters/getters
+ template <typename DatabaseT, typename ConnectionT, typename StatementT>
+ friend class Driver;
+
+ int CDetailCount() const { return impl_ ? impl_->details.size() : 0; }
+
+ AdbcErrorDetail CDetail(int index) const {
+ if (!impl_ || index < 0 || static_cast<size_t>(index) >= impl_->details.size()) {
+ return {nullptr, nullptr, 0};
+ }
+ const auto& detail = impl_->details[index];
+ return {detail.first.c_str(), reinterpret_cast<const uint8_t*>(detail.second.data()),
+ detail.second.size()};
+ }
+
+ static void CRelease(AdbcError* error) {
+ if (error->vendor_code == ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA) {
+ auto* error_obj = reinterpret_cast<Status*>(error->private_data);
+ delete error_obj;
+ std::memset(error, 0, ADBC_ERROR_1_1_0_SIZE);
+ } else {
+ delete[] error->message;
+ std::memset(error, 0, ADBC_ERROR_1_0_0_SIZE);
+ }
+ }
+};
+
+/// \brief A wrapper around a value, or an error.
+///
+/// We could probably do better by using a library like std::expected, but
+/// this will suffice for now. There doesn't seem to be a reasonably
+/// maintained std::expected backport.
+template <typename T>
+class Result {
+ public:
+ /// \brief Implicit constructor to allow returning a status in functions.
+ Result(Status s) // NOLINT(runtime/explicit)
+ : value_(std::move(s)) {
+ assert(!std::get<Status>(value_).ok());
+ }
+ /// \brief Implicit constructor to allow returning a value in functions.
+ template <typename U,
+ // Allow things that can construct T, not just T itself, but
+ // disallow T from being Status so which constructor to use is not
+ // ambiguous.
+ typename E = typename std::enable_if<
+ std::is_constructible<T, U>::value && std::is_convertible<U, T>::value &&
+ !std::is_same<typename std::remove_reference<
+ typename std::remove_cv<U>::type>::type,
+ Status>::value>::type>
+ Result(U&& t) : value_(std::forward<U>(t)) {} // NOLINT(runtime/explicit)
+
+ /// \brief Check if this has a value or not.
+ bool has_value() const { return !std::holds_alternative<Status>(value_); }
+
+ /// \brief Get the status (if present).
+ const Status& status() const& {
+ assert(std::holds_alternative<Status>(value_));
+ return std::get<Status>(value_);
+ }
+
+ /// \brief Move the status (if present).
+ Status&& status() && {
+ assert(std::holds_alternative<Status>(value_));
+ return std::move(std::get<Status>(value_));
+ }
+
+ /// \brief Get the value (if present).
+ T& value() {
+ assert(!std::holds_alternative<Status>(value_));
+ return std::get<T>(value_);
+ }
+
+ private:
+ std::variant<Status, T> value_;
+};
+
+#define RAISE_RESULT_IMPL(NAME, ERROR, LHS, RHS) \
+ auto&& NAME = (RHS); \
+ if (!(NAME).has_value()) { \
+ return (NAME).status().ToAdbc(ERROR); \
+ } \
+ LHS = std::move((NAME).value());
+
+#define RAISE_STATUS_IMPL(NAME, ERROR, RHS) \
+ auto&& NAME = (RHS); \
+ if (!(NAME).ok()) { \
+ return (NAME).ToAdbc(ERROR); \
+ }
+
+#define UNWRAP_RESULT_IMPL(name, lhs, rhs) \
+ auto&& name = (rhs); \
+ if (!(name).has_value()) { \
+ return std::move(name).status(); \
+ } \
+ lhs = std::move((name).value());
+
+#define UNWRAP_STATUS_IMPL(name, rhs) \
+ auto&& name = (rhs); \
+ if (!(name).ok()) { \
+ return std::move(name); \
+ }
+
+#define DRIVER_CONCAT(x, y) x##y
+#define UNWRAP_RESULT_NAME(x, y) DRIVER_CONCAT(x, y)
+
+/// \brief A helper to unwrap a Result in functions returning AdbcStatusCode.
+#define RAISE_RESULT(ERROR, LHS, RHS) \
+ RAISE_RESULT_IMPL(UNWRAP_RESULT_NAME(driver_raise_result, __COUNTER__), ERROR, LHS, RHS)
+/// \brief A helper to unwrap a Status in functions returning AdbcStatusCode.
+#define RAISE_STATUS(ERROR, RHS) \
+ RAISE_STATUS_IMPL(UNWRAP_RESULT_NAME(driver_raise_status, __COUNTER__), ERROR, RHS)
+/// \brief A helper to unwrap a Result in functions returning Result/Status.
+#define UNWRAP_RESULT(lhs, rhs) \
+ UNWRAP_RESULT_IMPL(UNWRAP_RESULT_NAME(driver_unwrap_result, __COUNTER__), lhs, rhs)
+/// \brief A helper to unwrap a Status in functions returning Result/Status.
+#define UNWRAP_STATUS(rhs) \
+ UNWRAP_STATUS_IMPL(UNWRAP_RESULT_NAME(driver_unwrap_status, __COUNTER__), rhs)
+
+} // namespace adbc::driver
+
+namespace adbc::driver::status {
+
+#define STATUS_CTOR(NAME, CODE) \
+ template <typename... Args> \
+ static Status NAME(std::string_view format_string, Args&&... args) { \
+ auto message = fmt::vformat(format_string, fmt::make_format_args(args...)); \
+ return Status(ADBC_STATUS_##CODE, std::move(message)); \
+ }
+
+// TODO: unit tests for internal utilities
+STATUS_CTOR(Internal, INTERNAL)
+STATUS_CTOR(InvalidArgument, INVALID_ARGUMENT)
+STATUS_CTOR(InvalidState, INVALID_STATE)
+STATUS_CTOR(IO, IO)
+STATUS_CTOR(NotFound, NOT_FOUND)
+STATUS_CTOR(NotImplemented, NOT_IMPLEMENTED)
+STATUS_CTOR(Unknown, UNKNOWN)
+
+#undef STATUS_CTOR
+
+inline driver::Status Ok() { return driver::Status(); }
+
+#define UNWRAP_ERRNO_IMPL(NAME, CODE, RHS) \
+ auto&& NAME = (RHS); \
+ if (NAME != 0) { \
+ return adbc::driver::status::CODE("Nanoarrow call failed: {} = ({}) {}", #RHS, NAME, \
+ std::strerror(NAME)); \
+ }
+
+#define UNWRAP_ERRNO(CODE, RHS) \
+ UNWRAP_ERRNO_IMPL(UNWRAP_RESULT_NAME(driver_errno, __COUNTER__), CODE, RHS)
+
+#define UNWRAP_NANOARROW_IMPL(NAME, ERROR, CODE, RHS) \
+ auto&& NAME = (RHS); \
+ if (NAME != 0) { \
+ return adbc::driver::status::CODE("Nanoarrow call failed: {} = ({}) {}. {}", #RHS, \
+ NAME, std::strerror(NAME), (ERROR).message); \
+ }
+
+#define UNWRAP_NANOARROW(ERROR, CODE, RHS) \
+ UNWRAP_NANOARROW_IMPL(UNWRAP_RESULT_NAME(driver_errno_na, __COUNTER__), ERROR, CODE, \
+ RHS)
+
+} // namespace adbc::driver::status
diff --git a/r/adbcsqlite/src/init.c b/c/driver/framework/type_fwd.h
similarity index 51%
copy from r/adbcsqlite/src/init.c
copy to c/driver/framework/type_fwd.h
index fa8a73c84..a7428bd28 100644
--- a/r/adbcsqlite/src/init.c
+++ b/c/driver/framework/type_fwd.h
@@ -15,28 +15,10 @@
// specific language governing permissions and limitations
// under the License.
-#define R_NO_REMAP
-#include <R.h>
-#include <Rinternals.h>
+#pragma once
-#include <adbc.h>
+#include "driver/framework/status.h"
-AdbcStatusCode SqliteDriverInit(int version, void* raw_driver, struct AdbcError* error);
-
-static SEXP init_func_xptr = 0;
-
-SEXP adbcsqlite_c_sqlite(void) { return init_func_xptr; }
-
-static const R_CallMethodDef CallEntries[] = {
- {"adbcsqlite_c_sqlite", (DL_FUNC)&adbcsqlite_c_sqlite, 0}, {NULL, NULL, 0}};
-
-void R_init_adbcsqlite(DllInfo* dll) {
- R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
- R_useDynamicSymbols(dll, FALSE);
-
- init_func_xptr =
- PROTECT(R_MakeExternalPtrFn((DL_FUNC)SqliteDriverInit, R_NilValue, R_NilValue));
- Rf_setAttrib(init_func_xptr, R_ClassSymbol, Rf_mkString("adbc_driver_init_func"));
- R_PreserveObject(init_func_xptr);
- UNPROTECT(1);
+namespace adbc::driver {
+struct GetObjectsHelper;
}
diff --git a/c/driver/postgresql/CMakeLists.txt b/c/driver/postgresql/CMakeLists.txt
index 18eb773d6..e8bbeac9e 100644
--- a/c/driver/postgresql/CMakeLists.txt
+++ b/c/driver/postgresql/CMakeLists.txt
@@ -44,11 +44,13 @@ add_arrow_lib(adbc_driver_postgresql
${ADBC_LINK_FLAGS}
SHARED_LINK_LIBS
adbc_driver_common
+ adbc_driver_framework
nanoarrow
${LIBPQ_LINK_LIBRARIES}
STATIC_LINK_LIBS
${LIBPQ_LINK_LIBRARIES}
adbc_driver_common
+ adbc_driver_framework
nanoarrow
${LIBPQ_STATIC_LIBRARIES})
diff --git a/c/driver/postgresql/connection.cc b/c/driver/postgresql/connection.cc
index 63d23fb29..5a6cdf241 100644
--- a/c/driver/postgresql/connection.cc
+++ b/c/driver/postgresql/connection.cc
@@ -31,8 +31,9 @@
#include <adbc.h>
#include <libpq-fe.h>
-#include "common/utils.h"
#include "database.h"
+#include "driver/common/utils.h"
+#include "driver/framework/catalog.h"
#include "error.h"
#include "result_helper.h"
@@ -108,7 +109,7 @@ class PqGetObjectsHelper {
private:
AdbcStatusCode InitArrowArray() {
- RAISE_ADBC(AdbcInitConnectionObjectsSchema(schema_, error_));
+ RAISE_ADBC(adbc::driver::AdbcInitConnectionObjectsSchema(schema_).ToAdbc(error_));
CHECK_NA_DETAIL(INTERNAL, ArrowArrayInitFromSchema(array_, schema_, &na_error_),
&na_error_, error_);
@@ -643,13 +644,14 @@ AdbcStatusCode PostgresConnection::Commit(struct AdbcError* error) {
AdbcStatusCode PostgresConnection::PostgresConnectionGetInfoImpl(
const uint32_t* info_codes, size_t info_codes_length, struct ArrowSchema* schema,
struct ArrowArray* array, struct AdbcError* error) {
- RAISE_ADBC(AdbcInitConnectionGetInfoSchema(schema, array, error));
+ RAISE_ADBC(adbc::driver::AdbcInitConnectionGetInfoSchema(schema, array).ToAdbc(error));
for (size_t i = 0; i < info_codes_length; i++) {
switch (info_codes[i]) {
case ADBC_INFO_VENDOR_NAME:
- RAISE_ADBC(
- AdbcConnectionGetInfoAppendString(array, info_codes[i], "PostgreSQL", error));
+ RAISE_ADBC(adbc::driver::AdbcConnectionGetInfoAppendString(array, info_codes[i],
+ "PostgreSQL")
+ .ToAdbc(error));
break;
case ADBC_INFO_VENDOR_VERSION: {
const char* stmt = "SHOW server_version_num";
@@ -663,26 +665,31 @@ AdbcStatusCode PostgresConnection::PostgresConnectionGetInfoImpl(
}
const char* server_version_num = (*it)[0].data;
- RAISE_ADBC(AdbcConnectionGetInfoAppendString(array, info_codes[i],
- server_version_num, error));
+ RAISE_ADBC(adbc::driver::AdbcConnectionGetInfoAppendString(array, info_codes[i],
+ server_version_num)
+ .ToAdbc(error));
break;
}
case ADBC_INFO_DRIVER_NAME:
- RAISE_ADBC(AdbcConnectionGetInfoAppendString(array, info_codes[i],
- "ADBC PostgreSQL Driver", error));
+ RAISE_ADBC(adbc::driver::AdbcConnectionGetInfoAppendString(
+ array, info_codes[i], "ADBC PostgreSQL Driver")
+ .ToAdbc(error));
break;
case ADBC_INFO_DRIVER_VERSION:
// TODO(lidavidm): fill in driver version
- RAISE_ADBC(
- AdbcConnectionGetInfoAppendString(array, info_codes[i], "(unknown)", error));
+ RAISE_ADBC(adbc::driver::AdbcConnectionGetInfoAppendString(array, info_codes[i],
+ "(unknown)")
+ .ToAdbc(error));
break;
case ADBC_INFO_DRIVER_ARROW_VERSION:
- RAISE_ADBC(AdbcConnectionGetInfoAppendString(array, info_codes[i],
- NANOARROW_VERSION, error));
+ RAISE_ADBC(adbc::driver::AdbcConnectionGetInfoAppendString(array, info_codes[i],
+ NANOARROW_VERSION)
+ .ToAdbc(error));
break;
case ADBC_INFO_DRIVER_ADBC_VERSION:
- RAISE_ADBC(AdbcConnectionGetInfoAppendInt(array, info_codes[i],
- ADBC_VERSION_1_1_0, error));
+ RAISE_ADBC(adbc::driver::AdbcConnectionGetInfoAppendInt(array, info_codes[i],
+ ADBC_VERSION_1_1_0)
+ .ToAdbc(error));
break;
default:
// Ignore
diff --git a/c/driver/postgresql/copy/copy_common.h b/c/driver/postgresql/copy/copy_common.h
index 04205907d..835a4f494 100644
--- a/c/driver/postgresql/copy/copy_common.h
+++ b/c/driver/postgresql/copy/copy_common.h
@@ -18,7 +18,9 @@
#pragma once
// Windows
+#if !defined(NOMINMAX)
#define NOMINMAX
+#endif
#include <cstdint>
diff --git a/c/driver/postgresql/database.cc b/c/driver/postgresql/database.cc
index 5de862809..2837e8233 100644
--- a/c/driver/postgresql/database.cc
+++ b/c/driver/postgresql/database.cc
@@ -27,7 +27,7 @@
#include <libpq-fe.h>
#include <nanoarrow/nanoarrow.h>
-#include "common/utils.h"
+#include "driver/common/utils.h"
namespace adbcpq {
diff --git a/c/driver/postgresql/error.cc b/c/driver/postgresql/error.cc
index ed93d1744..276aadc1c 100644
--- a/c/driver/postgresql/error.cc
+++ b/c/driver/postgresql/error.cc
@@ -25,7 +25,7 @@
#include <libpq-fe.h>
-#include "common/utils.h"
+#include "driver/common/utils.h"
namespace adbcpq {
diff --git a/c/driver/postgresql/postgresql.cc b/c/driver/postgresql/postgresql.cc
index 2e25c4bed..e1ffd543b 100644
--- a/c/driver/postgresql/postgresql.cc
+++ b/c/driver/postgresql/postgresql.cc
@@ -22,9 +22,9 @@
#include <adbc.h>
-#include "common/utils.h"
#include "connection.h"
#include "database.h"
+#include "driver/common/utils.h"
#include "statement.h"
using adbcpq::PostgresConnection;
diff --git a/c/driver/postgresql/result_helper.cc b/c/driver/postgresql/result_helper.cc
index 3a2a0d01d..ad5a54e00 100644
--- a/c/driver/postgresql/result_helper.cc
+++ b/c/driver/postgresql/result_helper.cc
@@ -17,7 +17,7 @@
#include "result_helper.h"
-#include "common/utils.h"
+#include "driver/common/utils.h"
#include "error.h"
namespace adbcpq {
diff --git a/c/driver/postgresql/statement.cc b/c/driver/postgresql/statement.cc
index 82e48929c..93e88ee82 100644
--- a/c/driver/postgresql/statement.cc
+++ b/c/driver/postgresql/statement.cc
@@ -35,10 +35,10 @@
#include <libpq-fe.h>
#include <nanoarrow/nanoarrow.hpp>
-#include "common/options.h"
-#include "common/utils.h"
#include "connection.h"
#include "copy/writer.h"
+#include "driver/common/options.h"
+#include "driver/common/utils.h"
#include "error.h"
#include "postgres_type.h"
#include "postgres_util.h"
diff --git a/c/driver/postgresql/statement.h b/c/driver/postgresql/statement.h
index d469ca112..33be8f0c3 100644
--- a/c/driver/postgresql/statement.h
+++ b/c/driver/postgresql/statement.h
@@ -26,8 +26,8 @@
#include <libpq-fe.h>
#include <nanoarrow/nanoarrow.h>
-#include "common/utils.h"
#include "copy/reader.h"
+#include "driver/common/utils.h"
#include "postgres_type.h"
#define ADBC_POSTGRESQL_OPTION_BATCH_SIZE_HINT_BYTES \
diff --git a/c/driver/sqlite/CMakeLists.txt b/c/driver/sqlite/CMakeLists.txt
index 1f2c9f6d1..941329c2f 100644
--- a/c/driver/sqlite/CMakeLists.txt
+++ b/c/driver/sqlite/CMakeLists.txt
@@ -27,7 +27,7 @@ endif()
add_arrow_lib(adbc_driver_sqlite
SOURCES
- sqlite.c
+ sqlite.cc
statement_reader.c
OUTPUTS
ADBC_LIBRARIES
@@ -40,10 +40,12 @@ add_arrow_lib(adbc_driver_sqlite
SHARED_LINK_LIBS
${SQLite3_LINK_LIBRARIES}
adbc_driver_common
+ adbc_driver_framework
nanoarrow
STATIC_LINK_LIBS
${SQLite3_LINK_LIBRARIES}
adbc_driver_common
+ adbc_driver_framework
nanoarrow
${LIBPQ_STATIC_LIBRARIES})
diff --git a/c/driver/sqlite/sqlite.c b/c/driver/sqlite/sqlite.c
deleted file mode 100644
index 83d2d6110..000000000
--- a/c/driver/sqlite/sqlite.c
+++ /dev/null
@@ -1,2064 +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.
-
-#include "adbc.h"
-
-#include <assert.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <nanoarrow/nanoarrow.h>
-#include <sqlite3.h>
-
-#include "common/options.h"
-#include "common/utils.h"
-#include "statement_reader.h"
-#include "types.h"
-
-static const char kDefaultUri[] = "file:adbc_driver_sqlite?mode=memory&cache=shared";
-static const char kConnectionOptionEnableLoadExtension[] =
- "adbc.sqlite.load_extension.enabled";
-static const char kConnectionOptionLoadExtensionPath[] =
- "adbc.sqlite.load_extension.path";
-static const char kConnectionOptionLoadExtensionEntrypoint[] =
- "adbc.sqlite.load_extension.entrypoint";
-// The batch size for query results (and for initial type inference)
-static const char kStatementOptionBatchRows[] = "adbc.sqlite.query.batch_rows";
-static const uint32_t kSupportedInfoCodes[] = {
- ADBC_INFO_VENDOR_NAME, ADBC_INFO_VENDOR_VERSION, ADBC_INFO_DRIVER_NAME,
- ADBC_INFO_DRIVER_VERSION, ADBC_INFO_DRIVER_ARROW_VERSION,
-};
-
-// Private names (to avoid conflicts when using the driver manager)
-
-#define CHECK_DB_INIT(NAME, ERROR) \
- if (!NAME->private_data) { \
- SetError(ERROR, "[SQLite] %s: database not initialized", __func__); \
- return ADBC_STATUS_INVALID_STATE; \
- }
-#define CHECK_CONN_INIT(NAME, ERROR) \
- if (!NAME->private_data) { \
- SetError(ERROR, "[SQLite] %s: connection not initialized", __func__); \
- return ADBC_STATUS_INVALID_STATE; \
- }
-#define CHECK_STMT_INIT(NAME, ERROR) \
- if (!NAME->private_data) { \
- SetError(ERROR, "[SQLite] %s: statement not initialized", __func__); \
- return ADBC_STATUS_INVALID_STATE; \
- }
-
-AdbcStatusCode SqliteDatabaseNew(struct AdbcDatabase* database, struct AdbcError* error) {
- if (database->private_data) {
- SetError(error, "[SQLite] AdbcDatabaseNew: database already allocated");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- database->private_data = malloc(sizeof(struct SqliteDatabase));
- memset(database->private_data, 0, sizeof(struct SqliteDatabase));
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteDatabaseSetOption(struct AdbcDatabase* database, const char* key,
- const char* value, struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- struct SqliteDatabase* db = (struct SqliteDatabase*)database->private_data;
-
- if (strcmp(key, "uri") == 0) {
- if (db->uri) free(db->uri);
- size_t len = strlen(value) + 1;
- db->uri = malloc(len);
- strncpy(db->uri, value, len);
- return ADBC_STATUS_OK;
- }
- SetError(error, "[SQLite] Unknown database option %s=%s", key,
- value ? value : "(NULL)");
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteDatabaseSetOptionBytes(struct AdbcDatabase* database,
- const char* key, const uint8_t* value,
- size_t length, struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteDatabaseSetOptionDouble(struct AdbcDatabase* database,
- const char* key, double value,
- struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteDatabaseSetOptionInt(struct AdbcDatabase* database, const char* key,
- int64_t value, struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-int OpenDatabase(const struct SqliteDatabase* database, sqlite3** db,
- struct AdbcError* error) {
- const char* uri = database->uri ? database->uri : kDefaultUri;
- int rc = sqlite3_open_v2(uri, db,
- SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI,
- /*zVfs=*/NULL);
- if (rc != SQLITE_OK) {
- if (*db) {
- SetError(error, "[SQLite] Failed to open %s: %s", uri, sqlite3_errmsg(*db));
- } else {
- SetError(error, "[SQLite] Failed to open %s: failed to allocate memory", uri);
- }
- (void)sqlite3_close(*db);
- *db = NULL;
- return ADBC_STATUS_IO;
- }
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode ExecuteQuery(struct SqliteConnection* conn, const char* query,
- struct AdbcError* error) {
- sqlite3_stmt* stmt = NULL;
- int rc = sqlite3_prepare_v2(conn->conn, query, strlen(query), &stmt, /*pzTail=*/NULL);
- while (rc != SQLITE_DONE && rc != SQLITE_ERROR) {
- rc = sqlite3_step(stmt);
- }
- rc = sqlite3_finalize(stmt);
- if (rc != SQLITE_OK && rc != SQLITE_DONE) {
- SetError(error, "[SQLite] Failed to execute query \"%s\": %s", query,
- sqlite3_errmsg(conn->conn));
- return ADBC_STATUS_INTERNAL;
- }
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteDatabaseGetOption(struct AdbcDatabase* database, const char* key,
- char* value, size_t* length,
- struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteDatabaseGetOptionBytes(struct AdbcDatabase* database,
- const char* key, uint8_t* value,
- size_t* length, struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteDatabaseGetOptionDouble(struct AdbcDatabase* database,
- const char* key, double* value,
- struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteDatabaseGetOptionInt(struct AdbcDatabase* database, const char* key,
- int64_t* value, struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteDatabaseInit(struct AdbcDatabase* database,
- struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- struct SqliteDatabase* db = (struct SqliteDatabase*)database->private_data;
-
- if (db->db) {
- SetError(error, "[SQLite] AdbcDatabaseInit: database already initialized");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- return OpenDatabase(db, &db->db, error);
-}
-
-AdbcStatusCode SqliteDatabaseRelease(struct AdbcDatabase* database,
- struct AdbcError* error) {
- CHECK_DB_INIT(database, error);
- struct SqliteDatabase* db = (struct SqliteDatabase*)database->private_data;
-
- size_t connection_count = db->connection_count;
- if (db->uri) free(db->uri);
- if (db->db) {
- if (sqlite3_close(db->db) == SQLITE_BUSY) {
- SetError(error, "[SQLite] AdbcDatabaseRelease: connection is busy");
- return ADBC_STATUS_IO;
- }
- }
- free(database->private_data);
- database->private_data = NULL;
-
- if (connection_count > 0) {
- // -Wpedantic gives a warning if we use size_t in a printf() context
- SetError(error, "[SQLite] AdbcDatabaseRelease: %ld open connections when released",
- (long)connection_count); // NOLINT(runtime/int)
- return ADBC_STATUS_INVALID_STATE;
- }
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionNew(struct AdbcConnection* connection,
- struct AdbcError* error) {
- if (connection->private_data) {
- SetError(error, "[SQLite] AdbcConnectionNew: connection already allocated");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- connection->private_data = malloc(sizeof(struct SqliteConnection));
- memset(connection->private_data, 0, sizeof(struct SqliteConnection));
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionSetOption(struct AdbcConnection* connection,
- const char* key, const char* value,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
- if (strcmp(key, ADBC_CONNECTION_OPTION_AUTOCOMMIT) == 0) {
- if (!conn->conn) {
- SetError(error, "[SQLite] %s can only be set after AdbcConnectionInit", key);
- return ADBC_STATUS_INVALID_STATE;
- }
-
- if (strcmp(value, ADBC_OPTION_VALUE_ENABLED) == 0) {
- if (conn->active_transaction) {
- AdbcStatusCode status = ExecuteQuery(conn, "COMMIT", error);
- if (status != ADBC_STATUS_OK) return status;
- conn->active_transaction = 0;
- } else {
- // no-op
- }
- } else if (strcmp(value, ADBC_OPTION_VALUE_DISABLED) == 0) {
- if (conn->active_transaction) {
- // no-op
- } else {
- // begin
- AdbcStatusCode status = ExecuteQuery(conn, "BEGIN", error);
- if (status != ADBC_STATUS_OK) return status;
- conn->active_transaction = 1;
- }
- } else {
- SetError(error, "[SQLite] Invalid connection option value %s=%s", key, value);
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- return ADBC_STATUS_OK;
- } else if (strcmp(key, kConnectionOptionEnableLoadExtension) == 0) {
- if (!conn->conn) {
- SetError(error, "[SQLite] %s can only be set after AdbcConnectionInit", key);
- return ADBC_STATUS_INVALID_STATE;
- }
-
- int rc = 0;
- if (strcmp(value, ADBC_OPTION_VALUE_ENABLED) == 0) {
- rc = sqlite3_db_config(conn->conn, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, NULL);
- } else if (strcmp(value, ADBC_OPTION_VALUE_DISABLED) == 0) {
- rc = sqlite3_db_config(conn->conn, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 0, NULL);
- } else {
- SetError(error, "[SQLite] Invalid connection option %s=%s", key,
- value ? value : "(NULL)");
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- if (rc != SQLITE_OK) {
- SetError(error, "[SQLite] Failed to configure extension loading: %s",
- sqlite3_errmsg(conn->conn));
- return ADBC_STATUS_IO;
- }
- return ADBC_STATUS_OK;
- } else if (strcmp(key, kConnectionOptionLoadExtensionPath) == 0) {
- if (!conn->conn) {
- SetError(error, "[SQLite] %s can only be set after AdbcConnectionInit", key);
- return ADBC_STATUS_INVALID_STATE;
- }
- if (conn->extension_path) {
- free(conn->extension_path);
- conn->extension_path = NULL;
- }
- if (!value) {
- SetError(error, "[SQLite] Must provide non-NULL %s", key);
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- conn->extension_path = strdup(value);
- return ADBC_STATUS_OK;
- } else if (strcmp(key, kConnectionOptionLoadExtensionEntrypoint) == 0) {
-#if !defined(ADBC_SQLITE_WITH_NO_LOAD_EXTENSION)
- if (!conn->conn) {
- SetError(error, "[SQLite] %s can only be set after AdbcConnectionInit", key);
- return ADBC_STATUS_INVALID_STATE;
- }
- if (!conn->extension_path) {
- SetError(error, "[SQLite] %s can only be set after setting %s", key,
- kConnectionOptionLoadExtensionPath);
- return ADBC_STATUS_INVALID_STATE;
- }
-
- char* message = NULL;
- int rc = sqlite3_load_extension(conn->conn, conn->extension_path, value, &message);
- if (rc != SQLITE_OK) {
- SetError(error, "[SQLite] Failed to load extension %s (entrypoint %s): %s",
- conn->extension_path, value ? value : "(NULL)",
- message ? message : "(unknown error)");
- if (message) sqlite3_free(message);
- return ADBC_STATUS_UNKNOWN;
- }
-
- free(conn->extension_path);
- conn->extension_path = NULL;
- return ADBC_STATUS_OK;
-#else
- SetError(error,
- "[SQLite] This build of the ADBC SQLite driver does not support extension "
- "loading");
- return ADBC_STATUS_NOT_IMPLEMENTED;
-#endif
- }
- SetError(error, "[SQLite] Unknown connection option %s=%s", key,
- value ? value : "(NULL)");
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteConnectionSetOptionBytes(struct AdbcConnection* connection,
- const char* key, const uint8_t* value,
- size_t length, struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteConnectionSetOptionDouble(struct AdbcConnection* connection,
- const char* key, double value,
- struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteConnectionSetOptionInt(struct AdbcConnection* connection,
- const char* key, int64_t value,
- struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteConnectionInit(struct AdbcConnection* connection,
- struct AdbcDatabase* database,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- CHECK_DB_INIT(database, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
- struct SqliteDatabase* db = (struct SqliteDatabase*)database->private_data;
-
- if (conn->conn) {
- SetError(error, "[SQLite] AdbcConnectionInit: connection already initialized");
- return ADBC_STATUS_INVALID_STATE;
- }
- return OpenDatabase(db, &conn->conn, error);
-}
-
-AdbcStatusCode SqliteConnectionRelease(struct AdbcConnection* connection,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
-
- if (conn->conn) {
- int rc = sqlite3_close(conn->conn);
- if (rc == SQLITE_BUSY) {
- SetError(error, "[SQLite] AdbcConnectionRelease: connection is busy");
- return ADBC_STATUS_IO;
- }
- conn->conn = NULL;
- }
- if (conn->extension_path) {
- free(conn->extension_path);
- conn->extension_path = NULL;
- }
- free(connection->private_data);
- connection->private_data = NULL;
-
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionGetInfoImpl(const uint32_t* info_codes,
- size_t info_codes_length,
- struct ArrowSchema* schema,
- struct ArrowArray* array,
- struct AdbcError* error) {
- RAISE_ADBC(AdbcInitConnectionGetInfoSchema(schema, array, error));
- for (size_t i = 0; i < info_codes_length; i++) {
- switch (info_codes[i]) {
- case ADBC_INFO_VENDOR_NAME:
- RAISE_ADBC(
- AdbcConnectionGetInfoAppendString(array, info_codes[i], "SQLite", error));
- break;
- case ADBC_INFO_VENDOR_VERSION:
- RAISE_ADBC(AdbcConnectionGetInfoAppendString(array, info_codes[i],
- sqlite3_libversion(), error));
- break;
- case ADBC_INFO_DRIVER_NAME:
- RAISE_ADBC(AdbcConnectionGetInfoAppendString(array, info_codes[i],
- "ADBC SQLite Driver", error));
- break;
- case ADBC_INFO_DRIVER_VERSION:
- // TODO(lidavidm): fill in driver version
- RAISE_ADBC(
- AdbcConnectionGetInfoAppendString(array, info_codes[i], "(unknown)", error));
- break;
- case ADBC_INFO_DRIVER_ARROW_VERSION:
- RAISE_ADBC(AdbcConnectionGetInfoAppendString(array, info_codes[i],
- NANOARROW_VERSION, error));
- break;
- default:
- // Ignore
- continue;
- }
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(array), error);
- }
-
- struct ArrowError na_error = {0};
- CHECK_NA_DETAIL(INTERNAL, ArrowArrayFinishBuildingDefault(array, &na_error), &na_error,
- error);
-
- return ADBC_STATUS_OK;
-} // NOLINT(whitespace/indent)
-
-AdbcStatusCode SqliteConnectionGetInfo(struct AdbcConnection* connection,
- const uint32_t* info_codes,
- size_t info_codes_length,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
-
- // XXX: mistake in adbc.h (should have been const pointer)
- const uint32_t* codes = info_codes;
- if (!info_codes) {
- codes = kSupportedInfoCodes;
- info_codes_length = sizeof(kSupportedInfoCodes) / sizeof(kSupportedInfoCodes[0]);
- }
-
- struct ArrowSchema schema = {0};
- struct ArrowArray array = {0};
-
- AdbcStatusCode status =
- SqliteConnectionGetInfoImpl(codes, info_codes_length, &schema, &array, error);
- if (status != ADBC_STATUS_OK) {
- if (schema.release) schema.release(&schema);
- if (array.release) array.release(&array);
- return status;
- }
-
- return BatchToArrayStream(&array, &schema, out, error);
-}
-
-static const char kTableQuery[] =
- "SELECT name, type "
- "FROM sqlite_master "
- "WHERE name LIKE ? AND type <> 'index'"
- "ORDER BY name ASC";
-static const char kColumnQuery[] =
- "SELECT cid, name, type, \"notnull\", dflt_value "
- "FROM pragma_table_info(?) "
- "WHERE name LIKE ? "
- "ORDER BY cid ASC";
-static const char kPrimaryKeyQuery[] =
- "SELECT name "
- "FROM pragma_table_info(?) "
- "WHERE pk > 0 "
- "ORDER BY pk ASC";
-static const char kForeignKeyQuery[] =
- "SELECT id, seq, \"table\", \"from\", \"to\" "
- "FROM pragma_foreign_key_list(?) "
- "ORDER BY id, seq ASC";
-
-AdbcStatusCode SqliteConnectionGetColumnsImpl(
- struct SqliteConnection* conn, const char* table_name, const char* column_name,
- struct ArrowArray* table_columns_col, sqlite3_stmt* stmt, struct AdbcError* error) {
- struct ArrowArray* table_columns_items = table_columns_col->children[0];
- struct ArrowArray* column_name_col = table_columns_items->children[0];
- struct ArrowArray* ordinal_position_col = table_columns_items->children[1];
- struct ArrowArray* remarks_col = table_columns_items->children[2];
- struct ArrowArray* xdbc_data_type_col = table_columns_items->children[3];
- struct ArrowArray* xdbc_type_name_col = table_columns_items->children[4];
- struct ArrowArray* xdbc_column_size_col = table_columns_items->children[5];
- struct ArrowArray* xdbc_decimal_digits_col = table_columns_items->children[6];
- struct ArrowArray* xdbc_num_prec_radix_col = table_columns_items->children[7];
- struct ArrowArray* xdbc_nullable_col = table_columns_items->children[8];
- struct ArrowArray* xdbc_column_def_col = table_columns_items->children[9];
- struct ArrowArray* xdbc_sql_data_type_col = table_columns_items->children[10];
- struct ArrowArray* xdbc_datetime_sub_col = table_columns_items->children[11];
- struct ArrowArray* xdbc_char_octet_length_col = table_columns_items->children[12];
- struct ArrowArray* xdbc_is_nullable_col = table_columns_items->children[13];
- struct ArrowArray* xdbc_scope_catalog_col = table_columns_items->children[14];
- struct ArrowArray* xdbc_scope_schema_col = table_columns_items->children[15];
- struct ArrowArray* xdbc_scope_table_col = table_columns_items->children[16];
- struct ArrowArray* xdbc_is_autoincrement_col = table_columns_items->children[17];
- struct ArrowArray* xdbc_is_generatedcolumn_col = table_columns_items->children[18];
-
- int rc = sqlite3_reset(stmt);
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- rc = sqlite3_bind_text64(stmt, 1, table_name, strlen(table_name), SQLITE_STATIC,
- SQLITE_UTF8);
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- if (column_name) {
- rc = sqlite3_bind_text64(stmt, 2, column_name, strlen(column_name), SQLITE_STATIC,
- SQLITE_UTF8);
- } else {
- rc = sqlite3_bind_text64(stmt, 2, "%", 1, SQLITE_STATIC, SQLITE_UTF8);
- }
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
- const char* col_name = (const char*)sqlite3_column_text(stmt, 1);
- struct ArrowStringView str = {.data = col_name,
- .size_bytes = sqlite3_column_bytes(stmt, 1)};
- CHECK_NA(INTERNAL, ArrowArrayAppendString(column_name_col, str), error);
-
- const int32_t col_cid = sqlite3_column_int(stmt, 0);
- CHECK_NA(INTERNAL, ArrowArrayAppendInt(ordinal_position_col, col_cid + 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(remarks_col, 1), error);
-
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_data_type_col, 1), error);
-
- const char* col_type = (const char*)sqlite3_column_text(stmt, 2);
- if (col_type) {
- str.data = col_type;
- str.size_bytes = sqlite3_column_bytes(stmt, 2);
- CHECK_NA(INTERNAL, ArrowArrayAppendString(xdbc_type_name_col, str), error);
- } else {
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_type_name_col, 1), error);
- }
-
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_column_size_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_decimal_digits_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_num_prec_radix_col, 1), error);
-
- const int32_t col_notnull = sqlite3_column_int(stmt, 3);
- if (col_notnull == 0) {
- // JDBC columnNullable == 1
- CHECK_NA(INTERNAL, ArrowArrayAppendInt(xdbc_nullable_col, 1), error);
- } else {
- // JDBC columnNoNulls == 0
- CHECK_NA(INTERNAL, ArrowArrayAppendInt(xdbc_nullable_col, 0), error);
- }
-
- const char* col_def = (const char*)sqlite3_column_text(stmt, 4);
- if (col_def) {
- str.data = col_def;
- str.size_bytes = sqlite3_column_bytes(stmt, 4);
- CHECK_NA(INTERNAL, ArrowArrayAppendString(xdbc_column_def_col, str), error);
- } else {
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_column_def_col, 1), error);
- }
-
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_sql_data_type_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_datetime_sub_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_char_octet_length_col, 1), error);
-
- if (col_notnull == 0) {
- str.data = "YES";
- str.size_bytes = 3;
- } else {
- str.data = "NO";
- str.size_bytes = 2;
- }
- CHECK_NA(INTERNAL, ArrowArrayAppendString(xdbc_is_nullable_col, str), error);
-
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_scope_catalog_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_scope_schema_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_scope_table_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_is_autoincrement_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(xdbc_is_generatedcolumn_col, 1), error);
-
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(table_columns_items), error);
- }
- RAISE(INTERNAL, rc == SQLITE_DONE, sqlite3_errmsg(conn->conn), error);
-
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionGetConstraintsImpl(
- struct SqliteConnection* conn, const char* table_name, const char* column_name,
- struct ArrowArray* table_constraints_col, sqlite3_stmt* pk_stmt,
- sqlite3_stmt* fk_stmt, struct AdbcError* error) {
- struct ArrowArray* table_constraints_items = table_constraints_col->children[0];
- struct ArrowArray* constraint_name_col = table_constraints_items->children[0];
- struct ArrowArray* constraint_type_col = table_constraints_items->children[1];
- struct ArrowArray* constraint_column_names_col = table_constraints_items->children[2];
- struct ArrowArray* constraint_column_names_items =
- constraint_column_names_col->children[0];
- struct ArrowArray* constraint_column_usage_col = table_constraints_items->children[3];
- struct ArrowArray* constraint_column_usage_items =
- constraint_column_usage_col->children[0];
- struct ArrowArray* fk_catalog_col = constraint_column_usage_items->children[0];
- struct ArrowArray* fk_db_schema_col = constraint_column_usage_items->children[1];
- struct ArrowArray* fk_table_col = constraint_column_usage_items->children[2];
- struct ArrowArray* fk_column_name_col = constraint_column_usage_items->children[3];
-
- // We can get primary keys and foreign keys, but not unique
- // constraints (unless we parse the SQL table definition)
-
- int rc = sqlite3_reset(pk_stmt);
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- rc = sqlite3_bind_text64(pk_stmt, 1, table_name, strlen(table_name), SQLITE_STATIC,
- SQLITE_UTF8);
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- char has_primary_key = 0;
- while ((rc = sqlite3_step(pk_stmt)) == SQLITE_ROW) {
- if (!has_primary_key) {
- has_primary_key = 1;
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(constraint_name_col, 1), error);
- CHECK_NA(INTERNAL,
- ArrowArrayAppendString(constraint_type_col, ArrowCharView("PRIMARY KEY")),
- error);
- }
- CHECK_NA(
- INTERNAL,
- ArrowArrayAppendString(
- constraint_column_names_items,
- (struct ArrowStringView){.data = (const char*)sqlite3_column_text(pk_stmt, 0),
- .size_bytes = sqlite3_column_bytes(pk_stmt, 0)}),
- error);
- }
- RAISE(INTERNAL, rc == SQLITE_DONE, sqlite3_errmsg(conn->conn), error);
- if (has_primary_key) {
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(constraint_column_names_col), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(constraint_column_usage_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(table_constraints_items), error);
- }
-
- rc = sqlite3_reset(fk_stmt);
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- rc = sqlite3_bind_text64(fk_stmt, 1, table_name, strlen(table_name), SQLITE_STATIC,
- SQLITE_UTF8);
- RAISE(INTERNAL, rc == SQLITE_OK, sqlite3_errmsg(conn->conn), error);
-
- int prev_fk_id = -1;
- while ((rc = sqlite3_step(fk_stmt)) == SQLITE_ROW) {
- const int fk_id = sqlite3_column_int(fk_stmt, 0);
- // Foreign key seq is sqlite3_column_int(fk_stmt, 1);
- const char* to_table = (const char*)sqlite3_column_text(fk_stmt, 2);
- const char* from_col = (const char*)sqlite3_column_text(fk_stmt, 3);
- const char* to_col = (const char*)sqlite3_column_text(fk_stmt, 4);
-
- // New foreign key constraint or -constraint sets
- if (fk_id != prev_fk_id) {
- // Not first constraint of the table
- if (prev_fk_id != -1) {
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(constraint_column_names_col), error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(constraint_column_usage_col), error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(table_constraints_items), error);
- }
- prev_fk_id = fk_id;
-
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(constraint_name_col, 1), error);
- CHECK_NA(INTERNAL,
- ArrowArrayAppendString(constraint_type_col, ArrowCharView("FOREIGN KEY")),
- error);
- }
- CHECK_NA(INTERNAL,
- ArrowArrayAppendString(
- constraint_column_names_items,
- (struct ArrowStringView){
- .data = from_col, .size_bytes = sqlite3_column_bytes(fk_stmt, 3)}),
- error);
- CHECK_NA(INTERNAL, ArrowArrayAppendString(fk_catalog_col, ArrowCharView("main")),
- error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(fk_db_schema_col, 1), error);
- CHECK_NA(INTERNAL,
- ArrowArrayAppendString(
- fk_table_col,
- (struct ArrowStringView){
- .data = to_table, .size_bytes = sqlite3_column_bytes(fk_stmt, 2)}),
- error);
- CHECK_NA(INTERNAL,
- ArrowArrayAppendString(
- fk_column_name_col,
- (struct ArrowStringView){
- .data = to_col, .size_bytes = sqlite3_column_bytes(fk_stmt, 4)}),
- error);
-
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(constraint_column_usage_items), error);
- }
- RAISE(INTERNAL, rc == SQLITE_DONE, sqlite3_errmsg(conn->conn), error);
- if (prev_fk_id != -1) {
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(constraint_column_names_col), error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(constraint_column_usage_col), error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(table_constraints_items), error);
- }
-
- return ADBC_STATUS_OK;
-} // NOLINT(whitespace/indent)
-
-AdbcStatusCode SqliteConnectionGetTablesInner(
- struct SqliteConnection* conn, sqlite3_stmt* tables_stmt, sqlite3_stmt* columns_stmt,
- sqlite3_stmt* pk_stmt, sqlite3_stmt* fk_stmt, const char** table_type,
- const char* column_name, struct ArrowArray* db_schema_tables_col,
- struct AdbcError* error) {
- struct ArrowArray* db_schema_tables_items = db_schema_tables_col->children[0];
- struct ArrowArray* table_name_col = db_schema_tables_items->children[0];
- struct ArrowArray* table_type_col = db_schema_tables_items->children[1];
- struct ArrowArray* table_columns_col = db_schema_tables_items->children[2];
- struct ArrowArray* table_constraints_col = db_schema_tables_items->children[3];
-
- int rc = SQLITE_OK;
- while ((rc = sqlite3_step(tables_stmt)) == SQLITE_ROW) {
- const char* cur_table_type = (const char*)sqlite3_column_text(tables_stmt, 1);
-
- if (table_type) {
- const char** current = table_type;
- char found = 0;
- while (*current) {
- if (strcmp(*current, cur_table_type) == 0) {
- found = 1;
- break;
- }
- current++;
- }
- if (!found) continue;
- }
-
- struct ArrowStringView str = {.data = cur_table_type,
- .size_bytes = sqlite3_column_bytes(tables_stmt, 1)};
- CHECK_NA(INTERNAL, ArrowArrayAppendString(table_type_col, str), error);
-
- const char* cur_table = (const char*)sqlite3_column_text(tables_stmt, 0);
- str.data = cur_table;
- str.size_bytes = sqlite3_column_bytes(tables_stmt, 0);
- CHECK_NA(INTERNAL, ArrowArrayAppendString(table_name_col, str), error);
-
- if (columns_stmt == NULL) {
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(table_columns_col, 1), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(table_constraints_col, 1), error);
- } else {
- // XXX: n + 1 query pattern. You can join on a pragma so we
- // could avoid this in principle but it complicates the
- // unpacking code here quite a bit, so ignore for now.
- RAISE_ADBC(SqliteConnectionGetColumnsImpl(conn, cur_table, column_name,
- table_columns_col, columns_stmt, error));
- // Not strictly necessary, but we passed SQLITE_STATIC when
- // binding so don't let the reference leak
- (void)sqlite3_clear_bindings(columns_stmt);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(table_columns_col), error);
-
- RAISE_ADBC(SqliteConnectionGetConstraintsImpl(
- conn, cur_table, column_name, table_constraints_col, pk_stmt, fk_stmt, error));
- (void)sqlite3_clear_bindings(pk_stmt);
- (void)sqlite3_clear_bindings(fk_stmt);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(table_constraints_col), error);
- }
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(db_schema_tables_items), error);
- }
-
- if (rc != SQLITE_DONE) {
- SetError(error, "[SQLite] Failed to query for tables: %s",
- sqlite3_errmsg(conn->conn));
- return ADBC_STATUS_INTERNAL;
- }
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(db_schema_tables_col), error);
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionGetTablesImpl(struct SqliteConnection* conn, int depth,
- const char* table_name,
- const char** table_type,
- const char* column_name,
- struct ArrowArray* db_schema_tables_col,
- struct AdbcError* error) {
- sqlite3_stmt* tables_stmt = NULL;
- sqlite3_stmt* columns_stmt = NULL;
- sqlite3_stmt* pk_stmt = NULL;
- sqlite3_stmt* fk_stmt = NULL;
- int rc = SQLITE_OK;
-
- if (rc == SQLITE_OK) {
- rc = sqlite3_prepare_v2(conn->conn, kTableQuery, sizeof(kTableQuery), &tables_stmt,
- /*pzTail=*/NULL);
- }
- if (rc == SQLITE_OK && depth == ADBC_OBJECT_DEPTH_COLUMNS) {
- rc = sqlite3_prepare_v2(conn->conn, kColumnQuery, sizeof(kColumnQuery), &columns_stmt,
- /*pzTail=*/NULL);
- }
- if (rc == SQLITE_OK && depth == ADBC_OBJECT_DEPTH_COLUMNS) {
- rc = sqlite3_prepare_v2(conn->conn, kPrimaryKeyQuery, sizeof(kPrimaryKeyQuery),
- &pk_stmt, /*pzTail=*/NULL);
- }
- if (rc == SQLITE_OK && depth == ADBC_OBJECT_DEPTH_COLUMNS) {
- rc = sqlite3_prepare_v2(conn->conn, kForeignKeyQuery, sizeof(kForeignKeyQuery),
- &fk_stmt, /*pzTail=*/NULL);
- }
- if (rc == SQLITE_OK) {
- if (table_name) {
- rc = sqlite3_bind_text64(tables_stmt, 1, table_name, strlen(table_name),
- SQLITE_STATIC, SQLITE_UTF8);
- } else {
- rc = sqlite3_bind_text64(tables_stmt, 1, "%", 1, SQLITE_STATIC, SQLITE_UTF8);
- }
- }
-
- AdbcStatusCode status = ADBC_STATUS_OK;
- if (rc == SQLITE_OK) {
- status = SqliteConnectionGetTablesInner(conn, tables_stmt, columns_stmt, pk_stmt,
- fk_stmt, table_type, column_name,
- db_schema_tables_col, error);
- } else {
- SetError(error, "[SQLite] Failed to query for tables: %s",
- sqlite3_errmsg(conn->conn));
- status = ADBC_STATUS_INTERNAL;
- }
-
- sqlite3_finalize(tables_stmt);
- sqlite3_finalize(columns_stmt);
- sqlite3_finalize(pk_stmt);
- sqlite3_finalize(fk_stmt);
- return status;
-}
-
-AdbcStatusCode SqliteConnectionGetObjectsImpl(
- struct SqliteConnection* conn, int depth, const char* catalog, const char* db_schema,
- const char* table_name, const char** table_type, const char* column_name,
- struct ArrowSchema* schema, struct ArrowArray* array, struct AdbcError* error) {
- RAISE_ADBC(AdbcInitConnectionObjectsSchema(schema, error));
-
- struct ArrowError na_error = {0};
- CHECK_NA_DETAIL(INTERNAL, ArrowArrayInitFromSchema(array, schema, &na_error), &na_error,
- error);
- CHECK_NA(INTERNAL, ArrowArrayStartAppending(array), error);
-
- struct ArrowArray* catalog_name_col = array->children[0];
- struct ArrowArray* catalog_db_schemas_col = array->children[1];
-
- struct ArrowArray* catalog_db_schemas_items = catalog_db_schemas_col->children[0];
- struct ArrowArray* db_schema_name_col = catalog_db_schemas_items->children[0];
- struct ArrowArray* db_schema_tables_col = catalog_db_schemas_items->children[1];
-
- // TODO: support proper filters
- if (!catalog || strcmp(catalog, "main") == 0) {
- // Default the primary catalog to "main"
- // https://www.sqlite.org/cli.html
- // > The ".databases" command shows a list of all databases open
- // > in the current connection. There will always be at least
- // > 2. The first one is "main", the original database opened.
-
- CHECK_NA(INTERNAL, ArrowArrayAppendString(catalog_name_col, ArrowCharView("main")),
- error);
-
- if (depth == ADBC_OBJECT_DEPTH_CATALOGS) {
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(catalog_db_schemas_col, 1), error);
- } else if (!db_schema || db_schema == NULL) {
- // For our purposes, we'll consider SQLite to always have a
- // single, unnamed schema within each catalog.
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(db_schema_name_col, 1), error);
- if (depth == ADBC_OBJECT_DEPTH_DB_SCHEMAS) {
- CHECK_NA(INTERNAL, ArrowArrayAppendNull(db_schema_tables_col, 1), error);
- } else {
- RAISE_ADBC(SqliteConnectionGetTablesImpl(conn, depth, table_name, table_type,
- column_name, db_schema_tables_col,
- error));
- }
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(catalog_db_schemas_items), error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(catalog_db_schemas_col), error);
- } else {
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(catalog_db_schemas_col), error);
- }
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(array), error);
-
- // TODO: implement "temp", other attached databases as catalogs
- }
-
- CHECK_NA_DETAIL(INTERNAL, ArrowArrayFinishBuildingDefault(array, &na_error), &na_error,
- error);
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionGetObjects(struct AdbcConnection* connection, int depth,
- const char* catalog, const char* db_schema,
- const char* table_name, const char** table_type,
- const char* column_name,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
-
- struct ArrowSchema schema = {0};
- struct ArrowArray array = {0};
-
- AdbcStatusCode status =
- SqliteConnectionGetObjectsImpl(conn, depth, catalog, db_schema, table_name,
- table_type, column_name, &schema, &array, error);
- if (status != ADBC_STATUS_OK) {
- if (schema.release) schema.release(&schema);
- if (array.release) array.release(&array);
- return status;
- }
-
- return BatchToArrayStream(&array, &schema, out, error);
-}
-
-AdbcStatusCode SqliteConnectionGetOption(struct AdbcConnection* connection,
- const char* key, char* value, size_t* length,
- struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteConnectionGetOptionBytes(struct AdbcConnection* connection,
- const char* key, uint8_t* value,
- size_t* length, struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteConnectionGetOptionDouble(struct AdbcConnection* connection,
- const char* key, double* value,
- struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteConnectionGetOptionInt(struct AdbcConnection* connection,
- const char* key, int64_t* value,
- struct AdbcError* error) {
- CHECK_DB_INIT(connection, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteConnectionGetTableSchema(struct AdbcConnection* connection,
- const char* catalog, const char* db_schema,
- const char* table_name,
- struct ArrowSchema* schema,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
- if (catalog != NULL && strlen(catalog) > 0) {
- // TODO: map 'catalog' to SQLite attached database
- memset(schema, 0, sizeof(*schema));
- return ADBC_STATUS_OK;
- } else if (db_schema != NULL && strlen(db_schema) > 0) {
- // SQLite does not support schemas
- memset(schema, 0, sizeof(*schema));
- return ADBC_STATUS_OK;
- } else if (table_name == NULL) {
- SetError(error, "[SQLite] AdbcConnectionGetTableSchema: must provide table_name");
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
-
- sqlite3_str* query = sqlite3_str_new(NULL);
- if (sqlite3_str_errcode(query)) {
- SetError(error, "[SQLite] %s", sqlite3_errmsg(conn->conn));
- return ADBC_STATUS_INTERNAL;
- }
-
- sqlite3_str_appendf(query, "%s%Q", "SELECT * FROM ", table_name);
- if (sqlite3_str_errcode(query)) {
- SetError(error, "[SQLite] %s", sqlite3_errmsg(conn->conn));
- sqlite3_free(sqlite3_str_finish(query));
- return ADBC_STATUS_INTERNAL;
- }
-
- sqlite3_stmt* stmt = NULL;
- int rc = sqlite3_prepare_v2(conn->conn, sqlite3_str_value(query),
- sqlite3_str_length(query), &stmt, /*pzTail=*/NULL);
- sqlite3_free(sqlite3_str_finish(query));
- if (rc != SQLITE_OK) {
- SetError(error, "[SQLite] GetTableSchema: %s", sqlite3_errmsg(conn->conn));
- return ADBC_STATUS_NOT_FOUND;
- }
-
- struct ArrowArrayStream stream = {0};
- AdbcStatusCode status = AdbcSqliteExportReader(conn->conn, stmt, /*binder=*/NULL,
- /*batch_size=*/64, &stream, error);
- if (status == ADBC_STATUS_OK) {
- int code = stream.get_schema(&stream, schema);
- if (code != 0) {
- SetError(error, "[SQLite] Failed to get schema: (%d) %s", code, strerror(code));
- status = ADBC_STATUS_IO;
- }
- }
- if (stream.release) {
- stream.release(&stream);
- }
- (void)sqlite3_finalize(stmt);
- return status;
-}
-
-AdbcStatusCode SqliteConnectionGetTableTypesImpl(struct ArrowSchema* schema,
- struct ArrowArray* array,
- struct AdbcError* error) {
- ArrowSchemaInit(schema);
- CHECK_NA(INTERNAL, ArrowSchemaSetType(schema, NANOARROW_TYPE_STRUCT), error);
- CHECK_NA(INTERNAL, ArrowSchemaAllocateChildren(schema, /*num_columns=*/1), error);
- ArrowSchemaInit(schema->children[0]);
- CHECK_NA(INTERNAL, ArrowSchemaSetType(schema->children[0], NANOARROW_TYPE_STRING),
- error);
- CHECK_NA(INTERNAL, ArrowSchemaSetName(schema->children[0], "table_type"), error);
- schema->children[0]->flags &= ~ARROW_FLAG_NULLABLE;
-
- CHECK_NA(INTERNAL, ArrowArrayInitFromSchema(array, schema, NULL), error);
- CHECK_NA(INTERNAL, ArrowArrayStartAppending(array), error);
-
- CHECK_NA(INTERNAL, ArrowArrayAppendString(array->children[0], ArrowCharView("table")),
- error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(array), error);
- CHECK_NA(INTERNAL, ArrowArrayAppendString(array->children[0], ArrowCharView("view")),
- error);
- CHECK_NA(INTERNAL, ArrowArrayFinishElement(array), error);
-
- CHECK_NA(INTERNAL, ArrowArrayFinishBuildingDefault(array, NULL), error);
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteConnectionGetTableTypes(struct AdbcConnection* connection,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
-
- struct ArrowSchema schema = {0};
- struct ArrowArray array = {0};
-
- AdbcStatusCode status = SqliteConnectionGetTableTypesImpl(&schema, &array, error);
- if (status != ADBC_STATUS_OK) {
- if (schema.release) schema.release(&schema);
- if (array.release) array.release(&array);
- return status;
- }
- return BatchToArrayStream(&array, &schema, out, error);
-}
-
-AdbcStatusCode SqliteConnectionReadPartition(struct AdbcConnection* connection,
- const uint8_t* serialized_partition,
- size_t serialized_length,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteConnectionCommit(struct AdbcConnection* connection,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
- if (!conn->active_transaction) {
- SetError(error, "[SQLite] No active transaction, cannot commit");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- AdbcStatusCode status = ExecuteQuery(conn, "COMMIT", error);
- if (status != ADBC_STATUS_OK) return status;
- return ExecuteQuery(conn, "BEGIN", error);
-}
-
-AdbcStatusCode SqliteConnectionRollback(struct AdbcConnection* connection,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
- if (!conn->active_transaction) {
- SetError(error, "[SQLite] No active transaction, cannot rollback");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- AdbcStatusCode status = ExecuteQuery(conn, "ROLLBACK", error);
- if (status != ADBC_STATUS_OK) return status;
- return ExecuteQuery(conn, "BEGIN", error);
-}
-
-AdbcStatusCode SqliteStatementNew(struct AdbcConnection* connection,
- struct AdbcStatement* statement,
- struct AdbcError* error) {
- CHECK_CONN_INIT(connection, error);
- struct SqliteConnection* conn = (struct SqliteConnection*)connection->private_data;
- if (statement->private_data) {
- SetError(error, "[SQLite] AdbcStatementNew: statement already allocated");
- return ADBC_STATUS_INVALID_STATE;
- } else if (!conn->conn) {
- SetError(error, "[SQLite] AdbcStatementNew: connection is not initialized");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- statement->private_data = malloc(sizeof(struct SqliteStatement));
- memset(statement->private_data, 0, sizeof(struct SqliteStatement));
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
- stmt->conn = conn->conn;
-
- // Default options
- stmt->batch_size = 1024;
-
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteStatementRelease(struct AdbcStatement* statement,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
-
- int rc = SQLITE_OK;
- if (stmt->stmt) {
- rc = sqlite3_finalize(stmt->stmt);
- }
- if (stmt->query) free(stmt->query);
- AdbcSqliteBinderRelease(&stmt->binder);
- if (stmt->target_catalog) free(stmt->target_catalog);
- if (stmt->target_table) free(stmt->target_table);
- if (rc != SQLITE_OK) {
- SetError(error,
- "[SQLite] AdbcStatementRelease: statement failed to finalize: (%d) %s", rc,
- sqlite3_errmsg(stmt->conn));
- }
- free(statement->private_data);
- statement->private_data = NULL;
-
- return rc == SQLITE_OK ? ADBC_STATUS_OK : ADBC_STATUS_IO;
-}
-
-AdbcStatusCode SqliteStatementPrepare(struct AdbcStatement* statement,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
-
- if (!stmt->query) {
- SetError(error, "[SQLite] Must SetSqlQuery before ExecuteQuery or Prepare");
- return ADBC_STATUS_INVALID_STATE;
- }
- if (stmt->prepared == 0) {
- if (stmt->stmt) {
- int rc = sqlite3_finalize(stmt->stmt);
- stmt->stmt = NULL;
- if (rc != SQLITE_OK) {
- SetError(error, "[SQLite] Failed to finalize previous statement: (%d) %s", rc,
- sqlite3_errmsg(stmt->conn));
- return ADBC_STATUS_IO;
- }
- }
-
- int rc =
- sqlite3_prepare_v2(stmt->conn, stmt->query, (int)stmt->query_len, &stmt->stmt,
- /*pzTail=*/NULL);
- if (rc != SQLITE_OK) {
- SetError(error, "[SQLite] Failed to prepare query: %s\nQuery:%s",
- sqlite3_errmsg(stmt->conn), stmt->query);
- (void)sqlite3_finalize(stmt->stmt);
- stmt->stmt = NULL;
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- stmt->prepared = 1;
- }
-
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteStatementInitIngest(struct SqliteStatement* stmt,
- sqlite3_stmt** insert_statement,
- struct AdbcError* error) {
- AdbcStatusCode code = ADBC_STATUS_OK;
-
- // Create statements for CREATE TABLE / INSERT
- sqlite3_str* create_query = NULL;
- sqlite3_str* insert_query = NULL;
- char* table = NULL;
-
- create_query = sqlite3_str_new(NULL);
- if (sqlite3_str_errcode(create_query)) {
- SetError(error, "[SQLite] %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- insert_query = sqlite3_str_new(NULL);
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- if (stmt->target_catalog != NULL && stmt->temporary != 0) {
- SetError(error, "[SQLite] Cannot specify both %s and %s",
- ADBC_INGEST_OPTION_TARGET_CATALOG, ADBC_INGEST_OPTION_TEMPORARY);
- code = ADBC_STATUS_INVALID_STATE;
- goto cleanup;
- }
-
- if (stmt->target_catalog != NULL) {
- table = sqlite3_mprintf("\"%w\" . \"%w\"", stmt->target_catalog, stmt->target_table);
- } else if (stmt->temporary == 0) {
- // If not temporary, explicitly target the main database
- table = sqlite3_mprintf("main . \"%w\"", stmt->target_table);
- } else {
- // OK to be redundant (CREATE TEMP TABLE temp.foo)
- table = sqlite3_mprintf("temp . \"%w\"", stmt->target_table);
- }
-
- if (table == NULL) {
- // Allocation failure
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- if (stmt->temporary != 0) {
- sqlite3_str_appendf(create_query, "CREATE TEMPORARY TABLE %s (", table);
- } else {
- sqlite3_str_appendf(create_query, "CREATE TABLE %s (", table);
- }
- if (sqlite3_str_errcode(create_query)) {
- SetError(error, "[SQLite] Failed to build CREATE: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- sqlite3_str_appendf(insert_query, "INSERT INTO %s (", table);
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] Failed to build INSERT: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- struct ArrowError arrow_error = {0};
- struct ArrowSchemaView view = {0};
- for (int i = 0; i < stmt->binder.schema.n_children; i++) {
- if (i > 0) {
- sqlite3_str_appendf(create_query, "%s", ", ");
- if (sqlite3_str_errcode(create_query)) {
- SetError(error, "[SQLite] Failed to build CREATE: %s",
- sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- sqlite3_str_appendf(insert_query, "%s", ", ");
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] Failed to build INSERT: %s",
- sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
- }
-
- sqlite3_str_appendf(create_query, "\"%w\"", stmt->binder.schema.children[i]->name);
- if (sqlite3_str_errcode(create_query)) {
- SetError(error, "[SQLite] Failed to build CREATE: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- sqlite3_str_appendf(insert_query, "\"%w\"", stmt->binder.schema.children[i]->name);
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] Failed to build INSERT: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- int status =
- ArrowSchemaViewInit(&view, stmt->binder.schema.children[i], &arrow_error);
- if (status != 0) {
- SetError(error, "[SQLite] Failed to parse schema for column %d: %s (%d): %s", i,
- strerror(status), status, arrow_error.message);
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- switch (view.type) {
- case NANOARROW_TYPE_BOOL:
- case NANOARROW_TYPE_UINT8:
- case NANOARROW_TYPE_UINT16:
- case NANOARROW_TYPE_UINT32:
- case NANOARROW_TYPE_UINT64:
- case NANOARROW_TYPE_INT8:
- case NANOARROW_TYPE_INT16:
- case NANOARROW_TYPE_INT32:
- case NANOARROW_TYPE_INT64:
- sqlite3_str_appendf(create_query, " INTEGER");
- break;
- case NANOARROW_TYPE_FLOAT:
- case NANOARROW_TYPE_DOUBLE:
- sqlite3_str_appendf(create_query, " REAL");
- break;
- case NANOARROW_TYPE_STRING:
- case NANOARROW_TYPE_LARGE_STRING:
- case NANOARROW_TYPE_DATE32:
- sqlite3_str_appendf(create_query, " TEXT");
- break;
- case NANOARROW_TYPE_BINARY:
- sqlite3_str_appendf(create_query, " BLOB");
- break;
- default:
- break;
- }
- }
-
- sqlite3_str_appendchar(create_query, 1, ')');
- if (sqlite3_str_errcode(create_query)) {
- SetError(error, "[SQLite] Failed to build CREATE: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- sqlite3_str_appendall(insert_query, ") VALUES (");
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] Failed to build INSERT: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- for (int i = 0; i < stmt->binder.schema.n_children; i++) {
- sqlite3_str_appendf(insert_query, "%s?", (i > 0 ? ", " : ""));
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] Failed to build INSERT: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
- }
-
- sqlite3_str_appendchar(insert_query, 1, ')');
- if (sqlite3_str_errcode(insert_query)) {
- SetError(error, "[SQLite] Failed to build INSERT: %s", sqlite3_errmsg(stmt->conn));
- code = ADBC_STATUS_INTERNAL;
- goto cleanup;
- }
-
- sqlite3_stmt* create = NULL;
- if (!stmt->append) {
- // Create table
- int rc =
- sqlite3_prepare_v2(stmt->conn, sqlite3_str_value(create_query),
- sqlite3_str_length(create_query), &create, /*pzTail=*/NULL);
- if (rc == SQLITE_OK) {
- rc = sqlite3_step(create);
- }
-
- if (rc != SQLITE_OK && rc != SQLITE_DONE) {
- SetError(error, "[SQLite] Failed to create table: %s (executed '%.*s')",
- sqlite3_errmsg(stmt->conn), sqlite3_str_length(create_query),
- sqlite3_str_value(create_query));
- code = ADBC_STATUS_INTERNAL;
- }
- }
-
- if (code == ADBC_STATUS_OK) {
- int rc = sqlite3_prepare_v2(stmt->conn, sqlite3_str_value(insert_query),
- sqlite3_str_length(insert_query), insert_statement,
- /*pzTail=*/NULL);
- if (rc != SQLITE_OK) {
- SetError(error, "[SQLite] Failed to prepare statement: %s (executed '%.*s')",
- sqlite3_errmsg(stmt->conn), sqlite3_str_length(insert_query),
- sqlite3_str_value(insert_query));
- code = ADBC_STATUS_INTERNAL;
- }
- }
-
- sqlite3_finalize(create);
-
-cleanup:
- sqlite3_free(sqlite3_str_finish(create_query));
- sqlite3_free(sqlite3_str_finish(insert_query));
- if (table != NULL) sqlite3_free(table);
- return code;
-}
-
-AdbcStatusCode SqliteStatementExecuteIngest(struct SqliteStatement* stmt,
- int64_t* rows_affected,
- struct AdbcError* error) {
- if (!stmt->binder.schema.release) {
- SetError(error, "[SQLite] Must Bind() before bulk ingestion");
- return ADBC_STATUS_INVALID_STATE;
- }
-
- sqlite3_stmt* insert = NULL;
- AdbcStatusCode status = SqliteStatementInitIngest(stmt, &insert, error);
-
- int64_t row_count = 0;
- int is_autocommit = sqlite3_get_autocommit(stmt->conn);
- if (status == ADBC_STATUS_OK) {
- if (is_autocommit) sqlite3_exec(stmt->conn, "BEGIN TRANSACTION", 0, 0, 0);
-
- while (1) {
- char finished = 0;
- status =
- AdbcSqliteBinderBindNext(&stmt->binder, stmt->conn, insert, &finished, error);
- if (status != ADBC_STATUS_OK || finished) break;
-
- int rc = 0;
- do {
- rc = sqlite3_step(insert);
- } while (rc == SQLITE_ROW);
- if (rc != SQLITE_DONE) {
- SetError(error, "[SQLite] Failed to execute statement: %s",
- sqlite3_errmsg(stmt->conn));
- status = ADBC_STATUS_INTERNAL;
- break;
- }
- row_count++;
- }
-
- if (is_autocommit) sqlite3_exec(stmt->conn, "COMMIT", 0, 0, 0);
- }
-
- if (rows_affected) *rows_affected = row_count;
- if (insert) sqlite3_finalize(insert);
- AdbcSqliteBinderRelease(&stmt->binder);
- return status;
-}
-
-AdbcStatusCode SqliteStatementExecuteQuery(struct AdbcStatement* statement,
- struct ArrowArrayStream* out,
- int64_t* rows_affected,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
-
- if (stmt->target_table) {
- return SqliteStatementExecuteIngest(stmt, rows_affected, error);
- }
-
- AdbcStatusCode status = SqliteStatementPrepare(statement, error);
- if (status != ADBC_STATUS_OK) return status;
-
- if (stmt->binder.schema.release) {
- int64_t expected = sqlite3_bind_parameter_count(stmt->stmt);
- int64_t actual = stmt->binder.schema.n_children;
- if (actual != expected) {
- SetError(error,
- "[SQLite] Parameter count mismatch: expected %" PRId64
- " but found %" PRId64,
- expected, actual);
- return ADBC_STATUS_INVALID_STATE;
- }
- }
-
- if (!out) {
- // Update
- sqlite3_mutex_enter(sqlite3_db_mutex(stmt->conn));
-
- AdbcStatusCode status = ADBC_STATUS_OK;
- int64_t rows = 0;
-
- while (1) {
- if (stmt->binder.schema.release) {
- char finished = 0;
- status = AdbcSqliteBinderBindNext(&stmt->binder, stmt->conn, stmt->stmt,
- &finished, error);
- if (status != ADBC_STATUS_OK || finished) {
- break;
- }
- }
-
- while (sqlite3_step(stmt->stmt) == SQLITE_ROW) {
- rows++;
- }
- if (!stmt->binder.schema.release) break;
- }
-
- if (sqlite3_reset(stmt->stmt) != SQLITE_OK) {
- status = ADBC_STATUS_IO;
- const char* msg = sqlite3_errmsg(stmt->conn);
- SetError(error, "[SQLite] Failed to execute query: %s",
- (msg == NULL) ? "(unknown error)" : msg);
- }
-
- sqlite3_mutex_leave(sqlite3_db_mutex(stmt->conn));
-
- AdbcSqliteBinderRelease(&stmt->binder);
- if (rows_affected) {
- if (sqlite3_column_count(stmt->stmt) == 0) {
- *rows_affected = sqlite3_changes(stmt->conn);
- } else {
- *rows_affected = rows;
- }
- }
- return status;
- }
-
- // Query
- if (rows_affected) *rows_affected = -1;
- struct AdbcSqliteBinder* binder = stmt->binder.schema.release ? &stmt->binder : NULL;
- return AdbcSqliteExportReader(stmt->conn, stmt->stmt, binder, stmt->batch_size, out,
- error);
-}
-
-AdbcStatusCode SqliteStatementSetSqlQuery(struct AdbcStatement* statement,
- const char* query, struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
-
- if (stmt->query) {
- free(stmt->query);
- stmt->query = NULL;
- }
- if (stmt->target_catalog) {
- free(stmt->target_catalog);
- stmt->target_catalog = NULL;
- }
- if (stmt->target_table) {
- free(stmt->target_table);
- stmt->target_table = NULL;
- }
- size_t len = strlen(query) + 1;
- stmt->query = malloc(len);
- stmt->query_len = len;
- stmt->prepared = 0;
- strncpy(stmt->query, query, len);
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteStatementSetSubstraitPlan(struct AdbcStatement* statement,
- const uint8_t* plan, size_t length,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- SetError(error, "[SQLite] Substrait is not supported");
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteStatementBind(struct AdbcStatement* statement,
- struct ArrowArray* values, struct ArrowSchema* schema,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
- return AdbcSqliteBinderSetArray(&stmt->binder, values, schema, error);
-}
-
-AdbcStatusCode SqliteStatementBindStream(struct AdbcStatement* statement,
- struct ArrowArrayStream* stream,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
- return AdbcSqliteBinderSetArrayStream(&stmt->binder, stream, error);
-}
-
-AdbcStatusCode SqliteStatementGetOption(struct AdbcStatement* statement, const char* key,
- char* value, size_t* length,
- struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteStatementGetOptionBytes(struct AdbcStatement* statement,
- const char* key, uint8_t* value,
- size_t* length, struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteStatementGetOptionDouble(struct AdbcStatement* statement,
- const char* key, double* value,
- struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteStatementGetOptionInt(struct AdbcStatement* statement,
- const char* key, int64_t* value,
- struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_FOUND;
-}
-
-AdbcStatusCode SqliteStatementGetParameterSchema(struct AdbcStatement* statement,
- struct ArrowSchema* schema,
- struct AdbcError* error) {
- AdbcStatusCode status = SqliteStatementPrepare(statement, error);
- if (status != ADBC_STATUS_OK) return status;
-
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
- int num_params = sqlite3_bind_parameter_count(stmt->stmt);
- if (num_params < 0) {
- // Should not happen
- SetError(error, "[SQLite] SQLite returned negative parameter count");
- return ADBC_STATUS_INTERNAL;
- }
-
- ArrowSchemaInit(schema);
- CHECK_NA(INTERNAL, ArrowSchemaSetType(schema, NANOARROW_TYPE_STRUCT), error);
- CHECK_NA(INTERNAL, ArrowSchemaAllocateChildren(schema, num_params), error);
- char buffer[12];
- for (int i = 0; i < num_params; i++) {
- const char* name = sqlite3_bind_parameter_name(stmt->stmt, i + 1);
- if (name == NULL) {
- snprintf(buffer, sizeof(buffer), "%d", i);
- name = buffer;
- }
- ArrowSchemaInit(schema->children[i]);
- CHECK_NA(INTERNAL, ArrowSchemaSetType(schema->children[i], NANOARROW_TYPE_NA), error);
- CHECK_NA(INTERNAL, ArrowSchemaSetName(schema->children[i], name), error);
- }
-
- return ADBC_STATUS_OK;
-}
-
-AdbcStatusCode SqliteStatementSetOption(struct AdbcStatement* statement, const char* key,
- const char* value, struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- struct SqliteStatement* stmt = (struct SqliteStatement*)statement->private_data;
-
- if (strcmp(key, ADBC_INGEST_OPTION_TARGET_TABLE) == 0) {
- if (stmt->query) {
- free(stmt->query);
- stmt->query = NULL;
- }
- if (stmt->target_table) {
- free(stmt->target_table);
- stmt->target_table = NULL;
- }
-
- size_t len = strlen(value) + 1;
- stmt->target_table = (char*)malloc(len);
- strncpy(stmt->target_table, value, len);
- return ADBC_STATUS_OK;
- } else if (strcmp(key, ADBC_INGEST_OPTION_TARGET_CATALOG) == 0) {
- if (stmt->query) {
- free(stmt->query);
- stmt->query = NULL;
- }
- if (stmt->target_catalog) {
- free(stmt->target_catalog);
- stmt->target_catalog = NULL;
- }
-
- size_t len = strlen(value) + 1;
- stmt->target_catalog = (char*)malloc(len);
- strncpy(stmt->target_catalog, value, len);
- return ADBC_STATUS_OK;
- } else if (strcmp(key, ADBC_INGEST_OPTION_MODE) == 0) {
- if (strcmp(value, ADBC_INGEST_OPTION_MODE_APPEND) == 0) {
- stmt->append = 1;
- } else if (strcmp(value, ADBC_INGEST_OPTION_MODE_CREATE) == 0) {
- stmt->append = 0;
- } else {
- SetError(error, "[SQLite] Invalid statement option value %s=%s", key, value);
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- return ADBC_STATUS_OK;
- } else if (strcmp(key, ADBC_INGEST_OPTION_TEMPORARY) == 0) {
- if (strcmp(value, ADBC_OPTION_VALUE_ENABLED) == 0) {
- stmt->temporary = 1;
- } else if (strcmp(value, ADBC_OPTION_VALUE_DISABLED) == 0) {
- stmt->temporary = 0;
- } else {
- SetError(error, "[SQLite] Invalid statement option value %s=%s", key, value);
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- return ADBC_STATUS_OK;
- } else if (strcmp(key, kStatementOptionBatchRows) == 0) {
- char* end = NULL;
- long batch_size = strtol(value, &end, /*base=*/10); // NOLINT(runtime/int)
- if (errno == ERANGE) {
- SetError(error, "[SQLite] Invalid statement option value %s=%s (out of range)", key,
- value);
- return ADBC_STATUS_INVALID_ARGUMENT;
- } else if (batch_size <= 0) {
- SetError(error,
- "[SQLite] Invalid statement option value %s=%s (value is non-positive or "
- "invalid)",
- key, value);
- return ADBC_STATUS_INVALID_ARGUMENT;
- } else if (batch_size > (long)INT_MAX) { // NOLINT(runtime/int)
- SetError(
- error,
- "[SQLite] Invalid statement option value %s=%s (value is out of range of int)",
- key, value);
- return ADBC_STATUS_INVALID_ARGUMENT;
- }
- stmt->batch_size = (int)batch_size;
- return ADBC_STATUS_OK;
- }
- SetError(error, "[SQLite] Unknown statement option %s=%s", key,
- value ? value : "(NULL)");
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteStatementSetOptionBytes(struct AdbcStatement* statement,
- const char* key, const uint8_t* value,
- size_t length, struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteStatementSetOptionDouble(struct AdbcStatement* statement,
- const char* key, double value,
- struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteStatementSetOptionInt(struct AdbcStatement* statement,
- const char* key, int64_t value,
- struct AdbcError* error) {
- CHECK_DB_INIT(statement, error);
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode SqliteStatementExecutePartitions(struct AdbcStatement* statement,
- struct ArrowSchema* schema,
- struct AdbcPartitions* partitions,
- int64_t* rows_affected,
- struct AdbcError* error) {
- CHECK_STMT_INIT(statement, error);
- SetError(error, "[SQLite] Partitioned result sets are not supported");
- return ADBC_STATUS_NOT_IMPLEMENTED;
-} // NOLINT(whitespace/indent)
-
-AdbcStatusCode SqliteDriverInit(int version, void* raw_driver, struct AdbcError* error) {
- if (version != ADBC_VERSION_1_0_0) {
- SetError(error, "[SQLite] Only version %d supported, got %d", ADBC_VERSION_1_0_0,
- version);
- return ADBC_STATUS_NOT_IMPLEMENTED;
- }
-
- struct AdbcDriver* driver = (struct AdbcDriver*)raw_driver;
- memset(driver, 0, ADBC_DRIVER_1_0_0_SIZE);
- driver->DatabaseInit = SqliteDatabaseInit;
- driver->DatabaseNew = SqliteDatabaseNew;
- driver->DatabaseRelease = SqliteDatabaseRelease;
- driver->DatabaseSetOption = SqliteDatabaseSetOption;
-
- driver->ConnectionCommit = SqliteConnectionCommit;
- driver->ConnectionGetInfo = SqliteConnectionGetInfo;
- driver->ConnectionGetObjects = SqliteConnectionGetObjects;
- driver->ConnectionGetTableSchema = SqliteConnectionGetTableSchema;
- driver->ConnectionGetTableTypes = SqliteConnectionGetTableTypes;
- driver->ConnectionInit = SqliteConnectionInit;
- driver->ConnectionNew = SqliteConnectionNew;
- driver->ConnectionReadPartition = SqliteConnectionReadPartition;
- driver->ConnectionRelease = SqliteConnectionRelease;
- driver->ConnectionRollback = SqliteConnectionRollback;
- driver->ConnectionSetOption = SqliteConnectionSetOption;
-
- driver->StatementBind = SqliteStatementBind;
- driver->StatementBindStream = SqliteStatementBindStream;
- driver->StatementExecuteQuery = SqliteStatementExecuteQuery;
- driver->StatementGetParameterSchema = SqliteStatementGetParameterSchema;
- driver->StatementNew = SqliteStatementNew;
- driver->StatementPrepare = SqliteStatementPrepare;
- driver->StatementRelease = SqliteStatementRelease;
- driver->StatementSetOption = SqliteStatementSetOption;
- driver->StatementSetSqlQuery = SqliteStatementSetSqlQuery;
- return ADBC_STATUS_OK;
-}
-
-// Public names
-
-AdbcStatusCode AdbcDatabaseGetOption(struct AdbcDatabase* database, const char* key,
- char* value, size_t* length,
- struct AdbcError* error) {
- return SqliteDatabaseGetOption(database, key, value, length, error);
-}
-
-AdbcStatusCode AdbcDatabaseGetOptionBytes(struct AdbcDatabase* database, const char* key,
- uint8_t* value, size_t* length,
- struct AdbcError* error) {
- return SqliteDatabaseGetOptionBytes(database, key, value, length, error);
-}
-
-AdbcStatusCode AdbcDatabaseGetOptionInt(struct AdbcDatabase* database, const char* key,
- int64_t* value, struct AdbcError* error) {
- return SqliteDatabaseGetOptionInt(database, key, value, error);
-}
-
-AdbcStatusCode AdbcDatabaseGetOptionDouble(struct AdbcDatabase* database, const char* key,
- double* value, struct AdbcError* error) {
- return SqliteDatabaseGetOptionDouble(database, key, value, error);
-}
-
-AdbcStatusCode AdbcDatabaseInit(struct AdbcDatabase* database, struct AdbcError* error) {
- return SqliteDatabaseInit(database, error);
-}
-
-AdbcStatusCode AdbcDatabaseNew(struct AdbcDatabase* database, struct AdbcError* error) {
- return SqliteDatabaseNew(database, error);
-}
-
-AdbcStatusCode AdbcDatabaseRelease(struct AdbcDatabase* database,
- struct AdbcError* error) {
- return SqliteDatabaseRelease(database, error);
-}
-
-AdbcStatusCode AdbcDatabaseSetOption(struct AdbcDatabase* database, const char* key,
- const char* value, struct AdbcError* error) {
- return SqliteDatabaseSetOption(database, key, value, error);
-}
-
-AdbcStatusCode AdbcDatabaseSetOptionBytes(struct AdbcDatabase* database, const char* key,
- const uint8_t* value, size_t length,
- struct AdbcError* error) {
- return SqliteDatabaseSetOptionBytes(database, key, value, length, error);
-}
-
-AdbcStatusCode AdbcDatabaseSetOptionInt(struct AdbcDatabase* database, const char* key,
- int64_t value, struct AdbcError* error) {
- return SqliteDatabaseSetOptionInt(database, key, value, error);
-}
-
-AdbcStatusCode AdbcDatabaseSetOptionDouble(struct AdbcDatabase* database, const char* key,
- double value, struct AdbcError* error) {
- return SqliteDatabaseSetOptionDouble(database, key, value, error);
-}
-
-AdbcStatusCode AdbcConnectionCancel(struct AdbcConnection* connection,
- struct AdbcError* error) {
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode AdbcConnectionGetOption(struct AdbcConnection* connection, const char* key,
- char* value, size_t* length,
- struct AdbcError* error) {
- return SqliteConnectionGetOption(connection, key, value, length, error);
-}
-
-AdbcStatusCode AdbcConnectionGetOptionBytes(struct AdbcConnection* connection,
- const char* key, uint8_t* value,
- size_t* length, struct AdbcError* error) {
- return SqliteConnectionGetOptionBytes(connection, key, value, length, error);
-}
-
-AdbcStatusCode AdbcConnectionGetOptionInt(struct AdbcConnection* connection,
- const char* key, int64_t* value,
- struct AdbcError* error) {
- return SqliteConnectionGetOptionInt(connection, key, value, error);
-}
-
-AdbcStatusCode AdbcConnectionGetOptionDouble(struct AdbcConnection* connection,
- const char* key, double* value,
- struct AdbcError* error) {
- return SqliteConnectionGetOptionDouble(connection, key, value, error);
-}
-
-AdbcStatusCode AdbcConnectionNew(struct AdbcConnection* connection,
- struct AdbcError* error) {
- return SqliteConnectionNew(connection, error);
-}
-
-AdbcStatusCode AdbcConnectionSetOption(struct AdbcConnection* connection, const char* key,
- const char* value, struct AdbcError* error) {
- return SqliteConnectionSetOption(connection, key, value, error);
-}
-
-AdbcStatusCode AdbcConnectionSetOptionBytes(struct AdbcConnection* connection,
- const char* key, const uint8_t* value,
- size_t length, struct AdbcError* error) {
- return SqliteConnectionSetOptionBytes(connection, key, value, length, error);
-}
-
-AdbcStatusCode AdbcConnectionSetOptionInt(struct AdbcConnection* connection,
- const char* key, int64_t value,
- struct AdbcError* error) {
- return SqliteConnectionSetOptionInt(connection, key, value, error);
-}
-
-AdbcStatusCode AdbcConnectionSetOptionDouble(struct AdbcConnection* connection,
- const char* key, double value,
- struct AdbcError* error) {
- return SqliteConnectionSetOptionDouble(connection, key, value, error);
-}
-
-AdbcStatusCode AdbcConnectionInit(struct AdbcConnection* connection,
- struct AdbcDatabase* database,
- struct AdbcError* error) {
- return SqliteConnectionInit(connection, database, error);
-}
-
-AdbcStatusCode AdbcConnectionRelease(struct AdbcConnection* connection,
- struct AdbcError* error) {
- return SqliteConnectionRelease(connection, error);
-}
-
-AdbcStatusCode AdbcConnectionGetInfo(struct AdbcConnection* connection,
- const uint32_t* info_codes, size_t info_codes_length,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- return SqliteConnectionGetInfo(connection, info_codes, info_codes_length, out, error);
-}
-
-AdbcStatusCode AdbcConnectionGetObjects(struct AdbcConnection* connection, int depth,
- const char* catalog, const char* db_schema,
- const char* table_name, const char** table_type,
- const char* column_name,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- return SqliteConnectionGetObjects(connection, depth, catalog, db_schema, table_name,
- table_type, column_name, out, error);
-}
-
-AdbcStatusCode AdbcConnectionGetStatistics(struct AdbcConnection* connection,
- const char* catalog, const char* db_schema,
- const char* table_name, char approximate,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode AdbcConnectionGetStatisticNames(struct AdbcConnection* connection,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode AdbcConnectionGetTableSchema(struct AdbcConnection* connection,
- const char* catalog, const char* db_schema,
- const char* table_name,
- struct ArrowSchema* schema,
- struct AdbcError* error) {
- return SqliteConnectionGetTableSchema(connection, catalog, db_schema, table_name,
- schema, error);
-}
-
-AdbcStatusCode AdbcConnectionGetTableTypes(struct AdbcConnection* connection,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- return SqliteConnectionGetTableTypes(connection, out, error);
-}
-
-AdbcStatusCode AdbcConnectionReadPartition(struct AdbcConnection* connection,
- const uint8_t* serialized_partition,
- size_t serialized_length,
- struct ArrowArrayStream* out,
- struct AdbcError* error) {
- return SqliteConnectionReadPartition(connection, serialized_partition,
- serialized_length, out, error);
-}
-
-AdbcStatusCode AdbcConnectionCommit(struct AdbcConnection* connection,
- struct AdbcError* error) {
- return SqliteConnectionCommit(connection, error);
-}
-
-AdbcStatusCode AdbcConnectionRollback(struct AdbcConnection* connection,
- struct AdbcError* error) {
- return SqliteConnectionRollback(connection, error);
-}
-
-AdbcStatusCode AdbcStatementCancel(struct AdbcStatement* statement,
- struct AdbcError* error) {
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode AdbcStatementNew(struct AdbcConnection* connection,
- struct AdbcStatement* statement,
- struct AdbcError* error) {
- return SqliteStatementNew(connection, statement, error);
-}
-
-AdbcStatusCode AdbcStatementRelease(struct AdbcStatement* statement,
- struct AdbcError* error) {
- return SqliteStatementRelease(statement, error);
-}
-
-AdbcStatusCode AdbcStatementExecuteQuery(struct AdbcStatement* statement,
- struct ArrowArrayStream* out,
- int64_t* rows_affected,
- struct AdbcError* error) {
- return SqliteStatementExecuteQuery(statement, out, rows_affected, error);
-}
-
-AdbcStatusCode AdbcStatementExecuteSchema(struct AdbcStatement* statement,
- struct ArrowSchema* schema,
- struct AdbcError* error) {
- return ADBC_STATUS_NOT_IMPLEMENTED;
-}
-
-AdbcStatusCode AdbcStatementPrepare(struct AdbcStatement* statement,
- struct AdbcError* error) {
- return SqliteStatementPrepare(statement, error);
-}
-
-AdbcStatusCode AdbcStatementSetSqlQuery(struct AdbcStatement* statement,
- const char* query, struct AdbcError* error) {
- return SqliteStatementSetSqlQuery(statement, query, error);
-}
-
-AdbcStatusCode AdbcStatementSetSubstraitPlan(struct AdbcStatement* statement,
- const uint8_t* plan, size_t length,
- struct AdbcError* error) {
- return SqliteStatementSetSubstraitPlan(statement, plan, length, error);
-}
-
-AdbcStatusCode AdbcStatementBind(struct AdbcStatement* statement,
- struct ArrowArray* values, struct ArrowSchema* schema,
- struct AdbcError* error) {
- return SqliteStatementBind(statement, values, schema, error);
-}
-
-AdbcStatusCode AdbcStatementBindStream(struct AdbcStatement* statement,
- struct ArrowArrayStream* stream,
- struct AdbcError* error) {
- return SqliteStatementBindStream(statement, stream, error);
-}
-
-AdbcStatusCode AdbcStatementGetOption(struct AdbcStatement* statement, const char* key,
- char* value, size_t* length,
- struct AdbcError* error) {
- return SqliteStatementGetOption(statement, key, value, length, error);
-}
-
-AdbcStatusCode AdbcStatementGetOptionBytes(struct AdbcStatement* statement,
- const char* key, uint8_t* value,
- size_t* length, struct AdbcError* error) {
- return SqliteStatementGetOptionBytes(statement, key, value, length, error);
-}
-
-AdbcStatusCode AdbcStatementGetOptionInt(struct AdbcStatement* statement, const char* key,
- int64_t* value, struct AdbcError* error) {
- return SqliteStatementGetOptionInt(statement, key, value, error);
-}
-
-AdbcStatusCode AdbcStatementGetOptionDouble(struct AdbcStatement* statement,
- const char* key, double* value,
- struct AdbcError* error) {
- return SqliteStatementGetOptionDouble(statement, key, value, error);
-}
-
-AdbcStatusCode AdbcStatementGetParameterSchema(struct AdbcStatement* statement,
- struct ArrowSchema* schema,
- struct AdbcError* error) {
- return SqliteStatementGetParameterSchema(statement, schema, error);
-}
-
-AdbcStatusCode AdbcStatementSetOption(struct AdbcStatement* statement, const char* key,
- const char* value, struct AdbcError* error) {
- return SqliteStatementSetOption(statement, key, value, error);
-}
-
-AdbcStatusCode AdbcStatementSetOptionBytes(struct AdbcStatement* statement,
- const char* key, const uint8_t* value,
- size_t length, struct AdbcError* error) {
- return SqliteStatementSetOptionBytes(statement, key, value, length, error);
-}
-
-AdbcStatusCode AdbcStatementSetOptionInt(struct AdbcStatement* statement, const char* key,
- int64_t value, struct AdbcError* error) {
- return SqliteStatementSetOptionInt(statement, key, value, error);
-}
-
-AdbcStatusCode AdbcStatementSetOptionDouble(struct AdbcStatement* statement,
- const char* key, double value,
- struct AdbcError* error) {
- return SqliteStatementSetOptionDouble(statement, key, value, error);
-}
-
-AdbcStatusCode AdbcStatementExecutePartitions(struct AdbcStatement* statement,
- struct ArrowSchema* schema,
- struct AdbcPartitions* partitions,
- int64_t* rows_affected,
- struct AdbcError* error) {
- return SqliteStatementExecutePartitions(statement, schema, partitions, rows_affected,
- error);
-} // NOLINT(whitespace/indent)
-// due to https://github.com/cpplint/cpplint/pull/189
-
-ADBC_EXPORT
-AdbcStatusCode AdbcDriverInit(int version, void* driver, struct AdbcError* error) {
- return SqliteDriverInit(version, driver, error);
-}
diff --git a/c/driver/sqlite/sqlite.cc b/c/driver/sqlite/sqlite.cc
new file mode 100644
index 000000000..364333789
--- /dev/null
+++ b/c/driver/sqlite/sqlite.cc
@@ -0,0 +1,1482 @@
+// 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 <cstdarg>
+#include <limits>
+
+#include <adbc.h>
+#include <nanoarrow/nanoarrow.h>
+#include <sqlite3.h>
+#include <nanoarrow/nanoarrow.hpp>
+
+#include "driver/common/options.h"
+#include "driver/common/utils.h"
+#include "driver/framework/base.h"
+#include "driver/framework/base_connection.h"
+#include "driver/framework/base_database.h"
+#include "driver/framework/base_statement.h"
+#include "driver/framework/catalog.h"
+#include "driver/framework/status.h"
+#include "driver/sqlite/statement_reader.h"
+
+namespace adbc::sqlite {
+
+using driver::Result;
+using driver::Status;
+namespace status = adbc::driver::status;
+
+namespace {
+constexpr std::string_view kDefaultUri =
+ "file:adbc_driver_sqlite?mode=memory&cache=shared";
+constexpr std::string_view kConnectionOptionEnableLoadExtension =
+ "adbc.sqlite.load_extension.enabled";
+constexpr std::string_view kConnectionOptionLoadExtensionPath =
+ "adbc.sqlite.load_extension.path";
+constexpr std::string_view kConnectionOptionLoadExtensionEntrypoint =
+ "adbc.sqlite.load_extension.entrypoint";
+/// The batch size for query results (and for initial type inference)
+constexpr std::string_view kStatementOptionBatchRows = "adbc.sqlite.query.batch_rows";
+
+std::string_view GetColumnText(sqlite3_stmt* stmt, int index) {
+ return {
+ reinterpret_cast<const char*>(sqlite3_column_text(stmt, index)),
+ static_cast<size_t>(sqlite3_column_bytes(stmt, index)),
+ };
+}
+
+class SqliteMutexGuard {
+ public:
+ explicit SqliteMutexGuard(sqlite3* conn) : conn_(conn) {
+ sqlite3_mutex_enter(sqlite3_db_mutex(conn_));
+ }
+ ~SqliteMutexGuard() {
+ if (conn_) {
+ sqlite3_mutex_leave(sqlite3_db_mutex(conn_));
+ }
+ conn_ = nullptr;
+ }
+
+ private:
+ sqlite3* conn_;
+};
+
+class SqliteStringBuilder {
+ public:
+ SqliteStringBuilder() : str_(sqlite3_str_new(nullptr)) {}
+
+ ~SqliteStringBuilder() {
+ // sqlite3_free is no-op on nullptr
+ sqlite3_free(result_);
+ result_ = nullptr;
+ if (str_) {
+ sqlite3_free(sqlite3_str_finish(str_));
+ str_ = nullptr;
+ }
+ }
+
+ void Reset() {
+ std::ignore = GetString();
+ sqlite3_free(result_);
+ result_ = nullptr;
+ str_ = sqlite3_str_new(nullptr);
+ }
+
+ void Append(std::string_view fmt, ...) {
+ if (str_) {
+ va_list args;
+ va_start(args, fmt);
+ sqlite3_str_vappendf(str_, fmt.data(), args);
+ va_end(args);
+ }
+ }
+
+ Result<std::string_view> GetString() {
+ int len = 0;
+ if (!result_) {
+ if (int rc = sqlite3_str_errcode(str_); rc == SQLITE_NOMEM) {
+ return status::Internal("out of memory building query");
+ } else if (rc == SQLITE_TOOBIG) {
+ return status::Internal("query too long");
+ } else if (rc != SQLITE_OK) {
+ return status::Internal("unknown SQLite error ({})", rc);
+ }
+ len = sqlite3_str_length(str_);
+ result_ = sqlite3_str_finish(str_);
+ str_ = nullptr;
+ }
+ return std::string_view(result_, len);
+ }
+
+ private:
+ sqlite3_str* str_ = nullptr;
+ char* result_ = nullptr;
+};
+
+class SqliteQuery {
+ public:
+ explicit SqliteQuery(sqlite3* conn, std::string_view query)
+ : conn_(conn), query_(query) {}
+
+ Status Init() {
+ int rc = sqlite3_prepare_v2(conn_, query_.data(), static_cast<int>(query_.size()),
+ &stmt_, /*pzTail=*/nullptr);
+ if (rc != SQLITE_OK) {
+ return Close(rc);
+ }
+ return status::Ok();
+ }
+
+ Result<bool> Next() {
+ if (!stmt_) {
+ return status::Internal(
+ "query already finished or never initialized\nquery was: {}", query_);
+ }
+ int rc = sqlite3_step(stmt_);
+ if (rc == SQLITE_ROW) {
+ return true;
+ } else if (rc == SQLITE_DONE) {
+ return false;
+ }
+ return Close(rc);
+ }
+
+ Status Close(int rc) {
+ if (stmt_) {
+ int rc = sqlite3_finalize(stmt_);
+ stmt_ = nullptr;
+ if (rc != SQLITE_OK && rc != SQLITE_DONE) {
+ return status::Internal("failed to execute: {}\nquery was: {}",
+ sqlite3_errmsg(conn_), query_);
+ }
+ } else if (rc != SQLITE_OK) {
+ return status::Internal("failed to execute: {}\nquery was: {}",
+ sqlite3_errmsg(conn_), query_);
+ }
+ return status::Ok();
+ }
+
+ Status Close() { return Close(SQLITE_OK); }
+
+ sqlite3_stmt* stmt() const { return stmt_; }
+
+ static Status Execute(sqlite3* conn, std::string_view query) {
+ SqliteQuery q(conn, query);
+ UNWRAP_STATUS(q.Init());
+ while (true) {
+ UNWRAP_RESULT(bool has_row, q.Next());
+ if (!has_row) break;
+ }
+ return q.Close();
+ }
+
+ template <typename BindFunc, typename RowFunc>
+ static Status Scan(sqlite3* conn, std::string_view query, BindFunc&& bind_func,
+ RowFunc&& row_func) {
+ SqliteQuery q(conn, query);
+ UNWRAP_STATUS(q.Init());
+
+ int rc = std::forward<BindFunc>(bind_func)(q.stmt_);
+ if (rc != SQLITE_OK) return q.Close();
+
+ while (true) {
+ UNWRAP_RESULT(bool has_row, q.Next());
+ if (!has_row) break;
+
+ int rc = std::forward<RowFunc>(row_func)(q.stmt_);
+ if (rc != SQLITE_OK) break;
+ }
+ return q.Close();
+ }
+
+ private:
+ sqlite3* conn_ = nullptr;
+ std::string_view query_;
+ sqlite3_stmt* stmt_ = nullptr;
+};
+
+constexpr std::string_view kNoFilter = "%";
+
+struct SqliteGetObjectsHelper : public driver::GetObjectsHelper {
+ explicit SqliteGetObjectsHelper(sqlite3* conn) : conn(conn) {}
+
+ Status Load(driver::GetObjectsDepth depth,
+ std::optional<std::string_view> catalog_filter,
+ std::optional<std::string_view> schema_filter,
+ std::optional<std::string_view> table_filter,
+ std::optional<std::string_view> column_filter,
+ const std::vector<std::string_view>& table_types) override {
+ std::string query =
+ "SELECT DISTINCT name FROM pragma_database_list() WHERE name LIKE ?";
+
+ this->table_filter = table_filter;
+ this->column_filter = column_filter;
+ this->table_types = table_types;
+
+ UNWRAP_STATUS(SqliteQuery::Scan(
+ conn, query,
+ [&](sqlite3_stmt* stmt) {
+ auto filter = catalog_filter.value_or(kNoFilter);
+ return sqlite3_bind_text(stmt, 1, filter.data(),
+ static_cast<int>(filter.size()), SQLITE_STATIC);
+ },
+ [&](sqlite3_stmt* stmt) {
+ catalogs.emplace_back(GetColumnText(stmt, 0));
+ return SQLITE_OK;
+ }));
+
+ // SQLite doesn't have schemas, so we assume each catalog has a single
+ // unnamed schema.
+ if (!schema_filter.has_value() || schema_filter->empty()) {
+ schemas = {""};
+ } else {
+ schemas = {};
+ }
+
+ return status::Ok();
+ }
+
+ Status LoadCatalogs() override { return status::Ok(); };
+
+ Result<std::optional<std::string_view>> NextCatalog() override {
+ if (next_catalog >= catalogs.size()) return std::nullopt;
+ return catalogs[next_catalog++];
+ }
+
+ Status LoadSchemas(std::string_view catalog) override {
+ next_schema = 0;
+ return status::Ok();
+ };
+
+ Result<std::optional<std::string_view>> NextSchema() override {
+ if (next_schema >= schemas.size()) return std::nullopt;
+ return schemas[next_schema++];
+ }
+
+ Status LoadTables(std::string_view catalog, std::string_view schema) override {
+ next_table = 0;
+ tables.clear();
+ if (!schema.empty()) return status::Ok();
+
+ SqliteStringBuilder builder;
+ builder.Append(R"(SELECT name, type FROM "%w" . sqlite_master WHERE name LIKE ?)",
+ catalog.data());
+ if (!table_types.empty()) {
+ builder.Append(" AND (");
+ bool first = true;
+ for (const auto& table_type : table_types) {
+ if (first) {
+ builder.Append(" type = %Q", table_type.data());
+ first = false;
+ } else {
+ builder.Append(" OR type = %Q", table_type.data());
+ }
+ }
+ builder.Append(" )");
+ }
+ UNWRAP_RESULT(auto query, builder.GetString());
+
+ return SqliteQuery::Scan(
+ conn, query,
+ [&](sqlite3_stmt* stmt) {
+ auto filter = table_filter.value_or(kNoFilter);
+ return sqlite3_bind_text(stmt, 1, filter.data(),
+ static_cast<int>(filter.size()), SQLITE_STATIC);
+ },
+ [&](sqlite3_stmt* stmt) {
+ tables.emplace_back(GetColumnText(stmt, 0), GetColumnText(stmt, 1));
+ return SQLITE_OK;
+ });
+ };
+
+ Result<std::optional<Table>> NextTable() override {
+ if (next_table >= tables.size()) return std::nullopt;
+ const auto& table = tables[next_table++];
+ return Table{table.first, table.second};
+ }
+
+ Status LoadColumns(std::string_view catalog, std::string_view schema,
+ std::string_view table) override {
+ // XXX: pragma_table_info doesn't appear to work with bind parameters
+ // XXX: because we're saving the SqliteQuery, we also need to save the string builder
+ columns_query.Reset();
+ columns_query.Append(
+ R"(SELECT cid, name, type, "notnull", dflt_value FROM pragma_table_info("%w" , "%w") WHERE NAME LIKE ?)",
+ table.data(), catalog.data());
+ UNWRAP_RESULT(auto query, columns_query.GetString());
+ assert(!query.empty());
+
+ columns.emplace(conn, query);
+ UNWRAP_STATUS(columns->Init());
+
+ auto filter = column_filter.value_or(kNoFilter);
+ int rc = sqlite3_bind_text(columns->stmt(), 1, filter.data(),
+ static_cast<int>(filter.size()), SQLITE_STATIC);
+ if (rc != SQLITE_OK) {
+ return columns->Close(rc);
+ }
+
+ // As with columns, we could return constraints iteratively instead of
+ // reading them all up front, but that complicates the state management
+
+ // We can get primary keys and foreign keys, but not unique constraints
+ // (unless we parse the SQL table definition)
+
+ // XXX: n + 1 query pattern. You can join on a pragma so we could avoid
+ // this in principle but it complicates the unpacking code here quite a
+ // bit, so ignore for now. Also, we already have to issue a query per table.
+ constraints.clear();
+ next_constraint = 0;
+
+ // Get the primary key
+ {
+ SqliteStringBuilder builder;
+ builder.Append(
+ R"(SELECT name FROM pragma_table_info("%w" , "%w") WHERE pk > 0 ORDER BY pk ASC)",
+ table.data(), catalog.data());
+ UNWRAP_RESULT(auto pk_query, builder.GetString());
+ std::vector<std::string> pk;
+ UNWRAP_STATUS(SqliteQuery::Scan(
+ conn, pk_query, [](sqlite3_stmt*) { return SQLITE_OK; },
+ [&](sqlite3_stmt* stmt) {
+ pk.emplace_back(std::string(GetColumnText(stmt, 0)));
+ return SQLITE_OK;
+ }));
+ if (!pk.empty()) {
+ // it would be nice to have C++20 designated initializers...
+ constraints.emplace_back(OwnedConstraint{
+ std::nullopt,
+ "PRIMARY KEY",
+ std::move(pk),
+ std::nullopt,
+ });
+ }
+ }
+
+ // Get any foreign keys
+ if (catalog == "main") {
+ // XXX: it appears experimentally that pragma_foreign_key_list won't let
+ // you specify the database, making the result ambiguous. We'll only
+ // query for the main catalog, but it appears if there's a table with
+ // the same name in a different database, SQLite will still happily
+ // return it here.
+ constexpr std::string_view kForeignKeyQuery =
+ R"(SELECT id, seq, "table", "from", "to"
+ FROM pragma_foreign_key_list(?)
+ ORDER BY id, seq ASC)";
+ int prev_id = -1;
+ UNWRAP_STATUS(SqliteQuery::Scan(
+ conn, kForeignKeyQuery,
+ [&](sqlite3_stmt* stmt) {
+ return sqlite3_bind_text(stmt, 1, table.data(),
+ static_cast<int>(table.size()), SQLITE_STATIC);
+ },
+ [&](sqlite3_stmt* stmt) {
+ int fk_id = sqlite3_column_int(stmt, 0);
+ auto to_table = GetColumnText(stmt, 2);
+ auto from_col = GetColumnText(stmt, 3);
+ auto to_col = GetColumnText(stmt, 4);
+
+ if (fk_id != prev_id) {
+ prev_id = fk_id;
+ constraints.emplace_back(OwnedConstraint{
+ std::nullopt,
+ "FOREIGN KEY",
+ {},
+ std::make_optional<std::vector<OwnedConstraintUsage>>(),
+ });
+ }
+ constraints.back().column_names.emplace_back(from_col);
+ constraints.back().usage->emplace_back(OwnedConstraintUsage{
+ "main",
+ "",
+ std::string(to_table),
+ std::string(to_col),
+ });
+
+ return SQLITE_OK;
+ }));
+ }
+
+ return status::Ok();
+ };
+
+ Result<std::optional<Column>> NextColumn() override {
+ if (!columns) return std::nullopt;
+ UNWRAP_RESULT(auto has_next, columns->Next());
+ if (!has_next) {
+ auto query = std::move(*columns);
+ columns.reset();
+ UNWRAP_STATUS(query.Close());
+ return std::nullopt;
+ }
+
+ ColumnXdbc xdbc;
+ bool notnull = sqlite3_column_int(columns->stmt(), 3) != 0;
+ xdbc.xdbc_type_name = GetColumnText(columns->stmt(), 2);
+ xdbc.xdbc_nullable = notnull ? 0 : 1;
+ if (sqlite3_column_type(columns->stmt(), 4) != SQLITE_NULL) {
+ xdbc.xdbc_column_def = GetColumnText(columns->stmt(), 4);
+ }
+ xdbc.xdbc_is_nullable = notnull ? "NO" : "YES";
+ return Column{
+ reinterpret_cast<const char*>(sqlite3_column_text(columns->stmt(), 1)),
+ sqlite3_column_int(columns->stmt(), 0) + 1,
+ std::nullopt,
+ xdbc,
+ };
+ }
+
+ Result<std::optional<Constraint>> NextConstraint() override {
+ if (next_constraint >= constraints.size()) return std::nullopt;
+ return constraints[next_constraint++].ToDriver();
+ }
+
+ struct OwnedConstraintUsage {
+ std::optional<std::string> catalog;
+ std::optional<std::string> schema;
+ std::string table;
+ std::string column;
+
+ ConstraintUsage ToDriver() const {
+ auto catalog = this->catalog ? std::make_optional(std::string_view(*this->catalog))
+ : std::nullopt;
+ auto schema = this->schema ? std::make_optional(std::string_view(*this->schema))
+ : std::nullopt;
+ return {catalog, schema, table, column};
+ }
+ };
+
+ struct OwnedConstraint {
+ std::optional<std::string> name;
+ std::string type;
+ std::vector<std::string> column_names;
+ std::optional<std::vector<OwnedConstraintUsage>> usage;
+
+ Constraint ToDriver() const {
+ auto name =
+ this->name ? std::make_optional(std::string_view(*this->name)) : std::nullopt;
+ std::vector<std::string_view> column_names;
+ std::vector<ConstraintUsage> usages;
+ for (const auto& column_name : this->column_names) {
+ column_names.emplace_back(column_name);
+ }
+ if (this->usage) {
+ for (const auto& usage : *this->usage) {
+ usages.emplace_back(usage.ToDriver());
+ }
+ return {name, type, std::move(column_names), std::move(usages)};
+ }
+ return {name, type, std::move(column_names), std::nullopt};
+ }
+ };
+
+ sqlite3* conn = nullptr;
+ std::optional<std::string_view> table_filter;
+ std::optional<std::string_view> column_filter;
+ std::vector<std::string_view> table_types;
+ std::vector<std::string> catalogs;
+ std::vector<std::string> schemas;
+ std::vector<std::pair<std::string, std::string>> tables;
+ std::vector<OwnedConstraint> constraints;
+ SqliteStringBuilder columns_query;
+ std::optional<SqliteQuery> columns;
+ size_t next_catalog = 0;
+ size_t next_schema = 0;
+ size_t next_table = 0;
+ size_t next_constraint = 0;
+};
+
+class SqliteDatabase : public driver::DatabaseBase<SqliteDatabase> {
+ public:
+ [[maybe_unused]] constexpr static std::string_view kErrorPrefix = "[SQLite]";
+
+ Result<sqlite3*> OpenConnection() {
+ sqlite3* conn;
+ int rc = sqlite3_open_v2(uri_.c_str(), &conn,
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI,
+ /*zVfs=*/nullptr);
+ if (rc != SQLITE_OK) {
+ Status status;
+ if (conn_) {
+ status = status::IO("failed to open '{}': {}", uri_, sqlite3_errmsg(conn));
+ } else {
+ status = status::IO("failed to open '{}': failed to allocate memory", uri_);
+ }
+ (void)sqlite3_close(conn);
+ return status;
+ }
+ return conn;
+ }
+
+ Status InitImpl() override {
+ UNWRAP_RESULT(conn_, OpenConnection());
+ return status::Ok();
+ }
+
+ Status ReleaseImpl() override {
+ if (conn_) {
+ int rc = sqlite3_close_v2(conn_);
+ if (rc != SQLITE_OK) {
+ return status::IO("failed to close connection: ({}) {}", rc,
+ sqlite3_errmsg(conn_));
+ }
+ conn_ = nullptr;
+ }
+ return Base::ReleaseImpl();
+ }
+
+ Status SetOptionImpl(std::string_view key, driver::Option value) override {
+ if (key == "uri") {
+ if (lifecycle_state_ != driver::LifecycleState::kUninitialized) {
+ return status::InvalidState("cannot set uri after AdbcDatabaseInit");
+ }
+ UNWRAP_RESULT(auto uri, value.AsString());
+ uri_ = std::move(uri);
+ return status::Ok();
+ }
+ return Base::SetOptionImpl(key, value);
+ }
+
+ private:
+ std::string uri_{kDefaultUri};
+ sqlite3* conn_ = nullptr;
+};
+
+class SqliteConnection : public driver::ConnectionBase<SqliteConnection> {
+ public:
+ [[maybe_unused]] constexpr static std::string_view kErrorPrefix = "[SQLite]";
+
+ sqlite3* conn() const { return conn_; }
+
+ Status CommitImpl() {
+ UNWRAP_STATUS(CheckOpen());
+ UNWRAP_STATUS(SqliteQuery::Execute(conn_, "COMMIT"));
+ // begin another transaction, since we're not in autocommit
+ return SqliteQuery::Execute(conn_, "BEGIN");
+ }
+
+ Result<std::optional<std::string>> GetCurrentCatalogImpl() { return "main"; }
+
+ Result<std::unique_ptr<driver::GetObjectsHelper>> GetObjectsImpl() {
+ return std::make_unique<SqliteGetObjectsHelper>(conn_);
+ }
+
+ Status GetTableSchemaImpl(std::optional<std::string_view> catalog,
+ std::optional<std::string_view> db_schema,
+ std::string_view table_name, ArrowSchema* schema) {
+ if (db_schema.has_value() && !db_schema->empty()) {
+ return status::NotImplemented("SQLite does not support schemas");
+ }
+
+ SqliteStringBuilder builder;
+ builder.Append(R"(SELECT * FROM "%w" . "%w")", catalog.value_or("main").data(),
+ table_name.data());
+ UNWRAP_RESULT(std::string_view query, builder.GetString());
+
+ sqlite3_stmt* stmt = nullptr;
+ int rc =
+ sqlite3_prepare_v2(conn_, query.data(), static_cast<int>(query.size()), &stmt,
+ /*pzTail=*/nullptr);
+ if (rc != SQLITE_OK) {
+ (void)sqlite3_finalize(stmt);
+ return status::NotFound("GetTableSchema: {}", sqlite3_errmsg(conn_));
+ }
+
+ nanoarrow::UniqueArrayStream stream;
+ struct AdbcError error = ADBC_ERROR_INIT;
+ AdbcStatusCode status =
+ AdbcSqliteExportReader(conn_, stmt, /*binder=*/NULL,
+ /*batch_size=*/64, stream.get(), &error);
+ if (status == ADBC_STATUS_OK) {
+ int code = stream->get_schema(stream.get(), schema);
+ if (code != 0) {
+ (void)sqlite3_finalize(stmt);
+ return status::IO("failed to get schema: ({}) {}", code, std::strerror(code));
+ }
+ }
+ (void)sqlite3_finalize(stmt);
+ return Status::FromAdbc(status, error);
+ }
+
+ Result<std::vector<std::string>> GetTableTypesImpl() {
+ return std::vector<std::string>{"table", "view"};
+ }
+
+ Result<std::vector<driver::InfoValue>> InfoImpl(const std::vector<uint32_t>& codes) {
+ static std::vector<uint32_t> kDefaultCodes{
+ ADBC_INFO_VENDOR_NAME, ADBC_INFO_VENDOR_VERSION, ADBC_INFO_DRIVER_NAME,
+ ADBC_INFO_DRIVER_VERSION, ADBC_INFO_DRIVER_ARROW_VERSION,
+ };
+ std::reference_wrapper<const std::vector<uint32_t>> codes_ref(codes);
+ if (codes.empty()) {
+ codes_ref = kDefaultCodes;
+ }
+
+ std::vector<driver::InfoValue> result;
+ for (const auto code : codes_ref.get()) {
+ switch (code) {
+ case ADBC_INFO_VENDOR_NAME:
+ result.emplace_back(code, "SQLite");
+ break;
+ case ADBC_INFO_VENDOR_VERSION:
+ result.emplace_back(code, sqlite3_libversion());
+ break;
+ case ADBC_INFO_DRIVER_NAME:
+ result.emplace_back(code, "ADBC SQLite Driver");
+ break;
+ case ADBC_INFO_DRIVER_VERSION:
+ // TODO(lidavidm): fill in driver version
+ result.emplace_back(code, "(unknown)");
+ break;
+ case ADBC_INFO_DRIVER_ARROW_VERSION:
+ result.emplace_back(code, NANOARROW_VERSION);
+ break;
+ default:
+ // Ignore
+ continue;
+ }
+ }
+
+ return result;
+ }
+
+ Status InitImpl(void* parent) {
+ auto& db = *reinterpret_cast<SqliteDatabase*>(parent);
+ UNWRAP_RESULT(conn_, db.OpenConnection());
+ return status::Ok();
+ }
+
+ Status ReleaseImpl() {
+ if (conn_) {
+ int rc = sqlite3_close_v2(conn_);
+ if (rc != SQLITE_OK) {
+ return status::IO("failed to close connection: ({}) {}", rc,
+ sqlite3_errmsg(conn_));
+ }
+ conn_ = nullptr;
+ }
+ return ConnectionBase::ReleaseImpl();
+ }
+
+ Status RollbackImpl() {
+ UNWRAP_STATUS(CheckOpen());
+ UNWRAP_STATUS(SqliteQuery::Execute(conn_, "ROLLBACK"));
+ return SqliteQuery::Execute(conn_, "BEGIN");
+ }
+
+ Status SetOptionImpl(std::string_view key, driver::Option value) {
+ if (key == kConnectionOptionEnableLoadExtension) {
+ if (!conn_ || lifecycle_state_ != driver::LifecycleState::kInitialized) {
+ return status::InvalidState(
+ "cannot enable extension loading before AdbcConnectionInit");
+ }
+ UNWRAP_RESULT(const bool enabled, value.AsBool());
+ int rc = sqlite3_db_config(conn_, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,
+ enabled ? 1 : 0, nullptr);
+ if (rc != SQLITE_OK) {
+ return status::IO("cannot enable extension loading: {}", sqlite3_errmsg(conn_));
+ }
+ return status::Ok();
+ } else if (key == kConnectionOptionLoadExtensionPath) {
+ if (!conn_ || lifecycle_state_ != driver::LifecycleState::kInitialized) {
+ return status::InvalidState("cannot load extension before AdbcConnectionInit");
+ }
+
+ UNWRAP_RESULT(extension_path_, value.AsString());
+ return status::Ok();
+ } else if (key == kConnectionOptionLoadExtensionEntrypoint) {
+#if !defined(ADBC_SQLITE_WITH_NO_LOAD_EXTENSION)
+ if (extension_path_.empty()) {
+ return status::InvalidState("{} can only be set after {}",
+ kConnectionOptionLoadExtensionEntrypoint,
+ kConnectionOptionLoadExtensionPath);
+ }
+ const char* extension_entrypoint = nullptr;
+ if (value.has_value()) {
+ UNWRAP_RESULT(auto entrypoint, value.AsString());
+ extension_entrypoint = entrypoint.data();
+ }
+
+ char* message = NULL;
+ int rc = sqlite3_load_extension(conn_, extension_path_.c_str(),
+ extension_entrypoint, &message);
+ if (rc != SQLITE_OK) {
+ auto status = status::Unknown(
+ "failed to load extension {} (entrypoint {}): {}", extension_path_,
+ extension_entrypoint ? extension_entrypoint : "(NULL)",
+ message ? message : "(unknown error)");
+ if (message) sqlite3_free(message);
+ return status;
+ }
+ extension_path_.clear();
+ return status::Ok();
+#else
+ return status::NotImplemented(
+ "this driver build does not support extension loading");
+#endif
+ }
+ return Base::SetOptionImpl(key, value);
+ }
+
+ Status ToggleAutocommitImpl(bool enable_autocommit) {
+ UNWRAP_STATUS(CheckOpen());
+ if (enable_autocommit) {
+ // that means we have an open transaction, just commit
+ return SqliteQuery::Execute(conn_, "COMMIT");
+ }
+ // that means we have no open transaction, just begin
+ return SqliteQuery::Execute(conn_, "BEGIN");
+ }
+
+ private:
+ Status CheckOpen() const {
+ if (!conn_) {
+ return status::InvalidState("connection is not open");
+ }
+ return status::Ok();
+ }
+
+ sqlite3* conn_ = nullptr;
+ // Temporarily hold the extension path (since the path and entrypoint need
+ // to be set separately)
+ std::string extension_path_;
+};
+
+class SqliteStatement : public driver::StatementBase<SqliteStatement> {
+ public:
+ [[maybe_unused]] constexpr static std::string_view kErrorPrefix = "[SQLite]";
+
+ Status BindImpl() {
+ if (bind_parameters_.release) {
+ struct AdbcError error = ADBC_ERROR_INIT;
+ if (AdbcStatusCode code =
+ AdbcSqliteBinderSetArrayStream(&binder_, &bind_parameters_, &error);
+ code != ADBC_STATUS_OK) {
+ return Status::FromAdbc(code, error);
+ }
+ }
+ return status::Ok();
+ }
+
+ Result<int64_t> ExecuteIngestImpl(IngestState& state) {
+ UNWRAP_STATUS(BindImpl());
+ if (!binder_.schema.release) {
+ return status::InvalidState("must Bind() before bulk ingestion");
+ }
+
+ // Parameter validation
+
+ if (state.target_catalog && state.temporary) {
+ return status::InvalidState("{} Cannot set both {} and {}", kErrorPrefix,
+ ADBC_INGEST_OPTION_TARGET_CATALOG,
+ ADBC_INGEST_OPTION_TEMPORARY);
+ } else if (state.target_schema) {
+ return status::NotImplemented("{} {} not supported", kErrorPrefix,
+ ADBC_INGEST_OPTION_TARGET_DB_SCHEMA);
+ } else if (!state.target_table) {
+ return status::InvalidState("{} Must set {}", kErrorPrefix,
+ ADBC_INGEST_OPTION_TARGET_TABLE);
+ }
+
+ // Create statements for creating the table, inserting a row, and the table name
+
+ SqliteStringBuilder create_query, drop_query, insert_query, table_builder;
+ if (state.target_catalog) {
+ table_builder.Append(R"("%w" . "%w")", state.target_catalog->c_str(),
+ state.target_table->c_str());
+ } else if (state.temporary) {
+ // OK to be redundant (CREATE TEMP TABLE temp.foo)
+ table_builder.Append(R"(temp . "%w")", state.target_table->c_str());
+ } else {
+ // If not temporary, explicitly target the main database
+ table_builder.Append(R"(main . "%w")", state.target_table->c_str());
+ }
+
+ UNWRAP_RESULT(std::string_view table, table_builder.GetString());
+
+ switch (state.table_exists_) {
+ case Base::TableExists::kAppend:
+ if (state.temporary) {
+ create_query.Append("CREATE TEMPORARY TABLE IF NOT EXISTS %s (", table.data());
+ } else {
+ create_query.Append("CREATE TABLE IF NOT EXISTS %s (", table.data());
+ }
+ break;
+ case Base::TableExists::kFail:
+ case Base::TableExists::kReplace:
+ if (state.temporary) {
+ create_query.Append("CREATE TEMPORARY TABLE %s (", table.data());
+ } else {
+ create_query.Append("CREATE TABLE %s (", table.data());
+ }
+ drop_query.Append("DROP TABLE IF EXISTS %s", table.data());
+ break;
+ }
+
+ insert_query.Append("INSERT INTO %s (", table.data());
+
+ struct ArrowError arrow_error = {0};
+ struct ArrowSchemaView view;
+ std::memset(&view, 0, sizeof(view));
+ for (int i = 0; i < binder_.schema.n_children; i++) {
+ if (i > 0) {
+ create_query.Append(", ");
+ insert_query.Append(", ");
+ }
+
+ create_query.Append(R"("%w")", binder_.schema.children[i]->name);
+ insert_query.Append(R"("%w")", binder_.schema.children[i]->name);
+
+ int status = ArrowSchemaViewInit(&view, binder_.schema.children[i], &arrow_error);
+ if (status != 0) {
+ return status::Internal("failed to parse schema for column {}: {} ({}): {}", i,
+ std::strerror(status), status, arrow_error.message);
+ }
+
+ switch (view.type) {
+ case NANOARROW_TYPE_BOOL:
+ case NANOARROW_TYPE_UINT8:
+ case NANOARROW_TYPE_UINT16:
+ case NANOARROW_TYPE_UINT32:
+ case NANOARROW_TYPE_UINT64:
+ case NANOARROW_TYPE_INT8:
+ case NANOARROW_TYPE_INT16:
+ case NANOARROW_TYPE_INT32:
+ case NANOARROW_TYPE_INT64:
+ create_query.Append(" INTEGER");
+ break;
+ case NANOARROW_TYPE_FLOAT:
+ case NANOARROW_TYPE_DOUBLE:
+ create_query.Append(" REAL");
+ break;
+ case NANOARROW_TYPE_STRING:
+ case NANOARROW_TYPE_LARGE_STRING:
+ case NANOARROW_TYPE_DATE32:
+ create_query.Append(" TEXT");
+ break;
+ case NANOARROW_TYPE_BINARY:
+ create_query.Append(" BLOB");
+ break;
+ default:
+ break;
+ }
+ }
+
+ create_query.Append(")");
+ insert_query.Append(") VALUES (");
+ for (int i = 0; i < binder_.schema.n_children; i++) {
+ insert_query.Append("%s?", (i > 0 ? ", " : ""));
+ }
+ insert_query.Append(")");
+
+ UNWRAP_RESULT(std::string_view create, create_query.GetString());
+ UNWRAP_RESULT(std::string_view drop, drop_query.GetString());
+ UNWRAP_RESULT(std::string_view insert, insert_query.GetString());
+
+ // Drop/create tables as needed
+
+ switch (state.table_exists_) {
+ case Base::TableExists::kAppend:
+ case Base::TableExists::kFail:
+ // Do nothing
+ break;
+ case Base::TableExists::kReplace: {
+ UNWRAP_STATUS(::adbc::sqlite::SqliteQuery::Execute(conn_, drop));
+ break;
+ }
+ }
+ switch (state.table_does_not_exist_) {
+ case Base::TableDoesNotExist::kCreate: {
+ UNWRAP_STATUS(::adbc::sqlite::SqliteQuery::Execute(conn_, create));
+ break;
+ }
+ case Base::TableDoesNotExist::kFail:
+ // Do nothing
+ break;
+ }
+
+ // Insert
+ int64_t row_count = 0;
+ const int is_autocommit = sqlite3_get_autocommit(conn_);
+ if (is_autocommit) {
+ UNWRAP_STATUS(::adbc::sqlite::SqliteQuery::Execute(conn_, "BEGIN"));
+ }
+
+ assert(!insert.empty());
+ sqlite3_stmt* stmt = nullptr;
+ {
+ int rc = sqlite3_prepare_v2(conn_, insert.data(), static_cast<int>(insert.size()),
+ &stmt, /*pzTail=*/nullptr);
+ if (rc != SQLITE_OK) {
+ std::ignore = sqlite3_finalize(stmt);
+ return status::Internal("failed to prepare: {}\nquery was: {}",
+ sqlite3_errmsg(conn_), insert);
+ }
+ }
+ assert(stmt != nullptr);
+
+ AdbcStatusCode status = ADBC_STATUS_OK;
+ struct AdbcError error = ADBC_ERROR_INIT;
+ while (true) {
+ char finished = 0;
+ status = AdbcSqliteBinderBindNext(&binder_, conn_, stmt, &finished, &error);
+ if (status != ADBC_STATUS_OK || finished) break;
+
+ int rc = 0;
+ do {
+ rc = sqlite3_step(stmt);
+ } while (rc == SQLITE_ROW);
+ if (rc != SQLITE_DONE) {
+ SetError(&error, "failed to execute: %s\nquery was: %s", sqlite3_errmsg(conn_),
+ insert.data());
+ status = ADBC_STATUS_INTERNAL;
+ break;
+ }
+ row_count++;
+ }
+ std::ignore = sqlite3_finalize(stmt);
+
+ if (is_autocommit) {
+ if (status == ADBC_STATUS_OK) {
+ UNWRAP_STATUS(::adbc::sqlite::SqliteQuery::Execute(conn_, "COMMIT"));
+ } else {
+ UNWRAP_STATUS(::adbc::sqlite::SqliteQuery::Execute(conn_, "ROLLBACK"));
+ }
+ }
+
+ if (status != ADBC_STATUS_OK) {
+ return Status::FromAdbc(status, error);
+ }
+ return row_count;
+ }
+
+ Result<int64_t> ExecuteQueryImpl(ArrowArrayStream* stream) {
+ struct AdbcError error = ADBC_ERROR_INIT;
+ UNWRAP_STATUS(BindImpl());
+
+ const int64_t expected = sqlite3_bind_parameter_count(stmt_);
+ const int64_t actual = binder_.schema.n_children;
+ if (actual != expected) {
+ return status::InvalidState("parameter count mismatch: expected {} but found {}",
+ expected, actual);
+ }
+
+ auto status =
+ AdbcSqliteExportReader(conn_, stmt_, binder_.schema.release ? &binder_ : nullptr,
+ batch_size_, stream, &error);
+ if (status != ADBC_STATUS_OK) {
+ return Status::FromAdbc(status, error);
+ }
+ return -1;
+ }
+
+ Result<int64_t> ExecuteQueryImpl(PreparedState& state, ArrowArrayStream* stream) {
+ return ExecuteQueryImpl(stream);
+ }
+
+ Result<int64_t> ExecuteQueryImpl(QueryState& state, ArrowArrayStream* stream) {
+ UNWRAP_STATUS(PrepareImpl(state));
+ return ExecuteQueryImpl(stream);
+ }
+
+ Result<int64_t> ExecuteUpdateImpl() {
+ UNWRAP_STATUS(BindImpl());
+
+ const int64_t expected = sqlite3_bind_parameter_count(stmt_);
+ const int64_t actual = binder_.schema.n_children;
+ if (actual != expected) {
+ return status::InvalidState("parameter count mismatch: expected {} but found {}",
+ expected, actual);
+ }
+
+ int64_t rows = 0;
+
+ SqliteMutexGuard guard(conn_);
+
+ while (true) {
+ if (binder_.schema.release) {
+ char finished = 0;
+ struct AdbcError error = ADBC_ERROR_INIT;
+ if (AdbcStatusCode code =
+ AdbcSqliteBinderBindNext(&binder_, conn_, stmt_, &finished, &error);
+ code != ADBC_STATUS_OK) {
+ AdbcSqliteBinderRelease(&binder_);
+ return Status::FromAdbc(code, error);
+ } else if (finished != 0) {
+ break;
+ }
+ }
+
+ while (sqlite3_step(stmt_) == SQLITE_ROW) {
+ rows++;
+ }
+
+ if (!binder_.schema.release) break;
+ }
+ AdbcSqliteBinderRelease(&binder_);
+
+ if (sqlite3_reset(stmt_) != SQLITE_OK) {
+ const char* msg = sqlite3_errmsg(conn_);
+ return status::IO("failed to execute query: {}", msg ? msg : "(unknown error)");
+ }
+
+ if (sqlite3_column_count(stmt_) == 0) {
+ rows = sqlite3_changes(conn_);
+ }
+ return rows;
+ }
+
+ Result<int64_t> ExecuteUpdateImpl(PreparedState& state) { return ExecuteUpdateImpl(); }
+
+ Result<int64_t> ExecuteUpdateImpl(QueryState& state) {
+ UNWRAP_STATUS(PrepareImpl(state));
+ return ExecuteUpdateImpl();
+ }
+
+ Status GetParameterSchemaImpl(PreparedState& state, ArrowSchema* schema) {
+ int num_params = sqlite3_bind_parameter_count(stmt_);
+ if (num_params < 0) {
+ // Should not happen
+ return status::Internal("{} SQLite returned negative parameter count",
+ kErrorPrefix);
+ }
+
+ nanoarrow::UniqueSchema uschema;
+ ArrowSchemaInit(uschema.get());
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(uschema.get(), NANOARROW_TYPE_STRUCT));
+ UNWRAP_ERRNO(Internal, ArrowSchemaAllocateChildren(uschema.get(), num_params));
+ char buffer[12];
+ for (int i = 0; i < num_params; i++) {
+ const char* name = sqlite3_bind_parameter_name(stmt_, i + 1);
+ if (name == NULL) {
+ snprintf(buffer, sizeof(buffer), "%d", i);
+ name = buffer;
+ }
+ ArrowSchemaInit(uschema->children[i]);
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetType(uschema->children[i], NANOARROW_TYPE_NA));
+ UNWRAP_ERRNO(Internal, ArrowSchemaSetName(uschema->children[i], name));
+ }
+
+ uschema.move(schema);
+ return status::Ok();
+ }
+
+ Status InitImpl(void* parent) {
+ conn_ = reinterpret_cast<SqliteConnection*>(parent)->conn();
+ return StatementBase::InitImpl(parent);
+ }
+
+ Status PrepareImpl(QueryState& state) {
+ if (stmt_) {
+ int rc = sqlite3_finalize(stmt_);
+ stmt_ = nullptr;
+ if (rc != SQLITE_OK) {
+ return status::IO("{} Failed to finalize previous statement: ({}) {}",
+ kErrorPrefix, rc, sqlite3_errmsg(conn_));
+ }
+ }
+
+ int rc = sqlite3_prepare_v2(conn_, state.query.c_str(),
+ static_cast<int>(state.query.size()), &stmt_,
+ /*pzTail=*/nullptr);
+ if (rc != SQLITE_OK) {
+ std::string msg = sqlite3_errmsg(conn_);
+ std::ignore = sqlite3_finalize(stmt_);
+ stmt_ = NULL;
+ return status::InvalidArgument("{} Failed to prepare query: {}\nquery: {}",
+ kErrorPrefix, msg, state.query);
+ }
+ return status::Ok();
+ }
+
+ Status ReleaseImpl() {
+ if (stmt_) {
+ int rc = sqlite3_finalize(stmt_);
+ stmt_ = nullptr;
+ if (rc != SQLITE_OK) {
+ return status::IO("{} Failed to finalize statement: ({}) {}", kErrorPrefix, rc,
+ sqlite3_errmsg(conn_));
+ }
+ }
+ AdbcSqliteBinderRelease(&binder_);
+ return StatementBase::ReleaseImpl();
+ }
+
+ Status SetOptionImpl(std::string_view key, driver::Option value) {
+ if (key == kStatementOptionBatchRows) {
+ UNWRAP_RESULT(int64_t batch_size, value.AsInt());
+ if (batch_size >= std::numeric_limits<int>::max() || batch_size <= 0) {
+ return status::InvalidArgument(
+ "{} Invalid statement option value {}={} (value is non-positive or out of "
+ "range of int)",
+ kErrorPrefix, key, value);
+ }
+ batch_size_ = static_cast<int>(batch_size);
+ return status::Ok();
+ }
+ return Base::SetOptionImpl(key, std::move(value));
+ }
+
+ int batch_size_ = 1024;
+ AdbcSqliteBinder binder_;
+ sqlite3* conn_ = nullptr;
+ sqlite3_stmt* stmt_ = nullptr;
+};
+
+using SqliteDriver =
+ adbc::driver::Driver<SqliteDatabase, SqliteConnection, SqliteStatement>;
+} // namespace
+} // namespace adbc::sqlite
+
+// Public names
+
+AdbcStatusCode AdbcDatabaseGetOption(struct AdbcDatabase* database, const char* key,
+ char* value, size_t* length,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOption<>(database, key, value, length, error);
+}
+
+AdbcStatusCode AdbcDatabaseGetOptionBytes(struct AdbcDatabase* database, const char* key,
+ uint8_t* value, size_t* length,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionBytes<>(database, key, value, length,
+ error);
+}
+
+AdbcStatusCode AdbcDatabaseGetOptionInt(struct AdbcDatabase* database, const char* key,
+ int64_t* value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionInt<>(database, key, value, error);
+}
+
+AdbcStatusCode AdbcDatabaseGetOptionDouble(struct AdbcDatabase* database, const char* key,
+ double* value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionDouble<>(database, key, value, error);
+}
+
+AdbcStatusCode AdbcDatabaseInit(struct AdbcDatabase* database, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CDatabaseInit(database, error);
+}
+
+AdbcStatusCode AdbcDatabaseNew(struct AdbcDatabase* database, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CNew<>(database, error);
+}
+
+AdbcStatusCode AdbcDatabaseRelease(struct AdbcDatabase* database,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CRelease<>(database, error);
+}
+
+AdbcStatusCode AdbcDatabaseSetOption(struct AdbcDatabase* database, const char* key,
+ const char* value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOption<>(database, key, value, error);
+}
+
+AdbcStatusCode AdbcDatabaseSetOptionBytes(struct AdbcDatabase* database, const char* key,
+ const uint8_t* value, size_t length,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionBytes<>(database, key, value, length,
+ error);
+}
+
+AdbcStatusCode AdbcDatabaseSetOptionInt(struct AdbcDatabase* database, const char* key,
+ int64_t value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionInt<>(database, key, value, error);
+}
+
+AdbcStatusCode AdbcDatabaseSetOptionDouble(struct AdbcDatabase* database, const char* key,
+ double value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionDouble<>(database, key, value, error);
+}
+
+AdbcStatusCode AdbcConnectionCancel(struct AdbcConnection* connection,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionCancel(connection, error);
+}
+
+AdbcStatusCode AdbcConnectionGetOption(struct AdbcConnection* connection, const char* key,
+ char* value, size_t* length,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOption<>(connection, key, value, length, error);
+}
+
+AdbcStatusCode AdbcConnectionGetOptionBytes(struct AdbcConnection* connection,
+ const char* key, uint8_t* value,
+ size_t* length, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionBytes<>(connection, key, value, length,
+ error);
+}
+
+AdbcStatusCode AdbcConnectionGetOptionInt(struct AdbcConnection* connection,
+ const char* key, int64_t* value,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionInt<>(connection, key, value, error);
+}
+
+AdbcStatusCode AdbcConnectionGetOptionDouble(struct AdbcConnection* connection,
+ const char* key, double* value,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionDouble<>(connection, key, value, error);
+}
+
+AdbcStatusCode AdbcConnectionNew(struct AdbcConnection* connection,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CNew<>(connection, error);
+}
+
+AdbcStatusCode AdbcConnectionSetOption(struct AdbcConnection* connection, const char* key,
+ const char* value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOption<>(connection, key, value, error);
+}
+
+AdbcStatusCode AdbcConnectionSetOptionBytes(struct AdbcConnection* connection,
+ const char* key, const uint8_t* value,
+ size_t length, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionBytes<>(connection, key, value, length,
+ error);
+}
+
+AdbcStatusCode AdbcConnectionSetOptionInt(struct AdbcConnection* connection,
+ const char* key, int64_t value,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionInt<>(connection, key, value, error);
+}
+
+AdbcStatusCode AdbcConnectionSetOptionDouble(struct AdbcConnection* connection,
+ const char* key, double value,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionDouble<>(connection, key, value, error);
+}
+
+AdbcStatusCode AdbcConnectionInit(struct AdbcConnection* connection,
+ struct AdbcDatabase* database,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionInit(connection, database, error);
+}
+
+AdbcStatusCode AdbcConnectionRelease(struct AdbcConnection* connection,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CRelease<>(connection, error);
+}
+
+AdbcStatusCode AdbcConnectionGetInfo(struct AdbcConnection* connection,
+ const uint32_t* info_codes, size_t info_codes_length,
+ struct ArrowArrayStream* out,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionGetInfo(connection, info_codes,
+ info_codes_length, out, error);
+}
+
+AdbcStatusCode AdbcConnectionGetObjects(struct AdbcConnection* connection, int depth,
+ const char* catalog, const char* db_schema,
+ const char* table_name, const char** table_type,
+ const char* column_name,
+ struct ArrowArrayStream* out,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionGetObjects(
+ connection, depth, catalog, db_schema, table_name, table_type, column_name, out,
+ error);
+}
+
+AdbcStatusCode AdbcConnectionGetStatistics(struct AdbcConnection* connection,
+ const char* catalog, const char* db_schema,
+ const char* table_name, char approximate,
+ struct ArrowArrayStream* out,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionGetStatistics(
+ connection, catalog, db_schema, table_name, approximate, out, error);
+}
+
+AdbcStatusCode AdbcConnectionGetStatisticNames(struct AdbcConnection* connection,
+ struct ArrowArrayStream* out,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionGetStatisticNames(connection, out, error);
+}
+
+AdbcStatusCode AdbcConnectionGetTableSchema(struct AdbcConnection* connection,
+ const char* catalog, const char* db_schema,
+ const char* table_name,
+ struct ArrowSchema* schema,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionGetTableSchema(
+ connection, catalog, db_schema, table_name, schema, error);
+}
+
+AdbcStatusCode AdbcConnectionGetTableTypes(struct AdbcConnection* connection,
+ struct ArrowArrayStream* out,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionGetTableTypes(connection, out, error);
+}
+
+AdbcStatusCode AdbcConnectionReadPartition(struct AdbcConnection* connection,
+ const uint8_t* serialized_partition,
+ size_t serialized_length,
+ struct ArrowArrayStream* out,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionReadPartition(
+ connection, serialized_partition, serialized_length, out, error);
+}
+
+AdbcStatusCode AdbcConnectionCommit(struct AdbcConnection* connection,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionCommit(connection, error);
+}
+
+AdbcStatusCode AdbcConnectionRollback(struct AdbcConnection* connection,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CConnectionRollback(connection, error);
+}
+
+AdbcStatusCode AdbcStatementCancel(struct AdbcStatement* statement,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementCancel(statement, error);
+}
+
+AdbcStatusCode AdbcStatementNew(struct AdbcConnection* connection,
+ struct AdbcStatement* statement,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementNew(connection, statement, error);
+}
+
+AdbcStatusCode AdbcStatementRelease(struct AdbcStatement* statement,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CRelease<>(statement, error);
+}
+
+AdbcStatusCode AdbcStatementExecuteQuery(struct AdbcStatement* statement,
+ struct ArrowArrayStream* out,
+ int64_t* rows_affected,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementExecuteQuery(statement, out, rows_affected,
+ error);
+}
+
+AdbcStatusCode AdbcStatementExecuteSchema(struct AdbcStatement* statement,
+ struct ArrowSchema* schema,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementExecuteSchema(statement, schema, error);
+}
+
+AdbcStatusCode AdbcStatementPrepare(struct AdbcStatement* statement,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementPrepare(statement, error);
+}
+
+AdbcStatusCode AdbcStatementSetSqlQuery(struct AdbcStatement* statement,
+ const char* query, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementSetSqlQuery(statement, query, error);
+}
+
+AdbcStatusCode AdbcStatementSetSubstraitPlan(struct AdbcStatement* statement,
+ const uint8_t* plan, size_t length,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementSetSubstraitPlan(statement, plan, length,
+ error);
+}
+
+AdbcStatusCode AdbcStatementBind(struct AdbcStatement* statement,
+ struct ArrowArray* values, struct ArrowSchema* schema,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementBind(statement, values, schema, error);
+}
+
+AdbcStatusCode AdbcStatementBindStream(struct AdbcStatement* statement,
+ struct ArrowArrayStream* stream,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementBindStream(statement, stream, error);
+}
+
+AdbcStatusCode AdbcStatementGetOption(struct AdbcStatement* statement, const char* key,
+ char* value, size_t* length,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOption<>(statement, key, value, length, error);
+}
+
+AdbcStatusCode AdbcStatementGetOptionBytes(struct AdbcStatement* statement,
+ const char* key, uint8_t* value,
+ size_t* length, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionBytes<>(statement, key, value, length,
+ error);
+}
+
+AdbcStatusCode AdbcStatementGetOptionInt(struct AdbcStatement* statement, const char* key,
+ int64_t* value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionInt<>(statement, key, value, error);
+}
+
+AdbcStatusCode AdbcStatementGetOptionDouble(struct AdbcStatement* statement,
+ const char* key, double* value,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CGetOptionDouble<>(statement, key, value, error);
+}
+
+AdbcStatusCode AdbcStatementGetParameterSchema(struct AdbcStatement* statement,
+ struct ArrowSchema* schema,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementGetParameterSchema(statement, schema,
+ error);
+}
+
+AdbcStatusCode AdbcStatementSetOption(struct AdbcStatement* statement, const char* key,
+ const char* value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOption<>(statement, key, value, error);
+}
+
+AdbcStatusCode AdbcStatementSetOptionBytes(struct AdbcStatement* statement,
+ const char* key, const uint8_t* value,
+ size_t length, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionBytes<>(statement, key, value, length,
+ error);
+}
+
+AdbcStatusCode AdbcStatementSetOptionInt(struct AdbcStatement* statement, const char* key,
+ int64_t value, struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionInt<>(statement, key, value, error);
+}
+
+AdbcStatusCode AdbcStatementSetOptionDouble(struct AdbcStatement* statement,
+ const char* key, double value,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CSetOptionDouble<>(statement, key, value, error);
+}
+
+AdbcStatusCode AdbcStatementExecutePartitions(struct AdbcStatement* statement,
+ struct ArrowSchema* schema,
+ struct AdbcPartitions* partitions,
+ int64_t* rows_affected,
+ struct AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::CStatementExecutePartitions(
+ statement, schema, partitions, rows_affected, error);
+}
+
+extern "C" {
+[[maybe_unused]] ADBC_EXPORT AdbcStatusCode AdbcDriverSqliteInit(int version,
+ void* raw_driver,
+ AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::Init(version, raw_driver, error);
+}
+
+[[maybe_unused]] ADBC_EXPORT AdbcStatusCode SqliteDriverInit(int version,
+ void* raw_driver,
+ AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::Init(version, raw_driver, error);
+}
+
+[[maybe_unused]] ADBC_EXPORT AdbcStatusCode AdbcDriverInit(int version, void* raw_driver,
+ AdbcError* error) {
+ return adbc::sqlite::SqliteDriver::Init(version, raw_driver, error);
+}
+}
diff --git a/c/driver/sqlite/sqlite_test.cc b/c/driver/sqlite/sqlite_test.cc
index 70a1ad670..72fe0d150 100644
--- a/c/driver/sqlite/sqlite_test.cc
+++ b/c/driver/sqlite/sqlite_test.cc
@@ -132,14 +132,13 @@ class SqliteQuirks : public adbc_validation::DriverQuirks {
return ddl;
}
- bool supports_bulk_ingest(const char* mode) const override {
- return std::strcmp(mode, ADBC_INGEST_OPTION_MODE_APPEND) == 0 ||
- std::strcmp(mode, ADBC_INGEST_OPTION_MODE_CREATE) == 0;
- }
+ bool supports_bulk_ingest(const char* mode) const override { return true; }
bool supports_bulk_ingest_catalog() const override { return true; }
bool supports_bulk_ingest_temporary() const override { return true; }
bool supports_concurrent_statements() const override { return true; }
- bool supports_get_option() const override { return false; }
+ bool supports_metadata_current_catalog() const override { return true; }
+ bool supports_metadata_current_db_schema() const override { return false; }
+ bool supports_get_option() const override { return true; }
std::optional<adbc_validation::SqlInfoValue> supports_get_sql_info(
uint32_t info_code) const override {
switch (info_code) {
diff --git a/c/driver/sqlite/statement_reader.c b/c/driver/sqlite/statement_reader.c
index 9e02ee3b8..0c57c1aff 100644
--- a/c/driver/sqlite/statement_reader.c
+++ b/c/driver/sqlite/statement_reader.c
@@ -28,7 +28,7 @@
#include <nanoarrow/nanoarrow.h>
#include <sqlite3.h>
-#include "common/utils.h"
+#include "driver/common/utils.h"
AdbcStatusCode AdbcSqliteBinderSet(struct AdbcSqliteBinder* binder,
struct AdbcError* error) {
diff --git a/c/driver/sqlite/types.h b/c/driver/sqlite/types.h
deleted file mode 100644
index 1b1b408cc..000000000
--- a/c/driver/sqlite/types.h
+++ /dev/null
@@ -1,64 +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.
-
-#pragma once
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <adbc.h>
-#include <sqlite3.h>
-
-#include "statement_reader.h"
-
-struct SqliteDatabase {
- sqlite3* db;
- char* uri;
- size_t connection_count;
-};
-
-struct SqliteConnection {
- sqlite3* conn;
- char active_transaction;
- char load_extension;
-
- // Temporarily store an extension to load (need both entrypoint and path)
- char* extension_path;
-};
-
-struct SqliteStatement {
- sqlite3* conn;
-
- // -- Query state -----------------------------------------
-
- sqlite3_stmt* stmt;
- char prepared;
- char* query;
- size_t query_len;
-
- // -- Bind state ------------------------------------------
- struct AdbcSqliteBinder binder;
-
- // -- Ingest state ----------------------------------------
- char* target_catalog;
- char* target_table;
- char append;
- char temporary;
-
- // -- Query options ---------------------------------------
- int batch_size;
-};
diff --git a/c/driver_manager/adbc_driver_manager_test.cc b/c/driver_manager/adbc_driver_manager_test.cc
index 18e0a87dc..0eaf644b9 100644
--- a/c/driver_manager/adbc_driver_manager_test.cc
+++ b/c/driver_manager/adbc_driver_manager_test.cc
@@ -105,7 +105,7 @@ TEST_F(DriverManager, ConnectionOptions) {
IsOkStatus(&error));
ASSERT_EQ(ADBC_STATUS_NOT_IMPLEMENTED,
AdbcConnectionInit(&connection, &database, &error));
- ASSERT_THAT(error.message, ::testing::HasSubstr("Unknown connection option foo=bar"));
+ ASSERT_THAT(error.message, ::testing::HasSubstr("Unknown connection option foo='bar'"));
ASSERT_THAT(AdbcConnectionRelease(&connection, &error), IsOkStatus(&error));
ASSERT_THAT(AdbcDatabaseRelease(&database, &error), IsOkStatus(&error));
@@ -144,7 +144,7 @@ TEST_F(DriverManager, MultiDriverTest) {
ASSERT_THAT(AdbcDatabaseSetOption(&sqlite_db.value, "unknown", "foo", &error.value),
IsStatus(ADBC_STATUS_NOT_IMPLEMENTED, &error.value));
ASSERT_THAT(error->message,
- ::testing::HasSubstr("[SQLite] Unknown database option unknown=foo"));
+ ::testing::HasSubstr("Unknown database option unknown='foo'"));
error->release(&error.value);
ASSERT_THAT(AdbcConnectionNew(&sqlite_conn.value, &error.value),
@@ -218,6 +218,8 @@ class SqliteQuirks : public adbc_validation::DriverQuirks {
return std::nullopt;
}
}
+ bool supports_metadata_current_catalog() const override { return true; }
+ std::string catalog() const override { return "main"; }
};
class SqliteDatabaseTest : public ::testing::Test, public adbc_validation::DatabaseTest {
diff --git a/c/validation/adbc_validation_connection.cc b/c/validation/adbc_validation_connection.cc
index 4ed1d0e09..4532c1855 100644
--- a/c/validation/adbc_validation_connection.cc
+++ b/c/validation/adbc_validation_connection.cc
@@ -105,8 +105,10 @@ void ConnectionTest::TestAutocommitDefault() {
// or rollback
ASSERT_THAT(AdbcConnectionCommit(&connection, &error),
IsStatus(ADBC_STATUS_INVALID_STATE, &error));
+ if (error.release) error.release(&error);
ASSERT_THAT(AdbcConnectionRollback(&connection, &error),
IsStatus(ADBC_STATUS_INVALID_STATE, &error));
+ if (error.release) error.release(&error);
// Invalid option value
ASSERT_THAT(AdbcConnectionSetOption(&connection, ADBC_CONNECTION_OPTION_AUTOCOMMIT,
@@ -531,7 +533,7 @@ void ConnectionTest::TestMetadataGetObjectsDbSchemas() {
<< ") should have nonempty catalog_db_schemas ";
ASSERT_FALSE(ArrowArrayViewIsNull(catalog_db_schemas_list, row));
for (int64_t list_index = start_offset; list_index < end_offset; list_index++) {
- ASSERT_TRUE(ArrowArrayViewIsNull(db_schema_tables_list, row + list_index))
+ EXPECT_TRUE(ArrowArrayViewIsNull(db_schema_tables_list, list_index))
<< "Row " << row << " should have null db_schema_tables";
}
}
@@ -617,18 +619,21 @@ void ConnectionTest::TestMetadataGetObjectsTables() {
ASSERT_FALSE(ArrowArrayViewIsNull(catalog_db_schemas_list, row))
<< "Row " << row << " should have non-null catalog_db_schemas";
- for (int64_t db_schemas_index =
- ArrowArrayViewListChildOffset(catalog_db_schemas_list, row);
- db_schemas_index <
- ArrowArrayViewListChildOffset(catalog_db_schemas_list, row + 1);
+ int64_t schema_start =
+ ArrowArrayViewListChildOffset(catalog_db_schemas_list, row);
+ int64_t schema_end =
+ ArrowArrayViewListChildOffset(catalog_db_schemas_list, row + 1);
+ ASSERT_LE(schema_start, schema_end);
+ for (int64_t db_schemas_index = schema_start; db_schemas_index < schema_end;
db_schemas_index++) {
ASSERT_FALSE(ArrowArrayViewIsNull(db_schema_tables_list, db_schemas_index))
<< "Row " << row << " should have non-null db_schema_tables";
- for (int64_t tables_index =
- ArrowArrayViewListChildOffset(db_schema_tables_list, db_schemas_index);
- tables_index <
- ArrowArrayViewListChildOffset(db_schema_tables_list, db_schemas_index + 1);
+ int64_t table_start =
+ ArrowArrayViewListChildOffset(db_schema_tables_list, db_schemas_index);
+ int64_t table_end =
+ ArrowArrayViewListChildOffset(db_schema_tables_list, db_schemas_index + 1);
+ for (int64_t tables_index = table_start; tables_index < table_end;
tables_index++) {
ArrowStringView table_name = ArrowArrayViewGetStringUnsafe(
db_schema_tables->children[0], tables_index);
@@ -816,6 +821,7 @@ void ConnectionTest::TestMetadataGetObjectsColumns() {
"bulk_ingest") &&
iequals(std::string(db_schema_name.data, db_schema_name.size_bytes),
quirks()->db_schema())) {
+ ASSERT_FALSE(found_expected_table);
found_expected_table = true;
for (int64_t columns_index =
diff --git a/c/vendor/fmt/.clang-format b/c/vendor/fmt/.clang-format
new file mode 100644
index 000000000..df55d340f
--- /dev/null
+++ b/c/vendor/fmt/.clang-format
@@ -0,0 +1,8 @@
+# Run manually to reformat a file:
+# clang-format -i --style=file <file>
+Language: Cpp
+BasedOnStyle: Google
+IndentPPDirectives: AfterHash
+IndentCaseLabels: false
+AlwaysBreakTemplateDeclarations: false
+DerivePointerAlignment: false
diff --git a/c/vendor/fmt/CMakeLists.txt b/c/vendor/fmt/CMakeLists.txt
new file mode 100644
index 000000000..0c3005cec
--- /dev/null
+++ b/c/vendor/fmt/CMakeLists.txt
@@ -0,0 +1,453 @@
+cmake_minimum_required(VERSION 3.8...3.26)
+
+# Fallback for using newer policies on CMake <3.12.
+if (${CMAKE_VERSION} VERSION_LESS 3.12)
+ cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
+endif ()
+
+# Determine if fmt is built as a subproject (using add_subdirectory)
+# or if it is the master project.
+if (NOT DEFINED FMT_MASTER_PROJECT)
+ set(FMT_MASTER_PROJECT OFF)
+ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
+ set(FMT_MASTER_PROJECT ON)
+ message(STATUS "CMake version: ${CMAKE_VERSION}")
+ endif ()
+endif ()
+
+# Joins arguments and places the results in ${result_var}.
+function(join result_var)
+ set(result "")
+ foreach (arg ${ARGN})
+ set(result "${result}${arg}")
+ endforeach ()
+ set(${result_var} "${result}" PARENT_SCOPE)
+endfunction()
+
+# DEPRECATED! Should be merged into add_module_library.
+function(enable_module target)
+ if (MSVC)
+ set(BMI ${CMAKE_CURRENT_BINARY_DIR}/${target}.ifc)
+ target_compile_options(${target}
+ PRIVATE /interface /ifcOutput ${BMI}
+ INTERFACE /reference fmt=${BMI})
+ set_target_properties(${target} PROPERTIES ADDITIONAL_CLEAN_FILES ${BMI})
+ set_source_files_properties(${BMI} PROPERTIES GENERATED ON)
+ endif ()
+endfunction()
+
+# Adds a library compiled with C++20 module support.
+# `enabled` is a CMake variables that specifies if modules are enabled.
+# If modules are disabled `add_module_library` falls back to creating a
+# non-modular library.
+#
+# Usage:
+# add_module_library(<name> [sources...] FALLBACK [sources...] [IF enabled])
+function(add_module_library name)
+ cmake_parse_arguments(AML "" "IF" "FALLBACK" ${ARGN})
+ set(sources ${AML_UNPARSED_ARGUMENTS})
+
+ add_library(${name} STATIC)
+ set_target_properties(${name} PROPERTIES LINKER_LANGUAGE CXX)
+
+ if (NOT ${${AML_IF}})
+ # Create a non-modular library.
+ target_sources(${name} PRIVATE ${AML_FALLBACK})
+ return()
+ endif ()
+
+ # Modules require C++20.
+ target_compile_features(${name} PUBLIC cxx_std_20)
+ if (CMAKE_COMPILER_IS_GNUCXX)
+ target_compile_options(${name} PUBLIC -fmodules-ts)
+ endif ()
+
+ # `std` is affected by CMake options and may be higher than C++20.
+ get_target_property(std ${name} CXX_STANDARD)
+
+ if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+ set(pcms)
+ foreach (src ${sources})
+ get_filename_component(pcm ${src} NAME_WE)
+ set(pcm ${pcm}.pcm)
+
+ # Propagate -fmodule-file=*.pcm to targets that link with this library.
+ target_compile_options(
+ ${name} PUBLIC -fmodule-file=${CMAKE_CURRENT_BINARY_DIR}/${pcm})
+
+ # Use an absolute path to prevent target_link_libraries prepending -l
+ # to it.
+ set(pcms ${pcms} ${CMAKE_CURRENT_BINARY_DIR}/${pcm})
+ add_custom_command(
+ OUTPUT ${pcm}
+ COMMAND ${CMAKE_CXX_COMPILER}
+ -std=c++${std} -x c++-module --precompile -c
+ -o ${pcm} ${CMAKE_CURRENT_SOURCE_DIR}/${src}
+ "-I$<JOIN:$<TARGET_PROPERTY:${name},INCLUDE_DIRECTORIES>,;-I>"
+ # Required by the -I generator expression above.
+ COMMAND_EXPAND_LISTS
+ DEPENDS ${src})
+ endforeach ()
+
+ # Add .pcm files as sources to make sure they are built before the library.
+ set(sources)
+ foreach (pcm ${pcms})
+ get_filename_component(pcm_we ${pcm} NAME_WE)
+ set(obj ${pcm_we}.o)
+ # Use an absolute path to prevent target_link_libraries prepending -l.
+ set(sources ${sources} ${pcm} ${CMAKE_CURRENT_BINARY_DIR}/${obj})
+ add_custom_command(
+ OUTPUT ${obj}
+ COMMAND ${CMAKE_CXX_COMPILER} $<TARGET_PROPERTY:${name},COMPILE_OPTIONS>
+ -c -o ${obj} ${pcm}
+ DEPENDS ${pcm})
+ endforeach ()
+ endif ()
+ target_sources(${name} PRIVATE ${sources})
+endfunction()
+
+include(CMakeParseArguments)
+
+# Sets a cache variable with a docstring joined from multiple arguments:
+# set(<variable> <value>... CACHE <type> <docstring>...)
+# This allows splitting a long docstring for readability.
+function(set_verbose)
+ # cmake_parse_arguments is broken in CMake 3.4 (cannot parse CACHE) so use
+ # list instead.
+ list(GET ARGN 0 var)
+ list(REMOVE_AT ARGN 0)
+ list(GET ARGN 0 val)
+ list(REMOVE_AT ARGN 0)
+ list(REMOVE_AT ARGN 0)
+ list(GET ARGN 0 type)
+ list(REMOVE_AT ARGN 0)
+ join(doc ${ARGN})
+ set(${var} ${val} CACHE ${type} ${doc})
+endfunction()
+
+# Set the default CMAKE_BUILD_TYPE to Release.
+# This should be done before the project command since the latter can set
+# CMAKE_BUILD_TYPE itself (it does so for nmake).
+if (FMT_MASTER_PROJECT AND NOT CMAKE_BUILD_TYPE)
+ set_verbose(CMAKE_BUILD_TYPE Release CACHE STRING
+ "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or "
+ "CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.")
+endif ()
+
+project(FMT CXX)
+include(GNUInstallDirs)
+set_verbose(FMT_INC_DIR ${CMAKE_INSTALL_INCLUDEDIR} CACHE STRING
+ "Installation directory for include files, a relative path that "
+ "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute path.")
+
+option(FMT_PEDANTIC "Enable extra warnings and expensive tests." OFF)
+option(FMT_WERROR "Halt the compilation with an error on compiler warnings."
+ OFF)
+
+# Options that control generation of various targets.
+option(FMT_DOC "Generate the doc target." ${FMT_MASTER_PROJECT})
+option(FMT_INSTALL "Generate the install target." ON)
+option(FMT_TEST "Generate the test target." ${FMT_MASTER_PROJECT})
+option(FMT_FUZZ "Generate the fuzz target." OFF)
+option(FMT_CUDA_TEST "Generate the cuda-test target." OFF)
+option(FMT_OS "Include core requiring OS (Windows/Posix) " ON)
+option(FMT_MODULE "Build a module instead of a traditional library." OFF)
+option(FMT_SYSTEM_HEADERS "Expose headers with marking them as system." OFF)
+
+if (FMT_TEST AND FMT_MODULE)
+ # The tests require {fmt} to be compiled as traditional library
+ message(STATUS "Testing is incompatible with build mode 'module'.")
+endif ()
+set(FMT_SYSTEM_HEADERS_ATTRIBUTE "")
+if (FMT_SYSTEM_HEADERS)
+ set(FMT_SYSTEM_HEADERS_ATTRIBUTE SYSTEM)
+endif ()
+if (CMAKE_SYSTEM_NAME STREQUAL "MSDOS")
+ set(FMT_TEST OFF)
+ message(STATUS "MSDOS is incompatible with gtest")
+endif ()
+
+# Get version from core.h
+file(READ include/fmt/core.h core_h)
+if (NOT core_h MATCHES "FMT_VERSION ([0-9]+)([0-9][0-9])([0-9][0-9])")
+ message(FATAL_ERROR "Cannot get FMT_VERSION from core.h.")
+endif ()
+# Use math to skip leading zeros if any.
+math(EXPR CPACK_PACKAGE_VERSION_MAJOR ${CMAKE_MATCH_1})
+math(EXPR CPACK_PACKAGE_VERSION_MINOR ${CMAKE_MATCH_2})
+math(EXPR CPACK_PACKAGE_VERSION_PATCH ${CMAKE_MATCH_3})
+join(FMT_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.
+ ${CPACK_PACKAGE_VERSION_PATCH})
+message(STATUS "Version: ${FMT_VERSION}")
+
+message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
+
+if (NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin)
+endif ()
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
+ "${CMAKE_CURRENT_SOURCE_DIR}/support/cmake")
+
+include(CheckCXXCompilerFlag)
+include(JoinPaths)
+
+if (FMT_MASTER_PROJECT AND NOT DEFINED CMAKE_CXX_VISIBILITY_PRESET)
+ set_verbose(CMAKE_CXX_VISIBILITY_PRESET hidden CACHE STRING
+ "Preset for the export of private symbols")
+ set_property(CACHE CMAKE_CXX_VISIBILITY_PRESET PROPERTY STRINGS
+ hidden default)
+endif ()
+
+if (FMT_MASTER_PROJECT AND NOT DEFINED CMAKE_VISIBILITY_INLINES_HIDDEN)
+ set_verbose(CMAKE_VISIBILITY_INLINES_HIDDEN ON CACHE BOOL
+ "Whether to add a compile flag to hide symbols of inline functions")
+endif ()
+
+if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
+ set(PEDANTIC_COMPILE_FLAGS -pedantic-errors -Wall -Wextra -pedantic
+ -Wold-style-cast -Wundef
+ -Wredundant-decls -Wwrite-strings -Wpointer-arith
+ -Wcast-qual -Wformat=2 -Wmissing-include-dirs
+ -Wcast-align
+ -Wctor-dtor-privacy -Wdisabled-optimization
+ -Winvalid-pch -Woverloaded-virtual
+ -Wconversion -Wundef
+ -Wno-ctor-dtor-privacy -Wno-format-nonliteral)
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.6)
+ set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS}
+ -Wno-dangling-else -Wno-unused-local-typedefs)
+ endif ()
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)
+ set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wdouble-promotion
+ -Wtrampolines -Wzero-as-null-pointer-constant -Wuseless-cast
+ -Wvector-operation-performance -Wsized-deallocation -Wshadow)
+ endif ()
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.0)
+ set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS} -Wshift-overflow=2
+ -Wnull-dereference -Wduplicated-cond)
+ endif ()
+ set(WERROR_FLAG -Werror)
+endif ()
+
+if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+ set(PEDANTIC_COMPILE_FLAGS -Wall -Wextra -pedantic -Wconversion -Wundef
+ -Wdeprecated -Wweak-vtables -Wshadow
+ -Wno-gnu-zero-variadic-macro-arguments)
+ check_cxx_compiler_flag(-Wzero-as-null-pointer-constant HAS_NULLPTR_WARNING)
+ if (HAS_NULLPTR_WARNING)
+ set(PEDANTIC_COMPILE_FLAGS ${PEDANTIC_COMPILE_FLAGS}
+ -Wzero-as-null-pointer-constant)
+ endif ()
+ set(WERROR_FLAG -Werror)
+endif ()
+
+if (MSVC)
+ set(PEDANTIC_COMPILE_FLAGS /W3)
+ set(WERROR_FLAG /WX)
+endif ()
+
+if (FMT_MASTER_PROJECT AND CMAKE_GENERATOR MATCHES "Visual Studio")
+ # If Microsoft SDK is installed create script run-msbuild.bat that
+ # calls SetEnv.cmd to set up build environment and runs msbuild.
+ # It is useful when building Visual Studio projects with the SDK
+ # toolchain rather than Visual Studio.
+ include(FindSetEnv)
+ if (WINSDK_SETENV)
+ set(MSBUILD_SETUP "call \"${WINSDK_SETENV}\"")
+ endif ()
+ # Set FrameworkPathOverride to get rid of MSB3644 warnings.
+ join(netfxpath
+ "C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\"
+ ".NETFramework\\v4.0")
+ file(WRITE run-msbuild.bat "
+ ${MSBUILD_SETUP}
+ ${CMAKE_MAKE_PROGRAM} -p:FrameworkPathOverride=\"${netfxpath}\" %*")
+endif ()
+
+function(add_headers VAR)
+ set(headers ${${VAR}})
+ foreach (header ${ARGN})
+ set(headers ${headers} include/fmt/${header})
+ endforeach()
+ set(${VAR} ${headers} PARENT_SCOPE)
+endfunction()
+
+# Define the fmt library, its includes and the needed defines.
+add_headers(FMT_HEADERS args.h chrono.h color.h compile.h core.h format.h
+ format-inl.h os.h ostream.h printf.h ranges.h std.h
+ xchar.h)
+set(FMT_SOURCES src/format.cc)
+if (FMT_OS)
+ set(FMT_SOURCES ${FMT_SOURCES} src/os.cc)
+endif ()
+
+add_module_library(fmt src/fmt.cc FALLBACK
+ ${FMT_SOURCES} ${FMT_HEADERS} README.md ChangeLog.md
+ IF FMT_MODULE)
+add_library(fmt::fmt ALIAS fmt)
+if (FMT_MODULE)
+ enable_module(fmt)
+endif ()
+
+if (FMT_WERROR)
+ target_compile_options(fmt PRIVATE ${WERROR_FLAG})
+endif ()
+if (FMT_PEDANTIC)
+ target_compile_options(fmt PRIVATE ${PEDANTIC_COMPILE_FLAGS})
+endif ()
+
+if (cxx_std_11 IN_LIST CMAKE_CXX_COMPILE_FEATURES)
+ target_compile_features(fmt PUBLIC cxx_std_11)
+else ()
+ message(WARNING "Feature cxx_std_11 is unknown for the CXX compiler")
+endif ()
+
+target_include_directories(fmt ${FMT_SYSTEM_HEADERS_ATTRIBUTE} PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${FMT_INC_DIR}>)
+
+set(FMT_DEBUG_POSTFIX d CACHE STRING "Debug library postfix.")
+
+set_target_properties(fmt PROPERTIES
+ VERSION ${FMT_VERSION} SOVERSION ${CPACK_PACKAGE_VERSION_MAJOR}
+ PUBLIC_HEADER "${FMT_HEADERS}"
+ DEBUG_POSTFIX "${FMT_DEBUG_POSTFIX}"
+
+ # Workaround for Visual Studio 2017:
+ # Ensure the .pdb is created with the same name and in the same directory
+ # as the .lib. Newer VS versions already do this by default, but there is no
+ # harm in setting it for those too. Ignored by other generators.
+ COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
+ COMPILE_PDB_NAME "fmt"
+ COMPILE_PDB_NAME_DEBUG "fmt${FMT_DEBUG_POSTFIX}")
+
+# Set FMT_LIB_NAME for pkg-config fmt.pc. We cannot use the OUTPUT_NAME target
+# property because it's not set by default.
+set(FMT_LIB_NAME fmt)
+if (CMAKE_BUILD_TYPE STREQUAL "Debug")
+ set(FMT_LIB_NAME ${FMT_LIB_NAME}${FMT_DEBUG_POSTFIX})
+endif ()
+
+if (BUILD_SHARED_LIBS)
+ target_compile_definitions(fmt PRIVATE FMT_LIB_EXPORT INTERFACE FMT_SHARED)
+endif ()
+if (FMT_SAFE_DURATION_CAST)
+ target_compile_definitions(fmt PUBLIC FMT_SAFE_DURATION_CAST)
+endif ()
+
+add_library(fmt-header-only INTERFACE)
+add_library(fmt::fmt-header-only ALIAS fmt-header-only)
+
+target_compile_definitions(fmt-header-only INTERFACE FMT_HEADER_ONLY=1)
+target_compile_features(fmt-header-only INTERFACE cxx_std_11)
+
+target_include_directories(fmt-header-only
+ ${FMT_SYSTEM_HEADERS_ATTRIBUTE} INTERFACE
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${FMT_INC_DIR}>)
+
+# Install targets.
+if (FMT_INSTALL)
+ include(CMakePackageConfigHelpers)
+ set_verbose(FMT_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/fmt CACHE STRING
+ "Installation directory for cmake files, a relative path that "
+ "will be joined with ${CMAKE_INSTALL_PREFIX} or an absolute "
+ "path.")
+ set(version_config ${PROJECT_BINARY_DIR}/fmt-config-version.cmake)
+ set(project_config ${PROJECT_BINARY_DIR}/fmt-config.cmake)
+ set(pkgconfig ${PROJECT_BINARY_DIR}/fmt.pc)
+ set(targets_export_name fmt-targets)
+
+ set_verbose(FMT_LIB_DIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING
+ "Installation directory for libraries, a relative path that "
+ "will be joined to ${CMAKE_INSTALL_PREFIX} or an absolute path.")
+
+ set_verbose(FMT_PKGCONFIG_DIR ${CMAKE_INSTALL_LIBDIR}/pkgconfig CACHE STRING
+ "Installation directory for pkgconfig (.pc) files, a relative "
+ "path that will be joined with ${CMAKE_INSTALL_PREFIX} or an "
+ "absolute path.")
+
+ # Generate the version, config and target files into the build directory.
+ write_basic_package_version_file(
+ ${version_config}
+ VERSION ${FMT_VERSION}
+ COMPATIBILITY AnyNewerVersion)
+
+ join_paths(libdir_for_pc_file "\${exec_prefix}" "${FMT_LIB_DIR}")
+ join_paths(includedir_for_pc_file "\${prefix}" "${FMT_INC_DIR}")
+
+ configure_file(
+ "${PROJECT_SOURCE_DIR}/support/cmake/fmt.pc.in"
+ "${pkgconfig}"
+ @ONLY)
+ configure_package_config_file(
+ ${PROJECT_SOURCE_DIR}/support/cmake/fmt-config.cmake.in
+ ${project_config}
+ INSTALL_DESTINATION ${FMT_CMAKE_DIR})
+
+ set(INSTALL_TARGETS fmt fmt-header-only)
+
+ # Install the library and headers.
+ install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name}
+ LIBRARY DESTINATION ${FMT_LIB_DIR}
+ ARCHIVE DESTINATION ${FMT_LIB_DIR}
+ PUBLIC_HEADER DESTINATION "${FMT_INC_DIR}/fmt"
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+
+ # Use a namespace because CMake provides better diagnostics for namespaced
+ # imported targets.
+ export(TARGETS ${INSTALL_TARGETS} NAMESPACE fmt::
+ FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake)
+
+ # Install version, config and target files.
+ install(
+ FILES ${project_config} ${version_config}
+ DESTINATION ${FMT_CMAKE_DIR})
+ install(EXPORT ${targets_export_name} DESTINATION ${FMT_CMAKE_DIR}
+ NAMESPACE fmt::)
+
+ install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}")
+endif ()
+
+if (FMT_DOC)
+ add_subdirectory(doc)
+endif ()
+
+if (FMT_TEST)
+ enable_testing()
+ add_subdirectory(test)
+endif ()
+
+# Control fuzzing independent of the unit tests.
+if (FMT_FUZZ)
+ add_subdirectory(test/fuzzing)
+
+ # The FMT_FUZZ macro is used to prevent resource exhaustion in fuzzing
+ # mode and make fuzzing practically possible. It is similar to
+ # FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION but uses a different name to
+ # avoid interfering with fuzzing of projects that use {fmt}.
+ # See also https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode.
+ target_compile_definitions(fmt PUBLIC FMT_FUZZ)
+endif ()
+
+set(gitignore ${PROJECT_SOURCE_DIR}/.gitignore)
+if (FMT_MASTER_PROJECT AND EXISTS ${gitignore})
+ # Get the list of ignored files from .gitignore.
+ file (STRINGS ${gitignore} lines)
+ list(REMOVE_ITEM lines /doc/html)
+ foreach (line ${lines})
+ string(REPLACE "." "[.]" line "${line}")
+ string(REPLACE "*" ".*" line "${line}")
+ set(ignored_files ${ignored_files} "${line}$" "${line}/")
+ endforeach ()
+ set(ignored_files ${ignored_files}
+ /.git /breathe /format-benchmark sphinx/ .buildinfo .doctrees)
+
+ set(CPACK_SOURCE_GENERATOR ZIP)
+ set(CPACK_SOURCE_IGNORE_FILES ${ignored_files})
+ set(CPACK_SOURCE_PACKAGE_FILE_NAME fmt-${FMT_VERSION})
+ set(CPACK_PACKAGE_NAME fmt)
+ set(CPACK_RESOURCE_FILE_README ${PROJECT_SOURCE_DIR}/README.md)
+ include(CPack)
+endif ()
diff --git a/c/vendor/fmt/CONTRIBUTING.md b/c/vendor/fmt/CONTRIBUTING.md
new file mode 100644
index 000000000..b82f14506
--- /dev/null
+++ b/c/vendor/fmt/CONTRIBUTING.md
@@ -0,0 +1,20 @@
+Contributing to {fmt}
+=====================
+
+By submitting a pull request or a patch, you represent that you have the right
+to license your contribution to the {fmt} project owners and the community,
+agree that your contributions are licensed under the {fmt} license, and agree
+to future changes to the licensing.
+
+All C++ code must adhere to [Google C++ Style Guide](
+https://google.github.io/styleguide/cppguide.html) with the following
+exceptions:
+
+* Exceptions are permitted
+* snake_case should be used instead of UpperCamelCase for function and type
+ names
+
+All documentation must adhere to the [Google Developer Documentation Style
+Guide](https://developers.google.com/style).
+
+Thanks for contributing!
diff --git a/c/vendor/fmt/ChangeLog.md b/c/vendor/fmt/ChangeLog.md
new file mode 100644
index 000000000..515f9fdc1
--- /dev/null
+++ b/c/vendor/fmt/ChangeLog.md
@@ -0,0 +1,5533 @@
+# 10.2.1 - 2024-01-03
+
+- Fixed ABI compatibility with earlier 10.x versions
+ (https://github.com/fmtlib/fmt/pull/3786). Thanks @saraedum.
+
+# 10.2.0 - 2024-01-01
+
+- Added support for the `%j` specifier (the number of days) for
+ `std::chrono::duration` (https://github.com/fmtlib/fmt/issues/3643,
+ https://github.com/fmtlib/fmt/pull/3732). Thanks @intelfx.
+
+- Added support for the chrono suffix for days and changed
+ the suffix for minutes from "m" to the correct "min"
+ (https://github.com/fmtlib/fmt/issues/3662,
+ https://github.com/fmtlib/fmt/pull/3664).
+ For example ([godbolt](https://godbolt.org/z/9KhMnq9ba)):
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ fmt::print("{}\n", std::chrono::days(42)); // prints "42d"
+ }
+ ```
+
+ Thanks @Richardk2n.
+
+- Fixed an overflow in `std::chrono::time_point` formatting with large dates
+ (https://github.com/fmtlib/fmt/issues/3725,
+ https://github.com/fmtlib/fmt/pull/3727). Thanks @cschreib.
+
+- Added a formatter for `std::source_location`
+ (https://github.com/fmtlib/fmt/pull/3730).
+ For example ([godbolt](https://godbolt.org/z/YajfKjhhr)):
+
+ ```c++
+ #include <source_location>
+ #include <fmt/std.h>
+
+ int main() {
+ fmt::print("{}\n", std::source_location::current());
+ }
+ ```
+
+ prints
+
+ ```
+ /app/example.cpp:5:51: int main()
+ ```
+
+ Thanks @felix642.
+
+- Added a formatter for `std::bitset`
+ (https://github.com/fmtlib/fmt/pull/3660).
+ For example ([godbolt](https://godbolt.org/z/bdEaGeYxe)):
+
+ ```c++
+ #include <bitset>
+ #include <fmt/std.h>
+
+ int main() {
+ fmt::print("{}\n", std::bitset<6>(42)); // prints "101010"
+ }
+ ```
+
+ Thanks @muggenhor.
+
+- Added an experimental `nested_formatter` that provides an easy way of
+ applying a formatter to one or more subobjects while automatically handling
+ width, fill and alignment. For example:
+
+ ```c++
+ #include <fmt/format.h>
+
+ struct point {
+ double x, y;
+ };
+
+ template <>
+ struct fmt::formatter<point> : nested_formatter<double> {
+ auto format(point p, format_context& ctx) const {
+ return write_padded(ctx, [=](auto out) {
+ return format_to(out, "({}, {})", nested(p.x), nested(p.y));
+ });
+ }
+ };
+
+ int main() {
+ fmt::print("[{:>20.2f}]", point{1, 2});
+ }
+ ```
+
+ prints
+
+ ```
+ [ (1.00, 2.00)]
+ ```
+
+- Added the generic representation (`g`) to `std::filesystem::path`
+ (https://github.com/fmtlib/fmt/issues/3715,
+ https://github.com/fmtlib/fmt/pull/3729). For example:
+
+ ```c++
+ #include <filesystem>
+ #include <fmt/std.h>
+
+ int main() {
+ fmt::print("{:g}\n", std::filesystem::path("C:\\foo"));
+ }
+ ```
+
+ prints `"C:/foo"` on Windows.
+
+ Thanks @js324.
+
+- Made `format_as` work with references
+ (https://github.com/fmtlib/fmt/pull/3739). Thanks @tchaikov.
+
+- Fixed formatting of invalid UTF-8 with precision
+ (https://github.com/fmtlib/fmt/issues/3284).
+
+- Fixed an inconsistency between `fmt::to_string` and `fmt::format`
+ (https://github.com/fmtlib/fmt/issues/3684).
+
+- Disallowed unsafe uses of `fmt::styled`
+ (https://github.com/fmtlib/fmt/issues/3625):
+
+ ```c++
+ auto s = fmt::styled(std::string("dangle"), fmt::emphasis::bold);
+ fmt::print("{}\n", s); // compile error
+ ```
+
+ Pass `fmt::styled(...)` as a parameter instead.
+
+- Added a null check when formatting a C string with the `s` specifier
+ (https://github.com/fmtlib/fmt/issues/3706).
+
+- Disallowed the `c` specifier for `bool`
+ (https://github.com/fmtlib/fmt/issues/3726,
+ https://github.com/fmtlib/fmt/pull/3734). Thanks @js324.
+
+- Made the default formatting unlocalized in `fmt::ostream_formatter` for
+ consistency with the rest of the library
+ (https://github.com/fmtlib/fmt/issues/3460).
+
+- Fixed localized formatting in bases other than decimal
+ (https://github.com/fmtlib/fmt/issues/3693,
+ https://github.com/fmtlib/fmt/pull/3750). Thanks @js324.
+
+- Fixed a performance regression in experimental `fmt::ostream::print`
+ (https://github.com/fmtlib/fmt/issues/3674).
+
+- Added synchronization with the underlying output stream when writing to
+ the Windows console
+ (https://github.com/fmtlib/fmt/pull/3668,
+ https://github.com/fmtlib/fmt/issues/3688,
+ https://github.com/fmtlib/fmt/pull/3689).
+ Thanks @Roman-Koshelev and @dimztimz.
+
+- Changed to only export `format_error` when {fmt} is built as a shared
+ library (https://github.com/fmtlib/fmt/issues/3626,
+ https://github.com/fmtlib/fmt/pull/3627). Thanks @phprus.
+
+- Made `fmt::streamed` `constexpr`.
+ (https://github.com/fmtlib/fmt/pull/3650). Thanks @muggenhor.
+
+- Enabled `consteval` on older versions of MSVC
+ (https://github.com/fmtlib/fmt/pull/3757). Thanks @phprus.
+
+- Added an option to build without `wchar_t` support on Windows
+ (https://github.com/fmtlib/fmt/issues/3631,
+ https://github.com/fmtlib/fmt/pull/3636). Thanks @glebm.
+
+- Improved build and CI configuration
+ (https://github.com/fmtlib/fmt/pull/3679,
+ https://github.com/fmtlib/fmt/issues/3701,
+ https://github.com/fmtlib/fmt/pull/3702,
+ https://github.com/fmtlib/fmt/pull/3749).
+ Thanks @jcar87, @pklima and @tchaikov.
+
+- Fixed various warnings, compilation and test issues
+ (https://github.com/fmtlib/fmt/issues/3607,
+ https://github.com/fmtlib/fmt/pull/3610,
+ https://github.com/fmtlib/fmt/pull/3624,
+ https://github.com/fmtlib/fmt/pull/3630,
+ https://github.com/fmtlib/fmt/pull/3634,
+ https://github.com/fmtlib/fmt/pull/3638,
+ https://github.com/fmtlib/fmt/issues/3645,
+ https://github.com/fmtlib/fmt/issues/3646,
+ https://github.com/fmtlib/fmt/pull/3647,
+ https://github.com/fmtlib/fmt/pull/3652,
+ https://github.com/fmtlib/fmt/issues/3654,
+ https://github.com/fmtlib/fmt/pull/3663,
+ https://github.com/fmtlib/fmt/issues/3670,
+ https://github.com/fmtlib/fmt/pull/3680,
+ https://github.com/fmtlib/fmt/issues/3694,
+ https://github.com/fmtlib/fmt/pull/3695,
+ https://github.com/fmtlib/fmt/pull/3699,
+ https://github.com/fmtlib/fmt/issues/3705,
+ https://github.com/fmtlib/fmt/issues/3710,
+ https://github.com/fmtlib/fmt/issues/3712,
+ https://github.com/fmtlib/fmt/pull/3713,
+ https://github.com/fmtlib/fmt/issues/3714,
+ https://github.com/fmtlib/fmt/pull/3716,
+ https://github.com/fmtlib/fmt/pull/3723,
+ https://github.com/fmtlib/fmt/issues/3738,
+ https://github.com/fmtlib/fmt/issues/3740,
+ https://github.com/fmtlib/fmt/pull/3741,
+ https://github.com/fmtlib/fmt/pull/3743,
+ https://github.com/fmtlib/fmt/issues/3745,
+ https://github.com/fmtlib/fmt/pull/3747,
+ https://github.com/fmtlib/fmt/pull/3748,
+ https://github.com/fmtlib/fmt/pull/3751,
+ https://github.com/fmtlib/fmt/pull/3754,
+ https://github.com/fmtlib/fmt/pull/3755,
+ https://github.com/fmtlib/fmt/issues/3760,
+ https://github.com/fmtlib/fmt/pull/3762,
+ https://github.com/fmtlib/fmt/issues/3763,
+ https://github.com/fmtlib/fmt/pull/3764,
+ https://github.com/fmtlib/fmt/issues/3774,
+ https://github.com/fmtlib/fmt/pull/3779).
+ Thanks @danakj, @vinayyadav3016, @cyyever, @phprus, @qimiko, @saschasc,
+ @gsjaardema, @lazka, @Zhaojun-Liu, @carlsmedstad, @hotwatermorning,
+ @cptFracassa, @kuguma, @PeterJohnson, @H1X4Dev, @asantoni, @eltociear,
+ @msimberg, @tchaikov, @waywardmonkeys.
+
+- Improved documentation and README
+ (https://github.com/fmtlib/fmt/issues/2086,
+ https://github.com/fmtlib/fmt/issues/3637,
+ https://github.com/fmtlib/fmt/pull/3642,
+ https://github.com/fmtlib/fmt/pull/3653,
+ https://github.com/fmtlib/fmt/pull/3655,
+ https://github.com/fmtlib/fmt/pull/3661,
+ https://github.com/fmtlib/fmt/issues/3673,
+ https://github.com/fmtlib/fmt/pull/3677,
+ https://github.com/fmtlib/fmt/pull/3737,
+ https://github.com/fmtlib/fmt/issues/3742,
+ https://github.com/fmtlib/fmt/pull/3744).
+ Thanks @idzm, @perlun, @joycebrum, @fennewald, @reinhardt1053, @GeorgeLS.
+
+- Updated CI dependencies
+ (https://github.com/fmtlib/fmt/pull/3615,
+ https://github.com/fmtlib/fmt/pull/3622,
+ https://github.com/fmtlib/fmt/pull/3623,
+ https://github.com/fmtlib/fmt/pull/3666,
+ https://github.com/fmtlib/fmt/pull/3696,
+ https://github.com/fmtlib/fmt/pull/3697,
+ https://github.com/fmtlib/fmt/pull/3759,
+ https://github.com/fmtlib/fmt/pull/3782).
+
+# 10.1.1 - 2023-08-28
+
+- Added formatters for `std::atomic` and `atomic_flag`
+ (https://github.com/fmtlib/fmt/pull/3574,
+ https://github.com/fmtlib/fmt/pull/3594).
+ Thanks @wangzw and @AlexGuteniev.
+- Fixed an error about partial specialization of `formatter<string>`
+ after instantiation when compiled with gcc and C++20
+ (https://github.com/fmtlib/fmt/issues/3584).
+- Fixed compilation as a C++20 module with gcc and clang
+ (https://github.com/fmtlib/fmt/issues/3587,
+ https://github.com/fmtlib/fmt/pull/3597,
+ https://github.com/fmtlib/fmt/pull/3605).
+ Thanks @MathewBensonCode.
+- Made `fmt::to_string` work with types that have `format_as`
+ overloads (https://github.com/fmtlib/fmt/pull/3575). Thanks @phprus.
+- Made `formatted_size` work with integral format specifiers at
+ compile time (https://github.com/fmtlib/fmt/pull/3591).
+ Thanks @elbeno.
+- Fixed a warning about the `no_unique_address` attribute on clang-cl
+ (https://github.com/fmtlib/fmt/pull/3599). Thanks @lukester1975.
+- Improved compatibility with the legacy GBK encoding
+ (https://github.com/fmtlib/fmt/issues/3598,
+ https://github.com/fmtlib/fmt/pull/3599). Thanks @YuHuanTin.
+- Added OpenSSF Scorecard analysis
+ (https://github.com/fmtlib/fmt/issues/3530,
+ https://github.com/fmtlib/fmt/pull/3571). Thanks @joycebrum.
+- Updated CI dependencies
+ (https://github.com/fmtlib/fmt/pull/3591,
+ https://github.com/fmtlib/fmt/pull/3592,
+ https://github.com/fmtlib/fmt/pull/3593,
+ https://github.com/fmtlib/fmt/pull/3602).
+
+# 10.1.0 - 2023-08-12
+
+- Optimized format string compilation resulting in up to 40% speed up
+ in compiled `format_to` and \~4x speed up in compiled `format_to_n`
+ on a concatenation benchmark
+ (https://github.com/fmtlib/fmt/issues/3133,
+ https://github.com/fmtlib/fmt/issues/3484).
+
+ {fmt} 10.0:
+
+ ---------------------------------------------------------
+ Benchmark Time CPU Iterations
+ ---------------------------------------------------------
+ BM_format_to 78.9 ns 78.9 ns 8881746
+ BM_format_to_n 568 ns 568 ns 1232089
+
+ {fmt} 10.1:
+
+ ---------------------------------------------------------
+ Benchmark Time CPU Iterations
+ ---------------------------------------------------------
+ BM_format_to 54.9 ns 54.9 ns 12727944
+ BM_format_to_n 133 ns 133 ns 5257795
+
+- Optimized storage of an empty allocator in `basic_memory_buffer`
+ (https://github.com/fmtlib/fmt/pull/3485). Thanks @Minty-Meeo.
+
+- Added formatters for proxy references to elements of
+ `std::vector<bool>` and `std::bitset<N>`
+ (https://github.com/fmtlib/fmt/issues/3567,
+ https://github.com/fmtlib/fmt/pull/3570). For example
+ ([godbolt](https://godbolt.org/z/zYb79Pvn8)):
+
+ ```c++
+ #include <vector>
+ #include <fmt/std.h>
+
+ int main() {
+ auto v = std::vector<bool>{true};
+ fmt::print("{}", v[0]);
+ }
+ ```
+
+ Thanks @phprus and @felix642.
+
+- Fixed an ambiguous formatter specialization for containers that look
+ like container adaptors such as `boost::flat_set`
+ (https://github.com/fmtlib/fmt/issues/3556,
+ https://github.com/fmtlib/fmt/pull/3561). Thanks @5chmidti.
+
+- Fixed compilation when formatting durations not convertible from
+ `std::chrono::seconds`
+ (https://github.com/fmtlib/fmt/pull/3430). Thanks @patlkli.
+
+- Made the `formatter` specialization for `char*` const-correct
+ (https://github.com/fmtlib/fmt/pull/3432). Thanks @timsong-cpp.
+
+- Made `{}` and `{:}` handled consistently during compile-time checks
+ (https://github.com/fmtlib/fmt/issues/3526).
+
+- Disallowed passing temporaries to `make_format_args` to improve API
+ safety by preventing dangling references.
+
+- Improved the compile-time error for unformattable types
+ (https://github.com/fmtlib/fmt/pull/3478). Thanks @BRevzin.
+
+- Improved the floating-point formatter
+ (https://github.com/fmtlib/fmt/pull/3448,
+ https://github.com/fmtlib/fmt/pull/3450).
+ Thanks @florimond-collette.
+
+- Fixed handling of precision for `long double` larger than 64 bits.
+ (https://github.com/fmtlib/fmt/issues/3539,
+ https://github.com/fmtlib/fmt/issues/3564).
+
+- Made floating-point and chrono tests less platform-dependent
+ (https://github.com/fmtlib/fmt/issues/3337,
+ https://github.com/fmtlib/fmt/issues/3433,
+ https://github.com/fmtlib/fmt/pull/3434). Thanks @phprus.
+
+- Removed the remnants of the Grisu floating-point formatter that has
+ been replaced by Dragonbox in earlier versions.
+
+- Added `throw_format_error` to the public API
+ (https://github.com/fmtlib/fmt/pull/3551). Thanks @mjerabek.
+
+- Made `FMT_THROW` assert even if assertions are disabled when
+ compiling with exceptions disabled
+ (https://github.com/fmtlib/fmt/issues/3418,
+ https://github.com/fmtlib/fmt/pull/3439). Thanks @BRevzin.
+
+- Made `format_as` and `std::filesystem::path` formatter work with
+ exotic code unit types.
+ (https://github.com/fmtlib/fmt/pull/3457,
+ https://github.com/fmtlib/fmt/pull/3476). Thanks @gix and @hmbj.
+
+- Added support for the `?` format specifier to
+ `std::filesystem::path` and made the default unescaped for
+ consistency with strings.
+
+- Deprecated the wide stream overload of `printf`.
+
+- Removed unused `basic_printf_parse_context`.
+
+- Improved RTTI detection used when formatting exceptions
+ (https://github.com/fmtlib/fmt/pull/3468). Thanks @danakj.
+
+- Improved compatibility with VxWorks7
+ (https://github.com/fmtlib/fmt/pull/3467). Thanks @wenshan1.
+
+- Improved documentation
+ (https://github.com/fmtlib/fmt/issues/3174,
+ https://github.com/fmtlib/fmt/issues/3423,
+ https://github.com/fmtlib/fmt/pull/3454,
+ https://github.com/fmtlib/fmt/issues/3458,
+ https://github.com/fmtlib/fmt/pull/3461,
+ https://github.com/fmtlib/fmt/issues/3487,
+ https://github.com/fmtlib/fmt/pull/3515).
+ Thanks @zencatalyst, @rlalik and @mikecrowe.
+
+- Improved build and CI configurations
+ (https://github.com/fmtlib/fmt/issues/3449,
+ https://github.com/fmtlib/fmt/pull/3451,
+ https://github.com/fmtlib/fmt/pull/3452,
+ https://github.com/fmtlib/fmt/pull/3453,
+ https://github.com/fmtlib/fmt/pull/3459,
+ https://github.com/fmtlib/fmt/issues/3481,
+ https://github.com/fmtlib/fmt/pull/3486,
+ https://github.com/fmtlib/fmt/issues/3489,
+ https://github.com/fmtlib/fmt/pull/3496,
+ https://github.com/fmtlib/fmt/issues/3517,
+ https://github.com/fmtlib/fmt/pull/3523,
+ https://github.com/fmtlib/fmt/pull/3563).
+ Thanks @joycebrum, @glebm, @phprus, @petrmanek, @setoye and @abouvier.
+
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/issues/3408,
+ https://github.com/fmtlib/fmt/issues/3424,
+ https://github.com/fmtlib/fmt/issues/3444,
+ https://github.com/fmtlib/fmt/pull/3446,
+ https://github.com/fmtlib/fmt/pull/3475,
+ https://github.com/fmtlib/fmt/pull/3482,
+ https://github.com/fmtlib/fmt/issues/3492,
+ https://github.com/fmtlib/fmt/pull/3493,
+ https://github.com/fmtlib/fmt/pull/3508,
+ https://github.com/fmtlib/fmt/issues/3509,
+ https://github.com/fmtlib/fmt/issues/3533,
+ https://github.com/fmtlib/fmt/pull/3542,
+ https://github.com/fmtlib/fmt/issues/3543,
+ https://github.com/fmtlib/fmt/issues/3540,
+ https://github.com/fmtlib/fmt/pull/3544,
+ https://github.com/fmtlib/fmt/issues/3548,
+ https://github.com/fmtlib/fmt/pull/3549,
+ https://github.com/fmtlib/fmt/pull/3550,
+ https://github.com/fmtlib/fmt/pull/3552).
+ Thanks @adesitter, @hmbj, @Minty-Meeo, @phprus, @TobiSchluter,
+ @kieranclancy, @alexeedm, @jurihock, @Ozomahtli and @razaqq.
+
+# 10.0.0 - 2023-05-09
+
+- Replaced Grisu with a new floating-point formatting algorithm for
+ given precision (https://github.com/fmtlib/fmt/issues/3262,
+ https://github.com/fmtlib/fmt/issues/2750,
+ https://github.com/fmtlib/fmt/pull/3269,
+ https://github.com/fmtlib/fmt/pull/3276). The new algorithm
+ is based on Dragonbox already used for the shortest representation
+ and gives substantial performance improvement:
+
+ 
+
+ - Red: new algorithm
+ - Green: new algorithm with `FMT_USE_FULL_CACHE_DRAGONBOX` defined
+ to 1
+ - Blue: old algorithm
+
+ Thanks @jk-jeon.
+
+- Replaced `snprintf`-based hex float formatter with an internal
+ implementation (https://github.com/fmtlib/fmt/pull/3179,
+ https://github.com/fmtlib/fmt/pull/3203). This removes the
+ last usage of `s(n)printf` in {fmt}. Thanks @phprus.
+
+- Fixed alignment of floating-point numbers with localization
+ (https://github.com/fmtlib/fmt/issues/3263,
+ https://github.com/fmtlib/fmt/pull/3272). Thanks @ShawnZhong.
+
+- Made handling of `#` consistent with `std::format`.
+
+- Improved C++20 module support
+ (https://github.com/fmtlib/fmt/pull/3134,
+ https://github.com/fmtlib/fmt/pull/3254,
+ https://github.com/fmtlib/fmt/pull/3386,
+ https://github.com/fmtlib/fmt/pull/3387,
+ https://github.com/fmtlib/fmt/pull/3388,
+ https://github.com/fmtlib/fmt/pull/3392,
+ https://github.com/fmtlib/fmt/pull/3397,
+ https://github.com/fmtlib/fmt/pull/3399,
+ https://github.com/fmtlib/fmt/pull/3400).
+ Thanks @laitingsheng, @Orvid and @DanielaE.
+
+- Switched to the [modules CMake library](https://github.com/vitaut/modules)
+ which allows building {fmt} as a C++20 module with clang:
+
+ CXX=clang++ cmake -DFMT_MODULE=ON .
+ make
+
+- Made `format_as` work with any user-defined type and not just enums.
+ For example ([godbolt](https://godbolt.org/z/b7rqhq5Kh)):
+
+ ```c++
+ #include <fmt/format.h>
+
+ struct floaty_mc_floatface {
+ double value;
+ };
+
+ auto format_as(floaty_mc_floatface f) { return f.value; }
+
+ int main() {
+ fmt::print("{:8}\n", floaty_mc_floatface{0.42}); // prints " 0.42"
+ }
+ ```
+
+- Removed deprecated implicit conversions for enums and conversions to
+ primitive types for compatibility with `std::format` and to prevent
+ potential ODR violations. Use `format_as` instead.
+
+- Added support for fill, align and width to the time point formatter
+ (https://github.com/fmtlib/fmt/issues/3237,
+ https://github.com/fmtlib/fmt/pull/3260,
+ https://github.com/fmtlib/fmt/pull/3275). For example
+ ([godbolt](https://godbolt.org/z/rKP6MGz6c)):
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ // prints " 2023"
+ fmt::print("{:>8%Y}\n", std::chrono::system_clock::now());
+ }
+ ```
+
+ Thanks @ShawnZhong.
+
+- Implemented formatting of subseconds
+ (https://github.com/fmtlib/fmt/issues/2207,
+ https://github.com/fmtlib/fmt/issues/3117,
+ https://github.com/fmtlib/fmt/pull/3115,
+ https://github.com/fmtlib/fmt/pull/3143,
+ https://github.com/fmtlib/fmt/pull/3144,
+ https://github.com/fmtlib/fmt/pull/3349). For example
+ ([godbolt](https://godbolt.org/z/45738oGEo)):
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ // prints 01.234567
+ fmt::print("{:%S}\n", std::chrono::microseconds(1234567));
+ }
+ ```
+
+ Thanks @patrickroocks @phprus and @BRevzin.
+
+- Added precision support to `%S`
+ (https://github.com/fmtlib/fmt/pull/3148). Thanks @SappyJoy
+
+- Added support for `std::utc_time`
+ (https://github.com/fmtlib/fmt/issues/3098,
+ https://github.com/fmtlib/fmt/pull/3110). Thanks @patrickroocks.
+
+- Switched formatting of `std::chrono::system_clock` from local time
+ to UTC for compatibility with the standard
+ (https://github.com/fmtlib/fmt/issues/3199,
+ https://github.com/fmtlib/fmt/pull/3230). Thanks @ned14.
+
+- Added support for `%Ez` and `%Oz` to chrono formatters.
+ (https://github.com/fmtlib/fmt/issues/3220,
+ https://github.com/fmtlib/fmt/pull/3222). Thanks @phprus.
+
+- Improved validation of format specifiers for `std::chrono::duration`
+ (https://github.com/fmtlib/fmt/issues/3219,
+ https://github.com/fmtlib/fmt/pull/3232). Thanks @ShawnZhong.
+
+- Fixed formatting of time points before the epoch
+ (https://github.com/fmtlib/fmt/issues/3117,
+ https://github.com/fmtlib/fmt/pull/3261). For example
+ ([godbolt](https://godbolt.org/z/f7bcznb3W)):
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ auto t = std::chrono::system_clock::from_time_t(0) -
+ std::chrono::milliseconds(250);
+ fmt::print("{:%S}\n", t); // prints 59.750000000
+ }
+ ```
+
+ Thanks @ShawnZhong.
+
+- Experimental: implemented glibc extension for padding seconds,
+ minutes and hours
+ (https://github.com/fmtlib/fmt/issues/2959,
+ https://github.com/fmtlib/fmt/pull/3271). Thanks @ShawnZhong.
+
+- Added a formatter for `std::exception`
+ (https://github.com/fmtlib/fmt/issues/2977,
+ https://github.com/fmtlib/fmt/issues/3012,
+ https://github.com/fmtlib/fmt/pull/3062,
+ https://github.com/fmtlib/fmt/pull/3076,
+ https://github.com/fmtlib/fmt/pull/3119). For example
+ ([godbolt](https://godbolt.org/z/8xoWGs9e4)):
+
+ ```c++
+ #include <fmt/std.h>
+ #include <vector>
+
+ int main() {
+ try {
+ std::vector<bool>().at(0);
+ } catch(const std::exception& e) {
+ fmt::print("{}", e);
+ }
+ }
+ ```
+
+ prints:
+
+ vector<bool>::_M_range_check: __n (which is 0) >= this->size() (which is 0)
+
+ on libstdc++. Thanks @zach2good and @phprus.
+
+- Moved `std::error_code` formatter from `fmt/os.h` to `fmt/std.h`.
+ (https://github.com/fmtlib/fmt/pull/3125). Thanks @phprus.
+
+- Added formatters for standard container adapters:
+ `std::priority_queue`, `std::queue` and `std::stack`
+ (https://github.com/fmtlib/fmt/issues/3215,
+ https://github.com/fmtlib/fmt/pull/3279). For example
+ ([godbolt](https://godbolt.org/z/74h1xY9qK)):
+
+ ```c++
+ #include <fmt/ranges.h>
+ #include <stack>
+ #include <vector>
+
+ int main() {
+ auto s = std::stack<bool, std::vector<bool>>();
+ for (auto b: {true, false, true}) s.push(b);
+ fmt::print("{}\n", s); // prints [true, false, true]
+ }
+ ```
+
+ Thanks @ShawnZhong.
+
+- Added a formatter for `std::optional` to `fmt/std.h`
+ (https://github.com/fmtlib/fmt/issues/1367,
+ https://github.com/fmtlib/fmt/pull/3303).
+ Thanks @tom-huntington.
+
+- Fixed formatting of valueless by exception variants
+ (https://github.com/fmtlib/fmt/pull/3347). Thanks @TheOmegaCarrot.
+
+- Made `fmt::ptr` accept `unique_ptr` with a custom deleter
+ (https://github.com/fmtlib/fmt/pull/3177). Thanks @hmbj.
+
+- Fixed formatting of noncopyable ranges and nested ranges of chars
+ (https://github.com/fmtlib/fmt/pull/3158
+ https://github.com/fmtlib/fmt/issues/3286,
+ https://github.com/fmtlib/fmt/pull/3290). Thanks @BRevzin.
+
+- Fixed issues with formatting of paths and ranges of paths
+ (https://github.com/fmtlib/fmt/issues/3319,
+ https://github.com/fmtlib/fmt/pull/3321
+ https://github.com/fmtlib/fmt/issues/3322). Thanks @phprus.
+
+- Improved handling of invalid Unicode in paths.
+
+- Enabled compile-time checks on Apple clang 14 and later
+ (https://github.com/fmtlib/fmt/pull/3331). Thanks @cloyce.
+
+- Improved compile-time checks of named arguments
+ (https://github.com/fmtlib/fmt/issues/3105,
+ https://github.com/fmtlib/fmt/pull/3214). Thanks @rbrich.
+
+- Fixed formatting when both alignment and `0` are given
+ (https://github.com/fmtlib/fmt/issues/3236,
+ https://github.com/fmtlib/fmt/pull/3248). Thanks @ShawnZhong.
+
+- Improved Unicode support in the experimental file API on Windows
+ (https://github.com/fmtlib/fmt/issues/3234,
+ https://github.com/fmtlib/fmt/pull/3293). Thanks @Fros1er.
+
+- Unified UTF transcoding
+ (https://github.com/fmtlib/fmt/pull/3416). Thanks @phprus.
+
+- Added support for UTF-8 digit separators via an experimental locale
+ facet (https://github.com/fmtlib/fmt/issues/1861). For
+ example ([godbolt](https://godbolt.org/z/f7bcznb3W)):
+
+ ```c++
+ auto loc = std::locale(
+ std::locale(), new fmt::format_facet<std::locale>("’"));
+ auto s = fmt::format(loc, "{:L}", 1000);
+ ```
+
+ where `’` is U+2019 used as a digit separator in the de_CH locale.
+
+- Added an overload of `formatted_size` that takes a locale
+ (https://github.com/fmtlib/fmt/issues/3084,
+ https://github.com/fmtlib/fmt/pull/3087). Thanks @gerboengels.
+
+- Removed the deprecated `FMT_DEPRECATED_OSTREAM`.
+
+- Fixed a UB when using a null `std::string_view` with
+ `fmt::to_string` or format string compilation
+ (https://github.com/fmtlib/fmt/issues/3241,
+ https://github.com/fmtlib/fmt/pull/3244). Thanks @phprus.
+
+- Added `starts_with` to the fallback `string_view` implementation
+ (https://github.com/fmtlib/fmt/pull/3080). Thanks @phprus.
+
+- Added `fmt::basic_format_string::get()` for compatibility with
+ `basic_format_string`
+ (https://github.com/fmtlib/fmt/pull/3111). Thanks @huangqinjin.
+
+- Added `println` for compatibility with C++23
+ (https://github.com/fmtlib/fmt/pull/3267). Thanks @ShawnZhong.
+
+- Renamed the `FMT_EXPORT` macro for shared library usage to
+ `FMT_LIB_EXPORT`.
+
+- Improved documentation
+ (https://github.com/fmtlib/fmt/issues/3108,
+ https://github.com/fmtlib/fmt/issues/3169,
+ https://github.com/fmtlib/fmt/pull/3243).
+ https://github.com/fmtlib/fmt/pull/3404).
+ Thanks @Cleroth and @Vertexwahn.
+
+- Improved build configuration and tests
+ (https://github.com/fmtlib/fmt/pull/3118,
+ https://github.com/fmtlib/fmt/pull/3120,
+ https://github.com/fmtlib/fmt/pull/3188,
+ https://github.com/fmtlib/fmt/issues/3189,
+ https://github.com/fmtlib/fmt/pull/3198,
+ https://github.com/fmtlib/fmt/pull/3205,
+ https://github.com/fmtlib/fmt/pull/3207,
+ https://github.com/fmtlib/fmt/pull/3210,
+ https://github.com/fmtlib/fmt/pull/3240,
+ https://github.com/fmtlib/fmt/pull/3256,
+ https://github.com/fmtlib/fmt/pull/3264,
+ https://github.com/fmtlib/fmt/issues/3299,
+ https://github.com/fmtlib/fmt/pull/3302,
+ https://github.com/fmtlib/fmt/pull/3312,
+ https://github.com/fmtlib/fmt/issues/3317,
+ https://github.com/fmtlib/fmt/pull/3328,
+ https://github.com/fmtlib/fmt/pull/3333,
+ https://github.com/fmtlib/fmt/pull/3369,
+ https://github.com/fmtlib/fmt/issues/3373,
+ https://github.com/fmtlib/fmt/pull/3395,
+ https://github.com/fmtlib/fmt/pull/3406,
+ https://github.com/fmtlib/fmt/pull/3411).
+ Thanks @dimztimz, @phprus, @DavidKorczynski, @ChrisThrasher,
+ @FrancoisCarouge, @kennyweiss, @luzpaz, @codeinred, @Mixaill, @joycebrum,
+ @kevinhwang and @Vertexwahn.
+
+- Fixed a regression in handling empty format specifiers after a colon
+ (`{:}`) (https://github.com/fmtlib/fmt/pull/3086). Thanks @oxidase.
+
+- Worked around a broken implementation of
+ `std::is_constant_evaluated` in some versions of libstdc++ on clang
+ (https://github.com/fmtlib/fmt/issues/3247,
+ https://github.com/fmtlib/fmt/pull/3281). Thanks @phprus.
+
+- Fixed formatting of volatile variables
+ (https://github.com/fmtlib/fmt/pull/3068).
+
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/pull/3057,
+ https://github.com/fmtlib/fmt/pull/3066,
+ https://github.com/fmtlib/fmt/pull/3072,
+ https://github.com/fmtlib/fmt/pull/3082,
+ https://github.com/fmtlib/fmt/pull/3091,
+ https://github.com/fmtlib/fmt/issues/3092,
+ https://github.com/fmtlib/fmt/pull/3093,
+ https://github.com/fmtlib/fmt/pull/3095,
+ https://github.com/fmtlib/fmt/issues/3096,
+ https://github.com/fmtlib/fmt/pull/3097,
+ https://github.com/fmtlib/fmt/issues/3128,
+ https://github.com/fmtlib/fmt/pull/3129,
+ https://github.com/fmtlib/fmt/pull/3137,
+ https://github.com/fmtlib/fmt/pull/3139,
+ https://github.com/fmtlib/fmt/issues/3140,
+ https://github.com/fmtlib/fmt/pull/3142,
+ https://github.com/fmtlib/fmt/issues/3149,
+ https://github.com/fmtlib/fmt/pull/3150,
+ https://github.com/fmtlib/fmt/issues/3154,
+ https://github.com/fmtlib/fmt/issues/3163,
+ https://github.com/fmtlib/fmt/issues/3178,
+ https://github.com/fmtlib/fmt/pull/3184,
+ https://github.com/fmtlib/fmt/pull/3196,
+ https://github.com/fmtlib/fmt/issues/3204,
+ https://github.com/fmtlib/fmt/pull/3206,
+ https://github.com/fmtlib/fmt/pull/3208,
+ https://github.com/fmtlib/fmt/issues/3213,
+ https://github.com/fmtlib/fmt/pull/3216,
+ https://github.com/fmtlib/fmt/issues/3224,
+ https://github.com/fmtlib/fmt/issues/3226,
+ https://github.com/fmtlib/fmt/issues/3228,
+ https://github.com/fmtlib/fmt/pull/3229,
+ https://github.com/fmtlib/fmt/pull/3259,
+ https://github.com/fmtlib/fmt/issues/3274,
+ https://github.com/fmtlib/fmt/issues/3287,
+ https://github.com/fmtlib/fmt/pull/3288,
+ https://github.com/fmtlib/fmt/issues/3292,
+ https://github.com/fmtlib/fmt/pull/3295,
+ https://github.com/fmtlib/fmt/pull/3296,
+ https://github.com/fmtlib/fmt/issues/3298,
+ https://github.com/fmtlib/fmt/issues/3325,
+ https://github.com/fmtlib/fmt/pull/3326,
+ https://github.com/fmtlib/fmt/issues/3334,
+ https://github.com/fmtlib/fmt/issues/3342,
+ https://github.com/fmtlib/fmt/pull/3343,
+ https://github.com/fmtlib/fmt/issues/3351,
+ https://github.com/fmtlib/fmt/pull/3352,
+ https://github.com/fmtlib/fmt/pull/3362,
+ https://github.com/fmtlib/fmt/issues/3365,
+ https://github.com/fmtlib/fmt/pull/3366,
+ https://github.com/fmtlib/fmt/pull/3374,
+ https://github.com/fmtlib/fmt/issues/3377,
+ https://github.com/fmtlib/fmt/pull/3378,
+ https://github.com/fmtlib/fmt/issues/3381,
+ https://github.com/fmtlib/fmt/pull/3398,
+ https://github.com/fmtlib/fmt/pull/3413,
+ https://github.com/fmtlib/fmt/issues/3415).
+ Thanks @phprus, @gsjaardema, @NewbieOrange, @EngineLessCC, @asmaloney,
+ @HazardyKnusperkeks, @sergiud, @Youw, @thesmurph, @czudziakm,
+ @Roman-Koshelev, @chronoxor, @ShawnZhong, @russelltg, @glebm, @tmartin-gh,
+ @Zhaojun-Liu, @louiswins and @mogemimi.
+
+# 9.1.0 - 2022-08-27
+
+- `fmt::formatted_size` now works at compile time
+ (https://github.com/fmtlib/fmt/pull/3026). For example
+ ([godbolt](https://godbolt.org/z/1MW5rMdf8)):
+
+ ```c++
+ #include <fmt/compile.h>
+
+ int main() {
+ using namespace fmt::literals;
+ constexpr size_t n = fmt::formatted_size("{}"_cf, 42);
+ fmt::print("{}\n", n); // prints 2
+ }
+ ```
+
+ Thanks @marksantaniello.
+
+- Fixed handling of invalid UTF-8
+ (https://github.com/fmtlib/fmt/pull/3038,
+ https://github.com/fmtlib/fmt/pull/3044,
+ https://github.com/fmtlib/fmt/pull/3056).
+ Thanks @phprus and @skeeto.
+
+- Improved Unicode support in `ostream` overloads of `print`
+ (https://github.com/fmtlib/fmt/pull/2994,
+ https://github.com/fmtlib/fmt/pull/3001,
+ https://github.com/fmtlib/fmt/pull/3025). Thanks @dimztimz.
+
+- Fixed handling of the sign specifier in localized formatting on
+ systems with 32-bit `wchar_t`
+ (https://github.com/fmtlib/fmt/issues/3041).
+
+- Added support for wide streams to `fmt::streamed`
+ (https://github.com/fmtlib/fmt/pull/2994). Thanks @phprus.
+
+- Added the `n` specifier that disables the output of delimiters when
+ formatting ranges (https://github.com/fmtlib/fmt/pull/2981,
+ https://github.com/fmtlib/fmt/pull/2983). For example
+ ([godbolt](https://godbolt.org/z/roKqGdj8c)):
+
+ ```c++
+ #include <fmt/ranges.h>
+ #include <vector>
+
+ int main() {
+ auto v = std::vector{1, 2, 3};
+ fmt::print("{:n}\n", v); // prints 1, 2, 3
+ }
+ ```
+
+ Thanks @BRevzin.
+
+- Worked around problematic `std::string_view` constructors introduced
+ in C++23 (https://github.com/fmtlib/fmt/issues/3030,
+ https://github.com/fmtlib/fmt/issues/3050). Thanks @strega-nil-ms.
+
+- Improve handling (exclusion) of recursive ranges
+ (https://github.com/fmtlib/fmt/issues/2968,
+ https://github.com/fmtlib/fmt/pull/2974). Thanks @Dani-Hub.
+
+- Improved error reporting in format string compilation
+ (https://github.com/fmtlib/fmt/issues/3055).
+
+- Improved the implementation of
+ [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm
+ used for the default floating-point formatting
+ (https://github.com/fmtlib/fmt/pull/2984). Thanks @jk-jeon.
+
+- Fixed issues with floating-point formatting on exotic platforms.
+
+- Improved the implementation of chrono formatting
+ (https://github.com/fmtlib/fmt/pull/3010). Thanks @phprus.
+
+- Improved documentation
+ (https://github.com/fmtlib/fmt/pull/2966,
+ https://github.com/fmtlib/fmt/pull/3009,
+ https://github.com/fmtlib/fmt/issues/3020,
+ https://github.com/fmtlib/fmt/pull/3037).
+ Thanks @mwinterb, @jcelerier and @remiburtin.
+
+- Improved build configuration
+ (https://github.com/fmtlib/fmt/pull/2991,
+ https://github.com/fmtlib/fmt/pull/2995,
+ https://github.com/fmtlib/fmt/issues/3004,
+ https://github.com/fmtlib/fmt/pull/3007,
+ https://github.com/fmtlib/fmt/pull/3040).
+ Thanks @dimztimz and @hwhsu1231.
+
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/issues/2969,
+ https://github.com/fmtlib/fmt/pull/2971,
+ https://github.com/fmtlib/fmt/issues/2975,
+ https://github.com/fmtlib/fmt/pull/2982,
+ https://github.com/fmtlib/fmt/pull/2985,
+ https://github.com/fmtlib/fmt/issues/2988,
+ https://github.com/fmtlib/fmt/issues/2989,
+ https://github.com/fmtlib/fmt/issues/3000,
+ https://github.com/fmtlib/fmt/issues/3006,
+ https://github.com/fmtlib/fmt/issues/3014,
+ https://github.com/fmtlib/fmt/issues/3015,
+ https://github.com/fmtlib/fmt/pull/3021,
+ https://github.com/fmtlib/fmt/issues/3023,
+ https://github.com/fmtlib/fmt/pull/3024,
+ https://github.com/fmtlib/fmt/pull/3029,
+ https://github.com/fmtlib/fmt/pull/3043,
+ https://github.com/fmtlib/fmt/issues/3052,
+ https://github.com/fmtlib/fmt/pull/3053,
+ https://github.com/fmtlib/fmt/pull/3054).
+ Thanks @h-friederich, @dimztimz, @olupton, @bernhardmgruber and @phprus.
+
+# 9.0.0 - 2022-07-04
+
+- Switched to the internal floating point formatter for all decimal
+ presentation formats. In particular this results in consistent
+ rounding on all platforms and removing the `s[n]printf` fallback for
+ decimal FP formatting.
+
+- Compile-time floating point formatting no longer requires the
+ header-only mode. For example
+ ([godbolt](https://godbolt.org/z/G37PTeG3b)):
+
+ ```c++
+ #include <array>
+ #include <fmt/compile.h>
+
+ consteval auto compile_time_dtoa(double value) -> std::array<char, 10> {
+ auto result = std::array<char, 10>();
+ fmt::format_to(result.data(), FMT_COMPILE("{}"), value);
+ return result;
+ }
+
+ constexpr auto answer = compile_time_dtoa(0.42);
+ ```
+
+ works with the default settings.
+
+- Improved the implementation of
+ [Dragonbox](https://github.com/jk-jeon/dragonbox), the algorithm
+ used for the default floating-point formatting
+ (https://github.com/fmtlib/fmt/pull/2713,
+ https://github.com/fmtlib/fmt/pull/2750). Thanks @jk-jeon.
+
+- Made `fmt::to_string` work with `__float128`. This uses the internal
+ FP formatter and works even on system without `__float128` support
+ in `[s]printf`.
+
+- Disabled automatic `std::ostream` insertion operator (`operator<<`)
+ discovery when `fmt/ostream.h` is included to prevent ODR
+ violations. You can get the old behavior by defining
+ `FMT_DEPRECATED_OSTREAM` but this will be removed in the next major
+ release. Use `fmt::streamed` or `fmt::ostream_formatter` to enable
+ formatting via `std::ostream` instead.
+
+- Added `fmt::ostream_formatter` that can be used to write `formatter`
+ specializations that perform formatting via `std::ostream`. For
+ example ([godbolt](https://godbolt.org/z/5sEc5qMsf)):
+
+ ```c++
+ #include <fmt/ostream.h>
+
+ struct date {
+ int year, month, day;
+
+ friend std::ostream& operator<<(std::ostream& os, const date& d) {
+ return os << d.year << '-' << d.month << '-' << d.day;
+ }
+ };
+
+ template <> struct fmt::formatter<date> : ostream_formatter {};
+
+ std::string s = fmt::format("The date is {}", date{2012, 12, 9});
+ // s == "The date is 2012-12-9"
+ ```
+
+- Added the `fmt::streamed` function that takes an object and formats
+ it via `std::ostream`. For example
+ ([godbolt](https://godbolt.org/z/5G3346G1f)):
+
+ ```c++
+ #include <thread>
+ #include <fmt/ostream.h>
+
+ int main() {
+ fmt::print("Current thread id: {}\n",
+ fmt::streamed(std::this_thread::get_id()));
+ }
+ ```
+
+ Note that `fmt/std.h` provides a `formatter` specialization for
+ `std::thread::id` so you don\'t need to format it via
+ `std::ostream`.
+
+- Deprecated implicit conversions of unscoped enums to integers for
+ consistency with scoped enums.
+
+- Added an argument-dependent lookup based `format_as` extension API
+ to simplify formatting of enums.
+
+- Added experimental `std::variant` formatting support
+ (https://github.com/fmtlib/fmt/pull/2941). For example
+ ([godbolt](https://godbolt.org/z/KG9z6cq68)):
+
+ ```c++
+ #include <variant>
+ #include <fmt/std.h>
+
+ int main() {
+ auto v = std::variant<int, std::string>(42);
+ fmt::print("{}\n", v);
+ }
+ ```
+
+ prints:
+
+ variant(42)
+
+ Thanks @jehelset.
+
+- Added experimental `std::filesystem::path` formatting support
+ (https://github.com/fmtlib/fmt/issues/2865,
+ https://github.com/fmtlib/fmt/pull/2902,
+ https://github.com/fmtlib/fmt/issues/2917,
+ https://github.com/fmtlib/fmt/pull/2918). For example
+ ([godbolt](https://godbolt.org/z/o44dMexEb)):
+
+ ```c++
+ #include <filesystem>
+ #include <fmt/std.h>
+
+ int main() {
+ fmt::print("There is no place like {}.", std::filesystem::path("/home"));
+ }
+ ```
+
+ prints:
+
+ There is no place like "/home".
+
+ Thanks @phprus.
+
+- Added a `std::thread::id` formatter to `fmt/std.h`. For example
+ ([godbolt](https://godbolt.org/z/j1azbYf3E)):
+
+ ```c++
+ #include <thread>
+ #include <fmt/std.h>
+
+ int main() {
+ fmt::print("Current thread id: {}\n", std::this_thread::get_id());
+ }
+ ```
+
+- Added `fmt::styled` that applies a text style to an individual
+ argument (https://github.com/fmtlib/fmt/pull/2793). For
+ example ([godbolt](https://godbolt.org/z/vWGW7v5M6)):
+
+ ```c++
+ #include <fmt/chrono.h>
+ #include <fmt/color.h>
+
+ int main() {
+ auto now = std::chrono::system_clock::now();
+ fmt::print(
+ "[{}] {}: {}\n",
+ fmt::styled(now, fmt::emphasis::bold),
+ fmt::styled("error", fg(fmt::color::red)),
+ "something went wrong");
+ }
+ ```
+
+ prints
+
+ 
+
+ Thanks @rbrugo.
+
+- Made `fmt::print` overload for text styles correctly handle UTF-8
+ (https://github.com/fmtlib/fmt/issues/2681,
+ https://github.com/fmtlib/fmt/pull/2701). Thanks @AlexGuteniev.
+
+- Fixed Unicode handling when writing to an ostream.
+
+- Added support for nested specifiers to range formatting
+ (https://github.com/fmtlib/fmt/pull/2673). For example
+ ([godbolt](https://godbolt.org/z/xd3Gj38cf)):
+
+ ```c++
+ #include <vector>
+ #include <fmt/ranges.h>
+
+ int main() {
+ fmt::print("{::#x}\n", std::vector{10, 20, 30});
+ }
+ ```
+
+ prints `[0xa, 0x14, 0x1e]`.
+
+ Thanks @BRevzin.
+
+- Implemented escaping of wide strings in ranges
+ (https://github.com/fmtlib/fmt/pull/2904). Thanks @phprus.
+
+- Added support for ranges with `begin` / `end` found via the
+ argument-dependent lookup
+ (https://github.com/fmtlib/fmt/pull/2807). Thanks @rbrugo.
+
+- Fixed formatting of certain kinds of ranges of ranges
+ (https://github.com/fmtlib/fmt/pull/2787). Thanks @BRevzin.
+
+- Fixed handling of maps with element types other than `std::pair`
+ (https://github.com/fmtlib/fmt/pull/2944). Thanks @BrukerJWD.
+
+- Made tuple formatter enabled only if elements are formattable
+ (https://github.com/fmtlib/fmt/issues/2939,
+ https://github.com/fmtlib/fmt/pull/2940). Thanks @jehelset.
+
+- Made `fmt::join` compatible with format string compilation
+ (https://github.com/fmtlib/fmt/issues/2719,
+ https://github.com/fmtlib/fmt/pull/2720). Thanks @phprus.
+
+- Made compile-time checks work with named arguments of custom types
+ and `std::ostream` `print` overloads
+ (https://github.com/fmtlib/fmt/issues/2816,
+ https://github.com/fmtlib/fmt/issues/2817,
+ https://github.com/fmtlib/fmt/pull/2819). Thanks @timsong-cpp.
+
+- Removed `make_args_checked` because it is no longer needed for
+ compile-time checks
+ (https://github.com/fmtlib/fmt/pull/2760). Thanks @phprus.
+
+- Removed the following deprecated APIs: `_format`, `arg_join`, the
+ `format_to` overload that takes a memory buffer, `[v]fprintf` that
+ takes an `ostream`.
+
+- Removed the deprecated implicit conversion of `[const] signed char*`
+ and `[const] unsigned char*` to C strings.
+
+- Removed the deprecated `fmt/locale.h`.
+
+- Replaced the deprecated `fileno()` with `descriptor()` in
+ `buffered_file`.
+
+- Moved `to_string_view` to the `detail` namespace since it\'s an
+ implementation detail.
+
+- Made access mode of a created file consistent with `fopen` by
+ setting `S_IWGRP` and `S_IWOTH`
+ (https://github.com/fmtlib/fmt/pull/2733). Thanks @arogge.
+
+- Removed a redundant buffer resize when formatting to `std::ostream`
+ (https://github.com/fmtlib/fmt/issues/2842,
+ https://github.com/fmtlib/fmt/pull/2843). Thanks @jcelerier.
+
+- Made precision computation for strings consistent with width
+ (https://github.com/fmtlib/fmt/issues/2888).
+
+- Fixed handling of locale separators in floating point formatting
+ (https://github.com/fmtlib/fmt/issues/2830).
+
+- Made sign specifiers work with `__int128_t`
+ (https://github.com/fmtlib/fmt/issues/2773).
+
+- Improved support for systems such as CHERI with extra data stored in
+ pointers (https://github.com/fmtlib/fmt/pull/2932).
+ Thanks @davidchisnall.
+
+- Improved documentation
+ (https://github.com/fmtlib/fmt/pull/2706,
+ https://github.com/fmtlib/fmt/pull/2712,
+ https://github.com/fmtlib/fmt/pull/2789,
+ https://github.com/fmtlib/fmt/pull/2803,
+ https://github.com/fmtlib/fmt/pull/2805,
+ https://github.com/fmtlib/fmt/pull/2815,
+ https://github.com/fmtlib/fmt/pull/2924).
+ Thanks @BRevzin, @Pokechu22, @setoye, @rtobar, @rbrugo, @anoonD and
+ @leha-bot.
+
+- Improved build configuration
+ (https://github.com/fmtlib/fmt/pull/2766,
+ https://github.com/fmtlib/fmt/pull/2772,
+ https://github.com/fmtlib/fmt/pull/2836,
+ https://github.com/fmtlib/fmt/pull/2852,
+ https://github.com/fmtlib/fmt/pull/2907,
+ https://github.com/fmtlib/fmt/pull/2913,
+ https://github.com/fmtlib/fmt/pull/2914).
+ Thanks @kambala-decapitator, @mattiasljungstrom, @kieselnb, @nathannaveen
+ and @Vertexwahn.
+
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/issues/2408,
+ https://github.com/fmtlib/fmt/issues/2507,
+ https://github.com/fmtlib/fmt/issues/2697,
+ https://github.com/fmtlib/fmt/issues/2715,
+ https://github.com/fmtlib/fmt/issues/2717,
+ https://github.com/fmtlib/fmt/pull/2722,
+ https://github.com/fmtlib/fmt/pull/2724,
+ https://github.com/fmtlib/fmt/pull/2725,
+ https://github.com/fmtlib/fmt/issues/2726,
+ https://github.com/fmtlib/fmt/pull/2728,
+ https://github.com/fmtlib/fmt/pull/2732,
+ https://github.com/fmtlib/fmt/issues/2738,
+ https://github.com/fmtlib/fmt/pull/2742,
+ https://github.com/fmtlib/fmt/issues/2744,
+ https://github.com/fmtlib/fmt/issues/2745,
+ https://github.com/fmtlib/fmt/issues/2746,
+ https://github.com/fmtlib/fmt/issues/2754,
+ https://github.com/fmtlib/fmt/pull/2755,
+ https://github.com/fmtlib/fmt/issues/2757,
+ https://github.com/fmtlib/fmt/pull/2758,
+ https://github.com/fmtlib/fmt/issues/2761,
+ https://github.com/fmtlib/fmt/pull/2762,
+ https://github.com/fmtlib/fmt/issues/2763,
+ https://github.com/fmtlib/fmt/pull/2765,
+ https://github.com/fmtlib/fmt/issues/2769,
+ https://github.com/fmtlib/fmt/pull/2770,
+ https://github.com/fmtlib/fmt/issues/2771,
+ https://github.com/fmtlib/fmt/issues/2777,
+ https://github.com/fmtlib/fmt/pull/2779,
+ https://github.com/fmtlib/fmt/pull/2782,
+ https://github.com/fmtlib/fmt/pull/2783,
+ https://github.com/fmtlib/fmt/issues/2794,
+ https://github.com/fmtlib/fmt/issues/2796,
+ https://github.com/fmtlib/fmt/pull/2797,
+ https://github.com/fmtlib/fmt/pull/2801,
+ https://github.com/fmtlib/fmt/pull/2802,
+ https://github.com/fmtlib/fmt/issues/2808,
+ https://github.com/fmtlib/fmt/issues/2818,
+ https://github.com/fmtlib/fmt/pull/2819,
+ https://github.com/fmtlib/fmt/issues/2829,
+ https://github.com/fmtlib/fmt/issues/2835,
+ https://github.com/fmtlib/fmt/issues/2848,
+ https://github.com/fmtlib/fmt/issues/2860,
+ https://github.com/fmtlib/fmt/pull/2861,
+ https://github.com/fmtlib/fmt/pull/2882,
+ https://github.com/fmtlib/fmt/issues/2886,
+ https://github.com/fmtlib/fmt/issues/2891,
+ https://github.com/fmtlib/fmt/pull/2892,
+ https://github.com/fmtlib/fmt/issues/2895,
+ https://github.com/fmtlib/fmt/issues/2896,
+ https://github.com/fmtlib/fmt/pull/2903,
+ https://github.com/fmtlib/fmt/issues/2906,
+ https://github.com/fmtlib/fmt/issues/2908,
+ https://github.com/fmtlib/fmt/pull/2909,
+ https://github.com/fmtlib/fmt/issues/2920,
+ https://github.com/fmtlib/fmt/pull/2922,
+ https://github.com/fmtlib/fmt/pull/2927,
+ https://github.com/fmtlib/fmt/pull/2929,
+ https://github.com/fmtlib/fmt/issues/2936,
+ https://github.com/fmtlib/fmt/pull/2937,
+ https://github.com/fmtlib/fmt/pull/2938,
+ https://github.com/fmtlib/fmt/pull/2951,
+ https://github.com/fmtlib/fmt/issues/2954,
+ https://github.com/fmtlib/fmt/pull/2957,
+ https://github.com/fmtlib/fmt/issues/2958,
+ https://github.com/fmtlib/fmt/pull/2960).
+ Thanks @matrackif @Tobi823, @ivan-volnov, @VasiliPupkin256,
+ @federico-busato, @barcharcraz, @jk-jeon, @HazardyKnusperkeks, @dalboris,
+ @seanm, @gsjaardema, @timsong-cpp, @seanm, @frithrah, @chronoxor, @Agga,
+ @madmaxoft, @JurajX, @phprus and @Dani-Hub.
+
+# 8.1.1 - 2022-01-06
+
+- Restored ABI compatibility with version 8.0.x
+ (https://github.com/fmtlib/fmt/issues/2695,
+ https://github.com/fmtlib/fmt/pull/2696). Thanks @saraedum.
+- Fixed chrono formatting on big endian systems
+ (https://github.com/fmtlib/fmt/issues/2698,
+ https://github.com/fmtlib/fmt/pull/2699).
+ Thanks @phprus and @xvitaly.
+- Fixed a linkage error with mingw
+ (https://github.com/fmtlib/fmt/issues/2691,
+ https://github.com/fmtlib/fmt/pull/2692). Thanks @rbberger.
+
+# 8.1.0 - 2022-01-02
+
+- Optimized chrono formatting
+ (https://github.com/fmtlib/fmt/pull/2500,
+ https://github.com/fmtlib/fmt/pull/2537,
+ https://github.com/fmtlib/fmt/issues/2541,
+ https://github.com/fmtlib/fmt/pull/2544,
+ https://github.com/fmtlib/fmt/pull/2550,
+ https://github.com/fmtlib/fmt/pull/2551,
+ https://github.com/fmtlib/fmt/pull/2576,
+ https://github.com/fmtlib/fmt/issues/2577,
+ https://github.com/fmtlib/fmt/pull/2586,
+ https://github.com/fmtlib/fmt/pull/2591,
+ https://github.com/fmtlib/fmt/pull/2594,
+ https://github.com/fmtlib/fmt/pull/2602,
+ https://github.com/fmtlib/fmt/pull/2617,
+ https://github.com/fmtlib/fmt/issues/2628,
+ https://github.com/fmtlib/fmt/pull/2633,
+ https://github.com/fmtlib/fmt/issues/2670,
+ https://github.com/fmtlib/fmt/pull/2671).
+
+ Processing of some specifiers such as `%z` and `%Y` is now up to
+ 10-20 times faster, for example on GCC 11 with libstdc++:
+
+ ----------------------------------------------------------------------------
+ Benchmark Before After
+ ----------------------------------------------------------------------------
+ FMTFormatter_z 261 ns 26.3 ns
+ FMTFormatterCompile_z 246 ns 11.6 ns
+ FMTFormatter_Y 263 ns 26.1 ns
+ FMTFormatterCompile_Y 244 ns 10.5 ns
+ ----------------------------------------------------------------------------
+
+ Thanks @phprus and @toughengineer.
+
+- Implemented subsecond formatting for chrono durations
+ (https://github.com/fmtlib/fmt/pull/2623). For example
+ ([godbolt](https://godbolt.org/z/es7vWTETe)):
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ fmt::print("{:%S}", std::chrono::milliseconds(1234));
+ }
+ ```
+
+ prints \"01.234\".
+
+ Thanks @matrackif.
+
+- Fixed handling of precision 0 when formatting chrono durations
+ (https://github.com/fmtlib/fmt/issues/2587,
+ https://github.com/fmtlib/fmt/pull/2588). Thanks @lukester1975.
+
+- Fixed an overflow on invalid inputs in the `tm` formatter
+ (https://github.com/fmtlib/fmt/pull/2564). Thanks @phprus.
+
+- Added `fmt::group_digits` that formats integers with a non-localized
+ digit separator (comma) for groups of three digits. For example
+ ([godbolt](https://godbolt.org/z/TxGxG9Poq)):
+
+ ```c++
+ #include <fmt/format.h>
+
+ int main() {
+ fmt::print("{} dollars", fmt::group_digits(1000000));
+ }
+ ```
+
+ prints \"1,000,000 dollars\".
+
+- Added support for faint, conceal, reverse and blink text styles
+ (https://github.com/fmtlib/fmt/pull/2394):
+
+ <https://user-images.githubusercontent.com/576385/147710227-c68f5317-f8fa-42c3-9123-7c4ba3c398cb.mp4>
+
+ Thanks @benit8 and @data-man.
+
+- Added experimental support for compile-time floating point
+ formatting (https://github.com/fmtlib/fmt/pull/2426,
+ https://github.com/fmtlib/fmt/pull/2470). It is currently
+ limited to the header-only mode. Thanks @alexezeder.
+
+- Added UDL-based named argument support to compile-time format string
+ checks (https://github.com/fmtlib/fmt/issues/2640,
+ https://github.com/fmtlib/fmt/pull/2649). For example
+ ([godbolt](https://godbolt.org/z/ohGbbvonv)):
+
+ ```c++
+ #include <fmt/format.h>
+
+ int main() {
+ using namespace fmt::literals;
+ fmt::print("{answer:s}", "answer"_a=42);
+ }
+ ```
+
+ gives a compile-time error on compilers with C++20 `consteval` and
+ non-type template parameter support (gcc 10+) because `s` is not a
+ valid format specifier for an integer.
+
+ Thanks @alexezeder.
+
+- Implemented escaping of string range elements. For example
+ ([godbolt](https://godbolt.org/z/rKvM1vKf3)):
+
+ ```c++
+ #include <fmt/ranges.h>
+ #include <vector>
+
+ int main() {
+ fmt::print("{}", std::vector<std::string>{"\naan"});
+ }
+ ```
+
+ is now printed as:
+
+ ["\naan"]
+
+ instead of:
+
+ ["
+ aan"]
+
+- Added an experimental `?` specifier for escaping strings.
+ (https://github.com/fmtlib/fmt/pull/2674). Thanks @BRevzin.
+
+- Switched to JSON-like representation of maps and sets for
+ consistency with Python\'s `str.format`. For example
+ ([godbolt](https://godbolt.org/z/seKjoY9W5)):
+
+ ```c++
+ #include <fmt/ranges.h>
+ #include <map>
+
+ int main() {
+ fmt::print("{}", std::map<std::string, int>{{"answer", 42}});
+ }
+ ```
+
+ is now printed as:
+
+ {"answer": 42}
+
+- Extended `fmt::join` to support C++20-only ranges
+ (https://github.com/fmtlib/fmt/pull/2549). Thanks @BRevzin.
+
+- Optimized handling of non-const-iterable ranges and implemented
+ initial support for non-const-formattable types.
+
+- Disabled implicit conversions of scoped enums to integers that was
+ accidentally introduced in earlier versions
+ (https://github.com/fmtlib/fmt/pull/1841).
+
+- Deprecated implicit conversion of `[const] signed char*` and
+ `[const] unsigned char*` to C strings.
+
+- Deprecated `_format`, a legacy UDL-based format API
+ (https://github.com/fmtlib/fmt/pull/2646). Thanks @alexezeder.
+
+- Marked `format`, `formatted_size` and `to_string` as `[[nodiscard]]`
+ (https://github.com/fmtlib/fmt/pull/2612). @0x8000-0000.
+
+- Added missing diagnostic when trying to format function and member
+ pointers as well as objects convertible to pointers which is
+ explicitly disallowed
+ (https://github.com/fmtlib/fmt/issues/2598,
+ https://github.com/fmtlib/fmt/pull/2609,
+ https://github.com/fmtlib/fmt/pull/2610). Thanks @AlexGuteniev.
+
+- Optimized writing to a contiguous buffer with `format_to_n`
+ (https://github.com/fmtlib/fmt/pull/2489). Thanks @Roman-Koshelev.
+
+- Optimized writing to non-`char` buffers
+ (https://github.com/fmtlib/fmt/pull/2477). Thanks @Roman-Koshelev.
+
+- Decimal point is now localized when using the `L` specifier.
+
+- Improved floating point formatter implementation
+ (https://github.com/fmtlib/fmt/pull/2498,
+ https://github.com/fmtlib/fmt/pull/2499). Thanks @Roman-Koshelev.
+
+- Fixed handling of very large precision in fixed format
+ (https://github.com/fmtlib/fmt/pull/2616).
+
+- Made a table of cached powers used in FP formatting static
+ (https://github.com/fmtlib/fmt/pull/2509). Thanks @jk-jeon.
+
+- Resolved a lookup ambiguity with C++20 format-related functions due
+ to ADL (https://github.com/fmtlib/fmt/issues/2639,
+ https://github.com/fmtlib/fmt/pull/2641). Thanks @mkurdej.
+
+- Removed unnecessary inline namespace qualification
+ (https://github.com/fmtlib/fmt/issues/2642,
+ https://github.com/fmtlib/fmt/pull/2643). Thanks @mkurdej.
+
+- Implemented argument forwarding in `format_to_n`
+ (https://github.com/fmtlib/fmt/issues/2462,
+ https://github.com/fmtlib/fmt/pull/2463). Thanks @owent.
+
+- Fixed handling of implicit conversions in `fmt::to_string` and
+ format string compilation
+ (https://github.com/fmtlib/fmt/issues/2565).
+
+- Changed the default access mode of files created by
+ `fmt::output_file` to `-rw-r--r--` for consistency with `fopen`
+ (https://github.com/fmtlib/fmt/issues/2530).
+
+- Make `fmt::ostream::flush` public
+ (https://github.com/fmtlib/fmt/issues/2435).
+
+- Improved C++14/17 attribute detection
+ (https://github.com/fmtlib/fmt/pull/2615). Thanks @AlexGuteniev.
+
+- Improved `consteval` detection for MSVC
+ (https://github.com/fmtlib/fmt/pull/2559). Thanks @DanielaE.
+
+- Improved documentation
+ (https://github.com/fmtlib/fmt/issues/2406,
+ https://github.com/fmtlib/fmt/pull/2446,
+ https://github.com/fmtlib/fmt/issues/2493,
+ https://github.com/fmtlib/fmt/issues/2513,
+ https://github.com/fmtlib/fmt/pull/2515,
+ https://github.com/fmtlib/fmt/issues/2522,
+ https://github.com/fmtlib/fmt/pull/2562,
+ https://github.com/fmtlib/fmt/pull/2575,
+ https://github.com/fmtlib/fmt/pull/2606,
+ https://github.com/fmtlib/fmt/pull/2620,
+ https://github.com/fmtlib/fmt/issues/2676).
+ Thanks @sobolevn, @UnePierre, @zhsj, @phprus, @ericcurtin and @Lounarok.
+
+- Improved fuzzers and added a fuzzer for chrono timepoint formatting
+ (https://github.com/fmtlib/fmt/pull/2461,
+ https://github.com/fmtlib/fmt/pull/2469). @pauldreik,
+
+- Added the `FMT_SYSTEM_HEADERS` CMake option setting which marks
+ {fmt}\'s headers as system. It can be used to suppress warnings
+ (https://github.com/fmtlib/fmt/issues/2644,
+ https://github.com/fmtlib/fmt/pull/2651). Thanks @alexezeder.
+
+- Added the Bazel build system support
+ (https://github.com/fmtlib/fmt/pull/2505,
+ https://github.com/fmtlib/fmt/pull/2516). Thanks @Vertexwahn.
+
+- Improved build configuration and tests
+ (https://github.com/fmtlib/fmt/issues/2437,
+ https://github.com/fmtlib/fmt/pull/2558,
+ https://github.com/fmtlib/fmt/pull/2648,
+ https://github.com/fmtlib/fmt/pull/2650,
+ https://github.com/fmtlib/fmt/pull/2663,
+ https://github.com/fmtlib/fmt/pull/2677).
+ Thanks @DanielaE, @alexezeder and @phprus.
+
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/pull/2353,
+ https://github.com/fmtlib/fmt/pull/2356,
+ https://github.com/fmtlib/fmt/pull/2399,
+ https://github.com/fmtlib/fmt/issues/2408,
+ https://github.com/fmtlib/fmt/pull/2414,
+ https://github.com/fmtlib/fmt/pull/2427,
+ https://github.com/fmtlib/fmt/pull/2432,
+ https://github.com/fmtlib/fmt/pull/2442,
+ https://github.com/fmtlib/fmt/pull/2434,
+ https://github.com/fmtlib/fmt/issues/2439,
+ https://github.com/fmtlib/fmt/pull/2447,
+ https://github.com/fmtlib/fmt/pull/2450,
+ https://github.com/fmtlib/fmt/issues/2455,
+ https://github.com/fmtlib/fmt/issues/2465,
+ https://github.com/fmtlib/fmt/issues/2472,
+ https://github.com/fmtlib/fmt/issues/2474,
+ https://github.com/fmtlib/fmt/pull/2476,
+ https://github.com/fmtlib/fmt/issues/2478,
+ https://github.com/fmtlib/fmt/issues/2479,
+ https://github.com/fmtlib/fmt/issues/2481,
+ https://github.com/fmtlib/fmt/pull/2482,
+ https://github.com/fmtlib/fmt/pull/2483,
+ https://github.com/fmtlib/fmt/issues/2490,
+ https://github.com/fmtlib/fmt/pull/2491,
+ https://github.com/fmtlib/fmt/pull/2510,
+ https://github.com/fmtlib/fmt/pull/2518,
+ https://github.com/fmtlib/fmt/issues/2528,
+ https://github.com/fmtlib/fmt/pull/2529,
+ https://github.com/fmtlib/fmt/pull/2539,
+ https://github.com/fmtlib/fmt/issues/2540,
+ https://github.com/fmtlib/fmt/pull/2545,
+ https://github.com/fmtlib/fmt/pull/2555,
+ https://github.com/fmtlib/fmt/issues/2557,
+ https://github.com/fmtlib/fmt/issues/2570,
+ https://github.com/fmtlib/fmt/pull/2573,
+ https://github.com/fmtlib/fmt/pull/2582,
+ https://github.com/fmtlib/fmt/issues/2605,
+ https://github.com/fmtlib/fmt/pull/2611,
+ https://github.com/fmtlib/fmt/pull/2647,
+ https://github.com/fmtlib/fmt/issues/2627,
+ https://github.com/fmtlib/fmt/pull/2630,
+ https://github.com/fmtlib/fmt/issues/2635,
+ https://github.com/fmtlib/fmt/issues/2638,
+ https://github.com/fmtlib/fmt/issues/2653,
+ https://github.com/fmtlib/fmt/issues/2654,
+ https://github.com/fmtlib/fmt/issues/2661,
+ https://github.com/fmtlib/fmt/pull/2664,
+ https://github.com/fmtlib/fmt/pull/2684).
+ Thanks @DanielaE, @mwinterb, @cdacamar, @TrebledJ, @bodomartin, @cquammen,
+ @white238, @mmarkeloff, @palacaze, @jcelerier, @mborn-adi, @BrukerJWD,
+ @spyridon97, @phprus, @oliverlee, @joshessman-llnl, @akohlmey, @timkalu,
+ @olupton, @Acretock, @alexezeder, @andrewcorrigan, @lucpelletier and
+ @HazardyKnusperkeks.
+
+# 8.0.1 - 2021-07-02
+
+- Fixed the version number in the inline namespace
+ (https://github.com/fmtlib/fmt/issues/2374).
+- Added a missing presentation type check for `std::string`
+ (https://github.com/fmtlib/fmt/issues/2402).
+- Fixed a linkage error when mixing code built with clang and gcc
+ (https://github.com/fmtlib/fmt/issues/2377).
+- Fixed documentation issues
+ (https://github.com/fmtlib/fmt/pull/2396,
+ https://github.com/fmtlib/fmt/issues/2403,
+ https://github.com/fmtlib/fmt/issues/2406). Thanks @mkurdej.
+- Removed dead code in FP formatter (
+ https://github.com/fmtlib/fmt/pull/2398). Thanks @javierhonduco.
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/issues/2351,
+ https://github.com/fmtlib/fmt/issues/2359,
+ https://github.com/fmtlib/fmt/pull/2365,
+ https://github.com/fmtlib/fmt/issues/2368,
+ https://github.com/fmtlib/fmt/pull/2370,
+ https://github.com/fmtlib/fmt/pull/2376,
+ https://github.com/fmtlib/fmt/pull/2381,
+ https://github.com/fmtlib/fmt/pull/2382,
+ https://github.com/fmtlib/fmt/issues/2386,
+ https://github.com/fmtlib/fmt/pull/2389,
+ https://github.com/fmtlib/fmt/pull/2395,
+ https://github.com/fmtlib/fmt/pull/2397,
+ https://github.com/fmtlib/fmt/issues/2400,
+ https://github.com/fmtlib/fmt/issues/2401,
+ https://github.com/fmtlib/fmt/pull/2407).
+ Thanks @zx2c4, @AidanSun05, @mattiasljungstrom, @joemmett, @erengy,
+ @patlkli, @gsjaardema and @phprus.
+
+# 8.0.0 - 2021-06-21
+
+- Enabled compile-time format string checks by default. For example
+ ([godbolt](https://godbolt.org/z/sMxcohGjz)):
+
+ ```c++
+ #include <fmt/core.h>
+
+ int main() {
+ fmt::print("{:d}", "I am not a number");
+ }
+ ```
+
+ gives a compile-time error on compilers with C++20 `consteval`
+ support (gcc 10+, clang 11+) because `d` is not a valid format
+ specifier for a string.
+
+ To pass a runtime string wrap it in `fmt::runtime`:
+
+ ```c++
+ fmt::print(fmt::runtime("{:d}"), "I am not a number");
+ ```
+
+- Added compile-time formatting
+ (https://github.com/fmtlib/fmt/pull/2019,
+ https://github.com/fmtlib/fmt/pull/2044,
+ https://github.com/fmtlib/fmt/pull/2056,
+ https://github.com/fmtlib/fmt/pull/2072,
+ https://github.com/fmtlib/fmt/pull/2075,
+ https://github.com/fmtlib/fmt/issues/2078,
+ https://github.com/fmtlib/fmt/pull/2129,
+ https://github.com/fmtlib/fmt/pull/2326). For example
+ ([godbolt](https://godbolt.org/z/Mxx9d89jM)):
+
+ ```c++
+ #include <fmt/compile.h>
+
+ consteval auto compile_time_itoa(int value) -> std::array<char, 10> {
+ auto result = std::array<char, 10>();
+ fmt::format_to(result.data(), FMT_COMPILE("{}"), value);
+ return result;
+ }
+
+ constexpr auto answer = compile_time_itoa(42);
+ ```
+
+ Most of the formatting functionality is available at compile time
+ with a notable exception of floating-point numbers and pointers.
+ Thanks @alexezeder.
+
+- Optimized handling of format specifiers during format string
+ compilation. For example, hexadecimal formatting (`"{:x}"`) is now
+ 3-7x faster than before when using `format_to` with format string
+ compilation and a stack-allocated buffer
+ (https://github.com/fmtlib/fmt/issues/1944).
+
+ Before (7.1.3):
+
+ ----------------------------------------------------------------------------
+ Benchmark Time CPU Iterations
+ ----------------------------------------------------------------------------
+ FMTCompileOld/0 15.5 ns 15.5 ns 43302898
+ FMTCompileOld/42 16.6 ns 16.6 ns 43278267
+ FMTCompileOld/273123 18.7 ns 18.6 ns 37035861
+ FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000
+ ----------------------------------------------------------------------------
+
+ After (8.x):
+
+ ----------------------------------------------------------------------------
+ Benchmark Time CPU Iterations
+ ----------------------------------------------------------------------------
+ FMTCompileNew/0 1.99 ns 1.99 ns 360523686
+ FMTCompileNew/42 2.33 ns 2.33 ns 279865664
+ FMTCompileNew/273123 3.72 ns 3.71 ns 190230315
+ FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631
+ ----------------------------------------------------------------------------
+
+ It is even faster than `std::to_chars` from libc++ compiled with
+ clang on macOS:
+
+ ----------------------------------------------------------------------------
+ Benchmark Time CPU Iterations
+ ----------------------------------------------------------------------------
+ ToChars/0 4.42 ns 4.41 ns 160196630
+ ToChars/42 5.00 ns 4.98 ns 140735201
+ ToChars/273123 7.26 ns 7.24 ns 95784130
+ ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534
+ ----------------------------------------------------------------------------
+
+ In other cases, especially involving `std::string` construction, the
+ speed up is usually lower because handling format specifiers takes a
+ smaller fraction of the total time.
+
+- Added the `_cf` user-defined literal to represent a compiled format
+ string. It can be used instead of the `FMT_COMPILE` macro
+ (https://github.com/fmtlib/fmt/pull/2043,
+ https://github.com/fmtlib/fmt/pull/2242):
+
+ ```c++
+ #include <fmt/compile.h>
+
+ using namespace fmt::literals;
+ auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙁 not modern
+ auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell
+ ```
+
+ It requires compiler support for class types in non-type template
+ parameters (a C++20 feature) which is available in GCC 9.3+.
+ Thanks @alexezeder.
+
+- Format string compilation now requires `format` functions of
+ `formatter` specializations for user-defined types to be `const`:
+
+ ```c++
+ template <> struct fmt::formatter<my_type>: formatter<string_view> {
+ template <typename FormatContext>
+ auto format(my_type obj, FormatContext& ctx) const { // Note const here.
+ // ...
+ }
+ };
+ ```
+
+- Added UDL-based named argument support to format string compilation
+ (https://github.com/fmtlib/fmt/pull/2243,
+ https://github.com/fmtlib/fmt/pull/2281). For example:
+
+ ```c++
+ #include <fmt/compile.h>
+
+ using namespace fmt::literals;
+ auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42);
+ ```
+
+ Here the argument named \"answer\" is resolved at compile time with
+ no runtime overhead. Thanks @alexezeder.
+
+- Added format string compilation support to `fmt::print`
+ (https://github.com/fmtlib/fmt/issues/2280,
+ https://github.com/fmtlib/fmt/pull/2304). Thanks @alexezeder.
+
+- Added initial support for compiling {fmt} as a C++20 module
+ (https://github.com/fmtlib/fmt/pull/2235,
+ https://github.com/fmtlib/fmt/pull/2240,
+ https://github.com/fmtlib/fmt/pull/2260,
+ https://github.com/fmtlib/fmt/pull/2282,
+ https://github.com/fmtlib/fmt/pull/2283,
+ https://github.com/fmtlib/fmt/pull/2288,
+ https://github.com/fmtlib/fmt/pull/2298,
+ https://github.com/fmtlib/fmt/pull/2306,
+ https://github.com/fmtlib/fmt/pull/2307,
+ https://github.com/fmtlib/fmt/pull/2309,
+ https://github.com/fmtlib/fmt/pull/2318,
+ https://github.com/fmtlib/fmt/pull/2324,
+ https://github.com/fmtlib/fmt/pull/2332,
+ https://github.com/fmtlib/fmt/pull/2340). Thanks @DanielaE.
+
+- Made symbols private by default reducing shared library size
+ (https://github.com/fmtlib/fmt/pull/2301). For example
+ there was a \~15% reported reduction on one platform. Thanks @sergiud.
+
+- Optimized includes making the result of preprocessing `fmt/format.h`
+ \~20% smaller with libstdc++/C++20 and slightly improving build
+ times (https://github.com/fmtlib/fmt/issues/1998).
+
+- Added support of ranges with non-const `begin` / `end`
+ (https://github.com/fmtlib/fmt/pull/1953). Thanks @kitegi.
+
+- Added support of `std::byte` and other formattable types to
+ `fmt::join` (https://github.com/fmtlib/fmt/issues/1981,
+ https://github.com/fmtlib/fmt/issues/2040,
+ https://github.com/fmtlib/fmt/pull/2050,
+ https://github.com/fmtlib/fmt/issues/2262). For example:
+
+ ```c++
+ #include <fmt/format.h>
+ #include <cstddef>
+ #include <vector>
+
+ int main() {
+ auto bytes = std::vector{std::byte(4), std::byte(2)};
+ fmt::print("{}", fmt::join(bytes, ""));
+ }
+ ```
+
+ prints \"42\".
+
+ Thanks @kamibo.
+
+- Implemented the default format for `std::chrono::system_clock`
+ (https://github.com/fmtlib/fmt/issues/2319,
+ https://github.com/fmtlib/fmt/pull/2345). For example:
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ fmt::print("{}", std::chrono::system_clock::now());
+ }
+ ```
+
+ prints \"2021-06-18 15:22:00\" (the output depends on the current
+ date and time). Thanks @sunmy2019.
+
+- Made more chrono specifiers locale independent by default. Use the
+ `'L'` specifier to get localized formatting. For example:
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ std::locale::global(std::locale("ru_RU.UTF-8"));
+ auto monday = std::chrono::weekday(1);
+ fmt::print("{}\n", monday); // prints "Mon"
+ fmt::print("{:L}\n", monday); // prints "пн"
+ }
+ ```
+
+- Improved locale handling in chrono formatting
+ (https://github.com/fmtlib/fmt/issues/2337,
+ https://github.com/fmtlib/fmt/pull/2349,
+ https://github.com/fmtlib/fmt/pull/2350). Thanks @phprus.
+
+- Deprecated `fmt/locale.h` moving the formatting functions that take
+ a locale to `fmt/format.h` (`char`) and `fmt/xchar` (other
+ overloads). This doesn\'t introduce a dependency on `<locale>` so
+ there is virtually no compile time effect.
+
+- Deprecated an undocumented `format_to` overload that takes
+ `basic_memory_buffer`.
+
+- Made parameter order in `vformat_to` consistent with `format_to`
+ (https://github.com/fmtlib/fmt/issues/2327).
+
+- Added support for time points with arbitrary durations
+ (https://github.com/fmtlib/fmt/issues/2208). For example:
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ using tp = std::chrono::time_point<
+ std::chrono::system_clock, std::chrono::seconds>;
+ fmt::print("{:%S}", tp(std::chrono::seconds(42)));
+ }
+ ```
+
+ prints \"42\".
+
+- Formatting floating-point numbers no longer produces trailing zeros
+ by default for consistency with `std::format`. For example:
+
+ ```c++
+ #include <fmt/core.h>
+
+ int main() {
+ fmt::print("{0:.3}", 1.1);
+ }
+ ```
+
+ prints \"1.1\". Use the `'#'` specifier to keep trailing zeros.
+
+- Dropped a limit on the number of elements in a range and replaced
+ `{}` with `[]` as range delimiters for consistency with Python\'s
+ `str.format`.
+
+- The `'L'` specifier for locale-specific numeric formatting can now
+ be combined with presentation specifiers as in `std::format`. For
+ example:
+
+ ```c++
+ #include <fmt/core.h>
+ #include <locale>
+
+ int main() {
+ std::locale::global(std::locale("fr_FR.UTF-8"));
+ fmt::print("{0:.2Lf}", 0.42);
+ }
+ ```
+
+ prints \"0,42\". The deprecated `'n'` specifier has been removed.
+
+- Made the `0` specifier ignored for infinity and NaN
+ (https://github.com/fmtlib/fmt/issues/2305,
+ https://github.com/fmtlib/fmt/pull/2310). Thanks @Liedtke.
+
+- Made the hexfloat formatting use the right alignment by default
+ (https://github.com/fmtlib/fmt/issues/2308,
+ https://github.com/fmtlib/fmt/pull/2317). Thanks @Liedtke.
+
+- Removed the deprecated numeric alignment (`'='`). Use the `'0'`
+ specifier instead.
+
+- Removed the deprecated `fmt/posix.h` header that has been replaced
+ with `fmt/os.h`.
+
+- Removed the deprecated `format_to_n_context`, `format_to_n_args` and
+ `make_format_to_n_args`. They have been replaced with
+ `format_context`, `` format_args` and ``make_format_args\`\`
+ respectively.
+
+- Moved `wchar_t`-specific functions and types to `fmt/xchar.h`. You
+ can define `FMT_DEPRECATED_INCLUDE_XCHAR` to automatically include
+ `fmt/xchar.h` from `fmt/format.h` but this will be disabled in the
+ next major release.
+
+- Fixed handling of the `'+'` specifier in localized formatting
+ (https://github.com/fmtlib/fmt/issues/2133).
+
+- Added support for the `'s'` format specifier that gives textual
+ representation of `bool`
+ (https://github.com/fmtlib/fmt/issues/2094,
+ https://github.com/fmtlib/fmt/pull/2109). For example:
+
+ ```c++
+ #include <fmt/core.h>
+
+ int main() {
+ fmt::print("{:s}", true);
+ }
+ ```
+
+ prints \"true\". Thanks @powercoderlol.
+
+- Made `fmt::ptr` work with function pointers
+ (https://github.com/fmtlib/fmt/pull/2131). For example:
+
+ ```c++
+ #include <fmt/format.h>
+
+ int main() {
+ fmt::print("My main: {}\n", fmt::ptr(main));
+ }
+ ```
+
+ Thanks @mikecrowe.
+
+- The undocumented support for specializing `formatter` for pointer
+ types has been removed.
+
+- Fixed `fmt::formatted_size` with format string compilation
+ (https://github.com/fmtlib/fmt/pull/2141,
+ https://github.com/fmtlib/fmt/pull/2161). Thanks @alexezeder.
+
+- Fixed handling of empty format strings during format string
+ compilation (https://github.com/fmtlib/fmt/issues/2042):
+
+ ```c++
+ auto s = fmt::format(FMT_COMPILE(""));
+ ```
+
+ Thanks @alexezeder.
+
+- Fixed handling of enums in `fmt::to_string`
+ (https://github.com/fmtlib/fmt/issues/2036).
+
+- Improved width computation
+ (https://github.com/fmtlib/fmt/issues/2033,
+ https://github.com/fmtlib/fmt/issues/2091). For example:
+
+ ```c++
+ #include <fmt/core.h>
+
+ int main() {
+ fmt::print("{:-<10}{}\n", "你好", "世界");
+ fmt::print("{:-<10}{}\n", "hello", "world");
+ }
+ ```
+
+ prints
+
+ 
+
+ on a modern terminal.
+
+- The experimental fast output stream (`fmt::ostream`) is now
+ truncated by default for consistency with `fopen`
+ (https://github.com/fmtlib/fmt/issues/2018). For example:
+
+ ```c++
+ #include <fmt/os.h>
+
+ int main() {
+ fmt::ostream out1 = fmt::output_file("guide");
+ out1.print("Zaphod");
+ out1.close();
+ fmt::ostream out2 = fmt::output_file("guide");
+ out2.print("Ford");
+ }
+ ```
+
+ writes \"Ford\" to the file \"guide\". To preserve the old file
+ content if any pass `fmt::file::WRONLY | fmt::file::CREATE` flags to
+ `fmt::output_file`.
+
+- Fixed moving of `fmt::ostream` that holds buffered data
+ (https://github.com/fmtlib/fmt/issues/2197,
+ https://github.com/fmtlib/fmt/pull/2198). Thanks @vtta.
+
+- Replaced the `fmt::system_error` exception with a function of the
+ same name that constructs `std::system_error`
+ (https://github.com/fmtlib/fmt/issues/2266).
+
+- Replaced the `fmt::windows_error` exception with a function of the
+ same name that constructs `std::system_error` with the category
+ returned by `fmt::system_category()`
+ (https://github.com/fmtlib/fmt/issues/2274,
+ https://github.com/fmtlib/fmt/pull/2275). The latter is
+ similar to `std::sytem_category` but correctly handles UTF-8.
+ Thanks @phprus.
+
+- Replaced `fmt::error_code` with `std::error_code` and made it
+ formattable (https://github.com/fmtlib/fmt/issues/2269,
+ https://github.com/fmtlib/fmt/pull/2270,
+ https://github.com/fmtlib/fmt/pull/2273). Thanks @phprus.
+
+- Added speech synthesis support
+ (https://github.com/fmtlib/fmt/pull/2206).
+
+- Made `format_to` work with a memory buffer that has a custom
+ allocator (https://github.com/fmtlib/fmt/pull/2300).
+ Thanks @voxmea.
+
+- Added `Allocator::max_size` support to `basic_memory_buffer`.
+ (https://github.com/fmtlib/fmt/pull/1960). Thanks @phprus.
+
+- Added wide string support to `fmt::join`
+ (https://github.com/fmtlib/fmt/pull/2236). Thanks @crbrz.
+
+- Made iterators passed to `formatter` specializations via a format
+ context satisfy C++20 `std::output_iterator` requirements
+ (https://github.com/fmtlib/fmt/issues/2156,
+ https://github.com/fmtlib/fmt/pull/2158,
+ https://github.com/fmtlib/fmt/issues/2195,
+ https://github.com/fmtlib/fmt/pull/2204). Thanks @randomnetcat.
+
+- Optimized the `printf` implementation
+ (https://github.com/fmtlib/fmt/pull/1982,
+ https://github.com/fmtlib/fmt/pull/1984,
+ https://github.com/fmtlib/fmt/pull/2016,
+ https://github.com/fmtlib/fmt/pull/2164).
+ Thanks @rimathia and @moiwi.
+
+- Improved detection of `constexpr` `char_traits`
+ (https://github.com/fmtlib/fmt/pull/2246,
+ https://github.com/fmtlib/fmt/pull/2257). Thanks @phprus.
+
+- Fixed writing to `stdout` when it is redirected to `NUL` on Windows
+ (https://github.com/fmtlib/fmt/issues/2080).
+
+- Fixed exception propagation from iterators
+ (https://github.com/fmtlib/fmt/issues/2097).
+
+- Improved `strftime` error handling
+ (https://github.com/fmtlib/fmt/issues/2238,
+ https://github.com/fmtlib/fmt/pull/2244). Thanks @yumeyao.
+
+- Stopped using deprecated GCC UDL template extension.
+
+- Added `fmt/args.h` to the install target
+ (https://github.com/fmtlib/fmt/issues/2096).
+
+- Error messages are now passed to assert when exceptions are disabled
+ (https://github.com/fmtlib/fmt/pull/2145). Thanks @NobodyXu.
+
+- Added the `FMT_MASTER_PROJECT` CMake option to control build and
+ install targets when {fmt} is included via `add_subdirectory`
+ (https://github.com/fmtlib/fmt/issues/2098,
+ https://github.com/fmtlib/fmt/pull/2100).
+ Thanks @randomizedthinking.
+
+- Improved build configuration
+ (https://github.com/fmtlib/fmt/pull/2026,
+ https://github.com/fmtlib/fmt/pull/2122).
+ Thanks @luncliff and @ibaned.
+
+- Fixed various warnings and compilation issues
+ (https://github.com/fmtlib/fmt/issues/1947,
+ https://github.com/fmtlib/fmt/pull/1959,
+ https://github.com/fmtlib/fmt/pull/1963,
+ https://github.com/fmtlib/fmt/pull/1965,
+ https://github.com/fmtlib/fmt/issues/1966,
+ https://github.com/fmtlib/fmt/pull/1974,
+ https://github.com/fmtlib/fmt/pull/1975,
+ https://github.com/fmtlib/fmt/pull/1990,
+ https://github.com/fmtlib/fmt/issues/2000,
+ https://github.com/fmtlib/fmt/pull/2001,
+ https://github.com/fmtlib/fmt/issues/2002,
+ https://github.com/fmtlib/fmt/issues/2004,
+ https://github.com/fmtlib/fmt/pull/2006,
+ https://github.com/fmtlib/fmt/pull/2009,
+ https://github.com/fmtlib/fmt/pull/2010,
+ https://github.com/fmtlib/fmt/issues/2038,
+ https://github.com/fmtlib/fmt/issues/2039,
+ https://github.com/fmtlib/fmt/issues/2047,
+ https://github.com/fmtlib/fmt/pull/2053,
+ https://github.com/fmtlib/fmt/issues/2059,
+ https://github.com/fmtlib/fmt/pull/2065,
+ https://github.com/fmtlib/fmt/pull/2067,
+ https://github.com/fmtlib/fmt/pull/2068,
+ https://github.com/fmtlib/fmt/pull/2073,
+ https://github.com/fmtlib/fmt/issues/2103,
+ https://github.com/fmtlib/fmt/issues/2105,
+ https://github.com/fmtlib/fmt/pull/2106,
+ https://github.com/fmtlib/fmt/pull/2107,
+ https://github.com/fmtlib/fmt/issues/2116,
+ https://github.com/fmtlib/fmt/pull/2117,
+ https://github.com/fmtlib/fmt/issues/2118,
+ https://github.com/fmtlib/fmt/pull/2119,
+ https://github.com/fmtlib/fmt/issues/2127,
+ https://github.com/fmtlib/fmt/pull/2128,
+ https://github.com/fmtlib/fmt/issues/2140,
+ https://github.com/fmtlib/fmt/issues/2142,
+ https://github.com/fmtlib/fmt/pull/2143,
+ https://github.com/fmtlib/fmt/pull/2144,
+ https://github.com/fmtlib/fmt/issues/2147,
+ https://github.com/fmtlib/fmt/issues/2148,
+ https://github.com/fmtlib/fmt/issues/2149,
+ https://github.com/fmtlib/fmt/pull/2152,
+ https://github.com/fmtlib/fmt/pull/2160,
+ https://github.com/fmtlib/fmt/issues/2170,
+ https://github.com/fmtlib/fmt/issues/2175,
+ https://github.com/fmtlib/fmt/issues/2176,
+ https://github.com/fmtlib/fmt/pull/2177,
+ https://github.com/fmtlib/fmt/issues/2178,
+ https://github.com/fmtlib/fmt/pull/2179,
+ https://github.com/fmtlib/fmt/issues/2180,
+ https://github.com/fmtlib/fmt/issues/2181,
+ https://github.com/fmtlib/fmt/pull/2183,
+ https://github.com/fmtlib/fmt/issues/2184,
+ https://github.com/fmtlib/fmt/issues/2185,
+ https://github.com/fmtlib/fmt/pull/2186,
+ https://github.com/fmtlib/fmt/pull/2187,
+ https://github.com/fmtlib/fmt/pull/2190,
+ https://github.com/fmtlib/fmt/pull/2192,
+ https://github.com/fmtlib/fmt/pull/2194,
+ https://github.com/fmtlib/fmt/pull/2205,
+ https://github.com/fmtlib/fmt/issues/2210,
+ https://github.com/fmtlib/fmt/pull/2211,
+ https://github.com/fmtlib/fmt/pull/2215,
+ https://github.com/fmtlib/fmt/pull/2216,
+ https://github.com/fmtlib/fmt/pull/2218,
+ https://github.com/fmtlib/fmt/pull/2220,
+ https://github.com/fmtlib/fmt/issues/2228,
+ https://github.com/fmtlib/fmt/pull/2229,
+ https://github.com/fmtlib/fmt/pull/2230,
+ https://github.com/fmtlib/fmt/issues/2233,
+ https://github.com/fmtlib/fmt/pull/2239,
+ https://github.com/fmtlib/fmt/issues/2248,
+ https://github.com/fmtlib/fmt/issues/2252,
+ https://github.com/fmtlib/fmt/pull/2253,
+ https://github.com/fmtlib/fmt/pull/2255,
+ https://github.com/fmtlib/fmt/issues/2261,
+ https://github.com/fmtlib/fmt/issues/2278,
+ https://github.com/fmtlib/fmt/issues/2284,
+ https://github.com/fmtlib/fmt/pull/2287,
+ https://github.com/fmtlib/fmt/pull/2289,
+ https://github.com/fmtlib/fmt/pull/2290,
+ https://github.com/fmtlib/fmt/pull/2293,
+ https://github.com/fmtlib/fmt/issues/2295,
+ https://github.com/fmtlib/fmt/pull/2296,
+ https://github.com/fmtlib/fmt/pull/2297,
+ https://github.com/fmtlib/fmt/issues/2311,
+ https://github.com/fmtlib/fmt/pull/2313,
+ https://github.com/fmtlib/fmt/pull/2315,
+ https://github.com/fmtlib/fmt/issues/2320,
+ https://github.com/fmtlib/fmt/pull/2321,
+ https://github.com/fmtlib/fmt/pull/2323,
+ https://github.com/fmtlib/fmt/issues/2328,
+ https://github.com/fmtlib/fmt/pull/2329,
+ https://github.com/fmtlib/fmt/pull/2333,
+ https://github.com/fmtlib/fmt/pull/2338,
+ https://github.com/fmtlib/fmt/pull/2341).
+ Thanks @darklukee, @fagg, @killerbot242, @jgopel, @yeswalrus, @Finkman,
+ @HazardyKnusperkeks, @dkavolis, @concatime, @chronoxor, @summivox, @yNeo,
+ @Apache-HB, @alexezeder, @toojays, @Brainy0207, @vadz, @imsherlock, @phprus,
+ @white238, @yafshar, @BillyDonahue, @jstaahl, @denchat, @DanielaE,
+ @ilyakurdyukov, @ilmai, @JessyDL, @sergiud, @mwinterb, @sven-herrmann,
+ @jmelas, @twoixter, @crbrz and @upsj.
+
+- Improved documentation
+ (https://github.com/fmtlib/fmt/issues/1986,
+ https://github.com/fmtlib/fmt/pull/2051,
+ https://github.com/fmtlib/fmt/issues/2057,
+ https://github.com/fmtlib/fmt/pull/2081,
+ https://github.com/fmtlib/fmt/issues/2084,
+ https://github.com/fmtlib/fmt/pull/2312).
+ Thanks @imba-tjd, @0x416c69 and @mordante.
+
+- Continuous integration and test improvements
+ (https://github.com/fmtlib/fmt/issues/1969,
+ https://github.com/fmtlib/fmt/pull/1991,
+ https://github.com/fmtlib/fmt/pull/2020,
+ https://github.com/fmtlib/fmt/pull/2110,
+ https://github.com/fmtlib/fmt/pull/2114,
+ https://github.com/fmtlib/fmt/issues/2196,
+ https://github.com/fmtlib/fmt/pull/2217,
+ https://github.com/fmtlib/fmt/pull/2247,
+ https://github.com/fmtlib/fmt/pull/2256,
+ https://github.com/fmtlib/fmt/pull/2336,
+ https://github.com/fmtlib/fmt/pull/2346).
+ Thanks @jgopel, @alexezeder and @DanielaE.
+
+# 7.1.3 - 2020-11-24
+
+- Fixed handling of buffer boundaries in `format_to_n`
+ (https://github.com/fmtlib/fmt/issues/1996,
+ https://github.com/fmtlib/fmt/issues/2029).
+- Fixed linkage errors when linking with a shared library
+ (https://github.com/fmtlib/fmt/issues/2011).
+- Reintroduced ostream support to range formatters
+ (https://github.com/fmtlib/fmt/issues/2014).
+- Worked around an issue with mixing std versions in gcc
+ (https://github.com/fmtlib/fmt/issues/2017).
+
+# 7.1.2 - 2020-11-04
+
+- Fixed floating point formatting with large precision
+ (https://github.com/fmtlib/fmt/issues/1976).
+
+# 7.1.1 - 2020-11-01
+
+- Fixed ABI compatibility with 7.0.x
+ (https://github.com/fmtlib/fmt/issues/1961).
+- Added the `FMT_ARM_ABI_COMPATIBILITY` macro to work around ABI
+ incompatibility between GCC and Clang on ARM
+ (https://github.com/fmtlib/fmt/issues/1919).
+- Worked around a SFINAE bug in GCC 8
+ (https://github.com/fmtlib/fmt/issues/1957).
+- Fixed linkage errors when building with GCC\'s LTO
+ (https://github.com/fmtlib/fmt/issues/1955).
+- Fixed a compilation error when building without `__builtin_clz` or
+ equivalent (https://github.com/fmtlib/fmt/pull/1968).
+ Thanks @tohammer.
+- Fixed a sign conversion warning
+ (https://github.com/fmtlib/fmt/pull/1964). Thanks @OptoCloud.
+
+# 7.1.0 - 2020-10-25
+
+- Switched from
+ [Grisu3](https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf)
+ to [Dragonbox](https://github.com/jk-jeon/dragonbox) for the default
+ floating-point formatting which gives the shortest decimal
+ representation with round-trip guarantee and correct rounding
+ (https://github.com/fmtlib/fmt/pull/1882,
+ https://github.com/fmtlib/fmt/pull/1887,
+ https://github.com/fmtlib/fmt/pull/1894). This makes {fmt}
+ up to 20-30x faster than common implementations of
+ `std::ostringstream` and `sprintf` on
+ [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark) and
+ faster than double-conversion and Ryū:
+
+ 
+
+ It is possible to get even better performance at the cost of larger
+ binary size by compiling with the `FMT_USE_FULL_CACHE_DRAGONBOX`
+ macro set to 1.
+
+ Thanks @jk-jeon.
+
+- Added an experimental unsynchronized file output API which, together
+ with [format string
+ compilation](https://fmt.dev/latest/api.html#compile-api), can give
+ [5-9 times speed up compared to
+ fprintf](https://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html)
+ on common platforms ([godbolt](https://godbolt.org/z/nsTcG8)):
+
+ ```c++
+ #include <fmt/os.h>
+
+ int main() {
+ auto f = fmt::output_file("guide");
+ f.print("The answer is {}.", 42);
+ }
+ ```
+
+- Added a formatter for `std::chrono::time_point<system_clock>`
+ (https://github.com/fmtlib/fmt/issues/1819,
+ https://github.com/fmtlib/fmt/pull/1837). For example
+ ([godbolt](https://godbolt.org/z/c4M6fh)):
+
+ ```c++
+ #include <fmt/chrono.h>
+
+ int main() {
+ auto now = std::chrono::system_clock::now();
+ fmt::print("The time is {:%H:%M:%S}.\n", now);
+ }
+ ```
+
+ Thanks @adamburgess.
+
+- Added support for ranges with non-const `begin`/`end` to `fmt::join`
+ (https://github.com/fmtlib/fmt/issues/1784,
+ https://github.com/fmtlib/fmt/pull/1786). For example
+ ([godbolt](https://godbolt.org/z/jP63Tv)):
+
+ ```c++
+ #include <fmt/ranges.h>
+ #include <range/v3/view/filter.hpp>
+
+ int main() {
+ using std::literals::string_literals::operator""s;
+ auto strs = std::array{"a"s, "bb"s, "ccc"s};
+ auto range = strs | ranges::views::filter(
+ [] (const std::string &x) { return x.size() != 2; }
+ );
+ fmt::print("{}\n", fmt::join(range, ""));
+ }
... 21273 lines suppressed ...