Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,19 @@
{
"type": "org.duckdb.DuckDBArray[]"
},
{
"type": "org.duckdb.DuckDBBignum",
"jniAccessible": true,
"methods": [
{
"name": "toBigDecimal",
"parameterTypes": [
"byte[]",
"int"
]
}
]
},
{
"type": "org.duckdb.DuckDBDate",
"jniAccessible": true,
Expand Down
26 changes: 14 additions & 12 deletions src/jni/bindings_logical_type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "refs.hpp"
#include "util.hpp"

#include <cstdint>
#include <cstring>
#include <vector>

Expand Down Expand Up @@ -81,6 +82,13 @@ static uint32_t get_decimal_param(duckdb_v2_logical_type_handle lt, idx_t index)
return res;
}

/*
* The width and the scale of a DECIMAL are 32-bit unsigned, the values that do not fit a Java int are clamped.
*/
static jint decimal_param_to_jint(uint32_t param) {
return param > static_cast<uint32_t>(INT32_MAX) ? INT32_MAX : static_cast<jint>(param);
}

/*
* Creates a type from type ID with the specified parameter values, takes ownership of the values.
*/
Expand Down Expand Up @@ -177,8 +185,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1create_1logical
JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1create_1decimal_1type(JNIEnv *env, jclass, jint width,
jint scale) {

if (width < 1 || width > 38) {
env->ThrowNew(J_SQLException, "Invalid decimal width: expected 1..38");
if (width < 1) {
env->ThrowNew(J_SQLException, "Invalid decimal width: expected at least 1");
return nullptr;
}
if (scale < 0 || scale > width) {
Expand All @@ -187,8 +195,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1create_1decimal
}
auto factory = default_factory();
std::vector<v2_value> values(2);
duckdb_v2_value_create_utinyint(factory, static_cast<uint8_t>(width), values[0].out(), nullptr);
duckdb_v2_value_create_utinyint(factory, static_cast<uint8_t>(scale), values[1].out(), nullptr);
duckdb_v2_value_create_uint(factory, static_cast<uint32_t>(width), values[0].out(), nullptr);
duckdb_v2_value_create_uint(factory, static_cast<uint32_t>(scale), values[1].out(), nullptr);
auto lt = create_type(factory, DUCKDB_V2_LOGICAL_TYPE_ID_DECIMAL, {}, std::move(values));
return make_logical_type_buf(env, lt);
}
Expand Down Expand Up @@ -224,9 +232,7 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1decimal_1width(JNI
if (logical_type_to_capi(lt) != capi_type::DECIMAL) {
return 0;
}
uint32_t width = get_decimal_param(lt, 0);
// same as in C API v1, wider decimals report 0
return width > UINT8_MAX ? 0 : static_cast<jint>(width);
return decimal_param_to_jint(get_decimal_param(lt, 0));
}

/*
Expand All @@ -245,11 +251,7 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1decimal_1scale(JNI
if (logical_type_to_capi(lt) != capi_type::DECIMAL) {
return 0;
}
if (get_decimal_param(lt, 0) > UINT8_MAX) {
return 0;
}
uint32_t scale = get_decimal_param(lt, 1);
return scale > UINT8_MAX ? 0 : static_cast<jint>(scale);
return decimal_param_to_jint(get_decimal_param(lt, 1));
}

/*
Expand Down
41 changes: 39 additions & 2 deletions src/jni/bindings_value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,38 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1get_1bignum(JNI
return nullptr;
}

/*
* Reads a DECIMAL that is stored as a BIGNUM blob (wider than 38 digits), returns nullptr for other values.
*/
static jobject get_wide_decimal(JNIEnv *env, duckdb_v2_value_handle val) {
v2_logical_type lt;
if (duckdb_v2_value_get_logical_type(val, lt.out(), nullptr) != DUCKDB_V2_ERROR_NONE) {
return nullptr;
}
if (logical_type_to_capi(lt.get()) != capi_type::DECIMAL) {
return nullptr;
}
const char *name_ptr = nullptr;
idx_t name_length = 0;
v2_value scale_value;
uint32_t scale = 0;
if (duckdb_v2_logical_type_get_param(lt.get(), 1, &name_ptr, &name_length, scale_value.out(), nullptr) !=
DUCKDB_V2_ERROR_NONE ||
duckdb_v2_value_get_uint(scale_value.get(), &scale, nullptr) != DUCKDB_V2_ERROR_NONE) {
return nullptr;
}
const char *blob_ptr = nullptr;
idx_t blob_length = 0;
if (duckdb_v2_value_get_blob(val, &blob_ptr, &blob_length, nullptr) != DUCKDB_V2_ERROR_NONE) {
return nullptr;
}
jbyteArray blob = make_jbyteArray(env, blob_ptr, blob_length);
if (env->ExceptionCheck()) {
return nullptr;
}
return env->CallStaticObjectMethod(J_Bignum, J_Bignum_toBigDecimal, blob, static_cast<jint>(scale));
}

/*
* Class: org_duckdb_DuckDBBindings
* Method: duckdb_get_decimal
Expand All @@ -282,12 +314,17 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1get_1decimal(JN
if (env->ExceptionCheck()) {
return nullptr;
}
// same as in C API v1, zero is returned for non-decimal and NULL values and for the decimals
// that cannot be represented
// same as in C API v1, zero is returned for non-decimal and NULL values
duckdb_v2_hugeint_t dec_value = {0, 0};
uint8_t dec_width = 0;
uint8_t dec_scale = 0;
if (duckdb_v2_value_get_decimal(val, &dec_value, &dec_width, &dec_scale, nullptr) != DUCKDB_V2_ERROR_NONE) {
// a decimal that is wider than 255 digits, or whose unscaled value does not fit in 128 bits, is read
// exactly from its BIGNUM storage
jobject wide = get_wide_decimal(env, val);
if (wide != nullptr || env->ExceptionCheck()) {
return wide;
}
dec_value = {0, 0};
dec_scale = 0;
}
Expand Down
45 changes: 27 additions & 18 deletions src/jni/duckdb_java.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,28 @@ static jobject make_vec_data_buf(JNIEnv *env, Vector &vec, idx_t row_count) {
return make_data_buf(env, vec_data, len);
}

static jobjectArray make_vec_byte_arrays(JNIEnv *env, Vector &vec, idx_t row_count) {
jobjectArray varlen_data = env->NewObjectArray(row_count, J_ByteArray, nullptr);
const string_t *vec_data = FlatVector::GetData<string_t>(vec);

for (idx_t row_idx = 0; row_idx < row_count; row_idx++) {
if (FlatVector::IsNull(vec, row_idx)) {
continue;
}

const string_t d_str = vec_data[row_idx];

auto j_arr = env->NewByteArray(d_str.GetSize());
auto j_arr_el = env->GetByteArrayElements(j_arr, nullptr);
memcpy(j_arr_el, d_str.GetData(), d_str.GetSize());
env->ReleaseByteArrayElements(j_arr, j_arr_el, 0);

env->SetObjectArrayElement(varlen_data, row_idx, j_arr);
env->DeleteLocalRef(j_arr);
}
return varlen_data;
}

jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_count) {
if (vec.GetVectorType() != VectorType::FLAT_VECTOR) {
vec.Flatten();
Expand Down Expand Up @@ -777,6 +799,10 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_
case PhysicalType::INT128:
constlen_data = make_vec_data_buf<hugeint_t>(env, vec, row_count);
break;
case PhysicalType::VARCHAR:
// wider than 38 digits, the BIGNUM blobs of the unscaled values are decoded on the Java side
varlen_data = make_vec_byte_arrays(env, vec, row_count);
break;
default:
throw InternalException("Unimplemented physical type for decimal");
}
Expand Down Expand Up @@ -850,24 +876,7 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_
}
case LogicalTypeId::BLOB:
case LogicalTypeId::GEOMETRY:
varlen_data = env->NewObjectArray(row_count, J_ByteArray, nullptr);

for (idx_t row_idx = 0; row_idx < row_count; row_idx++) {
if (FlatVector::IsNull(vec, row_idx)) {
continue;
}

const string_t *vec_data = FlatVector::GetData<string_t>(vec);
const string_t d_str = vec_data[row_idx];

auto j_arr = env->NewByteArray(d_str.GetSize());
auto j_arr_el = env->GetByteArrayElements(j_arr, nullptr);
memcpy(j_arr_el, d_str.GetData(), d_str.GetSize());
env->ReleaseByteArrayElements(j_arr, j_arr_el, 0);

env->SetObjectArrayElement(varlen_data, row_idx, j_arr);
env->DeleteLocalRef(j_arr);
}
varlen_data = make_vec_byte_arrays(env, vec, row_count);
break;
case LogicalTypeId::UUID:
constlen_data = make_vec_data_buf<hugeint_t>(env, vec, row_count);
Expand Down
4 changes: 4 additions & 0 deletions src/jni/refs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ jfieldID J_HugeInt_lower;
jfieldID J_HugeInt_upper;
jmethodID J_HugeInt_toBigInteger;
jmethodID J_HugeInt_toBigDecimal;
jclass J_Bignum;
jmethodID J_Bignum_toBigDecimal;

jclass J_DuckResultSetMeta;
jmethodID J_DuckResultSetMeta_init;
Expand Down Expand Up @@ -284,6 +286,8 @@ void create_refs(JNIEnv *env) {
J_HugeInt_upper = get_field_id(env, J_HugeInt, "upper", "J");
J_HugeInt_toBigInteger = get_static_method_id(env, J_HugeInt, "toBigInteger", "(JJ)Ljava/math/BigInteger;");
J_HugeInt_toBigDecimal = get_static_method_id(env, J_HugeInt, "toBigDecimal", "(JJI)Ljava/math/BigDecimal;");
J_Bignum = make_class_ref(env, "org/duckdb/DuckDBBignum");
J_Bignum_toBigDecimal = get_static_method_id(env, J_Bignum, "toBigDecimal", "([BI)Ljava/math/BigDecimal;");

J_DuckResultSetMeta = make_class_ref(env, "org/duckdb/DuckDBResultSetMetaData");
J_DuckResultSetMeta_init = env->GetMethodID(J_DuckResultSetMeta, "<init>",
Expand Down
2 changes: 2 additions & 0 deletions src/jni/refs.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ extern jfieldID J_HugeInt_lower;
extern jfieldID J_HugeInt_upper;
extern jmethodID J_HugeInt_toBigInteger;
extern jmethodID J_HugeInt_toBigDecimal;
extern jclass J_Bignum;
extern jmethodID J_Bignum_toBigDecimal;

extern jclass J_DuckResultSetMeta;
extern jmethodID J_DuckResultSetMeta_init;
Expand Down
15 changes: 10 additions & 5 deletions src/jni/types.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ std::string type_to_jduckdb_type(duckdb::LogicalType logical_type) {
std::string res = std::string("DECIMAL128;") + width_scale;
return res;
}
case duckdb::PhysicalType::VARCHAR: {
// wider than 38 digits, the unscaled value is stored as a BIGNUM blob
std::string res = std::string("DECIMALBIGNUM;") + width_scale;
return res;
}
default:
return std::string("no physical type found");
}
Expand Down Expand Up @@ -72,13 +77,13 @@ duckdb::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal) {
jlong result = env->CallLongMethod(no_point_dec, J_BigDecimal_longValue);
check_java_exception_and_rethrow(env);
val = duckdb::Value::DECIMAL((int64_t)result, (uint8_t)precision, (uint8_t)scale);
} else if (precision <= 38) { // larger than int64 -> get string and cast
} else { // larger than int64 -> get string and cast, the widths above 38 digits are exact too
jobject str_val = env->CallObjectMethod(decimal, J_BigDecimal_toPlainString);
check_java_exception_and_rethrow(env);
auto *str_char = env->GetStringUTFChars((jstring)str_val, 0);
val = duckdb::Value(str_char);
val = val.DefaultCastAs(duckdb::LogicalType::DECIMAL(precision, scale));
env->ReleaseStringUTFChars((jstring)str_val, str_char);
auto str = jstring_to_string(env, (jstring)str_val);
val = duckdb::Value(str);
val = val.DefaultCastAs(
duckdb::LogicalType::DECIMAL(static_cast<uint32_t>(precision), static_cast<uint32_t>(scale)));
}

return val;
Expand Down
8 changes: 7 additions & 1 deletion src/main/java/org/duckdb/DuckDBAppender.java
Original file line number Diff line number Diff line change
Expand Up @@ -1354,6 +1354,12 @@ private void putDecimal(Column col, long vectorIdx, BigDecimal value) throws SQL
putDecimal(col, vectorIdx, lower, upper);
break;
}
case DUCKDB_TYPE_VARINT: {
// wider than 38 digits, the unscaled value is stored as a BIGNUM blob
byte[] blob = DuckDBBignum.fromBigInteger(value.unscaledValue());
putStringOrBlob(col, vectorIdx, blob);
break;
}
default:
throw createAppenderException("invalid decimal internal type: '" + col.decimalInternalType + "'",
ErrorCode.APPENDER_CONVERSION);
Expand All @@ -1362,7 +1368,7 @@ private void putDecimal(Column col, long vectorIdx, BigDecimal value) throws SQL

private void putStringOrBlob(Column col, long vectorIdx, byte[] bytes) throws SQLException {
if (writeInlinedStrings && bytes.length < STRING_MAX_INLINE_BYTES) {
int pos = (int) (vectorIdx * col.colType.widthBytes);
int pos = (int) (vectorIdx * col.widthBytes());
col.data.position(pos);
col.data.putInt(bytes.length);
if (bytes.length > 0) {
Expand Down
61 changes: 61 additions & 0 deletions src/main/java/org/duckdb/DuckDBBignum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package org.duckdb;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
* Conversions between the BIGNUM storage blob and {@link BigInteger}. A DECIMAL wider than 38 digits stores its
* unscaled value in this form.
*
* <p>The blob is a 3-byte header followed by the magnitude in big-endian byte order without leading zero bytes
* (the magnitude of zero is a single zero byte). The header holds the number of magnitude bytes with the most
* significant bit set. For a negative value every byte of the blob, header included, is complemented.
*/
final class DuckDBBignum {
static final int HEADER_SIZE = 3;
static final int MAX_DATA_SIZE = 8388607;

private DuckDBBignum() {
}

static BigInteger toBigInteger(byte[] blob) {
if (blob == null || blob.length <= HEADER_SIZE) {
throw new IllegalArgumentException("Invalid BIGNUM blob size: " + (blob == null ? 0 : blob.length));
}
boolean negative = (blob[0] & 0x80) == 0;
byte[] magnitude = new byte[blob.length - HEADER_SIZE];
for (int i = 0; i < magnitude.length; i++) {
byte b = blob[HEADER_SIZE + i];
magnitude[i] = negative ? (byte) ~b : b;
}
return new BigInteger(negative ? -1 : 1, magnitude);
}

static BigDecimal toBigDecimal(byte[] blob, int scale) {
return new BigDecimal(toBigInteger(blob), scale);
}

static byte[] fromBigInteger(BigInteger value) {
boolean negative = value.signum() < 0;
// big-endian two's complement of the absolute value: at most one leading zero byte
byte[] magnitude = value.abs().toByteArray();
int skip = magnitude.length > 1 && magnitude[0] == 0 ? 1 : 0;
int size = magnitude.length - skip;
if (size > MAX_DATA_SIZE) {
throw new IllegalArgumentException("Value is too large for BIGNUM storage, bytes: " + size);
}
int header = size | 0x00800000;
if (negative) {
header = ~header;
}
byte[] blob = new byte[HEADER_SIZE + size];
blob[0] = (byte) (header >> 16);
blob[1] = (byte) (header >> 8);
blob[2] = (byte) header;
for (int i = 0; i < size; i++) {
byte b = magnitude[skip + i];
blob[HEADER_SIZE + i] = negative ? (byte) ~b : b;
}
return blob;
}
}
4 changes: 2 additions & 2 deletions src/main/java/org/duckdb/DuckDBBindings.java
Original file line number Diff line number Diff line change
Expand Up @@ -367,8 +367,8 @@ enum CAPIType {
DUCKDB_TYPE_TIMESTAMP_TZ(31, 8),
// enum type, only useful as logical type
DUCKDB_TYPE_ANY(34),
// duckdb_varint
DUCKDB_TYPE_VARINT(35),
// duckdb_bignum, also the storage of the decimals wider than 38 digits
DUCKDB_TYPE_VARINT(35, 16),
// enum type, only useful as logical type
DUCKDB_TYPE_SQLNULL(36),
// enum type, only useful as logical type
Expand Down
19 changes: 13 additions & 6 deletions src/main/java/org/duckdb/DuckDBColumnTypeMetaData.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
package org.duckdb;

public class DuckDBColumnTypeMetaData {
public final short type_size;
public final short width;
public final short scale;
/**
* Value of {@link #type_size} for a DECIMAL wider than 38 digits, such values have no fixed size.
*/
public static final int VARIABLE_TYPE_SIZE = 0;

public DuckDBColumnTypeMetaData(short type_size, short width, short scale) {
public final int type_size;
public final int width;
public final int scale;

public DuckDBColumnTypeMetaData(int type_size, int width, int scale) {
this.type_size = type_size;
this.width = width;
this.scale = scale;
}

public static DuckDBColumnTypeMetaData parseColumnTypeMetadata(String columnTypeDetail) {
String[] split_details = columnTypeDetail.split(";");
return new DuckDBColumnTypeMetaData(Short.parseShort(split_details[0].replace("DECIMAL", "")),
Short.parseShort(split_details[1]), Short.parseShort(split_details[2]));
String storage = split_details[0].replace("DECIMAL", "");
int type_size = "BIGNUM".equals(storage) ? VARIABLE_TYPE_SIZE : Integer.parseInt(storage);
return new DuckDBColumnTypeMetaData(type_size, Integer.parseInt(split_details[1]),
Integer.parseInt(split_details[2]));
}
}
Loading
Loading