Add support for parquet (#488)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-09-02 21:47:50 +02:00
committed by GitHub
parent 9e57aee378
commit 611712f5eb
49 changed files with 2390 additions and 55 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
strategy:
fail-fast: false
matrix:
format: ["JSON", "AVRO", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "XML", "TOML", "UBJSON", "YAML", "benchmarks"]
format: ["JSON", "AVRO", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"]
compiler: [llvm, gcc]
compiler-version: [11, 12, 13, 14, 16, 17, 18]
cxx: [20, 23]
+3 -1
View File
@@ -11,7 +11,7 @@ jobs:
fail-fast: false
matrix:
os: ["macos-latest", "macos-13"]
format: ["JSON", "AVRO", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "XML", "TOML", "UBJSON", "YAML", "benchmarks"]
format: ["JSON", "AVRO", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"]
name: "${{ matrix.os }} (${{ matrix.format }})"
runs-on: ${{ matrix.os }}
steps:
@@ -28,6 +28,8 @@ jobs:
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Run vcpkg
uses: lukka/run-vcpkg@v11
- name: Install bison
run: brew install bison
- name: Install ninja
run: brew install ninja
if: matrix.os == 'macos-latest'
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
strategy:
fail-fast: false
matrix:
format: ["JSON", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "XML", "TOML", "UBJSON", "YAML", "benchmarks"]
format: ["JSON", "AVRO", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"]
name: "windows-msvc (${{ matrix.format }})"
runs-on: windows-latest
steps:
+1
View File
@@ -49,6 +49,7 @@
*.fb
*.flexbuf
*.msgpack
*.parquet
*.toml
*.ubjson
*.xml
+18 -1
View File
@@ -11,6 +11,7 @@ option(REFLECTCPP_CAPNPROTO "Enable Cap’n Proto support" ${REFLECTCPP_ALL_FORM
option(REFLECTCPP_CBOR "Enable CBOR support" ${REFLECTCPP_ALL_FORMATS})
option(REFLECTCPP_FLEXBUFFERS "Enable flexbuffers support" ${REFLECTCPP_ALL_FORMATS})
option(REFLECTCPP_MSGPACK "Enable msgpack support" ${REFLECTCPP_ALL_FORMATS})
option(REFLECTCPP_PARQUET "Enable parquet support" ${REFLECTCPP_ALL_FORMATS})
option(REFLECTCPP_XML "Enable XML support" ${REFLECTCPP_ALL_FORMATS})
option(REFLECTCPP_TOML "Enable TOML support" ${REFLECTCPP_ALL_FORMATS})
option(REFLECTCPP_UBJSON "Enable UBJSON support" ${REFLECTCPP_ALL_FORMATS})
@@ -55,7 +56,8 @@ endif()
if (REFLECTCPP_BUILD_TESTS OR REFLECTCPP_BUILD_BENCHMARKS OR
(REFLECTCPP_JSON AND NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) OR REFLECTCPP_AVRO OR
REFLECTCPP_BSON OR REFLECTCPP_CAPNPROTO OR REFLECTCPP_CBOR OR REFLECTCPP_FLEXBUFFERS OR
REFLECTCPP_MSGPACK OR REFLECTCPP_XML OR REFLECTCPP_TOML OR REFLECTCPP_UBJSON OR REFLECTCPP_YAML)
REFLECTCPP_MSGPACK OR REFLECTCPP_PARQUET OR REFLECTCPP_XML OR
REFLECTCPP_TOML OR REFLECTCPP_UBJSON OR REFLECTCPP_YAML)
# enable vcpkg per default if features other than JSON are required
set(REFLECTCPP_USE_VCPKG_DEFAULT ON)
endif()
@@ -109,6 +111,10 @@ if (REFLECTCPP_USE_VCPKG)
list(APPEND VCPKG_MANIFEST_FEATURES "msgpack")
endif()
if (REFLECTCPP_PARQUET)
list(APPEND VCPKG_MANIFEST_FEATURES "parquet")
endif()
if (REFLECTCPP_TOML)
list(APPEND VCPKG_MANIFEST_FEATURES "toml")
endif()
@@ -260,6 +266,17 @@ if (REFLECTCPP_MSGPACK)
target_link_libraries(reflectcpp PUBLIC msgpack-c)
endif ()
if (REFLECTCPP_PARQUET)
if (NOT TARGET Arrow)
find_package(Arrow CONFIG REQUIRED)
endif()
if (NOT TARGET Parquet)
find_package(Parquet CONFIG REQUIRED)
endif()
target_link_libraries(reflectcpp PUBLIC "$<IF:$<BOOL:${ARROW_BUILD_STATIC}>,Arrow::arrow_static,Arrow::arrow_shared>")
target_link_libraries(reflectcpp PUBLIC "$<IF:$<BOOL:${ARROW_BUILD_STATIC}>,Parquet::parquet_static,Parquet::parquet_shared>")
endif ()
if (REFLECTCPP_TOML)
list(APPEND REFLECT_CPP_SOURCES
src/reflectcpp_toml.cpp
+31 -2
View File
@@ -30,7 +30,6 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile
<br>
## Table of Contents
### On this page
@@ -38,6 +37,7 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile
- [Feature Overview](#feature-overview)
- [Simple Example](#simple-example)
- [More Comprehensive Example](#more-comprehensive-example)
- [Tabular data](#tabular-data)
- [Error messages](#error-messages)
- [JSON schema](#json-schema)
- [Enums](#enums)
@@ -70,6 +70,7 @@ The following table lists the serialization formats currently supported by refle
| CBOR | [jsoncons](https://github.com/danielaparker/jsoncons)| >= 0.176.0 | BSL 1.0 | JSON-like binary format |
| flexbuffers | [flatbuffers](https://github.com/google/flatbuffers) | >= 23.5.26 | Apache 2.0 | Schema-less version of flatbuffers, binary format |
| msgpack | [msgpack-c](https://github.com/msgpack/msgpack-c) | >= 6.0.0 | BSL 1.0 | JSON-like binary format |
| parquet | [Apache Arrow](https://arrow.apache.org/) | >= 21.0.0 | Apache 2.0 | Tabular binary format |
| TOML | [toml++](https://github.com/marzer/tomlplusplus) | >= 3.4.0 | MIT | Textual format with an emphasis on readability |
| UBJSON | [jsoncons](https://github.com/danielaparker/jsoncons)| >= 0.176.0 | BSL 1.0 | JSON-like binary format |
| XML | [pugixml](https://github.com/zeux/pugixml) | >= 1.14 | MIT | Textual format used in many legacy projects |
@@ -145,7 +146,7 @@ age: 45
```
This will work for just about any example in the entire documentation
and any supported format, except where explicitly noted otherwise:
and any of the following formats, except where explicitly noted otherwise:
```cpp
rfl::avro::write(homer);
@@ -242,6 +243,34 @@ std::cout << "Hello, my name is " << homer2.first_name() << " "
<< homer2.last_name() << "." << std::endl;
```
### Tabular data
reflect-cpp also supports tabular data formats, like Parquet:
```cpp
#include <rfl/parquet.hpp>
const auto people =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
const auto bytestring = rfl::parquet::write(people);
```
### Error messages
reflect-cpp returns clear and comprehensive error messages:
+265
View File
@@ -0,0 +1,265 @@
For Parquet support, you must also include the header `<rfl/parquet.hpp>` and link to the [Apache Arrow](https://arrow.apache.org/) and [Apache Parquet](https://parquet.apache.org/) libraries.
Furthermore, when compiling reflect-cpp, you need to pass `-DREFLECTCPP_PARQUET=ON` to cmake.
Parquet is a columnar storage format optimized for analytical workloads. Unlike most other formats supported by reflect-cpp, Parquet is designed for tabular data and has specific limitations regarding nested structures.
## Reading and writing
Suppose you have a struct like this:
```cpp
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name;
rfl::Timestamp<"%Y-%m-%d"> birthday;
unsigned int age;
rfl::Email email;
};
```
**Important**: Parquet is a tabular format that requires collections of records. You cannot serialize individual structs - you must use containers like `std::vector<Person>`, `std::deque<Person>`, etc.
A collection of `Person` structs can be serialized to a bytes vector like this:
```cpp
const auto people = std::vector<Person>{
Person{.first_name = "Bart", .birthday = "1987-04-19", .age = 10, .email = "bart@simpson.com"},
Person{.first_name = "Lisa", .birthday = "1987-04-19", .age = 8, .email = "lisa@simpson.com"}
};
const std::vector<char> bytes = rfl::parquet::write(people);
```
You can parse bytes like this:
```cpp
const rfl::Result<std::vector<Person>> result = rfl::parquet::read<std::vector<Person>>(bytes);
```
## Settings and compression
Parquet supports various compression algorithms and chunk sizes. You can configure these using the `Settings` struct:
```cpp
const auto settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::GZIP)
.with_chunksize(1000);
const std::vector<char> bytes = rfl::parquet::write(people, settings);
```
Available compression options include:
- `UNCOMPRESSED` - No compression, fastest read/write but largest file size
- `SNAPPY` (default) - Fast compression/decompression, good balance of speed and size
- `GZIP` - Good compression ratio, slower than Snappy but better compression
- `BROTLI` - Good compression for text data, optimized for web content
- `ZSTD` - Excellent compression ratio, modern algorithm with good speed
- `LZ4` - Very fast compression/decompression, lower compression ratio
- `LZ4_FRAME` - LZ4 with frame format, better compatibility
- `LZO` - Fast compression, older algorithm
- `BZ2` - High compression ratio, slower compression/decompression
- `LZ4_HADOOP` - LZ4 optimized for Hadoop ecosystem
```cpp
// Examples of different compression settings
const auto snappy_settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::SNAPPY);
const auto gzip_settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::GZIP);
const auto zstd_settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::ZSTD);
const auto uncompressed_settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::UNCOMPRESSED);
```
## Loading and saving
You can also load and save to disk using a very similar syntax:
```cpp
const rfl::Result<std::vector<Person>> result = rfl::parquet::load<std::vector<Person>>("/path/to/file.parquet");
const auto people = std::vector<Person>{...};
rfl::parquet::save("/path/to/file.parquet", people);
```
With custom settings:
```cpp
const auto settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::GZIP);
rfl::parquet::save("/path/to/file.parquet", people, settings);
```
## Reading from and writing into streams
You can also read from and write into any `std::istream` and `std::ostream` respectively.
```cpp
const rfl::Result<std::vector<Person>> result = rfl::parquet::read<std::vector<Person>>(my_istream);
const auto people = std::vector<Person>{...};
rfl::parquet::write(people, my_ostream);
```
With custom settings:
```cpp
const auto settings = rfl::parquet::Settings{}
.with_compression(rfl::parquet::Compression::GZIP);
rfl::parquet::write(people, my_ostream, settings);
```
## Field name transformations
Like other formats, Parquet supports field name transformations. You can use processors like `SnakeCaseToCamelCase`:
```cpp
const auto people = std::vector<Person>{...};
const auto result = rfl::parquet::read<std::vector<Person>, rfl::SnakeCaseToCamelCase>(bytes);
```
This will automatically convert field names from snake_case to camelCase during serialization and deserialization.
## Supported processors
The following processors are **NOT supported** and will cause compilation errors:
- `rfl::AddTagsToVariants` - Cannot be used for tabular data
- `rfl::NoOptionals` - Cannot be used for tabular data
- `rfl::DefaultIfMissing` - Cannot be used for tabular data
- `rfl::NoExtraFields` - Cannot be used for tabular data
- `rfl::NoFieldNames` - Cannot be used for tabular data
```cpp
// ✅ This works
const auto result = rfl::parquet::read<std::vector<Person>, rfl::SnakeCaseToCamelCase>(bytes);
// ❌ This will cause compilation errors
const auto result = rfl::parquet::read<std::vector<Person>, rfl::AddTagsToVariants>(bytes);
const auto result = rfl::parquet::read<std::vector<Person>, rfl::NoOptionals>(bytes);
const auto result = rfl::parquet::read<std::vector<Person>, rfl::DefaultIfMissing>(bytes);
```
## Enums and validation
Parquet supports enums and validated types. Enums are stored as strings:
```cpp
enum class FirstName { Bart, Lisa, Maggie, Homer };
struct Person {
rfl::Rename<"firstName", FirstName> first_name;
rfl::Rename<"lastName", std::string> last_name;
rfl::Timestamp<"%Y-%m-%d"> birthday;
rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>> age;
rfl::Email email;
};
```
## No variant types
Parquet does not support variant types like `std::variant`, `rfl::Variant`, or `rfl::TaggedUnion`. These types cannot be serialized to Parquet format.
```cpp
// ❌ This will NOT work
struct Person {
std::string first_name;
std::variant<std::string, int> status; // Variant - not supported
rfl::Variant<std::string, int> type; // rfl::Variant - not supported
rfl::TaggedUnion<"type", std::string, int> category; // TaggedUnion - not supported
};
```
## Limitations of tabular formats
Parquet, like other tabular formats, has specific limitations that differ from hierarchical formats like JSON or XML:
### No nested objects
Unlike JSON or XML, Parquet cannot directly represent nested objects within a single row. Each field must be a primitive type, enum, or a simple container of primitives.
```cpp
// This works fine
struct Person {
std::string first_name;
std::string last_name;
unsigned int age;
};
// This would NOT work as expected - nested objects are not automatically flattened
struct Address {
std::string street;
std::string city;
};
struct Person {
std::string first_name;
std::string last_name;
Address address; // ❌ This will cause compilation errors
};
```
### Using rfl::Flatten for nested objects
If you need to include nested objects, you can use `rfl::Flatten` to explicitly flatten them:
```cpp
struct Address {
std::string street;
std::string city;
};
struct Person {
std::string first_name;
std::string last_name;
rfl::Flatten<Address> address; // ✅ This will flatten the Address fields
};
// The resulting Parquet file will have columns: first_name, last_name, street, city
```
### Collections requirement
You must serialize collections, not individual objects:
```cpp
std::vector<Person> people = {...}; // ✅ Correct
Person person = {...}; // ❌ Wrong - must be in a container
```
### No arrays (except bytestrings)
Parquet does not support arrays of any type except for binary data (bytestrings). This includes arrays of primitive types, strings, and objects.
```cpp
// ❌ This will NOT work
struct Person {
std::string first_name;
std::vector<std::string> hobbies; // Array of strings - not supported
std::vector<int> scores; // Array of integers - not supported
std::vector<Address> addresses; // Array of objects - not supported
};
// ✅ This works
struct Person {
std::string first_name;
std::string last_name;
std::vector<char> binary_data; // Binary data - supported as bytestring
};
```
### Use cases
Parquet is ideal for:
- Data warehousing and analytics
- Large datasets with repeated values
- Integration with big data tools (Spark, Hadoop, etc.)
- Simple, flat data structures with consistent types
Parquet is less suitable for:
- Complex nested data structures
- Data with arrays or variant types
- Frequent schema changes
- Row-oriented access patterns
- Small datasets where the overhead isn't justified
- Data with complex object hierarchies
+1
View File
@@ -76,6 +76,7 @@
#include "rfl/to_view.hpp"
#include "rfl/tuple_cat.hpp"
#include "rfl/type_name_t.hpp"
#include "rfl/view_t.hpp"
#include "rfl/visit.hpp"
#ifdef _MSC_VER
+19
View File
@@ -37,6 +37,15 @@ class Timestamp {
Timestamp(const std::tm& _tm) : tm_(_tm) {}
Timestamp(const time_t _t) : tm_(std::tm{}) {
auto t = _t;
#if defined(_MSC_VER) || defined(__MINGW32__)
gmtime_s(&tm_, &t);
#else
gmtime_r(&t, &tm_);
#endif
}
~Timestamp() = default;
/// Returns a result containing the timestamp when successful or an Error
@@ -71,6 +80,16 @@ class Timestamp {
/// Trivial (const) accessor to the underlying time stamp.
const std::tm& tm() const { return tm_; }
/// Returns a UTC time represented by a time_t type.
time_t to_time_t() const {
auto tm = tm_;
#if defined(_MSC_VER) || defined(__MINGW32__)
return _mkgmtime(&tm);
#else
return static_cast<time_t>(timegm(&tm) - tm_.tm_gmtoff);
#endif
}
private:
#if defined(_MSC_VER) || defined(__MINGW32__)
// This workaround is necessary, because strptime is not available on Windows.
@@ -1,29 +1,15 @@
#ifndef RFL_INTERNAL_HASREFLECTIONMETHODV_HPP_
#define RFL_INTERNAL_HASREFLECTIONMETHODV_HPP_
#include <type_traits>
#include <concepts>
namespace rfl {
namespace internal {
namespace rfl::internal {
template <typename Wrapper>
using reflection_method_t =
decltype(std::declval<const Wrapper>().reflection());
template <class T>
constexpr bool has_reflection_method_v = requires(T t) {
{ t.reflection() } -> std::convertible_to<typename T::ReflectionType>;
};
template <typename Wrapper, typename = std::void_t<>>
struct has_refl_m : std::false_type {};
template <typename Wrapper>
struct has_refl_m<Wrapper, std::void_t<reflection_method_t<Wrapper>>>
: std::true_type {};
/// Utility parameter for named tuple parsing, can be used by the
/// parsers to determine whether a class or struct has a method
/// called "reflection".
template <typename Wrapper>
constexpr bool has_reflection_method_v = has_refl_m<Wrapper>::value;
} // namespace internal
} // namespace rfl
} // namespace rfl::internal
#endif
+10 -23
View File
@@ -1,33 +1,20 @@
#ifndef RFL_HASREFLECTIONTYPEV_HPP_
#define RFL_HASREFLECTIONTYPEV_HPP_
#include <cstdint>
#include <utility>
#include <concepts>
namespace rfl {
namespace internal {
namespace rfl::internal {
template <class Wrapper>
class HasReflectionType {
private:
template <class U>
static std::int64_t foo(...);
template <class T>
struct ReflectionTypeWrapper {};
template <class U>
static std::int32_t foo(typename U::ReflectionType*);
public:
static constexpr bool value =
sizeof(foo<Wrapper>(nullptr)) == sizeof(std::int32_t);
template <typename T>
constexpr bool has_reflection_type_v = requires() {
{
ReflectionTypeWrapper<typename T::ReflectionType>{}
} -> std::same_as<ReflectionTypeWrapper<typename T::ReflectionType>>;
};
/// Utility parameter for named tuple parsing, can be used by the
/// parsers to determine whether a class or struct defines a type
/// called "ReflectionType".
template <typename Wrapper>
constexpr bool has_reflection_type_v = HasReflectionType<Wrapper>::value;
} // namespace internal
} // namespace rfl
} // namespace rfl::internal
#endif // RFL_HASNAMEDTUPLETYPEV_HPP_
+1 -1
View File
@@ -13,7 +13,7 @@ namespace internal {
template <class T>
using ptr_named_tuple_t =
typename std::invoke_result<decltype(to_ptr_named_tuple<T>), T>::type;
std::invoke_result_t<decltype(to_ptr_named_tuple<T>), T>;
} // namespace internal
} // namespace rfl
+5 -4
View File
@@ -6,18 +6,19 @@
#include <type_traits>
#include "NamedTuple.hpp"
#include "internal/ptr_named_tuple_t.hpp"
#include "Processors.hpp"
#include "internal/remove_ptrs_nt.hpp"
#include "to_named_tuple.hpp"
#include "view_t.hpp"
namespace rfl {
/// Generates the named tuple that is equivalent to the struct T.
/// This is the result you would expect from calling to_named_tuple(my_struct).
/// All fields of the struct must be an rfl::Field.
template <class T>
using named_tuple_t = typename internal::remove_ptrs_nt<
internal::ptr_named_tuple_t<T>>::NamedTupleType;
template <class T, class... Ps>
using named_tuple_t =
typename internal::remove_ptrs_nt<view_t<T, Ps...>>::NamedTupleType;
} // namespace rfl
+10
View File
@@ -0,0 +1,10 @@
#ifndef RFL_PARQUET_HPP_
#define RFL_PARQUET_HPP_
#include "../rfl.hpp"
#include "parquet/load.hpp"
#include "parquet/read.hpp"
#include "parquet/save.hpp"
#include "parquet/write.hpp"
#endif
+32
View File
@@ -0,0 +1,32 @@
#ifndef RFL_PARQUET_SETTINGS_HPP_
#define RFL_PARQUET_SETTINGS_HPP_
#include <arrow/io/api.h>
#include <parquet/arrow/writer.h>
#include "../Field.hpp"
#include "../replace.hpp"
namespace rfl::parquet {
using Compression = arrow::Compression::type;
struct Settings {
/// The size of the chunks of the parquet file.
size_t chunksize = 2000;
/// The compression algorithm used to compress the parquet file.
Compression compression = Compression::SNAPPY;
Settings with_chunksize(const size_t _chunksize) const noexcept {
return replace(*this, make_field<"chunksize">(_chunksize));
}
Settings with_compression(const Compression _compression) const noexcept {
return replace(*this, make_field<"compression">(_compression));
}
};
} // namespace rfl::parquet
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef RFL_PARQUET_LOAD_HPP_
#define RFL_PARQUET_LOAD_HPP_
#include "../Result.hpp"
#include "../io/load_bytes.hpp"
#include "read.hpp"
namespace rfl::parquet {
template <class T, class... Ps>
Result<T> load(const std::string& _fname) {
const auto read_bytes = [](const auto& _bytes) {
return read<T, Ps...>(_bytes);
};
return rfl::io::load_bytes(_fname).and_then(read_bytes);
}
} // namespace rfl::parquet
#endif
+67
View File
@@ -0,0 +1,67 @@
#ifndef RFL_PARQUET_READ_HPP_
#define RFL_PARQUET_READ_HPP_
#include <arrow/io/api.h>
#include <parquet/arrow/reader.h>
#include <istream>
#include <memory>
#include <string>
#include "../Processors.hpp"
#include "../Result.hpp"
#include "../concepts.hpp"
#include "../internal/wrap_in_rfl_array_t.hpp"
#include "../parsing/tabular/ArrowReader.hpp"
namespace rfl::parquet {
/// Parses an object from PARQUET using reflection.
template <class T, class... Ps>
Result<internal::wrap_in_rfl_array_t<T>> read(
const concepts::ByteLike auto* _bytes, const size_t _size) {
arrow::MemoryPool* pool = arrow::default_memory_pool();
const auto buffer = std::make_shared<arrow::Buffer>(
internal::ptr_cast<const uint8_t*>(_bytes), _size);
const auto input = std::make_shared<arrow::io::BufferReader>(buffer);
auto arrow_reader = ::parquet::arrow::OpenFile(input, pool);
if (!arrow_reader.ok()) {
return error(std::string("Could not generate the arrow reader: ") +
arrow_reader.status().message());
}
std::shared_ptr<arrow::Table> table;
const auto status = arrow_reader.ValueOrDie()->ReadTable(&table);
if (!status.ok()) {
return error("Could not read table: " + status.message());
}
using ArrowReader = parsing::tabular::ArrowReader<T, Ps...>;
return ArrowReader::make(table).and_then(
[](const auto& _r) { return _r.read(); });
}
/// Parses an object from PARQUET using reflection.
template <class T, class... Ps>
auto read(const concepts::ContiguousByteContainer auto& _bytes) {
return read<T, Ps...>(_bytes.data(), _bytes.size());
}
/// Parses an object from a stream.
template <class T, class... Ps>
auto read(std::istream& _stream) {
std::istreambuf_iterator<char> begin(_stream), end;
auto bytes = std::vector<char>(begin, end);
return read<T, Ps...>(bytes.data(), bytes.size());
}
} // namespace rfl::parquet
#endif
+24
View File
@@ -0,0 +1,24 @@
#ifndef RFL_PARQUET_SAVE_HPP_
#define RFL_PARQUET_SAVE_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "../Result.hpp"
#include "../io/save_bytes.hpp"
#include "write.hpp"
namespace rfl::parquet {
template <class... Ps>
Result<Nothing> save(const std::string& _fname, const auto& _obj) {
const auto write_func = [](const auto& _obj, auto& _stream) -> auto& {
return write<Ps...>(_obj, _stream);
};
return rfl::io::save_bytes(_fname, _obj, write_func);
}
} // namespace rfl::parquet
#endif
+81
View File
@@ -0,0 +1,81 @@
#ifndef RFL_PARQUET_WRITE_HPP_
#define RFL_PARQUET_WRITE_HPP_
#include <arrow/io/api.h>
#include <parquet/arrow/writer.h>
#include <cstdint>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include "../Processors.hpp"
#include "../Ref.hpp"
#include "../parsing/tabular/ArrowWriter.hpp"
#include "Settings.hpp"
namespace rfl::parquet {
/// Returns parquet bytes.
template <class... Ps>
Ref<arrow::Buffer> to_buffer(const auto& _arr, const Settings& _settings) {
using T = std::remove_cvref_t<decltype(_arr)>;
const auto table =
parsing::tabular::ArrowWriter<T, Ps...>(_settings.chunksize)
.to_table(_arr);
const auto props = ::parquet::WriterProperties::Builder()
.compression(_settings.compression)
->build();
const auto arrow_props =
::parquet::ArrowWriterProperties::Builder().store_schema()->build();
const auto output_buffer = arrow::io::BufferOutputStream::Create();
if (!output_buffer.ok()) {
throw std::runtime_error(output_buffer.status().message());
}
const auto status = ::parquet::arrow::WriteTable(
*table.get(), arrow::default_memory_pool(), output_buffer.ValueOrDie(),
_settings.chunksize, props, arrow_props);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
const auto buffer = output_buffer.ValueOrDie()->Finish();
if (!buffer.ok()) {
throw std::runtime_error(output_buffer.status().message());
}
return Ref<arrow::Buffer>::make(buffer.ValueOrDie()).value();
}
/// Returns parquet bytes.
template <class... Ps>
std::vector<char> write(const auto& _arr,
const Settings& _settings = Settings{}) {
const auto buffer = to_buffer<Ps...>(_arr, _settings);
const auto view = std::string_view(*buffer);
return std::vector<char>(view.begin(), view.end());
}
/// Writes a PARQUET into an ostream.
template <class... Ps>
std::ostream& write(const auto& _arr, std::ostream& _stream,
const Settings& _settings = Settings{}) noexcept {
auto buffer = to_buffer<Ps...>(_arr, _settings);
_stream << std::string_view(*buffer);
return _stream;
}
} // namespace rfl::parquet
#endif
+128
View File
@@ -0,0 +1,128 @@
#ifndef RFL_PARSING_TABULAR_ARROWREADER_HPP_
#define RFL_PARSING_TABULAR_ARROWREADER_HPP_
#include <arrow/api.h>
#include <array>
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include "../../Processors.hpp"
#include "../../Result.hpp"
#include "../../Tuple.hpp"
#include "../../apply.hpp"
#include "../../get.hpp"
#include "../../named_tuple_t.hpp"
#include "../../to_view.hpp"
#include "../../view_t.hpp"
#include "../call_destructors_where_necessary.hpp"
#include "make_chunked_array_iterators.hpp"
namespace rfl::parsing::tabular {
template <class VecType, class... Ps>
class ArrowReader {
static_assert(!Processors<Ps...>::add_tags_to_variants_,
"rfl::AddTagsToVariants cannot be used for tabular data.");
static_assert(!Processors<Ps...>::all_required_,
"rfl::NoOptionals cannot be used for tabular data.");
static_assert(!Processors<Ps...>::default_if_missing_,
"rfl::DefaultIfMissing cannot be used for tabular data.");
static_assert(!Processors<Ps...>::no_extra_fields_,
"rfl::NoExtraFields cannot be used for tabular data (neither "
"can rfl::ExtraFields).");
static_assert(!Processors<Ps...>::no_field_names_,
"rfl::NoFieldNames cannot be used for tabular data.");
public:
using ValueType = typename std::remove_cvref_t<typename VecType::value_type>;
static Result<ArrowReader> make(const std::shared_ptr<arrow::Table>& _table) {
try {
return ArrowReader(_table);
} catch (const std::exception& e) {
return error(std::string("Could not create ArrowReader: ") + e.what());
}
}
~ArrowReader() = default;
Result<VecType> read() const noexcept {
return make_chunked_array_iterators<named_tuple_t<ValueType, Ps...>>(table_)
.and_then([&](auto chunked_array_iterators) -> Result<VecType> {
VecType result;
while (!end(chunked_array_iterators)) {
auto value = new_value(&chunked_array_iterators);
if (!value) {
return error(value.error().what());
}
result.emplace_back(std::move(*value));
}
return result;
});
}
private:
ArrowReader(const std::shared_ptr<arrow::Table>& _table)
: table_(Ref<arrow::Table>::make(_table).value()) {}
bool end(const auto& _chunked_array_iterators) const {
return apply(
[](const auto&... _its) { return (false || ... || _its.end()); },
_chunked_array_iterators);
}
Result<ValueType> new_value(auto* _chunked_array_iterators) const noexcept {
alignas(ValueType) unsigned char buf[sizeof(ValueType)]{};
auto ptr = internal::ptr_cast<ValueType*>(&buf);
auto view = to_view(*ptr);
using ViewType = std::remove_cvref_t<decltype(view)>;
try {
const auto set_one = [&]<size_t _i>(std::integral_constant<size_t, _i>) {
using FieldType = tuple_element_t<_i, typename ViewType::Fields>;
using T = std::remove_cvref_t<
std::remove_pointer_t<typename FieldType::Type>>;
auto res = *_chunked_array_iterators->template get<_i>();
if (!res) {
destroy_value<_i>(&view);
throw std::runtime_error(
std::string("Field '") + typename FieldType::Name().str() +
std::string("' could not be set: ") + res.error().what());
}
::new (view.template get<_i>()) T(std::move(*res));
++_chunked_array_iterators->template get<_i>();
};
[&]<size_t... _is>(std::integer_sequence<size_t, _is...>) {
(set_one(std::integral_constant<size_t, _is>{}), ...);
}(std::make_integer_sequence<size_t, view.size()>());
return std::move(*ptr);
} catch (const std::exception& e) {
return error(e.what());
}
}
template <size_t _i, class ViewType>
void destroy_value(ViewType* _view) const {
static_assert(_i < ViewType::size(), "_i out of bounds.");
auto set = std::array<bool, ViewType::size()>();
for (size_t i = 0; i < _i; ++i) {
set[i] = true;
}
for (size_t i = _i; i < ViewType::size(); ++i) {
set[i] = false;
}
call_destructors_where_necessary(set, _view);
}
private:
Ref<arrow::Table> table_;
};
} // namespace rfl::parsing::tabular
#endif
+537
View File
@@ -0,0 +1,537 @@
#ifndef RFL_PARSING_TABULAR_ARROWTYPES_HPP_
#define RFL_PARSING_TABULAR_ARROWTYPES_HPP_
#include <arrow/api.h>
#include <array>
#include <cinttypes>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "../../Box.hpp"
#include "../../NamedTuple.hpp"
#include "../../Ref.hpp"
#include "../../Rename.hpp"
#include "../../Timestamp.hpp"
#include "../../Tuple.hpp"
#include "../../concepts.hpp"
#include "../../enums.hpp"
#include "../../internal/StringLiteral.hpp"
#include "../../internal/has_reflection_type_v.hpp"
#include "../../internal/ptr_cast.hpp"
#include "../../named_tuple_t.hpp"
namespace rfl::parsing::tabular {
template <class T>
struct ArrowTypes;
template <>
struct ArrowTypes<bool> {
using ArrayType = arrow::BooleanArray;
using BuilderType = arrow::BooleanBuilder;
static auto data_type() { return arrow::boolean(); }
static void add_to_builder(const bool _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<bool> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<uint8_t> {
using ArrayType = arrow::UInt8Array;
using BuilderType = arrow::UInt8Builder;
static auto data_type() { return arrow::uint8(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<uint8_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<uint16_t> {
using ArrayType = arrow::UInt16Array;
using BuilderType = arrow::UInt16Builder;
static auto data_type() { return arrow::uint16(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<uint16_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<uint32_t> {
using ArrayType = arrow::UInt32Array;
using BuilderType = arrow::UInt32Builder;
static auto data_type() { return arrow::uint32(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<uint32_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<uint64_t> {
using ArrayType = arrow::UInt64Array;
using BuilderType = arrow::UInt64Builder;
static auto data_type() { return arrow::uint64(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<uint64_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<int8_t> {
using ArrayType = arrow::Int8Array;
using BuilderType = arrow::Int8Builder;
static auto data_type() { return arrow::int8(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<int8_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<int16_t> {
using ArrayType = arrow::Int16Array;
using BuilderType = arrow::Int16Builder;
static auto data_type() { return arrow::int16(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<int16_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<int32_t> {
using ArrayType = arrow::Int32Array;
using BuilderType = arrow::Int32Builder;
static auto data_type() { return arrow::int32(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<int32_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<int64_t> {
using ArrayType = arrow::Int64Array;
using BuilderType = arrow::Int64Builder;
static auto data_type() { return arrow::int64(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<int64_t> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<float> {
using ArrayType = arrow::FloatArray;
using BuilderType = arrow::FloatBuilder;
static auto data_type() { return arrow::float32(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<float> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<double> {
using ArrayType = arrow::DoubleArray;
using BuilderType = arrow::DoubleBuilder;
static auto data_type() { return arrow::float64(); }
static void add_to_builder(const auto _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<double> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return _chunk->Value(_ix);
}
static auto make_builder() { return BuilderType(); }
};
template <>
struct ArrowTypes<std::string> {
using ArrayType = arrow::StringArray;
using BuilderType = arrow::StringBuilder;
static auto data_type() { return arrow::utf8(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
const auto status = _builder->Append(_val);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<std::string> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return std::string(_chunk->Value(_ix));
}
static auto make_builder() { return BuilderType(); }
};
template <class T>
requires enchantum::Enum<T>
struct ArrowTypes<T> {
using ArrayType = arrow::StringArray;
using BuilderType = arrow::StringBuilder;
static auto data_type() { return arrow::utf8(); }
static void add_to_builder(const T _val, BuilderType* _builder) {
const auto status = _builder->Append(enum_to_string(_val));
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<T> get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return string_to_enum<T>(std::string(_chunk->Value(_ix)));
}
static auto make_builder() { return BuilderType(); }
};
template <class T>
requires concepts::ContiguousByteContainer<T>
struct ArrowTypes<T> {
using ArrayType = arrow::BinaryArray;
using BuilderType = arrow::BinaryBuilder;
static auto data_type() { return arrow::binary(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
const auto status = _builder->Append(
internal::ptr_cast<const uint8_t*>(_val.data()), _val.size());
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<T> get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
const auto begin = internal::ptr_cast<const typename T::value_type*>(
_chunk->Value(_ix).data());
return T(begin, begin + _chunk->Value(_ix).size());
}
static auto make_builder() { return BuilderType(); }
};
template <internal::StringLiteral _format>
struct ArrowTypes<Timestamp<_format>> {
using ArrayType = arrow::TimestampArray;
using BuilderType = arrow::TimestampBuilder;
static auto data_type() { return arrow::timestamp(arrow::TimeUnit::SECOND); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
const auto status = _builder->Append(_val.to_time_t());
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
static Result<Timestamp<_format>> get_value(const Ref<ArrayType>& _chunk,
const int64_t _ix) {
return Timestamp<_format>(_chunk->Value(_ix) / 1000);
}
static auto make_builder() {
return BuilderType(data_type(), arrow::default_memory_pool());
}
};
template <class T>
requires internal::has_reflection_type_v<T>
struct ArrowTypes<T> {
using ArrayType = typename ArrowTypes<typename T::ReflectionType>::ArrayType;
using BuilderType =
typename ArrowTypes<typename T::ReflectionType>::BuilderType;
static auto data_type() {
return ArrowTypes<typename T::ReflectionType>::data_type();
}
static void add_to_builder(const auto& _val, BuilderType* _builder) {
ArrowTypes<typename T::ReflectionType>::add_to_builder(_val.reflection(),
_builder);
}
static Result<T> get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<typename T::ReflectionType>>::
get_value(_chunk, _ix)
.and_then([](const auto& _v) -> Result<T> {
try {
return T(_v);
} catch (const std::exception& e) {
return error(e.what());
}
});
}
static auto make_builder() {
return ArrowTypes<typename T::ReflectionType>::make_builder();
}
};
template <class T>
struct ArrowTypes<std::optional<T>> {
using ArrayType = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
using BuilderType = typename ArrowTypes<std::remove_cvref_t<T>>::BuilderType;
static auto data_type() { return ArrowTypes<T>::data_type(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
if (_val) {
ArrowTypes<T>::add_to_builder(*_val, _builder);
} else {
const auto status = _builder->AppendNull();
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
}
static auto get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<T>>::get_value(_chunk, _ix)
.transform([](const auto& _v) { return std::make_optional<T>(_v); });
}
static auto make_builder() { return ArrowTypes<T>::make_builder(); }
};
template <class T>
struct ArrowTypes<std::shared_ptr<T>> {
using ArrayType = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
using BuilderType = typename ArrowTypes<std::remove_cvref_t<T>>::BuilderType;
static auto data_type() { return ArrowTypes<T>::data_type(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
if (_val) {
ArrowTypes<T>::add_to_builder(*_val, _builder);
} else {
const auto status = _builder->AppendNull();
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
}
static auto get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<T>>::get_value(_chunk, _ix)
.transform([](const auto& _v) { return std::make_shared<T>(_v); });
}
static auto make_builder() { return ArrowTypes<T>::make_builder(); }
};
template <class T>
struct ArrowTypes<std::unique_ptr<T>> {
using ArrayType = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
using BuilderType = typename ArrowTypes<std::remove_cvref_t<T>>::BuilderType;
static auto data_type() { return ArrowTypes<T>::data_type(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
if (_val) {
ArrowTypes<T>::add_to_builder(*_val, _builder);
} else {
const auto status = _builder->AppendNull();
if (!status.ok()) {
throw std::runtime_error(status.message());
}
}
}
static auto get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<T>>::get_value(_chunk, _ix)
.transform([](const auto& _v) { return std::make_unique<T>(_v); });
}
static auto make_builder() { return ArrowTypes<T>::make_builder(); }
};
template <class T>
struct ArrowTypes<Box<T>> {
using ArrayType = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
using BuilderType = typename ArrowTypes<std::remove_cvref_t<T>>::BuilderType;
static auto data_type() { return ArrowTypes<T>::data_type(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
ArrowTypes<T>::add_to_builder(*_val, _builder);
}
static auto get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<T>>::get_value(_chunk, _ix)
.transform([](const auto& _v) { return Box<T>::make(_v); });
}
static auto make_builder() { return ArrowTypes<T>::make_builder(); }
};
template <class T>
struct ArrowTypes<Ref<T>> {
using ArrayType = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
using BuilderType = typename ArrowTypes<std::remove_cvref_t<T>>::BuilderType;
static auto data_type() { return ArrowTypes<T>::data_type(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
ArrowTypes<T>::add_to_builder(*_val, _builder);
}
static auto get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<T>>::get_value(_chunk, _ix)
.transform([](const auto& _v) { return Ref<T>::make(_v); });
}
static auto make_builder() { return ArrowTypes<T>::make_builder(); }
};
template <internal::StringLiteral _name, class T>
struct ArrowTypes<Rename<_name, T>> {
using ArrayType = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
using BuilderType = typename ArrowTypes<std::remove_cvref_t<T>>::BuilderType;
static auto data_type() { return ArrowTypes<T>::data_type(); }
static void add_to_builder(const auto& _val, BuilderType* _builder) {
ArrowTypes<T>::add_to_builder(_val.value(), _builder);
}
static auto get_value(const Ref<ArrayType>& _chunk, const int64_t _ix) {
return ArrowTypes<std::remove_cvref_t<T>>::get_value(_chunk, _ix)
.transform([](const auto& _v) { return Rename<_name, T>(_v); });
}
static auto make_builder() { return ArrowTypes<T>::make_builder(); }
};
} // namespace rfl::parsing::tabular
#endif
+117
View File
@@ -0,0 +1,117 @@
#ifndef RFL_PARSING_TABULAR_ARROWWRITER_HPP_
#define RFL_PARSING_TABULAR_ARROWWRITER_HPP_
#include <arrow/api.h>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include "../../Processors.hpp"
#include "../../Tuple.hpp"
#include "../../get.hpp"
#include "../../named_tuple_t.hpp"
#include "../../to_view.hpp"
#include "add_to_builder.hpp"
#include "make_arrow_builders.hpp"
#include "make_arrow_data_types.hpp"
#include "make_arrow_schema.hpp"
namespace rfl::parsing::tabular {
template <class VecType, class... Ps>
class ArrowWriter {
static_assert(!Processors<Ps...>::add_tags_to_variants_,
"rfl::AddTagsToVariants cannot be used for tabular data.");
static_assert(!Processors<Ps...>::all_required_,
"rfl::NoOptionals cannot be used for tabular data.");
static_assert(!Processors<Ps...>::default_if_missing_,
"rfl::DefaultIfMissing cannot be used for tabular data.");
static_assert(!Processors<Ps...>::no_extra_fields_,
"rfl::NoExtraFields cannot be used for tabular data (neither "
"can rfl::ExtraFields).");
static_assert(!Processors<Ps...>::no_field_names_,
"rfl::NoFieldNames cannot be used for tabular data.");
public:
using ValueType = typename std::remove_cvref_t<typename VecType::value_type>;
ArrowWriter(const size_t _chunksize) : chunksize_(_chunksize) {}
~ArrowWriter() = default;
std::shared_ptr<arrow::Table> to_table(const VecType& _data) const {
return arrow::Table::Make(
make_arrow_schema<named_tuple_t<ValueType, Ps...>>(),
to_chunked_arrays(_data));
}
private:
std::vector<std::shared_ptr<arrow::ChunkedArray>> to_chunked_arrays(
const VecType& _data) const;
private:
size_t chunksize_;
};
template <class VecType, class... Ps>
std::vector<std::shared_ptr<arrow::ChunkedArray>>
ArrowWriter<VecType, Ps...>::to_chunked_arrays(const VecType& _data) const {
using ValueType = typename VecType::value_type;
auto builders =
make_arrow_builders<named_tuple_t<typename VecType::value_type>>();
constexpr size_t size = tuple_size_v<decltype(builders)>;
std::vector<std::vector<std::shared_ptr<arrow::Array>>> array_chunks(size);
auto it = _data.begin();
while (it != _data.end()) {
size_t i = 0;
for (; it != _data.end() && (i < chunksize_ || chunksize_ == 0);
++i, ++it) {
const auto view = to_view(*it);
[&]<int... _is>(const auto& _v, auto* _b,
std::integer_sequence<int, _is...>) {
(add_to_builder(*get<_is>(_v), &(_b->template get<_is>())), ...);
}(view, &builders, std::make_integer_sequence<int, size>());
}
if (i != 0) {
std::vector<std::shared_ptr<arrow::Array>> chunks(size);
const auto finish_builder = [](auto* _b, auto* _c) {
const auto status = _b->Finish(_c);
if (!status.ok()) {
throw std::runtime_error(status.message());
}
};
[&]<size_t... _is>(auto* _b, auto* _c,
std::integer_sequence<size_t, _is...>) {
(finish_builder(&_b->template get<_is>(), &_c->at(_is)), ...);
}(&builders, &chunks, std::make_integer_sequence<size_t, size>());
for (size_t j = 0; j < size; ++j) {
array_chunks.at(j).emplace_back(std::move(chunks.at(j)));
}
}
}
const auto data_types = make_arrow_data_types<ValueType>();
return [&]<size_t... _is>(std::integer_sequence<size_t, _is...>) {
return std::vector<std::shared_ptr<arrow::ChunkedArray>>(
{std::make_shared<arrow::ChunkedArray>(array_chunks.at(_is),
std::get<_is>(data_types))...});
}(std::make_integer_sequence<size_t, size>());
}
} // namespace rfl::parsing::tabular
#endif
@@ -0,0 +1,96 @@
#ifndef RFL_PARSING_TABULAR_CHUNKEDARRAYITERATOR_HPP_
#define RFL_PARSING_TABULAR_CHUNKEDARRAYITERATOR_HPP_
#include <arrow/api.h>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include "../../Ref.hpp"
#include "../../Result.hpp"
#include "../../internal/ptr_cast.hpp"
#include "../is_required.hpp"
#include "array_t.hpp"
namespace rfl::parsing::tabular {
template <class T>
class ChunkedArrayIterator {
public:
using difference_type = std::ptrdiff_t;
using value_type = Result<T>;
using ArrayType = array_t<T>;
static ChunkedArrayIterator make(const Ref<arrow::ChunkedArray>& _arr) {
return ChunkedArrayIterator(_arr);
}
ChunkedArrayIterator(const Ref<arrow::ChunkedArray>& _arr)
: arr_(_arr), chunk_ix_(0), current_chunk_(get_chunk(arr_, 0)), ix_(0) {}
~ChunkedArrayIterator() = default;
Result<T> operator*() const noexcept {
const bool is_null =
current_chunk_
.transform([&](const auto& _c) { return _c->IsNull(ix_); })
.value_or(false);
if (is_null) {
if constexpr (is_required<T, false>()) {
return error("Value cannot be null.");
} else {
return T();
}
}
return current_chunk_.and_then(
[&](const auto& _c) { return ArrowTypes<T>::get_value(_c, ix_); });
}
bool end() const noexcept {
return !current_chunk_ || (chunk_ix_ >= arr_->num_chunks());
}
ChunkedArrayIterator<T>& operator++() noexcept {
if (!current_chunk_) {
return *this;
}
++ix_;
if (ix_ >= (*current_chunk_)->length()) {
++chunk_ix_;
current_chunk_ = get_chunk(arr_, chunk_ix_);
ix_ = 0;
}
return *this;
}
void operator++(int) noexcept { ++*this; }
private:
static Result<Ref<ArrayType>> get_chunk(const Ref<arrow::ChunkedArray>& _arr,
const int _chunk_ix) noexcept {
if (_chunk_ix < _arr->num_chunks()) {
return Ref<ArrayType>::make(
std::static_pointer_cast<ArrayType>(_arr->chunk(_chunk_ix)));
} else {
return error("chunk_ix out of bounds.");
}
}
private:
Ref<arrow::ChunkedArray> arr_;
int chunk_ix_;
Result<Ref<ArrayType>> current_chunk_;
int64_t ix_;
};
} // namespace rfl::parsing::tabular
#endif
@@ -0,0 +1,18 @@
#ifndef RFL_PARSING_TABULAR_ADD_TO_BUILDER_HPP_
#define RFL_PARSING_TABULAR_ADD_TO_BUILDER_HPP_
#include <type_traits>
#include "../../named_tuple_t.hpp"
#include "ArrowTypes.hpp"
namespace rfl::parsing::tabular {
template <class ValueType, class BuilderType>
inline void add_to_builder(const ValueType& _val, BuilderType* _builder) {
ArrowTypes<std::remove_cvref_t<ValueType>>::add_to_builder(_val, _builder);
}
} // namespace rfl::parsing::tabular
#endif
+13
View File
@@ -0,0 +1,13 @@
#ifndef RFL_PARSING_TABULAR_ARRAYT_HPP_
#define RFL_PARSING_TABULAR_ARRAYT_HPP_
#include "ArrowTypes.hpp"
namespace rfl::parsing::tabular {
template <class T>
using array_t = typename ArrowTypes<std::remove_cvref_t<T>>::ArrayType;
} // namespace rfl::parsing::tabular
#endif
@@ -0,0 +1,57 @@
#ifndef RFL_PARSING_TABULAR_MAKEARROWBUILDERS_HPP_
#define RFL_PARSING_TABULAR_MAKEARROWBUILDERS_HPP_
#include <arrow/api.h>
#include <array>
#include <cinttypes>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "../../named_tuple_t.hpp"
#include "ArrowTypes.hpp"
namespace rfl::parsing::tabular {
template <class T>
using arrow_builder_t = typename ArrowTypes<
std::remove_cvref_t<std::remove_pointer_t<T>>>::BuilderType;
template <class T>
struct ArrowBuildersType;
template <class... FieldTypes>
struct ArrowBuildersType<NamedTuple<FieldTypes...>> {
using Type = Tuple<arrow_builder_t<typename FieldTypes::Type>...>;
static auto data_types() {
return [&]<size_t... _is>(std::integer_sequence<size_t, _is...>) {
return std::array<std::shared_ptr<arrow::DataType>,
sizeof...(FieldTypes)>(
{ArrowTypes<typename FieldTypes::Type>::data_type()...});
}(std::make_integer_sequence<size_t, sizeof...(FieldTypes)>());
}
static Type make_builders() {
return Type(ArrowTypes<typename FieldTypes::Type>::make_builder()...);
}
static auto schema() {
const auto fields = std::vector<std::shared_ptr<arrow::Field>>(
{arrow::field(typename FieldTypes::Name().str(),
ArrowTypes<typename FieldTypes::Type>::data_type())...});
return arrow::schema(fields);
}
};
template <class T>
auto make_arrow_builders() {
return ArrowBuildersType<std::remove_cvref_t<T>>::make_builders();
}
} // namespace rfl::parsing::tabular
#endif
@@ -0,0 +1,18 @@
#ifndef RFL_PARSING_TABULAR_MAKE_ARROW_DATA_TYPES_HPP_
#define RFL_PARSING_TABULAR_MAKE_ARROW_DATA_TYPES_HPP_
#include <type_traits>
#include "../../named_tuple_t.hpp"
#include "make_arrow_builders.hpp"
namespace rfl::parsing::tabular {
template <class T>
inline auto make_arrow_data_types() {
return ArrowBuildersType<named_tuple_t<std::remove_cvref_t<T>>>::data_types();
}
} // namespace rfl::parsing::tabular
#endif
@@ -0,0 +1,18 @@
#ifndef RFL_PARSING_TABULAR_MAKE_ARROW_SCHEMA_HPP_
#define RFL_PARSING_TABULAR_MAKE_ARROW_SCHEMA_HPP_
#include <type_traits>
#include "../../named_tuple_t.hpp"
#include "make_arrow_builders.hpp"
namespace rfl::parsing::tabular {
template <class T>
inline auto make_arrow_schema() {
return ArrowBuildersType<named_tuple_t<std::remove_cvref_t<T>>>::schema();
}
} // namespace rfl::parsing::tabular
#endif
@@ -0,0 +1,57 @@
#ifndef RFL_PARSING_TABULAR_MAKECHUNKEDARRAYITERATORS_HPP_
#define RFL_PARSING_TABULAR_MAKECHUNKEDARRAYITERATORS_HPP_
#include <arrow/api.h>
#include <array>
#include <cinttypes>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "../../NamedTuple.hpp"
#include "../../Ref.hpp"
#include "../../Result.hpp"
#include "../../Tuple.hpp"
#include "ArrowTypes.hpp"
#include "ChunkedArrayIterator.hpp"
namespace rfl::parsing::tabular {
template <class NamedTupleType>
struct MakeChunkedArrayIterators;
template <class... FieldTypes>
struct MakeChunkedArrayIterators<NamedTuple<FieldTypes...>> {
using TupleType = Tuple<ChunkedArrayIterator<typename FieldTypes::Type>...>;
Result<TupleType> operator()(const Ref<arrow::Table>& _table) const {
const auto get_column =
[&](const std::string& _colname) -> Result<Ref<arrow::ChunkedArray>> {
const auto col = _table->GetColumnByName(_colname);
if (!col) {
return error("Column named '" + _colname + "' not found.");
}
return Ref<arrow::ChunkedArray>::make(col);
};
try {
return TupleType(
get_column(typename FieldTypes::Name().str())
.transform(ChunkedArrayIterator<typename FieldTypes::Type>::make)
.value()...);
} catch (const std::exception& e) {
return error(e.what());
}
}
};
template <class NamedTupleType>
const auto make_chunked_array_iterators =
MakeChunkedArrayIterators<NamedTupleType>{};
} // namespace rfl::parsing::tabular
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef RFL_VIEW_T_HPP_
#define RFL_VIEW_T_HPP_
#include <type_traits>
#include "Processors.hpp"
#include "internal/ptr_named_tuple_t.hpp"
namespace rfl {
/// Generates the named tuple that would be the result of to_view
template <class T, class... Ps>
using view_t =
std::invoke_result_t<decltype(Processors<Ps...>::template process<
T, internal::ptr_named_tuple_t<T>>),
internal::ptr_named_tuple_t<T>>;
} // namespace rfl
#endif
+4
View File
@@ -36,6 +36,10 @@ if (REFLECTCPP_MSGPACK)
add_subdirectory(msgpack)
endif()
if (REFLECTCPP_PARQUET)
add_subdirectory(parquet)
endif()
if (REFLECTCPP_TOML)
add_subdirectory(toml)
endif()
+21
View File
@@ -0,0 +1,21 @@
project(reflect-cpp-parquet-tests)
file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp")
add_executable(
reflect-cpp-parquet-tests
${SOURCES}
)
target_precompile_headers(reflect-cpp-parquet-tests PRIVATE [["rfl.hpp"]] <iostream> <string> <functional> <gtest/gtest.h>)
target_include_directories(reflect-cpp-parquet-tests SYSTEM PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/include")
target_link_libraries(
reflect-cpp-parquet-tests
PRIVATE
"${REFLECT_CPP_GTEST_LIB}"
)
find_package(GTest)
gtest_discover_tests(reflect-cpp-parquet-tests)
+47
View File
@@ -0,0 +1,47 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_boolean {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
bool is_child;
Age age;
rfl::Email email;
};
TEST(parquet, test_boolean) {
const auto people =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.is_child = true,
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.is_child = true,
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.is_child = true,
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.is_child = false,
.age = 45,
.email = "homer@simpson.com"}});
write_and_read(people);
}
} // namespace test_boolean
+47
View File
@@ -0,0 +1,47 @@
#include <iostream>
#include <memory>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_box {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Box<rfl::Email> email;
};
TEST(parquet, test_box) {
auto people = std::vector<Person>();
people.emplace_back(
Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = rfl::make_box<rfl::Email>("bart@simpson.com")});
people.emplace_back(
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = rfl::make_box<rfl::Email>("lisa@simpson.com")});
people.emplace_back(
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = rfl::make_box<rfl::Email>("maggie@simpson.com")});
people.emplace_back(
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = rfl::make_box<rfl::Email>("homer@simpson.com")});
write_and_read(people);
}
} // namespace test_box
+24
View File
@@ -0,0 +1,24 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_bytestring {
struct TestStruct {
rfl::Bytestring bytestring;
};
TEST(parquet, test_bytestring) {
const auto test_struct =
TestStruct{.bytestring = rfl::Bytestring({std::byte{13}, std::byte{14},
std::byte{15}, std::byte{16}})};
const auto test_structs = std::vector<TestStruct>(
{test_struct, test_struct, test_struct, test_struct});
write_and_read(test_structs);
}
} // namespace test_bytestring
+42
View File
@@ -0,0 +1,42 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_camel_case {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
std::string first_name;
std::string last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_camel_case) {
const auto people =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
write_and_read<rfl::SnakeCaseToCamelCase>(people);
}
} // namespace test_camel_case
+42
View File
@@ -0,0 +1,42 @@
#include <deque>
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include "write_and_read.hpp"
namespace test_deque {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_deque) {
const auto people =
std::deque<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
write_and_read(people);
}
} // namespace test_deque
+44
View File
@@ -0,0 +1,44 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_enums {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
enum class FirstName { Bart, Lisa, Maggie, Homer };
struct Person {
rfl::Rename<"firstName", FirstName> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_enums) {
const auto people =
std::vector<Person>({Person{.first_name = FirstName::Bart,
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = FirstName::Lisa,
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = FirstName::Lisa,
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = FirstName::Homer,
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
write_and_read(people);
}
} // namespace test_enums
+54
View File
@@ -0,0 +1,54 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_flatten {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Address {
std::string street;
std::string city;
};
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
rfl::Flatten<Address> address;
};
TEST(parquet, test_flatten) {
const auto address =
Address{.street = "Evergreen Terrace", .city = "Springfield"};
const auto people = std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com",
.address = address},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com",
.address = address},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com",
.address = address},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com",
.address = address}});
write_and_read(people);
}
} // namespace test_flatten
+45
View File
@@ -0,0 +1,45 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_gzip {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_gzip) {
const auto people =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
const auto settings = rfl::parquet::Settings{}.with_compression(
rfl::parquet::Compression::GZIP);
write_and_read(people, settings);
}
} // namespace test_gzip
+42
View File
@@ -0,0 +1,42 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_literal {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
std::string first_name;
rfl::Literal<"Simpson"> last_name;
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_literal) {
const auto people =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
write_and_read(people);
}
} // namespace test_literal
+40
View File
@@ -0,0 +1,40 @@
#include <iostream>
#include <optional>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_optionals {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
std::optional<rfl::Email> email;
};
TEST(parquet, test_optionals) {
const auto people = std::vector<Person>(
{Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie", .birthday = "1987-04-19", .age = 0},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
write_and_read(people);
}
} // namespace test_optionals
+42
View File
@@ -0,0 +1,42 @@
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_readme_example {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_readme_example) {
const auto people =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
write_and_read(people);
}
} // namespace test_readme_example
+47
View File
@@ -0,0 +1,47 @@
#include <iostream>
#include <memory>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_ref {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Ref<rfl::Email> email;
};
TEST(parquet, test_ref) {
auto people = std::vector<Person>();
people.emplace_back(
Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = rfl::make_ref<rfl::Email>("bart@simpson.com")});
people.emplace_back(
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = rfl::make_ref<rfl::Email>("lisa@simpson.com")});
people.emplace_back(
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = rfl::make_ref<rfl::Email>("maggie@simpson.com")});
people.emplace_back(
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = rfl::make_ref<rfl::Email>("homer@simpson.com")});
write_and_read(people);
}
} // namespace test_ref
+53
View File
@@ -0,0 +1,53 @@
#include <gtest/gtest.h>
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
namespace test_save_load {
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
std::string first_name;
std::string last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
};
TEST(parquet, test_save_load) {
const auto people1 =
std::vector<Person>({Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"},
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"},
Person{.first_name = "Maggie",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"},
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com"}});
rfl::parquet::save("people.parquet", people1);
const auto people2 =
rfl::parquet::load<std::vector<Person>>("people.parquet").value();
const auto bytes1 = rfl::parquet::write(people1);
const auto bytes2 = rfl::parquet::write(people2);
EXPECT_EQ(bytes1, bytes2);
}
} // namespace test_save_load
+44
View File
@@ -0,0 +1,44 @@
#include <iostream>
#include <memory>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_shared_ptr {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
std::shared_ptr<rfl::Email> email;
};
TEST(parquet, test_shared_ptr) {
auto people = std::vector<Person>();
people.emplace_back(
Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = std::make_shared<rfl::Email>("bart@simpson.com")});
people.emplace_back(
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = std::make_shared<rfl::Email>("lisa@simpson.com")});
people.emplace_back(
Person{.first_name = "Maggie", .birthday = "1987-04-19", .age = 0});
people.emplace_back(
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = std::make_shared<rfl::Email>("homer@simpson.com")});
write_and_read(people);
}
} // namespace test_shared_ptr
+44
View File
@@ -0,0 +1,44 @@
#include <iostream>
#include <memory>
#include <rfl/parquet.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_unique_ptr {
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
std::string town = "Springfield";
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
std::unique_ptr<rfl::Email> email;
};
TEST(parquet, test_unique_ptr) {
auto people = std::vector<Person>();
people.emplace_back(
Person{.first_name = "Bart",
.birthday = "1987-04-19",
.age = 10,
.email = std::make_unique<rfl::Email>("bart@simpson.com")});
people.emplace_back(
Person{.first_name = "Lisa",
.birthday = "1987-04-19",
.age = 8,
.email = std::make_unique<rfl::Email>("lisa@simpson.com")});
people.emplace_back(
Person{.first_name = "Maggie", .birthday = "1987-04-19", .age = 0});
people.emplace_back(
Person{.first_name = "Homer",
.birthday = "1987-04-19",
.age = 45,
.email = std::make_unique<rfl::Email>("homer@simpson.com")});
write_and_read(people);
}
} // namespace test_unique_ptr
+22
View File
@@ -0,0 +1,22 @@
#ifndef WRITE_AND_READ_
#define WRITE_AND_READ_
#include <gtest/gtest.h>
#include <iostream>
#include <rfl/parquet.hpp>
#include <string>
template <class... Ps>
void write_and_read(const auto& _vec, const rfl::parquet::Settings& _settings =
rfl::parquet::Settings{}) {
using T = std::remove_cvref_t<decltype(_vec)>;
const auto serialized1 = rfl::parquet::write<Ps...>(_vec, _settings);
const auto res = rfl::parquet::read<T, Ps...>(serialized1);
EXPECT_TRUE(res && true) << "Test failed on read. Error: "
<< res.error().what();
const auto serialized2 = rfl::parquet::write<Ps...>(res.value(), _settings);
EXPECT_EQ(serialized1, serialized2);
}
#endif
+10
View File
@@ -110,6 +110,16 @@
}
]
},
"parquet": {
"description": "Enable parquet support",
"dependencies": [
{
"name": "arrow",
"version>=": "21.0.0",
"features": ["parquet"]
}
]
},
"tests": {
"description": "Compile the tests",
"dependencies": [